diff --git a/C3d/Include/action_analysis.h b/C3d/Include/action_analysis.h index e143fc0..324d46e 100644 --- a/C3d/Include/action_analysis.h +++ b/C3d/Include/action_analysis.h @@ -26,7 +26,8 @@ enum MbeExtremsSearchingMethod { esm_GradientDescent = 1, ///< \ru Mетод градиентного спуска. \en Gradient Descent Method. - esm_LineSegregation = 2 ///< \ru Mетод выделения линий смены убывания / возрастания функции по u и по v. \en The method of segregation of lines of change of decrease / increase of the function in u and v directions. + esm_LineSegregation = 2, ///< \ru Mетод выделения линий смены убывания / возрастания функции по u и по v. \en The method of segregation of lines of change of decrease / increase of the function in u and v directions. + esm_AdaptiveCells = 3, ///< \ru Mетод адаптивного дробления ячеек. \en Adaptive cell splitting method. }; diff --git a/C3d/Include/action_b_shaper.h b/C3d/Include/action_b_shaper.h index da80e24..10f4135 100644 --- a/C3d/Include/action_b_shaper.h +++ b/C3d/Include/action_b_shaper.h @@ -130,6 +130,73 @@ public: }; +//------------------------------------------------------------------------------ +/** \brief \ru Параметры вписывания поверхности. + \en Parameters of surface fitting. \~ + \ingroup Polygonal_Objects +*/ +// --- +class MATH_CLASS MbSurfaceFitToGridParameters { +private: + + MbeSpaceType _surfaceType; ///< \ru Тип поверхности. \en A surface type. + double _tolerance; ///< \ru Точность распознавания. \en A fitting tolerance. + const c3d::IndicesVector & _indicies; ///< \ru Индексы полигонов сетки. \en Indicies of polygons. +public: + /// \ru Конструктор по умолчанию. \en Default constructor. + explicit MbSurfaceFitToGridParameters( MbeSpaceType surfaceType, + double tolerance, + const c3d::IndicesVector & indicies ) + : _surfaceType( surfaceType ) + , _tolerance( tolerance ) + , _indicies( indicies ) + {} + /// \ru Выдать тип поверхности. \en Get surface type. + MbeSpaceType GetSurfaceType() const { return _surfaceType; } + /// \ru Выдать точность распознавания. \en Get fitting tolerance. + double GetTolerance() const { return _tolerance; } + /// \ru Выдать индексы полигонов. \en Get indicies of polygons. + const c3d::IndicesVector & GetIndicies() const { return _indicies; } + + OBVIOUS_PRIVATE_COPY( MbSurfaceFitToGridParameters ) +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Результат вписывания поверхности. + \en Parameters of surface fitting. \~ + \ingroup Polygonal_Objects +*/ +// --- +class MATH_CLASS MbSurfaceFitToGridResults { +private: + c3d::SurfaceSPtr _surface; ///< \ru Поверхность. \en A surface. + double _tolerance; ///< \ru Достигнутая точность распознавания. \en Obtained tolerance. +public: + /// \ru Конструктор по умолчанию. \en Default constructor. + MbSurfaceFitToGridResults() + : _surface ( nullptr ) + , _tolerance( 0.0 ) + {} + /// \ru Конструктор по параметрам. \en Constructor by parameters. + MbSurfaceFitToGridResults( MbSurface * surface, double tolerance ) + : _surface( surface ) + , _tolerance( tolerance ) + {} + void Init( MbSurface * surface, double tolerance ) { + _surface = surface; + _tolerance = tolerance; + } + /// \ru Выдать поверхность. \en Get surface. + c3d::SurfaceSPtr GetSurface() const { return _surface; } + /// \ru Выдать достигнутую точность распознавания. \en Get obtained tolerance. + double GetTolerance() const { return _tolerance; } + + OBVIOUS_PRIVATE_COPY( MbSurfaceFitToGridResults ) +}; + + + //------------------------------------------------------------------------------ /** \brief \ru Класс для создания оболочки в граничном представлении по полигональной сетке. \en Class for creating a BRep shell by polygonal mesh. \~ @@ -292,7 +359,7 @@ public: Если сегментация не была вычислена, то вычисляется автоматическая сегментация (с параметрами по умолчанию). \n \en Create BRep shell that represents input mesh model. Current segmentation is used. - If segmentation is not computed yet, then automatic segmentation is performed (with default paramters). \n \~ + If segmentation is not computed yet, then automatic segmentation is performed (with default parameters). \n \~ \param[out] pShell - \ru Указатель на созданную оболочку. \en The pointer to created shell. \~ \param[in] smoothBoundaryEdges - \ru Флаг сглаживания краевых ребер. @@ -419,7 +486,7 @@ private: // UNDER DEVELOPMENT \en Returns operation result code. \~ \ingroup Polygonal_Objects */ - virtual MbResultType SegmentMeshBySeparators( const std::vector> & separators ) = 0; + virtual MbResultType SegmentMeshBySeparators( const std::vector & separators ) = 0; OBVIOUS_PRIVATE_COPY( MbMeshProcessor ) }; @@ -428,20 +495,20 @@ private: // UNDER DEVELOPMENT //------------------------------------------------------------------------------ /** \brief \ru Создать оболочку по полигональной сетке c автоматическим распознаванием поверхностей. \en Create shell from mesh with automatic surface reconstruction. \~ - \details \ru Создать оболочку в граничном представлении, соответствующее модели, заданной полигональной сеткой. - Алгоритм в автоматическом режиме распознает и реконструирует грани, соответствующие элементарным - поверхностям (плоскость, цилиндр, сфера, конус, тор). \n - \en Create BRep shell that represents input mesh model. - Algorithm automatically detect and reconstruct faces based on elementary surfaces (plane, cylinder, sphere, cone, torus). \n \~ - \param[in] mesh - \ru Входная сетка. - \en The input mesh. \~ - \param[out] shell - \ru Указатель на созданную оболочку. - \en The pointer to created shell. \~ - \param[in] params - \ru Параметры построения оболочки тела. - \en Parameters of BRep shell construction. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Polygonal_Objects + \details \ru Создать оболочку в граничном представлении, соответствующее модели, заданной полигональной сеткой. + Алгоритм в автоматическом режиме распознает и реконструирует грани, соответствующие элементарным + поверхностям (плоскость, цилиндр, сфера, конус, тор). \n + \en Create BRep shell that represents input mesh model. + Algorithm automatically detect and reconstruct faces based on elementary surfaces (plane, cylinder, sphere, cone, torus). \n \~ + \param[in] mesh - \ru Входная сетка. + \en The input mesh. \~ + \param[out] shell - \ru Указатель на созданную оболочку. + \en The pointer to created shell. \~ + \param[in] params - \ru Параметры построения оболочки тела. + \en Parameters of BRep shell construction. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Polygonal_Objects */ // --- MATH_FUNC( MbResultType ) ConvertMeshToShell( MbMesh & mesh, MbFaceShell *& shell, const MbMeshProcessorValues & params = MbMeshProcessorValues() ); @@ -450,22 +517,47 @@ MATH_FUNC( MbResultType ) ConvertMeshToShell( MbMesh & mesh, MbFaceShell *& shel //------------------------------------------------------------------------------ /** \brief \ru Создать оболочку по коллекции, содержащей полигональную сетку c автоматическим распознаванием поверхностей. \en Create shell from collection with automatic surface reconstruction. \~ - \details \ru Создать оболочку в граничном представлении, соответствующую модели, заданной полигональной сеткой. - Алгоритм в автоматическом режиме распознает и реконструирует грани, соответствующие элементарным - поверхностям (плоскость, цилиндр, сфера, конус, тор). \n - \en Create BRep shell that represents input mesh model from collection. - Algorithm automatically detect and reconstruct faces based on elementary surfaces (plane, cylinder, sphere, cone, torus). \n \~ - \param[in] collection - \ru Коллекция, содержащая входную сетку. - \en The input collection. \~ - \param[out] shell - \ru Указатель на созданную оболочку. - \en The pointer to created shell. \~ - \param[in] params - \ru Параметры построения оболочки тела. - \en Parameters of BRep shell construction. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Polygonal_Objects + \details \ru Создать оболочку в граничном представлении, соответствующую модели, заданной полигональной сеткой. + Алгоритм в автоматическом режиме распознает и реконструирует грани, соответствующие элементарным + поверхностям (плоскость, цилиндр, сфера, конус, тор). \n + \en Create BRep shell that represents input mesh model from collection. + Algorithm automatically detect and reconstruct faces based on elementary surfaces (plane, cylinder, sphere, cone, torus). \n \~ + \param[in] collection - \ru Коллекция, содержащая входную сетку. + \en The input collection. \~ + \param[out] shell - \ru Указатель на созданную оболочку. + \en The pointer to created shell. \~ + \param[in] params - \ru Параметры построения оболочки тела. + \en Parameters of BRep shell construction. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Polygonal_Objects */ // --- MATH_FUNC( MbResultType ) ConvertCollectionToShell( MbCollection & collection, MbFaceShell *& shell, const MbMeshProcessorValues & params = MbMeshProcessorValues() ); + +//------------------------------------------------------------------------------ +/** \brief \ru Вписать поверхность в множество полигонов сетки. + \en Fit the surface into polygon set. \~ + \details \ru Создать оболочку в граничном представлении, соответствующую модели, заданной полигональной сеткой. + Алгоритм в автоматическом режиме распознает и реконструирует грани, соответствующие элементарным + поверхностям (плоскость, цилиндр, сфера, конус, тор). \n + \en Create BRep shell that represents input mesh model from collection. + Algorithm automatically detect and reconstruct faces based on elementary surfaces (plane, cylinder, sphere, cone, torus). \n \~ + \param[in] grid - \ru Исходная триангуляция. + \en The initial triangulation. \~ + \param[in] params - \ru Параметры вписывания поверхности. + \en The fitting parameters. \~ + \param[out] results - \ru Результаты вписывания поверхности. + \en Results of surface fitting. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \warning \ru В разработке. + \en Under development. \~ + \ingroup Polygonal_Objects +*/ +// --- +MATH_FUNC( MbResultType ) FitSurfaceToGrid( const MbGrid & grid, const MbSurfaceFitToGridParameters & params, MbSurfaceFitToGridResults & results ); + + #endif // __ACTION_B_SHAPER_H diff --git a/C3d/Include/action_curve3d.h b/C3d/Include/action_curve3d.h index a5d53a0..021e349 100644 --- a/C3d/Include/action_curve3d.h +++ b/C3d/Include/action_curve3d.h @@ -1110,6 +1110,41 @@ MATH_FUNC (MbResultType) CreateFairBSplineCurveOnBasePolylineOfHermiteGD( MbCurv MbCurve3D *& result ); +//------------------------------------------------------------------------------ + /** \brief \ru Создать плавную и сглаживающую B-сплайновую кривую на опорной ломаной ГО Эрмита. + \en Create a fair B-spline curve on base polyline of Hermite GD. \~ + \details \ru Создать плавную V-кривую на опорной ломаной и аппроксимировать B-сплайновой кривой. \n + Степень сплайна m, (m = 3, 4, ... , 9, 10) устанавливается в переменной degreeBSpline. + Для гармоничного перераспределения точек значение переменной arrange == true. В противном случае == false. + Для уплотнения кривой значение переменной subdivision > 0 (1 - для однократного уплотнения, 2 - для двукратного). + Направление вектора в точках перегиба учитывается по значению переменной accountInflexVector (0 - как направление звена S-полигона, + 1 - как направление касательного вектора). \n + Кривизна в концевых точках учитывается по значению accountCurvature (0 - не учитывается, 1 - в начальной точке, 2 - в конечной точке, 3 - учитываются на обоих концах). + \en Create a fair V-curve on the base polyline and approximate by a B-spline curve. \ n + The degree of spline m, (m = 3, 4, ... , 9, 10) is set by variable degreeBSpline. + For harmonious redistribution of points, the value of the variable arrange == true. Otherwise, == false. + To subdivide a curve, the value of the variable subdivision > 0 (1 for a single subdivision, 2 for a double subdivision). + The directions of the tangent vectors of the Hermite GD determine the directions of the S-polygon segmentss. \n + The direction of the vector at the inflection points is taken into account by the value of the variable InflexVector (0 - as the direction of the S-polygon segment, \ n + 1 - as the direction of the tangent vector). \n + The curvature at the end points is taken into account by the value of accountCurvature (0 - not taken into account, 1 - at the start point, 2 - at the end point, 3 - are taken into account at both ends). \~ + \attention \ru Экспериментальный класс. \en Experimental class. \~ + \param[in] polyline - \ru Исходная ломаная. + \en An initial polyline. \~ + \param[in] data - \ru Данные построения кривой. + \en The curve construction data. \~ + \param[out] result - \ru Сплайновая кривая. + \en The spline curve. \~ + \return \ru Возвращает значение результата операции. 0 - при успешном построении кривой. При > 0 значение равно номеру сообщения об ошибке из списка сообщений метода MessageError. + \en Returns operation result value. 0 - upon successful creation of the curve. If > 0, the value is equal to the error message number from the message list of the MessageError method.\~ +\ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC( MbResultType ) CreateFairBSplineCurveOnBasePolylineOfHermiteGDInflex( MbCurve3D * pllne, + MbFairCurveData & data, + MbCurve3D *& resCurve ); + + //------------------------------------------------------------------------------ /** \brief \ru Создать плавную B-сплайновую кривую на касательных прямых ГО Эрмита. \en Create a fair B-spline curve on tangent lines of Hermite GD. \~ diff --git a/C3d/Include/action_mesh.h b/C3d/Include/action_mesh.h index fcae212..042c75f 100644 --- a/C3d/Include/action_mesh.h +++ b/C3d/Include/action_mesh.h @@ -18,12 +18,12 @@ #include #include #include +#include #include class MATH_CLASS MbPlacement3D; class MATH_CLASS MbMesh; -class MATH_CLASS MbCurve3D; class MATH_CLASS MbSurface; class MATH_CLASS MbSolid; class MATH_CLASS MbPlaneItem; @@ -112,12 +112,11 @@ private: \param[out] polygon - \ru Рассчитанный полигон. \en Calculated polygon. \~ \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (void) CalculatePolygon( const MbCurve & curve, +*/ // --- +MATH_FUNC (void) CalculatePolygon( const MbCurve & curve, const MbPlacement3D & plane, - double sag, - MbPolygon3D & polygon ); + double sag, + MbPolygon3D & polygon ); //------------------------------------------------------------------------------ @@ -136,12 +135,11 @@ MATH_FUNC (void) CalculatePolygon( const MbCurve & curve, \param[out] mesh - \ru Полигональный объект. \en Polygonal object. \~ \ingroup Polygonal_Objects -*/ -// --- -MATH_FUNC (void) CalculateWire( const MbPlaneItem & obj, +*/ // --- +MATH_FUNC (void) CalculateWire( const MbPlaneItem & obj, const MbPlacement3D & plane, - double sag, - MbMesh & mesh ); + double sag, + MbMesh & mesh ); //------------------------------------------------------------------------------ @@ -160,12 +158,11 @@ MATH_FUNC (void) CalculateWire( const MbPlaneItem & obj, \return \ru Возвращает код результата операции. \en Returns operation result code. \~ \ingroup Polygonal_Objects -*/ -// --- +*/ // --- MATH_FUNC (MbResultType) CreateIcosahedron( const MbPlacement3D & place, - double radius, - const MbFormNote & fn, - MbMesh *& result ); + double radius, + const MbFormNote & fn, + MbMesh *& result ); //------------------------------------------------------------------------------ @@ -194,9 +191,8 @@ MATH_FUNC (MbResultType) CreateIcosahedron( const MbPlacement3D & place, \return \ru Возвращает код результата операции. \en Returns operation result code. \~ \ingroup Polygonal_Objects -*/ -// --- -MATH_FUNC (MbResultType) CreateBoxMesh( const MbMatrix3D & trans, +*/ // --- +MATH_FUNC (MbResultType) CreateBoxMesh( const MbMatrix3D & trans, SPtr & result ); @@ -206,9 +202,8 @@ MATH_FUNC (MbResultType) CreateBoxMesh( const MbMatrix3D & trans, \details \ru Функция конструирует проволочный каркас параллелепипеда по тем же правилам, что и #CreateBoxMesh. \en The function makes the wireframe of the oriented box by the same rules as #CreateBoxMesh. \ingroup Polygonal_Objects -*/ -//--- -MATH_FUNC (MbResultType) CreateBoxWire( const MbMatrix3D & trans, +*/ //--- +MATH_FUNC (MbResultType) CreateBoxWire( const MbMatrix3D & trans, SPtr & result ); @@ -224,8 +219,7 @@ MATH_FUNC (MbResultType) CreateBoxWire( const MbMatrix3D & trans, \param[in] isVisibleOnly - \ru В случае если флаг true, то обрабатываются только видимые полигоны сетки. \en If true only visible mesh polygons are processed. \~ \ingroup Polygonal_Objects -*/ -// --- +*/ // --- MATH_FUNC( void ) MakeSpaceWireFrame( const MbItem & item, RPArray & wire, bool isVisibleOnly = false ); @@ -243,8 +237,7 @@ MATH_FUNC( void ) MakeSpaceWireFrame( const MbItem & item, \param[out] wire - \ru Набор пространственных кривых, характеризующих полигональных объект. \en A spatial wireframe by a mesh. \~ \ingroup Polygonal_Objects -*/ -// --- +*/ // --- MATH_FUNC( void ) MakePlaneWireFrame( const MbItem & item, const MbPlacement3D & place, RPArray & wire ); @@ -264,8 +257,7 @@ MATH_FUNC( void ) MakePlaneWireFrame( const MbItem & item, \param[out] wire - \ru Набор пространственных кривых, характеризующих полигональных объект. \en A spatial wireframe by a mesh. \~ \ingroup Polygonal_Objects -*/ -// --- +*/ // --- MATH_FUNC( void ) MakePlaneVistaWireFrame( const MbItem & item, const MbPlacement3D & place, const MbCartPoint3D & vista, @@ -284,8 +276,7 @@ MATH_FUNC( void ) MakePlaneVistaWireFrame( const MbItem & item, \param[out] wire - \ru Набор двумерных кривых, характеризующих полигональных объект. \en A spatial wireframe by a mesh. \~ \ingroup Polygonal_Objects -*/ -// --- +*/ // --- MATH_FUNC( void ) MakePlaneWireFrame( const MbItem & item, const MbPlacement3D & place, RPArray & wire ); @@ -305,8 +296,7 @@ MATH_FUNC( void ) MakePlaneWireFrame( const MbItem & item, \param[out] wire - \ru Набор двумерных кривых, характеризующих полигональных объект. \en A spatial wireframe by a mesh. \~ \ingroup Polygonal_Objects -*/ -// --- +*/ // --- MATH_FUNC( void ) MakePlaneVistaWireFrame( const MbItem & item, const MbPlacement3D & place, const MbCartPoint3D & vista, @@ -330,12 +320,11 @@ MATH_FUNC( void ) MakePlaneVistaWireFrame( const MbItem & item, \return \ru Возвращает код результата операции. \en Returns operation result code. \~ \ingroup Polygonal_Objects -*/ -// --- +*/ // --- MATH_FUNC (MbResultType) CreateSpherePolyhedron( const MbPlacement3D & place, - double radius, - double & epsilon, - MbMesh *& result ); + double radius, + double & epsilon, + MbMesh *& result ); //------------------------------------------------------------------------------ @@ -350,8 +339,7 @@ MATH_FUNC (MbResultType) CreateSpherePolyhedron( const MbPlacement3D & place, \return \ru Возвращает код результата операции. \en Returns operation result code. \~ \ingroup Polygonal_Objects -*/ -// --- +*/ // --- MATH_FUNC (MbResultType) CreateConvexPolyhedron( const SArray & points, MbMesh *& result ); @@ -368,8 +356,7 @@ MATH_FUNC (MbResultType) CreateConvexPolyhedron( const SArray & \return \ru Возвращает код результата операции. \en Returns operation result code. \~ \ingroup Polygonal_Objects -*/ -// --- +*/ // --- MATH_FUNC( MbResultType ) CreateConvexPolyhedron( const std::vector & points, MbMesh *& result ); @@ -386,11 +373,11 @@ MATH_FUNC( MbResultType ) CreateConvexPolyhedron( const std::vector & points, MbMesh *& result ); + //------------------------------------------------------------------------------ /** \brief \ru Вычислить выпуклую оболочку для множества точек. \en Calculate a convex hull of a point set. \~ @@ -403,8 +390,7 @@ MATH_FUNC( MbResultType ) CreateConvexPolyhedron( const SArray & \return \ru Возвращает код результата операции. \en Returns operation result code. \~ \ingroup Polygonal_Objects -*/ -// --- +*/ // --- MATH_FUNC( MbResultType ) CreateConvexPolyhedron( const std::vector & points, MbMesh *& result ); @@ -430,8 +416,7 @@ MATH_FUNC( MbResultType ) CreateConvexPolyhedron( const std::vector & polylines ); +//------------------------------------------------------------------------------ +/** \brief \ru Построить контур сечения полигонального объекта плоскостью. + \en Create a section contour of a polygon figure. \~ + \details \ru Построить контур сечения присланного объекта плоскостью XY локальной системы координат. \n + \en Construct curves of the section of the mesh object lying on the XY plane of the local coordinate system. \n + \param[in] mesh - \ru Исходный полигональный объект. + \en The source polygonal object. \~ + \param[in] place - \ru Секущая плоскость. + \en A cutting plane. \~ + \param[out] polylines - \ru Построенные ломаные контура сечения объекта. + \en The resultant contours. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Polygonal_Objects +*/ // --- +MATH_FUNC( MbResultType ) MeshSection( const MbMesh & mesh, + const MbPlacement3D & place, + c3d::SpaceCurvesSPtrVector & polylines ); //------------------------------------------------------------------------------ @@ -534,11 +535,11 @@ MATH_FUNC (MbResultType) MeshSection( const MbMesh & mesh, \return \ru Возвращает код результата операции. \en Returns operation result code. \~ \ingroup Polygonal_Objects -*/ -// --- -MATH_FUNC( MbResultType ) MeshMeshIntersection( const MbMesh & mesh1, - const MbMesh & mesh2, - std::vector< SPtr > & polylines ); +*/ // --- +MATH_FUNC( MbResultType ) MeshMeshIntersection( const MbMesh & mesh1, + const MbMesh & mesh2, + c3d::SpaceCurvesSPtrVector & polylines ); + //------------------------------------------------------------------------------ /** \brief \ru Создать полигональный объект булевой операции. @@ -556,11 +557,12 @@ MATH_FUNC( MbResultType ) MeshMeshIntersection( const MbMesh & mesh1, \result \ru Возвращает код результата операции. \en Returns the operation result code. \~ \ingroup Model_Creators -*/ -// --- -MATH_FUNC( MbResultType ) CreateBoolean( const MbMesh & mesh1, const MbMesh & mesh2, - OperationType operation, - SPtr & newMesh ); +*/ // --- +MATH_FUNC( MbResultType ) CreateBoolean( const MbMesh & mesh1, + const MbMesh & mesh2, + OperationType operation, + c3d::MeshSPtr & newMesh ); + //------------------------------------------------------------------------------ /** \brief \ru Построить триангуляцию по облаку точек на основе алгоритма поворотного шара. @@ -578,8 +580,7 @@ MATH_FUNC( MbResultType ) CreateBoolean( const MbMesh & mesh1, const MbMesh & me \return \ru Возвращает код результата операции. \en Returns operation result code. \~ \ingroup Polygonal_Objects -*/ -// --- +*/ // --- MATH_FUNC (MbResultType) CalculateBallPivotingGrid( const MbCollection & collection, double radius, double radiusMin, @@ -597,8 +598,7 @@ MATH_FUNC (MbResultType) CalculateBallPivotingGrid( const MbCollection & collect \ingroup Polygonal_Objects \warning \ru В разработке. \en Under development. \~ -*/ -// --- +*/ // --- MATH_FUNC (MbResultType) RepairInconsistentMesh( MbMesh & mesh ); @@ -614,8 +614,7 @@ MATH_FUNC (MbResultType) RepairInconsistentMesh( MbMesh & mesh ); \return \ru Возвращает код результата операции. \en Returns operation result code. \~ \ingroup Polygonal_Objects -*/ -// --- +*/ // --- MATH_FUNC ( MbResultType ) ConvertMeshToInstance( std::vector> & meshContainer, double accuracy = Math::metricRegion ); @@ -632,8 +631,7 @@ MATH_FUNC ( MbResultType ) ConvertMeshToInstance( std::vector> & me \ingroup Polygonal_Objects \warning \ru В разработке. \en Under development. \~ -*/ -// --- +*/ // --- MATH_FUNC( bool ) CheckMeshClosure( const MbMesh & mesh, MeshInfo & info ); @@ -651,8 +649,7 @@ MATH_FUNC( bool ) CheckMeshClosure( const MbMesh & mesh, MeshInfo & info ); \ingroup Polygonal_Objects \warning \ru В разработке. \en Under development. \~ -*/ -// --- +*/ // --- MATH_FUNC( bool ) InspectMeshClosure( const MbMesh & mesh, MeshInfo & info ); diff --git a/C3d/Include/alg_draw.h b/C3d/Include/alg_draw.h index b42684c..b14ac70 100644 --- a/C3d/Include/alg_draw.h +++ b/C3d/Include/alg_draw.h @@ -14,6 +14,7 @@ #include #include #include +#include #define TRGB_BLACK 0, 0, 0 ///< \ru Черный цвет. \en Black color. \~ \ingroup Drawing @@ -1072,6 +1073,35 @@ void DrawVertexEdges( const Vertex * vertex, int vR, int vG, int vB, MATH_FUNC (void) SetDrawGI( const IfDrawGI * iDrawGIImpl ); +//------------------------------------------------------------------------------ +// отрисовка контуров прямоугольной области +//--- +//------------------------------------------------------------------------------ +/** \brief \ru Функция отрисовки контуров прямоугольной области. + \en Rectangular area contour drawing function. \~ + \details \ru Отрисовка прямоугольной области на поверхности по четырем точкам. + \en Drawing a rectangular area on the surface by four points. \~ + \ingroup Drawing +*/ +// --- +template +static void DrawRectangle( const Rect & rect, const MbSurface & surf, int r, int g, int b ) +{ + SArray corners( 4, 1 ); + MbCartPoint corner; + rect.GetVertex( 0, corner ); + corners.Add( corner ); + rect.GetVertex( 1, corner ); + corners.Add( corner ); + rect.GetVertex( 2, corner ); + corners.Add( corner ); + rect.GetVertex( 3, corner ); + corners.Add( corner ); + MbContour contour; + contour.InitByPoints( corners ); + DrawGI::DrawItem( &contour, &surf, r, g, b ); +} + #endif // defined(_DRAWGI) diff --git a/C3d/Include/assembly.h b/C3d/Include/assembly.h index c31f7e6..4955473 100644 --- a/C3d/Include/assembly.h +++ b/C3d/Include/assembly.h @@ -126,7 +126,7 @@ public: // \ru Добавить полигональную сетку объекта. \en Add a polygonal mesh of the object. bool AddYourMesh( const MbStepData & stepData, const MbFormNote & note, MbMesh & mesh ) const override; // \ru Разрезать полигональный объект одной или двумя параллельными плоскостями. \en Cut the polygonal object by one or two parallel planes. - MbItem * CutMesh( const MbPlacement3D & cutPlace, double distance ) const override; + MbItem * CutMesh( const MbPlacement3D & cutPlace, double distance, const MbSNameMaker * = nullptr ) const override; // \ru Найти ближайший объект или имя ближайшего объекта. \en Find the closest object or its name. bool NearestMesh( MbeSpaceType sType, MbeTopologyType tType, MbePlaneType pType, const MbAxis3D & axis, double maxDistance, bool gridPriority, double & t, double & dMin, diff --git a/C3d/Include/attr_common_attribute.h b/C3d/Include/attr_common_attribute.h index 986b9a2..86d93ca 100644 --- a/C3d/Include/attr_common_attribute.h +++ b/C3d/Include/attr_common_attribute.h @@ -379,4 +379,44 @@ OBVIOUS_PRIVATE_COPY( MbInt64VectorAttribute ) IMPL_PERSISTENT_OPS( MbInt64VectorAttribute ) +//------------------------------------------------------------------------------ +/** \brief \ru Атрибут массив действительных чисел типа double. + \en Array of real (double) values attribute. \~ + \details \ru Атрибут массив действительных чисел типа double. \n + \en Array of real (double) values attribute. \n \~ + \ingroup Model_Attributes +*/ +class MATH_CLASS MbDoubleVectorAttribute : public MbCommonAttribute { +private: + std::vector value_; ///< \ru Значение. \en The value. + +public: + /// \ru Конструктор. \en Constructor. + explicit MbDoubleVectorAttribute( const c3d::string_t & prompt, const bool change, const std::vector & value ); + /// \ru Деструктор. \en Destructor. + virtual ~MbDoubleVectorAttribute(); + +public: + MbeAttributeType AttributeType() const override; // \ru Выдать подтип атрибута. \en Get subtype of an attribute. + void GetCharValue( TCHAR * v ) const override; // \ru Выдать строковое значение свойства. \en Get a string value of the property. + MbAttribute & Duplicate( MbRegDuplicate * = nullptr ) const override; // \ru Сделать копию элемента. \en Create a copy of the element. + bool IsSame( const MbAttribute &, double accuracy ) const override; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. + bool Init( const MbAttribute & ) override; // \ru Инициализировать данные по присланным. \en Initialize data. + 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. + + const std::vector & GetValue() const; // \ru Выдать значение свойства. \en Get a value of the property. + bool SetValue( const std::vector & val ); // \ru Установить новое значение свойства. \en Set new value of the property. + + size_t Count() const; // \ru Выдать число элементов в массиве. \en Get a number of elements in the array. + + double operator [] ( size_t ind ) const; /// \ru Доступ к элементу массива по индексу (без проверки на выход за границы). \en Access to array element by index (without bounds checking). + +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbDoubleVectorAttribute ) +OBVIOUS_PRIVATE_COPY( MbDoubleVectorAttribute ) +}; + +IMPL_PERSISTENT_OPS( MbDoubleVectorAttribute ) + #endif // __ATTR_COMMON_ATTRIBUE_H diff --git a/C3d/Include/attr_identifier.h b/C3d/Include/attr_identifier.h index 39c3885..0ad3bcb 100644 --- a/C3d/Include/attr_identifier.h +++ b/C3d/Include/attr_identifier.h @@ -112,6 +112,8 @@ public : size_t GetParentNamesCount() const { return parentNames.size(); } /// \ru Удалить имена родительских объектов. \en Delete names of parent objects. void DeleteParentNames(); + /// \ru Удалить имя родительского объекта. \en Delete the name of a parent object. + bool DeleteParentName( const MbName & ); /// \ru Добавить имя родительского объекта. \en Add a name of parent object. bool AddParentName( const MbName &, bool isTemporal = false ); /// \ru Добавить имена родительских объектов. \en Add names of parent objects. diff --git a/C3d/Include/attribute_item.h b/C3d/Include/attribute_item.h index da49563..da1e8d4 100644 --- a/C3d/Include/attribute_item.h +++ b/C3d/Include/attribute_item.h @@ -86,6 +86,7 @@ enum MbeAttributeType at_SweptFlangeAttribute = 210, ///< \ru Атрибут отбортовки листового тела. \en Swept flange attribute of a sheet solid. \n at_Int32VectorAttribute = 211, ///< \ru Атрибут массив целочисленных значений типа int32. \en Array of integer (int32) values attribute. at_Int64VectorAttribute = 212, ///< \ru Атрибут массив целочисленных значений типа int64. \en Array of integer (int64) values attribute. + at_DoubleVectorAttribute = 213, ///< \ru Атрибут массив действительных чисел типа double. \en Array of real (double) values attribute. at_CommonLast = 300, ///< \ru Обобщенные атрибуты вставлять перед этим значением. \en Common attributes should be inserted before this value. \n // \ru Типы связующих атрибутов. \en Types of linking attributes. diff --git a/C3d/Include/cdet_data.h b/C3d/Include/cdet_data.h index 40fb0b0..1500f1d 100644 --- a/C3d/Include/cdet_data.h +++ b/C3d/Include/cdet_data.h @@ -68,6 +68,7 @@ struct cdet_query CBACK_VOID , CBACK_SUFFICIENT ///< This code means that an app stops collision query for given pair of lumps , CBACK_SKIP ///< Skip testing a given pair of the lumps + , CBACK_NEED ///< Enable testing a given pair of the lumps , CBACK_BREAK ///< Break search of all collisions of the set , CBACK_SEARCH_MORE = CBACK_VOID ///< This code notifies a collision detector to continue working at cases CDET_INTERSECTED, CDET_TOUCHED. }; @@ -418,7 +419,7 @@ class MATH_CLASS MbProximityParameters public: MbCartPoint3D fstPnt, sndPnt; // \ru Пара точек близости, принадлежащие триангуляционным сеткам. \en The points of the proximity belonging to the triangulation grids. - MbCartPoint thePar1, thePar2; // \ru Пара точек близости, заданная в поверхностных координатах граненй. \en The points of the proximity specified in the surface coordinates of the faces. + MbCartPoint thePar1, thePar2; // \ru Пара точек близости, заданная в поверхностных координатах граней. \en The points of the proximity specified in the surface coordinates of the faces. double theDistance; // \ru Расстояние. \en Distance. double upperDist; // \ru Верхняя оценка для поиска минимальной дистанции. \en The upper bound of the minimal distance estimation. diff --git a/C3d/Include/check_geometry.h b/C3d/Include/check_geometry.h index 53e370f..65c5c1c 100644 --- a/C3d/Include/check_geometry.h +++ b/C3d/Include/check_geometry.h @@ -271,6 +271,35 @@ void MbShellsIntersectionData::GetFaceNumbersPairs( OutputIndicesPairsVector & o MATH_FUNC (bool) IsDegeneratedCurve( const MbCurve3D & curve, double eps ); +//------------------------------------------------------------------------------ +/** \brief \ru Проверка вырожденности поверхности в точке. + \en Checking the degeneracy of a surface at a point.\~ + \details \ru Проверка вырожденности поверхности в точке. + \en Checking the degeneracy of a surface at a point.\~ + \param[in] surf - \ru Поверхность. + \en Surface. \~ + \param[in] u, v - \ru Координаты точки на поверхности. + \en The coordinates of a point on a surface.\~ + \param[in] eps - \ru Точность оценки. \n + Для линейной оценивается отношение минимальной к максимальной длин первых производных.\n + Для угловой оценивается угол между первыми производными. \~ + \en Estimation accuracy. \n + For a linear one, the ratio of the minimum to the maximum lengths of the first derivatives is estimated.\n + For a angular one, the angle between the first derivatives is estimated.\~ + \param[in] degRu - \ru Оценивает вырожденность поверхности по длине производной Ru. + \en Estimates the degeneracy of a surface by the length of the derivative Ru.\~ + \param[in] degRv - \ru Оценивает вырожденность поверхности по длине производной Rv. + \en Estimates the degeneracy of a surface by the length of the derivative Rv.\~ + \param[in] degRuv- \ru Оценивает вырожденность поверхности по углу между Ru и Rv. + \en Estimates the degeneracy of a surface by the angle between Ru and Rv.\~ + \return \ru Возвращает статус вырожденности. + \en Returns the degeneracy status. \~ + \ingroup Algorithms_3D +*/ //--- +MATH_FUNC (bool) CheckSurfaceDegeneracy( const MbSurface & surf, double u, double v, double eps, + bool & degRu, bool & degRv, bool & colUV ); + + //------------------------------------------------------------------------------ /** \brief \ru Проверка оболочки тела на замкнутость. \en Check of solid's shell for closedness. \~ diff --git a/C3d/Include/conv_topo_mesh.h b/C3d/Include/conv_topo_mesh.h index a486c55..678d39d 100644 --- a/C3d/Include/conv_topo_mesh.h +++ b/C3d/Include/conv_topo_mesh.h @@ -1,4 +1,4 @@ -//////////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// /** \file \brief Преобразователь сетки к форме, сохраняющей связи граней и полигонов. @@ -16,6 +16,7 @@ #include #include +class MbGrid; class MbMesh; class MbTriangle; @@ -107,4 +108,10 @@ namespace JTC { }; +//------------------------------------------------------------------------------ +// Построить сетку по полигонам +// --- +CONV_FUNC( MbGrid* ) CreateGridByPolyonPoints( const std::vector>& polygonsAsPoints ); + + #endif // !__CONV_TOPO_MESH_H diff --git a/C3d/Include/cr_boolean_solid.h b/C3d/Include/cr_boolean_solid.h index cacfd9e..83913d3 100644 --- a/C3d/Include/cr_boolean_solid.h +++ b/C3d/Include/cr_boolean_solid.h @@ -101,35 +101,36 @@ public : // \ru Общие функции твердого тела. \en Common functions of solid. bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; // \ru Построение \en Construction + RPArray * items = nullptr ) override; // \ru Построение \en Construction void SetYourVersion( VERSION version, bool forAll ) override; public: - /// \ru Тип булевой операции над телами. \en Type of Boolean operation on solids. - OperationType GetOperationType() const { return operation; } - /// \ru Угловое отклонение при движении по кривым и поверхностям. \en Angular deviation while moving along curves and surfaces. - double GetBuildSag() const { return buildSag; } + /// \ru Тип булевой операции над телами. \en Type of Boolean operation on solids. + OperationType GetOperationType() const { return operation; } + /// \ru Угловое отклонение при движении по кривым и поверхностям. \en Angular deviation while moving along curves and surfaces. + double GetBuildSag() const { return buildSag; } - /// \ru Количество общих строителей тел. \en The number of common creators. - size_t GetSharedCount() const { return sharedCount; } - /// \ru Количество строителей первого тела. \en The number of first-solid creators. - size_t GetFirstCount() const { return firstCount; } - /// \ru Общее количество строителей. \en Total count of creators. - size_t GetCreatorsCount() const { return creators.size(); } - /// \ru Дать строитель. \en Get the creator. + /// \ru Количество общих строителей тел. \en The number of common creators. + size_t GetSharedCount() const { return sharedCount; } + /// \ru Количество строителей первого тела. \en The number of first-solid creators. + size_t GetFirstCount() const { return firstCount; } + /// \ru Общее количество строителей. \en Total count of creators. + size_t GetCreatorsCount() const { return creators.size(); } + /// \ru Дать строитель. \en Get the creator. const MbCreator * GetCreator( size_t k ) const { return ( (k < creators.size()) ? creators[k] : nullptr ); } - /// \ru Удалить из журнала строители первого тела. \en Delete first-solid creators from the history tree. - bool DeleteFirstCreators(); + /// \ru Удалить из журнала строители первого тела. \en Delete first-solid creators from the history tree. + bool DeleteFirstCreators(); private : - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbBooleanSolid & ); + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbBooleanSolid & ); DECLARE_PERSISTENT_CLASS_NEW_DEL( MbBooleanSolid ) -}; +}; // MbBooleanSolid IMPL_PERSISTENT_OPS( MbBooleanSolid ) + //------------------------------------------------------------------------------ /** \brief \ru Создать оболочку булевой операции. \en Create the shell of Boolean operation. \~ @@ -182,6 +183,7 @@ MATH_FUNC (MbCreator *) CreateBoolean( MbFaceShell * shell1, MbResultType & res, MbFaceShell *& shell ); + //------------------------------------------------------------------------------ /** \brief \ru Создать оболочку булевой операции. \en Create the shell of Boolean operation. \~ @@ -225,4 +227,5 @@ MATH_FUNC (MbCreator *) CreateBoolean( c3d::ShellSPtr & shell1, MbResultType & res, c3d::ShellSPtr & shell ); + #endif // __CR_BOOLEAN_SOLID_H diff --git a/C3d/Include/cr_chamfer_solid.h b/C3d/Include/cr_chamfer_solid.h index c62a00f..4c8da71 100644 --- a/C3d/Include/cr_chamfer_solid.h +++ b/C3d/Include/cr_chamfer_solid.h @@ -51,18 +51,19 @@ public : // \ru Общие функции твердого тела \en Common functions of solid bool CreateShell( MbFaceShell *&shell, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; // \ru Построение \en Construction + RPArray * items = nullptr ) override; // \ru Построение \en Construction private : void ReadDistances ( reader &in ) override; - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbChamferSolid & ); + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbChamferSolid & ); DECLARE_PERSISTENT_CLASS_NEW_DEL( MbChamferSolid ) }; // MbChamferSolid IMPL_PERSISTENT_OPS( MbChamferSolid ) + //------------------------------------------------------------------------------ /** \brief \ru Создать оболочку с фасками ребeр. \en Create a shell with edges' chamfers. \~ diff --git a/C3d/Include/cr_connecting_curve.h b/C3d/Include/cr_connecting_curve.h index bd3ad9f..68c1374 100644 --- a/C3d/Include/cr_connecting_curve.h +++ b/C3d/Include/cr_connecting_curve.h @@ -80,13 +80,13 @@ public : void SetBasisPoints( const MbControlData3D & ) override; // \ru Изменить объект по контрольным точкам. \en Change the object by control points. // \ru Построить кривую по журналу построения \en Create a curve from the history tree - bool CreateWireFrame( MbWireFrame *&, MbeCopyMode, RPArray * items = nullptr ) override; + bool CreateWireFrame( MbWireFrame *&, MbeCopyMode, RPArray * items = nullptr ) override; /** \} */ private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation, to prevent an assignment by default. - void operator = ( const MbConnectingCurveCreator & ); + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation, to prevent an assignment by default. + void operator = ( const MbConnectingCurveCreator & ); DECLARE_PERSISTENT_CLASS_NEW_DEL( MbConnectingCurveCreator ) }; diff --git a/C3d/Include/cr_cutting_solid.h b/C3d/Include/cr_cutting_solid.h index 465a1be..b85f3b8 100644 --- a/C3d/Include/cr_cutting_solid.h +++ b/C3d/Include/cr_cutting_solid.h @@ -85,19 +85,19 @@ public : // \ru Общие функции твердого тела \en Common functions of solid bool CreateShell( MbFaceShell *&, MbeCopyMode sameShell, - RPArray * = nullptr ) override; // \ru Построение \en Construction + RPArray * = nullptr ) override; // \ru Построение \en Construction - // \ru Оставляемая часть (если part больше 0, то оставляем часть тела со стороны нормали поверхности). \en A part to be kept (if part is bigger than 0, then keep a part of solid from the side of surface normal). - ThreeStates GetPart() const { return part; } - void SetPart( ThreeStates p ) { part = p; } - void SetOppositePart() { if ( part == ts_negative ) - part = ts_positive; - else if ( part == ts_positive ) - part = ts_negative; } + // \ru Оставляемая часть (если part больше 0, то оставляем часть тела со стороны нормали поверхности). \en A part to be kept (if part is bigger than 0, then keep a part of solid from the side of surface normal). + ThreeStates GetPart() const { return part; } + void SetPart( ThreeStates p ) { part = p; } + void SetOppositePart() { if ( part == ts_negative ) + part = ts_positive; + else if ( part == ts_positive ) + part = ts_negative; } private : - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbCuttingSolid & ); + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbCuttingSolid & ); DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCuttingSolid ) }; // MbCuttingSolid diff --git a/C3d/Include/cr_detach_solid.h b/C3d/Include/cr_detach_solid.h index 3eb312e..ec0239b 100644 --- a/C3d/Include/cr_detach_solid.h +++ b/C3d/Include/cr_detach_solid.h @@ -56,21 +56,21 @@ public : bool SetEqual ( const MbCreator & ) override; // \ru Сделать равным. \en Make equal. bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; // \ru Построение \en Construction + RPArray * items = nullptr ) override; // \ru Построение \en Construction /** \} */ /** \ru \name Функции строителя, разделяющие отдельные части оболочки. \en \name Functions of the creator subdividing separate parts of the shell. \{ */ - /// \ru Дать номер части, выделенной из общей оболочки. \en Get number of the part extracted from the common shell. - ptrdiff_t GetPartNumber() const { return part; } - /// \ru Установить номер части, выделенной из общей оболочки. \en Set number of the part extracted from the common shell. - void SetPartNumber( ptrdiff_t p ) { part = p; } - /// \ru Сортированы ли части по габаритам (диагоналям). \en Whether the parts are sorted by bounding boxes (diagonals). - bool IsSort() const { return sort; } + /// \ru Дать номер части, выделенной из общей оболочки. \en Get number of the part extracted from the common shell. + ptrdiff_t GetPartNumber() const { return part; } + /// \ru Установить номер части, выделенной из общей оболочки. \en Set number of the part extracted from the common shell. + void SetPartNumber( ptrdiff_t p ) { part = p; } + /// \ru Сортированы ли части по габаритам (диагоналям). \en Whether the parts are sorted by bounding boxes (diagonals). + bool IsSort() const { return sort; } /** \} */ private : - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbDetachSolid & ); + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbDetachSolid & ); DECLARE_PERSISTENT_CLASS_NEW_DEL( MbDetachSolid ) }; // MbDetachSolid diff --git a/C3d/Include/cr_displace_creator.h b/C3d/Include/cr_displace_creator.h index 8ded823..f161e27 100644 --- a/C3d/Include/cr_displace_creator.h +++ b/C3d/Include/cr_displace_creator.h @@ -55,32 +55,32 @@ public: // \ru Общие функции математического объе /// \ru Построение оболочки \en Creation of a shell. bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; + RPArray * items = nullptr ) override; /// \ru Построение каркаса кривых. \en Creation of a wire-frame. bool CreateWireFrame( MbWireFrame *& frame, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; + RPArray * items = nullptr ) override; /// \ru Построение каркаса точек. \en Creation of a point-frame. bool CreatePointFrame( MbPointFrame *& frame, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; + RPArray * items = nullptr ) override; /// \ru Создать полигональный объект. \en Create a polygonal object. bool CreateMesh( MbMesh *& mesh, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; + RPArray * items = nullptr ) override; /// \ru Переместить строитель. \en Displace the creator. bool Perform( MbCreator * ) const override; - // \ru Добавить перемещение объекта вдоль вектора. \en Add a displacement vector. - void AddVector( const MbVector3D & ); - // \ru Дать параметры. \en Get the parameters. - void GetVector( MbVector3D & m ) const { m = vector; } - // \ru Установить параметры. \en Set the parameters. - void SetVector( const MbVector3D & m ) { vector = m; } + // \ru Добавить перемещение объекта вдоль вектора. \en Add a displacement vector. + void AddVector( const MbVector3D & ); + // \ru Дать параметры. \en Get the parameters. + void GetVector( MbVector3D & m ) const { m = vector; } + // \ru Установить параметры. \en Set the parameters. + void SetVector( const MbVector3D & m ) { vector = m; } private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbMotionMaker & ); + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbMotionMaker & ); -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbMotionMaker ) -}; + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbMotionMaker ) +}; // MbMotionMaker IMPL_PERSISTENT_OPS( MbMotionMaker ) @@ -126,32 +126,32 @@ public: // \ru Общие функции математического объе /// \ru Построение оболочки \en Creation of a shell. bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; + RPArray * items = nullptr ) override; /// \ru Построение каркаса кривых. \en Creation of a wire-frame. bool CreateWireFrame( MbWireFrame *& frame, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; + RPArray * items = nullptr ) override; /// \ru Построение каркаса точек. \en Creation of a point-frame. bool CreatePointFrame( MbPointFrame *& frame, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; + RPArray * items = nullptr ) override; /// \ru Создать полигональный объект. \en Create a polygonal object. bool CreateMesh( MbMesh *& mesh, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; + RPArray * items = nullptr ) override; /// \ru Переместить строитель. \en Displace the creator. bool Perform( MbCreator * ) const override; - // \ru Добавить поворот вокруг оси. \en Add an angle of rotatation. - bool AddAngle( const MbAxis3D & ax, double an ); - // \ru Дать параметры. \en Get the parameters. - void GetAxis3D( MbAxis3D & m ) const { m = axis; } - // \ru Установить параметры. \en Set the parameters. - void SetAxis3D( const MbAxis3D & m ) { axis = m; } + // \ru Добавить поворот вокруг оси. \en Add an angle of rotatation. + bool AddAngle( const MbAxis3D & ax, double an ); + // \ru Дать параметры. \en Get the parameters. + void GetAxis3D( MbAxis3D & m ) const { m = axis; } + // \ru Установить параметры. \en Set the parameters. + void SetAxis3D( const MbAxis3D & m ) { axis = m; } private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbRotationMaker & ); + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbRotationMaker & ); DECLARE_PERSISTENT_CLASS_NEW_DEL( MbRotationMaker ) -}; +}; // MbRotationMaker IMPL_PERSISTENT_OPS( MbRotationMaker ) @@ -196,32 +196,32 @@ public: // \ru Общие функции математического объе /// \ru Построение оболочки \en Creation of a shell. bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; + RPArray * items = nullptr ) override; /// \ru Построение каркаса кривых. \en Creation of a wire-frame. bool CreateWireFrame( MbWireFrame *& frame, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; + RPArray * items = nullptr ) override; /// \ru Построение каркаса точек. \en Creation of a point-frame. bool CreatePointFrame( MbPointFrame *& frame, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; + RPArray * items = nullptr ) override; /// \ru Создать полигональный объект. \en Create a polygonal object. bool CreateMesh( MbMesh *& mesh, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; + RPArray * items = nullptr ) override; /// \ru Переместить строитель. \en Displace the creator. bool Perform( MbCreator * ) const override; - // \ru Добавить модификацию по матрице \en Add a modification by a matrix - void AddMatrix( const MbMatrix3D & ); - // \ru Дать параметры. \en Get the parameters. - void GetMatrix( MbMatrix3D & m ) const { m = matrix; } - // \ru Установить параметры. \en Set the parameters. - void SetMatrix( const MbMatrix3D & m ) { matrix = m; } + // \ru Добавить модификацию по матрице \en Add a modification by a matrix + void AddMatrix( const MbMatrix3D & ); + // \ru Дать параметры. \en Get the parameters. + void GetMatrix( MbMatrix3D & m ) const { m = matrix; } + // \ru Установить параметры. \en Set the parameters. + void SetMatrix( const MbMatrix3D & m ) { matrix = m; } private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbTransformationMaker & ); + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbTransformationMaker & ); DECLARE_PERSISTENT_CLASS_NEW_DEL( MbTransformationMaker ) -}; +}; // MbTransformationMaker IMPL_PERSISTENT_OPS( MbTransformationMaker ) diff --git a/C3d/Include/cr_draft_solid.h b/C3d/Include/cr_draft_solid.h index 7051ab2..f431b24 100644 --- a/C3d/Include/cr_draft_solid.h +++ b/C3d/Include/cr_draft_solid.h @@ -98,17 +98,18 @@ public : // \ru Общие функции твердого тела \en Common functions of solid bool CreateShell( MbFaceShell *&, MbeCopyMode sameShell, - RPArray * = nullptr ) override; // \ru Построение \en Construction + RPArray * = nullptr ) override; // \ru Построение \en Construction private : - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbDraftSolid & ); + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbDraftSolid & ); DECLARE_PERSISTENT_CLASS_NEW_DEL( MbDraftSolid ) -}; +}; // MbDraftSolid IMPL_PERSISTENT_OPS( MbDraftSolid ) + //------------------------------------------------------------------------------ /** \brief \ru Построить оболочку с уклоном граней. \en Create a shell with drafted faces. \~ diff --git a/C3d/Include/cr_duplication_solid.h b/C3d/Include/cr_duplication_solid.h index f818e84..fbcb362 100644 --- a/C3d/Include/cr_duplication_solid.h +++ b/C3d/Include/cr_duplication_solid.h @@ -60,7 +60,7 @@ public: bool SetEqual ( const MbCreator & ) override; // \ru сделать равным \en make equal bool CreateShell( MbFaceShell *&, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; + RPArray * items = nullptr ) override; private : // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. @@ -126,4 +126,6 @@ MATH_FUNC (MbCreator *) CreateDuplication( const MbFaceShell & soli const MbDuplicationSolidParams & params, MbResultType & res, c3d::ShellSPtr & resShell ); + + #endif // CR_DUPLICATION_SOLID_H diff --git a/C3d/Include/cr_elementary_solid.h b/C3d/Include/cr_elementary_solid.h index 792ddb1..9b78f50 100644 --- a/C3d/Include/cr_elementary_solid.h +++ b/C3d/Include/cr_elementary_solid.h @@ -129,15 +129,15 @@ public : bool SetEqual( const MbCreator & ) override; // \ru Сделать равным \en Make equal bool CreateShell( MbFaceShell *&, MbeCopyMode sameShell, - RPArray * = nullptr ) override; // \ru Построение \en Construction + RPArray * = nullptr ) override; // \ru Построение \en Construction /** \} */ private: - /// \ru Установить параметры по типу и набору точек. \en Set parameters by type and points. - bool SetParameters(); + /// \ru Установить параметры по типу и набору точек. \en Set parameters by type and points. + bool SetParameters(); private : - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbElementarySolid & ); + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbElementarySolid & ); DECLARE_PERSISTENT_CLASS_NEW_DEL( MbElementarySolid ) }; // MbElementarySolid diff --git a/C3d/Include/cr_evolution_solid.h b/C3d/Include/cr_evolution_solid.h index 82358ee..b9e11c0 100644 --- a/C3d/Include/cr_evolution_solid.h +++ b/C3d/Include/cr_evolution_solid.h @@ -156,21 +156,22 @@ public : /** \ru \name Функции строителя оболочки кинематического тела. \en \name Functions of creator of evolution solid shell. \{ */ - /// \ru Дать параметры. \en Get the parameters. - void GetParameters( EvolutionValues & params ) const { params = parameters; } - /// \ru Установить параметры. \en Set the parameters. - void SetParameters( const EvolutionValues & params ) { parameters = params; } + /// \ru Дать параметры. \en Get the parameters. + void GetParameters( EvolutionValues & params ) const { params = parameters; } + /// \ru Установить параметры. \en Set the parameters. + void SetParameters( const EvolutionValues & params ) { parameters = params; } /** \} */ private : - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbCurveEvolutionSolid & ); + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbCurveEvolutionSolid & ); DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCurveEvolutionSolid ) }; // MbCurveEvolutionSolid IMPL_PERSISTENT_OPS( MbCurveEvolutionSolid ) + //------------------------------------------------------------------------------ /** \brief \ru Создать оболочку кинематического тела. \en Create a shell of evolution solid. \~ diff --git a/C3d/Include/cr_extending_curve.h b/C3d/Include/cr_extending_curve.h index 1865679..918c4ef 100644 --- a/C3d/Include/cr_extending_curve.h +++ b/C3d/Include/cr_extending_curve.h @@ -47,35 +47,36 @@ public: // \ru Общие функции строителя. \en The common functions of the creator. MbeCreatorType IsA() const override { return ct_ExtensionCurveCreator; }; // \ru Тип элемента. \en A type of element. - MbCreator & Duplicate( MbRegDuplicate * iReg = nullptr ) const override; // \ru Сделать копию. \en Create a copy. + 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. + 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 the axis. + 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 the 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. + 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. /** \} */ //DEPRECATE_DECLARE_REPLACE( CreateWireFrame with 'c3d::WireFrameSPtr' argument ) - bool CreateWireFrame( MbWireFrame *&, MbeCopyMode, RPArray * ) override; // \ru Построить кривую по журналу построения. \en Create a curve from the history tree. \~ - bool CreateWireFrame( c3d::WireFrameSPtr & result ); // \ru Построить кривую по журналу построения. \en Create a curve from the history tree. \~ + bool CreateWireFrame( MbWireFrame *&, MbeCopyMode, RPArray * ) override; // \ru Построить кривую по журналу построения. \en Create a curve from the history tree. \~ + bool CreateWireFrame( c3d::WireFrameSPtr & result ); // \ru Построить кривую по журналу построения. \en Create a curve from the history tree. \~ private: // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation, to prevent an assignment by default. void operator = ( const MbExtendCurveCreator & ); DECLARE_PERSISTENT_CLASS_NEW_DEL( MbExtendCurveCreator ) -}; +}; // MbExtendCurveCreator IMPL_PERSISTENT_OPS( MbExtendCurveCreator ) + //------------------------------------------------------------------------------ /** \brief \ru Создание строителя продления кривой. \en Create a constructor of extending curve. \~ @@ -101,4 +102,5 @@ MATH_FUNC( c3d::CreatorSPtr ) CreateExtendedCurve( const MbCurve3D & MbResultType & res, c3d::SpaceCurveSPtr & resCurve ); + #endif // __CR_EXTENDING_CURVE_H \ No newline at end of file diff --git a/C3d/Include/cr_extension_shell.h b/C3d/Include/cr_extension_shell.h index 3e2048f..fef2aa9 100644 --- a/C3d/Include/cr_extension_shell.h +++ b/C3d/Include/cr_extension_shell.h @@ -62,18 +62,17 @@ public : // \ru Общие функции твердого тела \en Common functions of solid solid bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; // \ru Построение \en Construction + RPArray * items = nullptr ) override; // \ru Построение \en Construction - // \ru Дать параметры. \en Get the parameters. - void GetParameters( ExtensionValues & params ) const { params = parameters; } - // \ru Установить параметры. \en Set the parameters. - void SetParameters( const ExtensionValues & params ) { parameters = params; } + // \ru Дать параметры. \en Get the parameters. + void GetParameters( ExtensionValues & params ) const { params = parameters; } + // \ru Установить параметры. \en Set the parameters. + void SetParameters( const ExtensionValues & params ) { parameters = params; } -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbExtensionShell ) -OBVIOUS_PRIVATE_COPY( MbExtensionShell ) + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbExtensionShell ) + OBVIOUS_PRIVATE_COPY( MbExtensionShell ) }; // MbExtensionShell - IMPL_PERSISTENT_OPS( MbExtensionShell ) @@ -155,4 +154,5 @@ MATH_FUNC (MbCreator *) CreateExtensionShell( c3d::ShellSPtr & sol MbResultType & res, c3d::ShellSPtr & shell ); + #endif // __CR_EXTENSION_SHELL_H diff --git a/C3d/Include/cr_extrusion_solid.h b/C3d/Include/cr_extrusion_solid.h index 48723b8..beeb70c 100644 --- a/C3d/Include/cr_extrusion_solid.h +++ b/C3d/Include/cr_extrusion_solid.h @@ -94,7 +94,7 @@ public : \en \name Common functions of the rigid solid (forming operations). \{ */ bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; // \ru Построение. \en Construction. + RPArray * items = nullptr ) override; // \ru Построение. \en Construction. MbFaceShell * InitShell( bool in ) override; void InitBasis( RPArray & items ) override; @@ -108,20 +108,20 @@ public : /// \ru Направление выдавливания. \en An extrusion direction. const MbVector3D & GetDirection() const { return direction; } - /// \ru Дать параметры. \en Get the parameters. - void GetParameters( ExtrusionValues & params ) const { params = parameters; } - /// \ru Установить параметры. \en Set the parameters. - void SetParameters( const ExtrusionValues & params ) { parameters = params; } - /// \ru Дать габарит контуров на плейсменте. \en Get bounding boxes of contours in the placement. - void AddPlacementRect( MbRect & r ) const; + /// \ru Дать параметры. \en Get the parameters. + void GetParameters( ExtrusionValues & params ) const { params = parameters; } + /// \ru Установить параметры. \en Set the parameters. + void SetParameters( const ExtrusionValues & params ) { parameters = params; } + /// \ru Дать габарит контуров на плейсменте. \en Get bounding boxes of contours in the placement. + void AddPlacementRect( MbRect & r ) const; /** \} */ private : - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbCurveExtrusionSolid & ); // \ru НЕЛЬЗЯ!!! \en NOT ALLOWED!!! + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbCurveExtrusionSolid & ); // \ru НЕЛЬЗЯ!!! \en NOT ALLOWED!!! DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCurveExtrusionSolid ) -}; +}; // MbCurveExtrusionSolid IMPL_PERSISTENT_OPS( MbCurveExtrusionSolid ) diff --git a/C3d/Include/cr_fair_curve.h b/C3d/Include/cr_fair_curve.h index fb3b807..1a8ead3 100644 --- a/C3d/Include/cr_fair_curve.h +++ b/C3d/Include/cr_fair_curve.h @@ -30,31 +30,31 @@ class MATH_CLASS MbFireCreator : public MbCreator protected: c3d::SpaceCurveSPtr _initCurve; ///< \ru Исходная кривая. \en An initial curve. MbFairCurveMethod _method; ///< \ru Метод построения кривой. \en Method of a curve construction. + protected: /// \ru Конструктор копирования. \en Copy-constructor. MbFireCreator( const MbFireCreator &, MbRegDuplicate * ); - /// \ru Конструктор по параметрам. \en Constructor by parameters. MbFireCreator( const MbCurve3D & curve, const MbFairCurveMethod & method, - const MbSNameMaker & nm ); + const MbSNameMaker & nm ); +private: + MbFireCreator(); // \ru Не реализовано. \en Not implemented. public: /// \ru Деструктор. \en Destructor. ~MbFireCreator() override; - 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 the axis. - - void GetProperties( MbProperties & ) override; // \ru Выдать свойства объекта. \en Get properties of the object. - void SetProperties( const MbProperties & ) override; // \ru Записать свойства объекта. \en Set properties of the object. + 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 the axis. + void GetProperties( MbProperties & ) override; // \ru Выдать свойства объекта. \en Get properties of the object. + void SetProperties( const MbProperties & ) override; // \ru Записать свойства объекта. \en Set properties of the object. private: - MbFireCreator(); // \ru Не реализовано. \en Not implemented. OBVIOUS_PRIVATE_COPY( MbFireCreator ) - DECLARE_PERSISTENT_CLASS( MbFireCreator ) + DECLARE_PERSISTENT_CLASS( MbFireCreator ) }; IMPL_PERSISTENT_OPS( MbFireCreator ) @@ -75,11 +75,12 @@ private: protected: /// \ru Конструктор копирования. \en Copy-constructor. MbFireCurveCreator( const MbFireCurveCreator &, MbRegDuplicate * iReg ); - public: /// \ru Конструктор по параметрам. \en Constructor by parameters. MbFireCurveCreator( const MbCurve3D & curve, const MbFairCurveMethod & method, const MbFairCreateData & params, const MbSNameMaker & nm ); +private: + MbFireCurveCreator(); // \ru Не реализовано. \en Not implemented. /// \ru Деструктор. \en Destructor. ~MbFireCurveCreator() override; @@ -101,7 +102,6 @@ public: bool CreateWireFrame( c3d::WireFrameSPtr & result ); // \ru Построить кривую по журналу построения. \en Create a curve from the history tree. \~ private: - MbFireCurveCreator(); // \ru Не реализовано. \en Not implemented. OBVIOUS_PRIVATE_COPY( MbFireCurveCreator ) DECLARE_PERSISTENT_CLASS_NEW_DEL( MbFireCurveCreator ) @@ -125,6 +125,8 @@ private: protected: /// \ru Конструктор копирования. \en Copy-constructor. MbFireFilletCreator( const MbFireFilletCreator &, MbRegDuplicate * iReg ); +private: + MbFireFilletCreator(); // \ru Не реализовано. \en Not implemented. public: /// \ru Конструктор по параметрам. \en Constructor by parameters. MbFireFilletCreator( const MbCurve3D & curve, const MbFairCurveMethod & method, @@ -150,7 +152,6 @@ public: bool CreateWireFrame( c3d::WireFrameSPtr & result ); // \ru Построить кривую по журналу построения. \en Create a curve from the history tree. \~ private: - MbFireFilletCreator(); // \ru Не реализовано. \en Not implemented. OBVIOUS_PRIVATE_COPY( MbFireFilletCreator ) DECLARE_PERSISTENT_CLASS_NEW_DEL( MbFireFilletCreator ) @@ -174,6 +175,8 @@ private: protected: /// \ru Конструктор копирования. \en Copy-constructor. MbFireClothoidCreator( const MbFireClothoidCreator &, MbRegDuplicate * iReg ); +private: + MbFireClothoidCreator(); // \ru Не реализовано. \en Not implemented. public: /// \ru Конструктор по параметрам. \en Constructor by parameters. MbFireClothoidCreator( const MbClothoidParams & params, const MbSNameMaker & nm ); @@ -202,7 +205,6 @@ public: bool CreateWireFrame( c3d::WireFrameSPtr & result ); // \ru Построить кривую по журналу построения. \en Create a curve from the history tree. \~ private: - MbFireClothoidCreator(); // \ru Не реализовано. \en Not implemented. OBVIOUS_PRIVATE_COPY( MbFireClothoidCreator ) DECLARE_PERSISTENT_CLASS_NEW_DEL( MbFireClothoidCreator ) @@ -226,7 +228,8 @@ private: protected: /// \ru Конструктор копирования. \en Copy-constructor. MbFireChangeCreator( const MbFireChangeCreator &, MbRegDuplicate * iReg ); - +private: + MbFireChangeCreator(); // \ru Не реализовано. \en Not implemented. public: /// \ru Конструктор по параметрам. \en Constructor by parameters. MbFireChangeCreator( const MbCurve3D & curve, const MbFairCurveMethod & method, @@ -247,12 +250,10 @@ public: void GetProperties( MbProperties & ) override; // \ru Выдать свойства объекта. \en Get properties of the object. void SetProperties( const MbProperties & ) override; // \ru Записать свойства объекта. \en Set properties of the object. - bool CreateWireFrame( MbWireFrame *&, MbeCopyMode, RPArray * ) override; // \ru Построить кривую по журналу построения. \en Create a curve from the history tree. \~ bool CreateWireFrame( c3d::WireFrameSPtr & result ); // \ru Построить кривую по журналу построения. \en Create a curve from the history tree. \~ private: - MbFireChangeCreator(); // \ru Не реализовано. \en Not implemented. OBVIOUS_PRIVATE_COPY( MbFireChangeCreator ) DECLARE_PERSISTENT_CLASS_NEW_DEL( MbFireChangeCreator ) @@ -290,6 +291,7 @@ MATH_FUNC( c3d::CreatorSPtr ) CreateFairCurve( const c3d::SpaceCurveSPtr & sourc MbResultType & res, c3d::SpaceCurveSPtr & resCurve ); + //------------------------------------------------------------------------------ /** \brief \ru Изменение плавной кривой. \en Changing a fair curve. \~ @@ -370,4 +372,5 @@ MATH_FUNC( c3d::CreatorSPtr ) CreateFairCurve( const MbClothoidParams & paramete MbResultType & res, c3d::SpaceCurveSPtr & resCurve ); + #endif // __CR_FIRE_CURVE_H \ No newline at end of file diff --git a/C3d/Include/cr_fillet_solid.h b/C3d/Include/cr_fillet_solid.h index d05e73f..08dc165 100644 --- a/C3d/Include/cr_fillet_solid.h +++ b/C3d/Include/cr_fillet_solid.h @@ -76,12 +76,12 @@ public : // \ru Общие функции твердого тела \en Common functions of solid bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; // \ru Построение \en Construction + RPArray * items = nullptr ) override; // \ru Построение \en Construction private : void ReadDistances ( reader &in ) override; - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbFilletSolid & ); // \ru НЕЛЬЗЯ!!! \en NOT ALLOWED!!! + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbFilletSolid & ); // \ru НЕЛЬЗЯ!!! \en NOT ALLOWED!!! DECLARE_PERSISTENT_CLASS_NEW_DEL( MbFilletSolid ) }; // MbFilletSolid diff --git a/C3d/Include/cr_hole_solid.h b/C3d/Include/cr_hole_solid.h index e8d2b90..4bf62be 100644 --- a/C3d/Include/cr_hole_solid.h +++ b/C3d/Include/cr_hole_solid.h @@ -88,18 +88,18 @@ public : // \ru Общие функции твердого тела \en Common functions of solid bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; // \ru Построение \en Construction + RPArray * items = nullptr ) override; // \ru Построение \en Construction MbFaceShell * InitShell( bool in ) override; void InitBasis( RPArray & items ) override; bool GetPlacement( MbPlacement3D & p ) const override; private : - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbHoleSolid & ); // \ru Не реализовано!!! \en Not implemented!!! + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbHoleSolid & ); // \ru Не реализовано!!! \en Not implemented!!! DECLARE_PERSISTENT_CLASS_NEW_DEL( MbHoleSolid ) -}; +}; // MbHoleSolid IMPL_PERSISTENT_OPS( MbHoleSolid ) @@ -141,6 +141,7 @@ MATH_FUNC (MbCreator *) CreateHole( MbFaceShell * solid, MbResultType & res, MbFaceShell *& shell ); + //------------------------------------------------------------------------------ /** \brief \ru Создать оболочку с отверстием, карманом, или фигурным пазом. \en Create a shell with a hole, a pocket or a groove. \~ @@ -169,6 +170,7 @@ MATH_FUNC (MbCreator *) CreateHole( const c3d::ShellSPtr & solid, MbResultType & res, c3d::ShellSPtr & shell ); + //------------------------------------------------------------------------------ /** \brief \ru Определить глубину отверстия "до указанной поверхности" при построении оболочки с отверстием. \en Determine the hole depth "to the specified surface" while creating a shell with a hole. \~ diff --git a/C3d/Include/cr_intersection_curve.h b/C3d/Include/cr_intersection_curve.h index b31a628..05c992a 100644 --- a/C3d/Include/cr_intersection_curve.h +++ b/C3d/Include/cr_intersection_curve.h @@ -68,12 +68,13 @@ public: /** \} */ private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation, to prevent an assignment by default. - void operator = ( const MbIntCurveCreator & ); // \ru Не реализовано!!! \en Not implemented!!! + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation, to prevent an assignment by default. + void operator = ( const MbIntCurveCreator & ); // \ru Не реализовано!!! \en Not implemented!!! -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbIntCurveCreator ) -}; + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbIntCurveCreator ) +}; // MbIntCurveCreator IMPL_PERSISTENT_OPS( MbIntCurveCreator ) + #endif // __CR_INTERSECTION_CURVE_H diff --git a/C3d/Include/cr_join_shell.h b/C3d/Include/cr_join_shell.h index eeaf311..525fcff 100644 --- a/C3d/Include/cr_join_shell.h +++ b/C3d/Include/cr_join_shell.h @@ -58,22 +58,22 @@ public : // \ru Общие функции твердого тела \en Common functions of solid solid bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; ///< \ru Построение \en Construction - + RPArray * items = nullptr ) override; ///< \ru Построение \en Construction - // \ru Дать параметры. \en Get the parameters. - void GetParameters( JoinSurfaceValues & params ) const { params = parameters; } - // \ru Установить параметры. \en Set the parameters. - void SetParameters( const JoinSurfaceValues & params ) { parameters = params; } + // \ru Дать параметры. \en Get the parameters. + void GetParameters( JoinSurfaceValues & params ) const { params = parameters; } + // \ru Установить параметры. \en Set the parameters. + void SetParameters( const JoinSurfaceValues & params ) { parameters = params; } const MbCurve3D & GetCurve( ptrdiff_t num ) const; -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbJoinShell ) -OBVIOUS_PRIVATE_COPY( MbJoinShell ) -}; + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbJoinShell ) + OBVIOUS_PRIVATE_COPY( MbJoinShell ) +}; // MbJoinShell IMPL_PERSISTENT_OPS( MbJoinShell ) + //------------------------------------------------------------------------------ /* \brief \ru Проверить необходимость модификации второй кривой. \en Check if a modification of the second curve is necessary. \~ diff --git a/C3d/Include/cr_lofted_solid.h b/C3d/Include/cr_lofted_solid.h index d48691d..913e84c 100644 --- a/C3d/Include/cr_lofted_solid.h +++ b/C3d/Include/cr_lofted_solid.h @@ -87,22 +87,23 @@ public : void InitBasis( RPArray & items ) override; bool GetPlacement( MbPlacement3D & ) const override; - /// \ru Дать параметры. \en Get the parameters. - void GetParameters( LoftedValues & params ) const { params = parameters; } - /// \ru Установить параметры. \en Set the parameters. - void SetParameters( const LoftedValues & params ) { parameters = params; } - /// \ru Направляющая кривая. \en The spine curve. - const MbCurve3D * GetSpine() const { return spine.get(); } + /// \ru Дать параметры. \en Get the parameters. + void GetParameters( LoftedValues & params ) const { params = parameters; } + /// \ru Установить параметры. \en Set the parameters. + void SetParameters( const LoftedValues & params ) { parameters = params; } + /// \ru Направляющая кривая. \en The spine curve. + const MbCurve3D * GetSpine() const { return spine.get(); } private : - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbCurveLoftedSolid & ); + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbCurveLoftedSolid & ); DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCurveLoftedSolid ) -}; +}; // MbCurveLoftedSolid IMPL_PERSISTENT_OPS( MbCurveLoftedSolid ) + //------------------------------------------------------------------------------ /** \brief \ru Создать тело по плоским сечениям. \en Create a solid from a planar sections. \~ @@ -133,6 +134,7 @@ MATH_FUNC (c3d::CreatorSPtr) CreateCurveLofted( c3d::ShellSPtr & srcS MbResultType & res, c3d::ShellSPtr & resShell ); + //------------------------------------------------------------------------------ /** \brief \ru Создать тело по плоским сечениям. \en Create a solid from a planar sections. \~ diff --git a/C3d/Include/cr_median_shell.h b/C3d/Include/cr_median_shell.h index e20d5ec..909fc2f 100644 --- a/C3d/Include/cr_median_shell.h +++ b/C3d/Include/cr_median_shell.h @@ -62,17 +62,16 @@ public: // \ru Построение оболочки по исходным данным \en Construction of a shell from the given data bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; + RPArray * items = nullptr ) override; - /// \ru Дать параметры. \en Get the parameters. - void GetParameters( MedianShellValues & params ) const { params = parameters; } - /// \ru Установить параметры. \en Set the parameters. - void SetParameters( const MedianShellValues & params ) { parameters = params; } + /// \ru Дать параметры. \en Get the parameters. + void GetParameters( MedianShellValues & params ) const { params = parameters; } + /// \ru Установить параметры. \en Set the parameters. + void SetParameters( const MedianShellValues & params ) { parameters = params; } - -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbMedianShell ) -OBVIOUS_PRIVATE_COPY( MbMedianShell ) -}; + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbMedianShell ) + OBVIOUS_PRIVATE_COPY( MbMedianShell ) +}; // MbMedianShell IMPL_PERSISTENT_OPS( MbMedianShell ) diff --git a/C3d/Include/cr_mesh_shell.h b/C3d/Include/cr_mesh_shell.h index b57293e..3b69637 100644 --- a/C3d/Include/cr_mesh_shell.h +++ b/C3d/Include/cr_mesh_shell.h @@ -59,18 +59,20 @@ public: // \ru Общие функции математического объе public: /// \ru Построение оболочки \en Creation of a shell bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; - // \ru Дать параметры. \en Get the parameters. - void GetParameters( MeshSurfaceValues & params ) const; - // \ru Установить параметры. \en Set the parameters. - void SetParameters( const MeshSurfaceValues & params ); + RPArray * items = nullptr ) override; -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbMeshShell ) -OBVIOUS_PRIVATE_COPY( MbMeshShell ) -}; // MbMeshShell + // \ru Дать параметры. \en Get the parameters. + void GetParameters( MeshSurfaceValues & params ) const; + // \ru Установить параметры. \en Set the parameters. + void SetParameters( const MeshSurfaceValues & params ); + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbMeshShell ) + OBVIOUS_PRIVATE_COPY( MbMeshShell ) +}; // MbMeshShell IMPL_PERSISTENT_OPS( MbMeshShell ) + //------------------------------------------------------------------------------ /** \brief \ru Построить оболочку на сетке кривых. \en Construct a shell from a mesh of curves. \~ @@ -102,6 +104,7 @@ MATH_FUNC (MbCreator *) CreateMeshShell( MeshSurfaceValues & parameters, MbResultType & res, MbFaceShell *& shell ); + //------------------------------------------------------------------------------ /** \brief \ru Построить оболочку на сетке кривых. \en Construct a shell from a mesh of curves. \~ @@ -124,4 +127,5 @@ MATH_FUNC (MbCreator *) CreateMeshShell( const MbMeshShellParameters & parameter MbResultType & res, c3d::ShellSPtr & shell ); + #endif // __CR_MESH_SHELL_H diff --git a/C3d/Include/cr_modified_solid.h b/C3d/Include/cr_modified_solid.h index 7d8d3c1..c35f222 100644 --- a/C3d/Include/cr_modified_solid.h +++ b/C3d/Include/cr_modified_solid.h @@ -77,28 +77,29 @@ public: /// \ru Построение оболочки \en Creation of a shell bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; + RPArray * items = nullptr ) override; void Refresh( MbFaceShell & outer ) override; ///< \ru Обновить форму оболочки \en Update shape of the shell - // \ru Дать параметры. \en Get the parameters. - void GetParameters( ModifyValues & params ) const { params = parameters; } - // \ru Установить параметры. \en Set the parameters. - void SetParameters( const ModifyValues & params ) { parameters = params; } + // \ru Дать параметры. \en Get the parameters. + void GetParameters( ModifyValues & params ) const { params = parameters; } + // \ru Установить параметры. \en Set the parameters. + void SetParameters( const ModifyValues & params ) { parameters = params; } - void GetFaceIndices( SArray & faces ) const { faces = faceIndices; } // \ru Идентификаторы модифицированных граней. \en Identifiers of the modified faces. - void GetEdgeIndices( SArray & edges ) const { edges = edgeIndices; } // \ru Идентификаторы модифицированных рёбер. \en Identifiers of the modified edges. + void GetFaceIndices( SArray & faces ) const { faces = faceIndices; } // \ru Идентификаторы модифицированных граней. \en Identifiers of the modified faces. + void GetEdgeIndices( SArray & edges ) const { edges = edgeIndices; } // \ru Идентификаторы модифицированных рёбер. \en Identifiers of the modified edges. private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbFaceModifiedSolid & ); - void SurfacesFree(); // \ru Удалить поверхности \en Delete the surfaces - void SurfacesAddRef(); // \ru Учесть поверхности \en Consider the surfaces + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbFaceModifiedSolid & ); + void SurfacesFree(); // \ru Удалить поверхности \en Delete the surfaces + void SurfacesAddRef(); // \ru Учесть поверхности \en Consider the surfaces DECLARE_PERSISTENT_CLASS_NEW_DEL( MbFaceModifiedSolid ) -}; +}; // MbFaceModifiedSolid IMPL_PERSISTENT_OPS( MbFaceModifiedSolid ) + //------------------------------------------------------------------------------ /** \brief \ru Построить модифицированную оболочку. \en Construct the modified shell. \~ diff --git a/C3d/Include/cr_nurbs3d.h b/C3d/Include/cr_nurbs3d.h index 484acbb..31f8fed 100644 --- a/C3d/Include/cr_nurbs3d.h +++ b/C3d/Include/cr_nurbs3d.h @@ -76,10 +76,10 @@ public: /** \} */ private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation, to prevent an assignment by default. - void operator = ( const MbNurbs3DCreator & ); // \ru Не реализовано!!! \en Not implemented!!! + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation, to prevent an assignment by default. + void operator = ( const MbNurbs3DCreator & ); // \ru Не реализовано!!! \en Not implemented!!! -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbNurbs3DCreator ) + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbNurbs3DCreator ) }; IMPL_PERSISTENT_OPS( MbNurbs3DCreator ) diff --git a/C3d/Include/cr_nurbs_block_solid.h b/C3d/Include/cr_nurbs_block_solid.h index a58e210..081d831 100644 --- a/C3d/Include/cr_nurbs_block_solid.h +++ b/C3d/Include/cr_nurbs_block_solid.h @@ -57,18 +57,19 @@ public: // \ru Общие функции математического объе public: /// \ru Построение оболочки \en Creation of a shell bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; + RPArray * items = nullptr ) override; void Refresh( MbFaceShell & outer ) override; ///< \ru Обновить форму оболочки \en Update shape of the shell private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbNurbsBlockSolid & ); + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbNurbsBlockSolid & ); DECLARE_PERSISTENT_CLASS_NEW_DEL( MbNurbsBlockSolid ) -}; +}; // MbNurbsBlockSolid IMPL_PERSISTENT_OPS( MbNurbsBlockSolid ) + //------------------------------------------------------------------------------ /** \brief \ru Построить модифицированную оболочку. \en Construct the modified shell. \~ diff --git a/C3d/Include/cr_nurbs_surfaces_solid.h b/C3d/Include/cr_nurbs_surfaces_solid.h index f7a3336..e2929f1 100644 --- a/C3d/Include/cr_nurbs_surfaces_solid.h +++ b/C3d/Include/cr_nurbs_surfaces_solid.h @@ -67,20 +67,21 @@ public: // \ru Общие функции математического объе public: /// \ru построение оболочки \en creation of a shell bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; + RPArray * items = nullptr ) override; void Refresh( MbFaceShell & outer ) override; ///< \ru обновить форму оболочки \en update shape of the shell - // \ru Дать параметры. \en Get the parameters. - void GetParameters( NurbsSurfaceValues & params ) const { params = parameters; } - // \ru Установить параметры. \en Set the parameters. - void SetParameters( const NurbsSurfaceValues & params ) { parameters = params; } + // \ru Дать параметры. \en Get the parameters. + void GetParameters( NurbsSurfaceValues & params ) const { params = parameters; } + // \ru Установить параметры. \en Set the parameters. + void SetParameters( const NurbsSurfaceValues & params ) { parameters = params; } -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbNurbsSurfacesSolid ) -OBVIOUS_PRIVATE_COPY( MbNurbsSurfacesSolid ) -}; + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbNurbsSurfacesSolid ) + OBVIOUS_PRIVATE_COPY( MbNurbsSurfacesSolid ) +}; // MbNurbsSurfacesSolid IMPL_PERSISTENT_OPS( MbNurbsSurfacesSolid ) + //------------------------------------------------------------------------------ /** \brief \ru Построить оболочку из NURBS-поверхностей. \en Construct a shell from NURBS-surfaces. \~ @@ -141,4 +142,5 @@ MATH_FUNC (c3d::CreatorSPtr) CreateNurbsShell( const MbNurbsSurfacesShellParams c3d::ShellSPtr & shell, IProgressIndicator * indicator = nullptr ); + #endif // __CR_NURBS_SURFACES_SOLID_H diff --git a/C3d/Include/cr_offset_curve.h b/C3d/Include/cr_offset_curve.h index af50f5d..bb353c9 100644 --- a/C3d/Include/cr_offset_curve.h +++ b/C3d/Include/cr_offset_curve.h @@ -118,14 +118,15 @@ public : /** \} */ private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation, to prevent an assignment by default. - void operator = ( const MbOffsetCurveCreator & ); // \ru Не реализовано!!! \en Not implemented!!! + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation, to prevent an assignment by default. + void operator = ( const MbOffsetCurveCreator & ); // \ru Не реализовано!!! \en Not implemented!!! -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbOffsetCurveCreator ) + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbOffsetCurveCreator ) }; IMPL_PERSISTENT_OPS( MbOffsetCurveCreator ) + //------------------------------------------------------------------------------ /** \brief \ru Создать офсетную кривую по трехмерной кривой и вектору направления. \en Create an offset curve from three-dimensional curve and direction. \~ diff --git a/C3d/Include/cr_patch_creator.h b/C3d/Include/cr_patch_creator.h index d7ce683..335c66f 100644 --- a/C3d/Include/cr_patch_creator.h +++ b/C3d/Include/cr_patch_creator.h @@ -72,19 +72,20 @@ public : // \ru Построение оболочки по исходным данным \en Construction of a shell from the given data bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; + RPArray * items = nullptr ) override; - // \ru Дать параметры. \en Get the parameters. - void GetParameters( PatchValues & params ) const { params = parameters; } - // \ru Установить параметры. \en Set the parameters. - void SetParameters( const PatchValues & params ) { parameters = params; } + // \ru Дать параметры. \en Get the parameters. + void GetParameters( PatchValues & params ) const { params = parameters; } + // \ru Установить параметры. \en Set the parameters. + void SetParameters( const PatchValues & params ) { parameters = params; } -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbPatchCreator ) -OBVIOUS_PRIVATE_COPY( MbPatchCreator ) -}; + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbPatchCreator ) + OBVIOUS_PRIVATE_COPY( MbPatchCreator ) +}; // MbPatchCreator IMPL_PERSISTENT_OPS( MbPatchCreator ) + //------------------------------------------------------------------------------ /** \brief \ru Построить оболочку в форме заплатки. \en Construct a patch-shaped shell. \~ diff --git a/C3d/Include/cr_projection_curve.h b/C3d/Include/cr_projection_curve.h index bf09493..8399b83 100644 --- a/C3d/Include/cr_projection_curve.h +++ b/C3d/Include/cr_projection_curve.h @@ -78,12 +78,13 @@ public: /** \} */ private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation, to prevent an assignment by default. - void operator = ( const MbProjCurveCreator & ); // \ru Не реализовано!!! \en Not implemented!!! + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation, to prevent an assignment by default. + void operator = ( const MbProjCurveCreator & ); // \ru Не реализовано!!! \en Not implemented!!! DECLARE_PERSISTENT_CLASS_NEW_DEL( MbProjCurveCreator ) }; IMPL_PERSISTENT_OPS( MbProjCurveCreator ) + #endif // __CR_PROJECTION_CURVE_H diff --git a/C3d/Include/cr_revolution_solid.h b/C3d/Include/cr_revolution_solid.h index fc2f305..affcccf 100644 --- a/C3d/Include/cr_revolution_solid.h +++ b/C3d/Include/cr_revolution_solid.h @@ -95,18 +95,18 @@ public : const MbSurface * GetSurface() const { return sweptData.GetSurface(); } ///< \ru Поверхность двумерных контуров. \en Surface of two-dimensional contours. const MbAxis3D & GetAxis() const { return axis; } ///< \ru Ось вращения. \en Rotation axis. - /// \ru Дать параметры. \en Get the parameters. - void GetParameters( RevolutionValues & p ) const { p = parameters; } - /// \ru Установить параметры. \en Set the parameters. - void SetParameters( const RevolutionValues & p ) { parameters = p; } + /// \ru Дать параметры. \en Get the parameters. + void GetParameters( RevolutionValues & p ) const { p = parameters; } + /// \ru Установить параметры. \en Set the parameters. + void SetParameters( const RevolutionValues & p ) { parameters = p; } /** \} */ private : - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbCurveRevolutionSolid & ); + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbCurveRevolutionSolid & ); DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCurveRevolutionSolid ) -}; +}; // MbCurveRevolutionSolid IMPL_PERSISTENT_OPS( MbCurveRevolutionSolid ) diff --git a/C3d/Include/cr_rib_solid.h b/C3d/Include/cr_rib_solid.h index 044c1f9..ba1e835 100644 --- a/C3d/Include/cr_rib_solid.h +++ b/C3d/Include/cr_rib_solid.h @@ -14,7 +14,10 @@ #include #include + class MbRibSolidParameters; + + //------------------------------------------------------------------------------ /** \brief \ru Строитель тела с ребром жёсткости. \en Constructor of a solid with a rib. \~ @@ -60,16 +63,16 @@ public : // \ru Общие функции твердого тела \en Common functions of solid bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * = nullptr ) override; // \ru Построение \en Construction + RPArray * = nullptr ) override; // \ru Построение \en Construction - // \ru Дать параметры. \en Get the parameters. - void GetParameters( RibValues & params ) const { params = parameters; } - // \ru Установить параметры. \en Set the parameters. - void SetParameters( const RibValues & params ) { parameters = params; } + // \ru Дать параметры. \en Get the parameters. + void GetParameters( RibValues & params ) const { params = parameters; } + // \ru Установить параметры. \en Set the parameters. + void SetParameters( const RibValues & params ) { parameters = params; } private : - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbRibSolid & ); // \ru НЕЛЬЗЯ!!! \en NOT ALLOWED!!! + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbRibSolid & ); // \ru НЕЛЬЗЯ!!! \en NOT ALLOWED!!! DECLARE_PERSISTENT_CLASS_NEW_DEL( MbRibSolid ) }; // MbRibSolid @@ -190,6 +193,7 @@ MATH_FUNC (MbCreator *) CreateRibElement( MbFaceShell * solid, MbResultType & res, MbFaceShell *& shell ); + //------------------------------------------------------------------------------ /** \brief \ru Создать отдельное ребро жёсткости. \en Create a separate rib. \~ @@ -223,4 +227,5 @@ MATH_FUNC (MbCreator *) CreateRibElement( c3d::ShellSPtr & solid, MbResultType & res, c3d::ShellSPtr & shell ); + #endif // __CR_RIB_SOLID_H diff --git a/C3d/Include/cr_ruled_shell.h b/C3d/Include/cr_ruled_shell.h index 61e278d..18f14db 100644 --- a/C3d/Include/cr_ruled_shell.h +++ b/C3d/Include/cr_ruled_shell.h @@ -63,14 +63,15 @@ public: // \ru Общие функции математического объе public: /// \ru Построение оболочки \en Creation of a shell bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; - // \ru Дать параметры. \en Get the parameters. - void GetParameters( RuledSurfaceValues & params ) const; - // \ru Установить параметры. \en Set the parameters. - void SetParameters( const RuledSurfaceValues & params ); + RPArray * items = nullptr ) override; -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbRuledShell ) -OBVIOUS_PRIVATE_COPY( MbRuledShell ) + // \ru Дать параметры. \en Get the parameters. + void GetParameters( RuledSurfaceValues & params ) const; + // \ru Установить параметры. \en Set the parameters. + void SetParameters( const RuledSurfaceValues & params ); + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbRuledShell ) + OBVIOUS_PRIVATE_COPY( MbRuledShell ) }; // MbRuledShell IMPL_PERSISTENT_OPS( MbRuledShell ) @@ -137,4 +138,5 @@ MATH_FUNC (MbCreator *) CreateRuledShell( const MbRuledShellParams & ruledParams MbResultType & res, c3d::ShellSPtr & shell ); + #endif // __CR_RULED_SHELL_H diff --git a/C3d/Include/cr_section_shell.h b/C3d/Include/cr_section_shell.h index 24feb7a..7dcfa1c 100644 --- a/C3d/Include/cr_section_shell.h +++ b/C3d/Include/cr_section_shell.h @@ -72,7 +72,7 @@ public : \en \name Common functions of the rigid solid (forming operations). \{ */ bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; // \ru Построение \en Construction + RPArray * items = nullptr ) override; // \ru Построение \en Construction virtual void SetYourVersion( VERSION version ); /** \} */ @@ -81,9 +81,9 @@ public : \en \name Functions of creator of evolution solid shell. \{ */ /// \ru Дать параметры. \en Get the parameters. - const MbSectionData & GetSectionData() { return sectionData; } - /// \ru Установить параметры. \en Set the parameters. - void SetSectionData( const MbSectionData & data ) { sectionData = data; } + const MbSectionData & GetSectionData() { return sectionData; } + /// \ru Установить параметры. \en Set the parameters. + void SetSectionData( const MbSectionData & data ) { sectionData = data; } /** \} */ /** \brief \ru Создать оболочку на поверхности переменного сечения. @@ -117,8 +117,8 @@ public : c3d::ShellSPtr & shell ); private : - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbSectionShell & ); + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbSectionShell & ); DECLARE_PERSISTENT_CLASS_NEW_DEL( MbSectionShell ) diff --git a/C3d/Include/cr_sheet_bend_any_solid.h b/C3d/Include/cr_sheet_bend_any_solid.h index aa7ccda..e4e245f 100644 --- a/C3d/Include/cr_sheet_bend_any_solid.h +++ b/C3d/Include/cr_sheet_bend_any_solid.h @@ -64,18 +64,19 @@ public: // \ru Общие функции твердого тела \en Common functions of solid solid bool CreateShell( MbFaceShell *& shell, - MbeCopyMode sameShell, - RPArray * items = nullptr ) override; // \ru Построение \en Construction + MbeCopyMode sameShell, + RPArray * items = nullptr ) override; // \ru Построение \en Construction private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. MbBendAnySolid & operator = ( const MbBendAnySolid & ); // \ru Не реализовано \en Not implemented DECLARE_PERSISTENT_CLASS_NEW_DEL( MbBendAnySolid ) -}; +}; // MbBendAnySolid IMPL_PERSISTENT_OPS( MbBendAnySolid ) + //------------------------------------------------------------------------------ /** \brief \ru Построить оболочку с выполнеными сгибами. \en Construct a shell with bends. \~ diff --git a/C3d/Include/cr_sheet_bend_by_edge_solid.h b/C3d/Include/cr_sheet_bend_by_edge_solid.h index 8dde0ca..e1ca258 100644 --- a/C3d/Include/cr_sheet_bend_by_edge_solid.h +++ b/C3d/Include/cr_sheet_bend_by_edge_solid.h @@ -74,24 +74,25 @@ public: // \ru Общие функции твердого тела \en Common functions of solid solid - bool CreateShell( MbFaceShell *& shell, - MbeCopyMode sameShell, - RPArray * items = nullptr ) override; // \ru Построение \en Construction + bool CreateShell( MbFaceShell *& shell, + MbeCopyMode sameShell, + RPArray * items = nullptr ) override; // \ru Построение \en Construction - // \ru Дать параметры. \en Get the parameters. - void GetParameters( MbBendByEdgeValues & params ) const { params = parameters; } - // \ru Установить параметры. \en Set the parameters. - void SetParameters( const MbBendByEdgeValues & params ) { parameters = params; } + // \ru Дать параметры. \en Get the parameters. + void GetParameters( MbBendByEdgeValues & params ) const { params = parameters; } + // \ru Установить параметры. \en Set the parameters. + void SetParameters( const MbBendByEdgeValues & params ) { parameters = params; } private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. MbBendsByEdgesSolid & operator = ( const MbBendsByEdgesSolid & ); // \ru Не реализовано \en Not implemented DECLARE_PERSISTENT_CLASS_NEW_DEL( MbBendsByEdgesSolid ) -}; +}; // MbBendsByEdgesSolid IMPL_PERSISTENT_OPS( MbBendsByEdgesSolid ) + //------------------------------------------------------------------------------ /** \brief \ru Построить сгибы вдоль рёбер оболочки. \en Construct bends along edges of a shell. \~ diff --git a/C3d/Include/cr_sheet_bend_over_seg_solid.h b/C3d/Include/cr_sheet_bend_over_seg_solid.h index f73e958..28a82c1 100644 --- a/C3d/Include/cr_sheet_bend_over_seg_solid.h +++ b/C3d/Include/cr_sheet_bend_over_seg_solid.h @@ -69,22 +69,23 @@ public: // \ru Общие функции твердого тела \en Common functions of solid solid bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; // \ru Построение \en Construction + RPArray * items = nullptr ) override; // \ru Построение \en Construction - // \ru Дать параметры. \en Get the parameters. - void GetParameters( MbBendOverSegValues & params ) const { params = parameters; } - // \ru Установить параметры. \en Set the parameters. - void SetParameters( const MbBendOverSegValues & params ) { parameters = params; } + // \ru Дать параметры. \en Get the parameters. + void GetParameters( MbBendOverSegValues & params ) const { params = parameters; } + // \ru Установить параметры. \en Set the parameters. + void SetParameters( const MbBendOverSegValues & params ) { parameters = params; } private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. MbBendOverSegSolid & operator = ( const MbBendOverSegSolid & ); DECLARE_PERSISTENT_CLASS_NEW_DEL( MbBendOverSegSolid ) -}; +}; // MbBendOverSegSolid IMPL_PERSISTENT_OPS( MbBendOverSegSolid ) + //------------------------------------------------------------------------------ /** \brief \ru Построить оболочку из листового материала, согнутую вдоль отрезка. \en Create a shell from sheet material bent along a segment. \~ diff --git a/C3d/Include/cr_sheet_bend_unbend_solid.h b/C3d/Include/cr_sheet_bend_unbend_solid.h index 3f9c13b..047610a 100644 --- a/C3d/Include/cr_sheet_bend_unbend_solid.h +++ b/C3d/Include/cr_sheet_bend_unbend_solid.h @@ -67,18 +67,19 @@ public: // \ru Общие функции твердого тела \en Common functions of solid solid bool CreateShell( MbFaceShell *& shell, - MbeCopyMode sameShell, - RPArray * items = nullptr ) override; // \ru Построение \en Construction + MbeCopyMode sameShell, + RPArray * items = nullptr ) override; // \ru Построение \en Construction private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. MbBendUnbendSolid & operator = ( const MbBendUnbendSolid & ); // \ru Не реализовано \en Not implemented DECLARE_PERSISTENT_CLASS_NEW_DEL( MbBendUnbendSolid ) -}; +}; // MbBendUnbendSolid IMPL_PERSISTENT_OPS( MbBendUnbendSolid ) + //------------------------------------------------------------------------------ /** \brief \ru Построить оболочку с выполненым сгибом/разгибом. \en Construct a shell with bend/unbend. \~ @@ -125,5 +126,4 @@ MATH_FUNC (MbCreator *) CreateBendUnbend( SPtr & init RPArray * ribContours = nullptr ); - #endif // __CR_SHEET_BEND_UNBEND_SOLID_H diff --git a/C3d/Include/cr_sheet_builder_solid.h b/C3d/Include/cr_sheet_builder_solid.h index 6d9c50b..39a6184 100644 --- a/C3d/Include/cr_sheet_builder_solid.h +++ b/C3d/Include/cr_sheet_builder_solid.h @@ -60,17 +60,17 @@ public: // \ru Общие функции твердого тела. \en Common functions of solid. - // \ru Построение оболочки листового тела. \en Construction of a sheet metal shell. + // \ru Построение оболочки листового тела. \en Construction of a sheet metal shell. bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, RPArray *items = nullptr ) override; - // \ru Получить параметры. \en Get the parameters. - void GetParameters( MbSolidToSheetMetalValues & params ) const { params = parameters; } - // \ru Установить параметры. \en Set the parameters. - void SetParameters( const MbSolidToSheetMetalValues & params ) { parameters = params; } + // \ru Получить параметры. \en Get the parameters. + void GetParameters( MbSolidToSheetMetalValues & params ) const { params = parameters; } + // \ru Установить параметры. \en Set the parameters. + void SetParameters( const MbSolidToSheetMetalValues & params ) { parameters = params; } private: OBVIOUS_PRIVATE_COPY( MbBuildSheetMetalSolid ) DECLARE_PERSISTENT_CLASS_NEW_DEL( MbBuildSheetMetalSolid ) -}; +}; // MbBuildSheetMetalSolid IMPL_PERSISTENT_OPS( MbBuildSheetMetalSolid ) @@ -144,4 +144,5 @@ MATH_FUNC (c3d::CreatorSPtr) ConvertShellToSheetMetall( const c3d::ShellSPtr & MbResultType & res, c3d::ShellSPtr & resultShell ); + #endif // __CR_SHEET_BUILDER_SOLID_H diff --git a/C3d/Include/cr_sheet_closed_corner_solid.h b/C3d/Include/cr_sheet_closed_corner_solid.h index 7385be9..45c1667 100644 --- a/C3d/Include/cr_sheet_closed_corner_solid.h +++ b/C3d/Include/cr_sheet_closed_corner_solid.h @@ -66,24 +66,25 @@ public: // \ru Общие функции твердого тела \en Common functions of solid solid - bool CreateShell( MbFaceShell *& shell, - MbeCopyMode sameShell, - RPArray * items = nullptr ) override; // \ru Построение \en Construction + bool CreateShell( MbFaceShell *& shell, + MbeCopyMode sameShell, + RPArray * items = nullptr ) override; // \ru Построение \en Construction - // \ru Дать параметры. \en Get the parameters. - void GetParameters( MbClosedCornerValues & params ) const { params = parameters; } - // \ru Установить параметры. \en Set the parameters. - void SetParameters( const MbClosedCornerValues & params ) { parameters = params; } + // \ru Дать параметры. \en Get the parameters. + void GetParameters( MbClosedCornerValues & params ) const { params = parameters; } + // \ru Установить параметры. \en Set the parameters. + void SetParameters( const MbClosedCornerValues & params ) { parameters = params; } private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. MbClosedCornerSolid & operator = ( const MbClosedCornerSolid & ); DECLARE_PERSISTENT_CLASS_NEW_DEL( MbClosedCornerSolid ) -}; +}; // MbClosedCornerSolid IMPL_PERSISTENT_OPS( MbClosedCornerSolid ) + //------------------------------------------------------------------------------ /** \brief \ru Построить оболочку из листового материала с замыканием угла. \en Construct a shell form sheet material with corner closure. \~ diff --git a/C3d/Include/cr_sheet_joint_bend_solid.h b/C3d/Include/cr_sheet_joint_bend_solid.h index aaeacf5..0e075ad 100644 --- a/C3d/Include/cr_sheet_joint_bend_solid.h +++ b/C3d/Include/cr_sheet_joint_bend_solid.h @@ -72,24 +72,25 @@ public: MbePrompt GetPropertyName() override; // \ru Выдать заголовок свойства объекта \en Get a name of object property // \ru Общие функции твердого тела \en Common functions of solid solid - bool CreateShell( MbFaceShell *& shell, - MbeCopyMode sameShell, - RPArray * items = nullptr ) override; // \ru Построение \en Construction + bool CreateShell( MbFaceShell *& shell, + MbeCopyMode sameShell, + RPArray * items = nullptr ) override; // \ru Построение \en Construction - // \ru Дать параметры. \en Get the parameters. - void GetParameters( MbJointBendValues & params ) const { params = parameters; } - // \ru Установить параметры. \en Set the parameters. - void SetParameters( const MbJointBendValues & params ) { parameters = params; } + // \ru Дать параметры. \en Get the parameters. + void GetParameters( MbJointBendValues & params ) const { params = parameters; } + // \ru Установить параметры. \en Set the parameters. + void SetParameters( const MbJointBendValues & params ) { parameters = params; } private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. MbJointBendSolid & operator = ( const MbJointBendSolid & ); // \ru Не реализовано \en Not implemented DECLARE_PERSISTENT_CLASS_NEW_DEL( MbJointBendSolid ) -}; +}; // MbJointBendSolid IMPL_PERSISTENT_OPS( MbJointBendSolid ) + //------------------------------------------------------------------------------ /** \brief \ru Построить комбинированные сгибы. \en Construct composite bends. \~ diff --git a/C3d/Include/cr_sheet_metal_solid.h b/C3d/Include/cr_sheet_metal_solid.h index 1e9c49c..6eb7411 100644 --- a/C3d/Include/cr_sheet_metal_solid.h +++ b/C3d/Include/cr_sheet_metal_solid.h @@ -101,26 +101,27 @@ public : // \ru Общие функции твердого тела \en Common functions of solid solid bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; // \ru Построение \en Construction + RPArray * items = nullptr ) override; // \ru Построение \en Construction virtual MbFaceShell * InitShell( bool in ); - const MbPlacement3D & GetPlacement() const; + const MbPlacement3D & GetPlacement() const; - // \ru Дать параметры. \en Get the parameters. - void GetParameters( MbSheetMetalValues & params ) const { params = parameters; } - // \ru Установить параметры. \en Set the parameters. - void SetParameters( const MbSheetMetalValues & params ) { parameters = params; } + // \ru Дать параметры. \en Get the parameters. + void GetParameters( MbSheetMetalValues & params ) const { params = parameters; } + // \ru Установить параметры. \en Set the parameters. + void SetParameters( const MbSheetMetalValues & params ) { parameters = params; } private : - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbSheetMetalSolid & ); + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbSheetMetalSolid & ); DECLARE_PERSISTENT_CLASS_NEW_DEL( MbSheetMetalSolid ) -}; +}; // MbSheetMetalSolid IMPL_PERSISTENT_OPS( MbSheetMetalSolid ) + //------------------------------------------------------------------------------ /** \brief \ru Построить оболочку из листового материала. \en Construct a shell from sheet material. \~ diff --git a/C3d/Include/cr_sheet_normalize_holes_solid.h b/C3d/Include/cr_sheet_normalize_holes_solid.h index 59f1977..ddd729b 100644 --- a/C3d/Include/cr_sheet_normalize_holes_solid.h +++ b/C3d/Include/cr_sheet_normalize_holes_solid.h @@ -55,21 +55,22 @@ public: void SetProperties( const MbProperties & properties ) override; // \ru Записать свойства объекта \en Set properties of the object MbePrompt GetPropertyName() override; // \ru Выдать заголовок свойства объекта \en Get a name of object property - // \ru Общие функции твердого тела \en Common functions of solid solid + // \ru Общие функции твердого тела \en Common functions of solid solid bool CreateShell( MbFaceShell *& shell, - MbeCopyMode sameShell, - RPArray * items = nullptr ) override; // \ru Построение \en Construction + MbeCopyMode sameShell, + RPArray * items = nullptr ) override; // \ru Построение \en Construction private: // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. MbNormalizeHolesSolid & operator = ( const MbNormalizeHolesSolid & ); // \ru Не реализовано \en Not implemented DECLARE_PERSISTENT_CLASS_NEW_DEL( MbNormalizeHolesSolid ) -}; +}; // MbNormalizeHolesSolid IMPL_PERSISTENT_OPS( MbNormalizeHolesSolid ) + //------------------------------------------------------------------------------ /** \brief \ru Нормализовать вырезы листового тела. \en Normalize of the holes of sheet solid. \~ @@ -124,4 +125,6 @@ MATH_FUNC (MbCreator *) NormalizeHolesSides ( c3d::ShellSPtr & const MbNormalizeCutSidesParams & normParam, MbResultType & res, c3d::ShellSPtr & shell ); + + #endif // __CR_SHEET_NORMALIZE_HOLES_SOLID_H diff --git a/C3d/Include/cr_sheet_restored_edges_solid.h b/C3d/Include/cr_sheet_restored_edges_solid.h index 559327e..a76309e 100644 --- a/C3d/Include/cr_sheet_restored_edges_solid.h +++ b/C3d/Include/cr_sheet_restored_edges_solid.h @@ -61,19 +61,20 @@ public: // \ru Общие функции твердого тела \en Common functions of solid solid - bool CreateShell( MbFaceShell *& shell, - MbeCopyMode sameShell, - RPArray * items = nullptr ) override; // \ru Построение \en Construction + bool CreateShell( MbFaceShell *& shell, + MbeCopyMode sameShell, + RPArray * items = nullptr ) override; // \ru Построение \en Construction private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. MbRestoredEdgesSolid & operator = ( const MbRestoredEdgesSolid & ); DECLARE_PERSISTENT_CLASS_NEW_DEL( MbRestoredEdgesSolid ) -}; +}; // MbRestoredEdgesSolid IMPL_PERSISTENT_OPS( MbRestoredEdgesSolid ) + //------------------------------------------------------------------------------ /** \brief \ru Построить боковых рёбер сгибов. \en Construct side edges of bends. \~ diff --git a/C3d/Include/cr_sheet_simplified_flat_solid.h b/C3d/Include/cr_sheet_simplified_flat_solid.h index 3681caa..8ce2757 100644 --- a/C3d/Include/cr_sheet_simplified_flat_solid.h +++ b/C3d/Include/cr_sheet_simplified_flat_solid.h @@ -59,18 +59,19 @@ public: // \ru Общие функции твердого тела \en Common functions of solid solid bool CreateShell( MbFaceShell *& shell, - MbeCopyMode sameShell, - RPArray * items = nullptr ) override; // \ru Построение \en Construction + MbeCopyMode sameShell, + RPArray * items = nullptr ) override; // \ru Построение \en Construction private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. MbSimplifyFlatSolid & operator = ( const MbSimplifyFlatSolid & ); // \ru Не реализовано \en Not implemented DECLARE_PERSISTENT_CLASS_NEW_DEL( MbSimplifyFlatSolid ) -}; +}; // MbSimplifyFlatSolid IMPL_PERSISTENT_OPS( MbSimplifyFlatSolid ) + //------------------------------------------------------------------------------ /** \brief \ru Упростить развёртку листового тела. \en Simplify flattened sheet solid. \~ diff --git a/C3d/Include/cr_sheet_union_solid.h b/C3d/Include/cr_sheet_union_solid.h index e6b9712..50a723a 100644 --- a/C3d/Include/cr_sheet_union_solid.h +++ b/C3d/Include/cr_sheet_union_solid.h @@ -36,6 +36,8 @@ public : MbSheetUnionSolid( const RPArray & solid2, const bool same2, const MbSNameMaker & n ); private : MbSheetUnionSolid( const MbSheetUnionSolid & init, MbRegDuplicate *ireg ); + // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. + MbSheetUnionSolid( const MbSheetUnionSolid & init ); public : virtual ~MbSheetUnionSolid(); @@ -62,31 +64,30 @@ public : // \ru Общие функции твердого тела \en Common functions of solid bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; // \ru Построение \en Construction + RPArray * items = nullptr ) override; // \ru Построение \en Construction void SetYourVersion( VERSION version, bool forAll ) override; - /// \ru Количество строителей первого тела. \en Count of creators of the first solid. - size_t GetCountOne() const { return countOne; } - /// \ru Общее количество строителей. \en Total count of creators. - size_t GetCreatorsCount() const { return creators.Count(); } - /// \ru Добавить в журнал. \en Add to the history tree. - void AddCreator ( MbCreator & creator ); - /// \ru Дать строитель. \en Get the constructor. - MbCreator * GetCreator ( const size_t ind ) const; - void DeleteCreator( const size_t ind ); + /// \ru Количество строителей первого тела. \en Count of creators of the first solid. + size_t GetCountOne() const { return countOne; } + /// \ru Общее количество строителей. \en Total count of creators. + size_t GetCreatorsCount() const { return creators.Count(); } + /// \ru Добавить в журнал. \en Add to the history tree. + void AddCreator ( MbCreator & creator ); + /// \ru Дать строитель. \en Get the constructor. + MbCreator * GetCreator ( const size_t ind ) const; + void DeleteCreator( const size_t ind ); private : - // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. - MbSheetUnionSolid( const MbSheetUnionSolid & init ); - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - MbSheetUnionSolid & operator = ( const MbSheetUnionSolid & ); + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + MbSheetUnionSolid & operator = ( const MbSheetUnionSolid & ); DECLARE_PERSISTENT_CLASS_NEW_DEL( MbSheetUnionSolid ) -}; +}; // MbSheetUnionSolid IMPL_PERSISTENT_OPS( MbSheetUnionSolid ) + //------------------------------------------------------------------------------ /** \brief \ru Создать оболочку объединённых по торцу листовых тел. \en Create a shell of sheet solids united by a butt. \~ diff --git a/C3d/Include/cr_simple_creator.h b/C3d/Include/cr_simple_creator.h index 12a294c..9b83c81 100644 --- a/C3d/Include/cr_simple_creator.h +++ b/C3d/Include/cr_simple_creator.h @@ -85,25 +85,25 @@ public : bool SetEqual( const MbCreator & ) override; // \ru Сделать равным \en Make equal bool CreateShell( MbFaceShell *&shell, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; // \ru Построение \en Construction + RPArray * items = nullptr ) override; // \ru Построение \en Construction /** \} */ - const MbFaceShell * GetShell() const { return outer; } /// \ru Дать оболочку. \en Get a shell. - void SetShell( const MbFaceShell & ); /// \ru Заменить оболочку. \en Replace a shell. - OperationType GetOperationType() { return operation; } /// \ru Дать оболочку. \en Get a shell. - void SetOperationType( OperationType t ) { operation = t; } /// \ru Заменить оболочку. \en Replace a shell. + const MbFaceShell * GetShell() const { return outer; } /// \ru Дать оболочку. \en Get a shell. + void SetShell( const MbFaceShell & ); /// \ru Заменить оболочку. \en Replace a shell. + OperationType GetOperationType() { return operation; } /// \ru Дать оболочку. \en Get a shell. + void SetOperationType( OperationType t ) { operation = t; } /// \ru Заменить оболочку. \en Replace a shell. - /// \ru Удалить копии оболочек в простых построителях (MbSimpleCreator). \en Delete shell copies in simple creators (MbSimpleCreator). - template + /// \ru Удалить копии оболочек в простых построителях (MbSimpleCreator). \en Delete shell copies in simple creators (MbSimpleCreator). + template static bool DeleteShellCopies( const CreatorsVector & ); - /// \ru Есть ли в каком-то простом построителе (MbSimpleCreator) заданная оболочка. \en Is there a simple builder (MbSimpleCreator) that contains a given shell?. - template + /// \ru Есть ли в каком-то простом построителе (MbSimpleCreator) заданная оболочка. \en Is there a simple builder (MbSimpleCreator) that contains a given shell?. + template static bool IsThisShell( const MbFaceShell &, const CreatorsVector & ); /// \ru Есть ли в каком-то простом построителе (MbSimpleCreator) заданная оболочка. \en Is there a simple builder (MbSimpleCreator) that contains a given shell?. static bool IsThisShell( const MbSolid & ); -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbSimpleCreator ) -OBVIOUS_PRIVATE_COPY( MbSimpleCreator ) + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbSimpleCreator ) + OBVIOUS_PRIVATE_COPY( MbSimpleCreator ) }; // MbSimpleCreator IMPL_PERSISTENT_OPS( MbSimpleCreator ) @@ -131,6 +131,7 @@ bool AreEqualShellPointers( const c3d::IndexConstShell & is1, const c3d::IndexCo return false; } + //------------------------------------------------------------------------------ // Sort by index (ascending) // --- @@ -204,6 +205,7 @@ bool MbSimpleCreator::DeleteShellCopies( const CreatorsVector & creators ) return res; } + //------------------------------------------------------------------------------ // \ru Есть ли в каком-то простом построителе (MbSimpleCreator) заданная оболочка. \en Is there a simple builder (MbSimpleCreator) that contains a given shell?. // --- @@ -267,13 +269,14 @@ public : bool IsSimilar ( const MbCreator & ) const override; // \ru Являются ли объекты подобными \en Whether the objects are similar bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; // \ru Построение \en Construction + RPArray * items = nullptr ) override; // \ru Построение \en Construction /** \} */ -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbReverseCreator ) -OBVIOUS_PRIVATE_COPY( MbReverseCreator ) + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbReverseCreator ) + OBVIOUS_PRIVATE_COPY( MbReverseCreator ) }; // MbReverseCreator IMPL_PERSISTENT_OPS( MbReverseCreator ) + #endif // __CR_SIMPLE_CREATOR_H diff --git a/C3d/Include/cr_smooth_solid.h b/C3d/Include/cr_smooth_solid.h index 6b66229..b1c1365 100644 --- a/C3d/Include/cr_smooth_solid.h +++ b/C3d/Include/cr_smooth_solid.h @@ -59,19 +59,20 @@ public : //virtual bool CreateShell( MbFaceShell *&shell, MbeCopyMode sameShell, // RPArray * items = nullptr ) = 0; // \ru Построение \en Construction - /// \ru Дать параметры. \en Get the parameters. - void GetParameters( SmoothValues & params ) const { params = parameters; } - /// \ru Установить параметры. \en Set the parameters. - void SetParameters( const SmoothValues & params ) { parameters = params; } + /// \ru Дать параметры. \en Get the parameters. + void GetParameters( SmoothValues & params ) const { params = parameters; } + /// \ru Установить параметры. \en Set the parameters. + void SetParameters( const SmoothValues & params ) { parameters = params; } private : virtual void ReadDistances ( reader &in ) = 0; - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbSmoothSolid & ); + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbSmoothSolid & ); DECLARE_PERSISTENT_CLASS( MbSmoothSolid ) }; // MbSmoothSolid IMPL_PERSISTENT_OPS( MbSmoothSolid ) + #endif // __CR_SMOOTH_SOLID_H diff --git a/C3d/Include/cr_split_shell.h b/C3d/Include/cr_split_shell.h index 6ea19ad..fa98515 100644 --- a/C3d/Include/cr_split_shell.h +++ b/C3d/Include/cr_split_shell.h @@ -58,19 +58,20 @@ public : // \ru Общие функции твердого тела \en Common functions of solid bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; // \ru Построение \en Construction + RPArray * items = nullptr ) override; // \ru Построение \en Construction private: // \ru Не реализовано \en Not implemented // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. MbSplitShell( const MbSplitShell & ); - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbSplitShell & ); + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbSplitShell & ); DECLARE_PERSISTENT_CLASS_NEW_DEL( MbSplitShell ) -}; +}; // MbSplitShell IMPL_PERSISTENT_OPS( MbSplitShell ) + //------------------------------------------------------------------------------ /** \brief \ru Построить оболочку с разбиением граней выдавливанием. \en Create a shell with faces splitting by extrusion. \~ diff --git a/C3d/Include/cr_stamp_bead_solid.h b/C3d/Include/cr_stamp_bead_solid.h index 7d18142..88a0926 100644 --- a/C3d/Include/cr_stamp_bead_solid.h +++ b/C3d/Include/cr_stamp_bead_solid.h @@ -87,22 +87,23 @@ public: // \ru Общие функции твердого тела \en Common functions of solid bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; // \ru Построение \en Construction + RPArray * items = nullptr ) override; // \ru Построение \en Construction - // \ru Дать параметры. \en Get the parameters. - void GetParameters( MbBeadValues & params ) const { params = parameters; } - // \ru Установить параметры. \en Set the parameters. - void SetParameters( const MbBeadValues & params ) { parameters = params; } + // \ru Дать параметры. \en Get the parameters. + void GetParameters( MbBeadValues & params ) const { params = parameters; } + // \ru Установить параметры. \en Set the parameters. + void SetParameters( const MbBeadValues & params ) { parameters = params; } private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. MbBeadSolid & operator = ( const MbBeadSolid & ); DECLARE_PERSISTENT_CLASS_NEW_DEL( MbBeadSolid ) -}; +}; // MbBeadSolid IMPL_PERSISTENT_OPS( MbBeadSolid ) + //------------------------------------------------------------------------------ /** \brief \ru Построить оболочку из листового материала с буртиком. \en Construct a shell from sheet material with a bead. \~ diff --git a/C3d/Include/cr_stamp_jalousie_solid.h b/C3d/Include/cr_stamp_jalousie_solid.h index 7bc2eb7..7a830fe 100644 --- a/C3d/Include/cr_stamp_jalousie_solid.h +++ b/C3d/Include/cr_stamp_jalousie_solid.h @@ -84,22 +84,23 @@ public: // \ru Общие функции твердого тела \en Common functions of solid bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; // \ru Построение \en Construction + RPArray * items = nullptr ) override; // \ru Построение \en Construction - // \ru Дать параметры. \en Get the parameters. - void GetParameters( MbJalousieValues & params ) const { params = parameters; } - // \ru Установить параметры. \en Set the parameters. - void SetParameters( const MbJalousieValues & params ) { parameters = params; } + // \ru Дать параметры. \en Get the parameters. + void GetParameters( MbJalousieValues & params ) const { params = parameters; } + // \ru Установить параметры. \en Set the parameters. + void SetParameters( const MbJalousieValues & params ) { parameters = params; } private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. MbJalousieSolid & operator = ( const MbJalousieSolid & ); // \ru Не реализовано \en Not implemented DECLARE_PERSISTENT_CLASS_NEW_DEL( MbJalousieSolid ) -}; +}; // MbJalousieSolid IMPL_PERSISTENT_OPS( MbJalousieSolid ) + //------------------------------------------------------------------------------ /** \brief \ru Построить оболочку из листового материала с жалюзи. \en Construct a shell from a sheet material with jalousie. \~ diff --git a/C3d/Include/cr_stamp_jog_solid.h b/C3d/Include/cr_stamp_jog_solid.h index d457a20..971047c 100644 --- a/C3d/Include/cr_stamp_jog_solid.h +++ b/C3d/Include/cr_stamp_jog_solid.h @@ -80,28 +80,29 @@ public: // \ru Общие функции твердого тела \en Common functions of solid - bool CreateShell( MbFaceShell *& shell, - MbeCopyMode sameShell, - RPArray * items = nullptr ) override; // \ru Построение \en Construction + bool CreateShell( MbFaceShell *& shell, + MbeCopyMode sameShell, + RPArray * items = nullptr ) override; // \ru Построение \en Construction - // \ru Дать параметры. \en Get the parameters. - void GetParameters( MbJogValues & params ) const { params = jogParameters; } - // \ru Установить параметры. \en Set the parameters. - void SetParameters( const MbJogValues & params ) { jogParameters = params; } - // \ru Дать параметры. \en Get the parameters. - void GetParameters( MbBendValues & params ) const { params = secondBendParameters; } - // \ru Установить параметры. \en Set the parameters. - void SetParameters( const MbBendValues & params ) { secondBendParameters = params; } + // \ru Дать параметры. \en Get the parameters. + void GetParameters( MbJogValues & params ) const { params = jogParameters; } + // \ru Установить параметры. \en Set the parameters. + void SetParameters( const MbJogValues & params ) { jogParameters = params; } + // \ru Дать параметры. \en Get the parameters. + void GetParameters( MbBendValues & params ) const { params = secondBendParameters; } + // \ru Установить параметры. \en Set the parameters. + void SetParameters( const MbBendValues & params ) { secondBendParameters = params; } private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - MbJogSolid & operator = ( const MbJogSolid & ); + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + MbJogSolid & operator = ( const MbJogSolid & ); DECLARE_PERSISTENT_CLASS_NEW_DEL( MbJogSolid ) -}; +}; // MbJogSolid IMPL_PERSISTENT_OPS( MbJogSolid ) + //------------------------------------------------------------------------------ /** \brief \ru Построить оболочки из листового материала с подсечкой. \en Construct shells from the sheet material with a jog. \~ diff --git a/C3d/Include/cr_stamp_remove_solid.h b/C3d/Include/cr_stamp_remove_solid.h index f679588..8f2ef9e 100644 --- a/C3d/Include/cr_stamp_remove_solid.h +++ b/C3d/Include/cr_stamp_remove_solid.h @@ -85,15 +85,15 @@ public: // \ru Общие функции твердого тела \en Common functions of solid solid bool CreateShell( MbFaceShell *& shell, - MbeCopyMode sameShell, - RPArray * items = nullptr ) override; // \ru Построение \en Construction + MbeCopyMode sameShell, + RPArray * items = nullptr ) override; // \ru Построение \en Construction private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. MbRemoveOperationSolid & operator = ( const MbRemoveOperationSolid & ); // \ru Не реализовано \en Not implemented DECLARE_PERSISTENT_CLASS_NEW_DEL( MbRemoveOperationSolid ) -}; +}; // MbRemoveOperationSolid IMPL_PERSISTENT_OPS( MbRemoveOperationSolid ) diff --git a/C3d/Include/cr_stamp_rib_solid.h b/C3d/Include/cr_stamp_rib_solid.h index 297f9e1..3630b6d 100644 --- a/C3d/Include/cr_stamp_rib_solid.h +++ b/C3d/Include/cr_stamp_rib_solid.h @@ -65,22 +65,23 @@ public : // \ru Общие функции твердого тела \en Common functions of solid bool CreateShell( MbFaceShell *&shell, MbeCopyMode sameShell, - RPArray *items = nullptr ) override; // \ru Построение \en Construction + RPArray *items = nullptr ) override; // \ru Построение \en Construction - // \ru Дать параметры. \en Get the parameters. - void GetParameters( SheetRibValues & params ) const { params = parameters; } - // \ru Установить параметры. \en Set the parameters. - void SetParameters( const SheetRibValues & params ) { parameters = params; } + // \ru Дать параметры. \en Get the parameters. + void GetParameters( SheetRibValues & params ) const { params = parameters; } + // \ru Установить параметры. \en Set the parameters. + void SetParameters( const SheetRibValues & params ) { parameters = params; } private : - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbStampRibSolid & ); // \ru НЕЛЬЗЯ!!! \en NOT ALLOWED!!! + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbStampRibSolid & ); // \ru НЕЛЬЗЯ!!! \en NOT ALLOWED!!! DECLARE_PERSISTENT_CLASS_NEW_DEL( MbStampRibSolid ) -}; // MbRibSolid +}; // MbStampRibSolid IMPL_PERSISTENT_OPS( MbStampRibSolid ) + //------------------------------------------------------------------------------ /** \brief \ru Создать оболочку с ребром жёсткости. \en Create a shell with a rib. \~ @@ -197,4 +198,5 @@ MATH_FUNC (MbResultType) CreateSheetRibParts( const c3d::ShellSPtr & soli c3d::ShellSPtr & shellToAdd, c3d::ShellSPtr & shellToSubtract ); + #endif // __CR_STAMP_RIB_SOLID_H diff --git a/C3d/Include/cr_stamp_ruled_solid.h b/C3d/Include/cr_stamp_ruled_solid.h index 2b6cd9e..156d9df 100644 --- a/C3d/Include/cr_stamp_ruled_solid.h +++ b/C3d/Include/cr_stamp_ruled_solid.h @@ -67,26 +67,27 @@ public: // \ru Общие функции твердого тела. \en Common functions of solid. - bool CreateShell( MbFaceShell *& shell, - MbeCopyMode sameShell, - RPArray * items = nullptr ) override; // \ru Построение \en Construction - // \ru Дать базовые объекты. \en Get the base objects. + bool CreateShell( MbFaceShell *& shell, + MbeCopyMode sameShell, + RPArray * items = nullptr ) override; // \ru Построение \en Construction + // \ru Дать базовые объекты. \en Get the base objects. void GetBasisItems( RPArray & s ) override; - // \ru Дать параметры. \en Get the parameters. - void GetParameters( MbRuledSolidValues & params ) const { params = parameters; } - // \ru Установить параметры. \en Set the parameters. - void SetParameters( const MbRuledSolidValues & params ) { parameters = params; } + // \ru Дать параметры. \en Get the parameters. + void GetParameters( MbRuledSolidValues & params ) const { params = parameters; } + // \ru Установить параметры. \en Set the parameters. + void SetParameters( const MbRuledSolidValues & params ) { parameters = params; } private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - MbRuledSolid & operator = ( const MbRuledSolid & ); + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + MbRuledSolid & operator = ( const MbRuledSolid & ); DECLARE_PERSISTENT_CLASS_NEW_DEL( MbRuledSolid ) -}; +}; // MbRuledSolid IMPL_PERSISTENT_OPS( MbRuledSolid ) + //------------------------------------------------------------------------------ /** \brief \ru Построить линейчатую оболочку по контуру. \en Create a ruled shell from the contour. \~ diff --git a/C3d/Include/cr_stamp_solid.h b/C3d/Include/cr_stamp_solid.h index 1c120a9..cecc29f 100644 --- a/C3d/Include/cr_stamp_solid.h +++ b/C3d/Include/cr_stamp_solid.h @@ -85,22 +85,23 @@ public: // \ru Общие функции твердого тела \en Common functions of solid bool CreateShell( MbFaceShell *&shell, MbeCopyMode sameShell, - RPArray *items = nullptr ) override; // \ru Построение \en Construction + RPArray *items = nullptr ) override; // \ru Построение \en Construction - // \ru Дать параметры. \en Get the parameters. - void GetParameters( MbStampingValues & params ) const { params = parameters; } - // \ru Установить параметры. \en Set the parameters. - void SetParameters( const MbStampingValues & params ) { parameters = params; } + // \ru Дать параметры. \en Get the parameters. + void GetParameters( MbStampingValues & params ) const { params = parameters; } + // \ru Установить параметры. \en Set the parameters. + void SetParameters( const MbStampingValues & params ) { parameters = params; } private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - MbStampSolid & operator = ( const MbStampSolid & ); // \ru Не реализовано \en Not implemented + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + MbStampSolid & operator = ( const MbStampSolid & ); // \ru Не реализовано \en Not implemented DECLARE_PERSISTENT_CLASS_NEW_DEL( MbStampSolid ) -}; +}; // MbStampSolid IMPL_PERSISTENT_OPS( MbStampSolid ) + //------------------------------------------------------------------------------ /** \brief \ru Построить оболочку из листового материала штамповкой. \en Construct a shell form sheet material by stamping. \~ diff --git a/C3d/Include/cr_stamp_spherical_solid.h b/C3d/Include/cr_stamp_spherical_solid.h index 552ce0f..f4b939a 100644 --- a/C3d/Include/cr_stamp_spherical_solid.h +++ b/C3d/Include/cr_stamp_spherical_solid.h @@ -80,22 +80,23 @@ public: // \ru Общие функции твердого тела \en Common functions of solid bool CreateShell( MbFaceShell *&shell, MbeCopyMode sameShell, - RPArray *items = nullptr ) override; // \ru Построение \en Construction + RPArray *items = nullptr ) override; // \ru Построение \en Construction - // \ru Дать параметры. \en Get the parameters. - void GetParameters( MbStampingValues & params ) const { params = parameters; } - // \ru Установить параметры. \en Set the parameters. - void SetParameters( const MbStampingValues & params ) { parameters = params; } + // \ru Дать параметры. \en Get the parameters. + void GetParameters( MbStampingValues & params ) const { params = parameters; } + // \ru Установить параметры. \en Set the parameters. + void SetParameters( const MbStampingValues & params ) { parameters = params; } private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - MbSphericalStampSolid & operator = ( const MbSphericalStampSolid & ); // \ru Не реализовано \en Not implemented + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + MbSphericalStampSolid & operator = ( const MbSphericalStampSolid & ); // \ru Не реализовано \en Not implemented DECLARE_PERSISTENT_CLASS_NEW_DEL( MbSphericalStampSolid ) -}; +}; // MbSphericalStampSolid IMPL_PERSISTENT_OPS( MbSphericalStampSolid ) + //------------------------------------------------------------------------------ /** \brief \ru Построить оболочку из листового материала со сферической штамповкой. \en Construct a shell form sheet material by spherical stamping. \~ diff --git a/C3d/Include/cr_stamp_user_solid.h b/C3d/Include/cr_stamp_user_solid.h index d4e39f3..70daf2e 100644 --- a/C3d/Include/cr_stamp_user_solid.h +++ b/C3d/Include/cr_stamp_user_solid.h @@ -6,8 +6,8 @@ */ //////////////////////////////////////////////////////////////////////////////// -#ifndef __CR_USERSTAMP_SOLID_H -#define __CR_USERSTAMP_SOLID_H +#ifndef __CR_STAMP_USER_SOLID_H +#define __CR_STAMP_USER_SOLID_H #include @@ -77,17 +77,17 @@ public: // \ru Общие функции твердого тела. \en Common functions of solid. bool CreateShell( MbFaceShell *&shell, MbeCopyMode sameShell, - RPArray *items = nullptr ) override; // \ru Построение оболочки штамповки. \en Construction of a stamping shell. + RPArray *items = nullptr ) override; // \ru Построение оболочки штамповки. \en Construction of a stamping shell. - // \ru Получить параметры. \en Get the parameters. - void GetParameters( MbToolStampingValues & params ) const { params = parameters; } - // \ru Установить параметры. \en Set the parameters. - void SetParameters( const MbToolStampingValues & params ) { parameters = params; } + // \ru Получить параметры. \en Get the parameters. + void GetParameters( MbToolStampingValues & params ) const { params = parameters; } + // \ru Установить параметры. \en Set the parameters. + void SetParameters( const MbToolStampingValues & params ) { parameters = params; } private: OBVIOUS_PRIVATE_COPY( MbUserStampSolid ) DECLARE_PERSISTENT_CLASS_NEW_DEL( MbUserStampSolid ) -}; +}; // MbUserStampSolid IMPL_PERSISTENT_OPS( MbUserStampSolid ) @@ -251,4 +251,5 @@ MbFaceShell * MakeUserStampShellForStampParts ( c3d::ShellSPtr & const MbeCopyMode sameShellTool, const MbStampWithToolPartsParams & params ); -#endif // __CR_USERSTAMP_SOLID_H + +#endif // __CR_STAMP_USER_SOLID_H diff --git a/C3d/Include/cr_stitch_solid.h b/C3d/Include/cr_stitch_solid.h index fc7c4c5..304a79d 100644 --- a/C3d/Include/cr_stitch_solid.h +++ b/C3d/Include/cr_stitch_solid.h @@ -197,6 +197,8 @@ public : private: MbStitchedSolid( const MbStitchedSolid & init, MbRegDuplicate * ireg ); + // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. + MbStitchedSolid( const MbStitchedSolid & ); public: virtual ~MbStitchedSolid(); @@ -224,19 +226,17 @@ public: // \ru Общие функции твердого тела \en Common functions of solid bool CreateShell( MbFaceShell *& shell, - MbeCopyMode sameShell, - RPArray * items = nullptr ) override; // \ru Построение \en Construction + MbeCopyMode sameShell, + RPArray * items = nullptr ) override; // \ru Построение \en Construction void SetYourVersion( VERSION version, bool forAll ) override; private: - // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. - MbStitchedSolid( const MbStitchedSolid & ); // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. MbStitchedSolid & operator = ( const MbStitchedSolid & ); DECLARE_PERSISTENT_CLASS_NEW_DEL( MbStitchedSolid ) -}; +}; // MbStitchedSolid IMPL_PERSISTENT_OPS( MbStitchedSolid ) diff --git a/C3d/Include/cr_surface_spline.h b/C3d/Include/cr_surface_spline.h index bf430bd..990104d 100644 --- a/C3d/Include/cr_surface_spline.h +++ b/C3d/Include/cr_surface_spline.h @@ -83,14 +83,15 @@ public : /** \} */ private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation, to prevent an assignment by default. - void operator = ( const MbSurfaceSplineCreator & ); // \ru Не реализовано!!! \en Not implemented!!! + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation, to prevent an assignment by default. + void operator = ( const MbSurfaceSplineCreator & ); // \ru Не реализовано!!! \en Not implemented!!! DECLARE_PERSISTENT_CLASS_NEW_DEL( MbSurfaceSplineCreator ) }; IMPL_PERSISTENT_OPS( MbSurfaceSplineCreator ) + //------------------------------------------------------------------------------ /** \brief \ru Создать кривую на поверхности. \en Create a curve on a surface. \~ diff --git a/C3d/Include/cr_swept_solid.h b/C3d/Include/cr_swept_solid.h index dd4502f..569e577 100644 --- a/C3d/Include/cr_swept_solid.h +++ b/C3d/Include/cr_swept_solid.h @@ -99,7 +99,7 @@ public : \en \name Common functions of the rigid solid (forming operations). \{ */ bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; // \ru Построение \en Construction + RPArray * items = nullptr ) override; // \ru Построение \en Construction virtual MbFaceShell * InitShell( bool in ) = 0; virtual void InitBasis( RPArray & ) = 0; @@ -108,15 +108,16 @@ public : void SetOperation( OperationType op ) { operation = op; } /** \} */ protected : - /// \ru Удалить строители ближайшего тела. \en Delete internal creators. - void DeleteCreators(); + /// \ru Удалить строители ближайшего тела. \en Delete internal creators. + void DeleteCreators(); private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbCurveSweptSolid & ); + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbCurveSweptSolid & ); DECLARE_PERSISTENT_CLASS( MbCurveSweptSolid ) }; // MbCurveSweptSolid IMPL_PERSISTENT_OPS( MbCurveSweptSolid ) + #endif // __CR_SWEPT_SOLID_H diff --git a/C3d/Include/cr_symmetry_solid.h b/C3d/Include/cr_symmetry_solid.h index 8eeb27c..67e3bd8 100644 --- a/C3d/Include/cr_symmetry_solid.h +++ b/C3d/Include/cr_symmetry_solid.h @@ -63,17 +63,18 @@ public : // \ru Общие функции твердого тела \en Common functions of solid bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; // \ru Построение \en Construction + RPArray * items = nullptr ) override; // \ru Построение \en Construction private : - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbSymmetrySolid & ); + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbSymmetrySolid & ); DECLARE_PERSISTENT_CLASS_NEW_DEL( MbSymmetrySolid ) }; // MbSymmetrySolid IMPL_PERSISTENT_OPS( MbSymmetrySolid ) + //------------------------------------------------------------------------------ /** \brief \ru Создать симметричную оболочку. \en Create a symmetric shell. \~ diff --git a/C3d/Include/cr_thin_sheet.h b/C3d/Include/cr_thin_sheet.h index dab4ceb..cb92e3e 100644 --- a/C3d/Include/cr_thin_sheet.h +++ b/C3d/Include/cr_thin_sheet.h @@ -63,16 +63,16 @@ public : // \ru Общие функции твердого тела \en Common functions of solid solid bool CreateShell( MbFaceShell *&shell, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; // \ru Построение \en Construction + RPArray * items = nullptr ) override; // \ru Построение \en Construction - // \ru Дать параметры. \en Get the parameters. - void GetParameters( SweptValues & params ) const { params = parameters; } - // \ru Установить параметры. \en Set the parameters. - void SetParameters( const SweptValues & params ) { parameters = params; } + // \ru Дать параметры. \en Get the parameters. + void GetParameters( SweptValues & params ) const { params = parameters; } + // \ru Установить параметры. \en Set the parameters. + void SetParameters( const SweptValues & params ) { parameters = params; } private : - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbThinShellCreator & ); + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbThinShellCreator & ); DECLARE_PERSISTENT_CLASS_NEW_DEL( MbThinShellCreator ) }; // MbThinShellCreator @@ -171,4 +171,5 @@ MATH_FUNC (MbCreator *) CreateLoftedShell( const MbLoftedCurvesShellParams & par MbResultType & res, MbFaceShell *& shell ); + #endif // __CR_THIN_SHEET_H diff --git a/C3d/Include/cr_thin_shell_solid.h b/C3d/Include/cr_thin_shell_solid.h index 73c7d2e..b057040 100644 --- a/C3d/Include/cr_thin_shell_solid.h +++ b/C3d/Include/cr_thin_shell_solid.h @@ -79,12 +79,12 @@ public : // \ru Общие функции твердого тела \en Common functions of solid bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; // \ru Построение \en Construction + RPArray * items = nullptr ) override; // \ru Построение \en Construction - /// \ru Дать параметры. \en Get the parameters. - void GetParameters( SweptValues & params ) const { params = parameters; } - /// \ru Установить параметры. \en Set the parameters. - void SetParameters( const SweptValues & params ) { parameters = params; } + /// \ru Дать параметры. \en Get the parameters. + void GetParameters( SweptValues & params ) const { params = parameters; } + /// \ru Установить параметры. \en Set the parameters. + void SetParameters( const SweptValues & params ) { parameters = params; } DECLARE_PERSISTENT_CLASS_NEW_DEL( MbShellSolid ) OBVIOUS_PRIVATE_COPY( MbShellSolid ) @@ -92,6 +92,7 @@ OBVIOUS_PRIVATE_COPY( MbShellSolid ) IMPL_PERSISTENT_OPS( MbShellSolid ) + //------------------------------------------------------------------------------ /** \brief \ru Создать эквидистантную оболочку с общим эквидистантным смещением. \en Create an offset shell with the common offset distance. \~ diff --git a/C3d/Include/cr_transformed_solid.h b/C3d/Include/cr_transformed_solid.h index dd35c7a..b70d11b 100644 --- a/C3d/Include/cr_transformed_solid.h +++ b/C3d/Include/cr_transformed_solid.h @@ -58,25 +58,26 @@ public: // \ru Общие функции математического объе /// \ru Построение оболочки \en Creation of a shell bool CreateShell( MbFaceShell *&, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; + RPArray * items = nullptr ) override; void Refresh( MbFaceShell & ) override; ///< \ru Обновить форму оболочки \en Update shape of the shell - // \ru Добавить модификацию по матрице \en Add a modification by a matrix - void AddMatrix( MbFaceShell &, const MbMatrix3D & ); + // \ru Добавить модификацию по матрице \en Add a modification by a matrix + void AddMatrix( MbFaceShell &, const MbMatrix3D & ); - // \ru Дать параметры. \en Get the parameters. - void GetParameters( TransformValues & params ) const { params = parameters; } - // \ru Установить параметры. \en Set the parameters. - void SetParameters( const TransformValues & params ) { parameters = params; } + // \ru Дать параметры. \en Get the parameters. + void GetParameters( TransformValues & params ) const { params = parameters; } + // \ru Установить параметры. \en Set the parameters. + void SetParameters( const TransformValues & params ) { parameters = params; } private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbTransformedSolid & ); + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbTransformedSolid & ); DECLARE_PERSISTENT_CLASS_NEW_DEL( MbTransformedSolid ) -}; +}; // MbTransformedSolid IMPL_PERSISTENT_OPS( MbTransformedSolid ) + //------------------------------------------------------------------------------ /** \brief \ru Создание строителя масштабированной оболочки. \en Creation of constructor of a scaled shell. \~ diff --git a/C3d/Include/cr_truncated_shell.h b/C3d/Include/cr_truncated_shell.h index c022efc..f09e746 100644 --- a/C3d/Include/cr_truncated_shell.h +++ b/C3d/Include/cr_truncated_shell.h @@ -90,17 +90,18 @@ public: // \ru Построение оболочки по исходным данным \en Construction of a shell from the given data bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; + RPArray * items = nullptr ) override; - // \ru Установить номера выбраных граней усекаемого тела \en Set indices of selected faces of the solid being truncated. - void SetSelIndices( const std::vector & selInds ); + // \ru Установить номера выбраных граней усекаемого тела \en Set indices of selected faces of the solid being truncated. + void SetSelIndices( const std::vector & selInds ); -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbTruncatedShell ) -OBVIOUS_PRIVATE_COPY( MbTruncatedShell ) -}; + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbTruncatedShell ) + OBVIOUS_PRIVATE_COPY( MbTruncatedShell ) +}; // MbTruncatedShell IMPL_PERSISTENT_OPS( MbTruncatedShell ) + //------------------------------------------------------------------------------ /** \brief \ru Построить усечённую оболочку. \en Build a truncated shell. \~ diff --git a/C3d/Include/cr_union_solid.h b/C3d/Include/cr_union_solid.h index 5ce4437..b3b8b8f 100644 --- a/C3d/Include/cr_union_solid.h +++ b/C3d/Include/cr_union_solid.h @@ -102,35 +102,35 @@ public : // \ru Общие функции твердого тела \en Common functions of solid bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = nullptr ) override; // \ru Построение \en Construction + RPArray * items = nullptr ) override; // \ru Построение \en Construction void SetYourVersion( VERSION version, bool forAll ) override; -public: - /// \ru Тип булевой операции над телами. \en Type of Boolean operation on solids. - OperationType GetOperationType() const { return operation; } - /// \ru Угловое отклонение при движении по кривым и поверхностям. \en Angular deviation while moving along curves and surfaces. - double GetBuildSag() const { return buildSag; } + /// \ru Тип булевой операции над телами. \en Type of Boolean operation on solids. + OperationType GetOperationType() const { return operation; } + /// \ru Угловое отклонение при движении по кривым и поверхностям. \en Angular deviation while moving along curves and surfaces. + double GetBuildSag() const { return buildSag; } - /// \ru Общее количество строителей. \en Total count of creators. - size_t GetCreatorsCount() const { return creators.size(); } - /// \ru Дать строитель. \en Get the creator. - const MbCreator * GetCreator( size_t k ) const { return ((k < creators.size()) ? &(*creators[k]) : nullptr); } - /// \ru Дать строитель. \en Get the creator. - MbCreator * SetCreator( size_t k ) { return ((k < creators.size()) ? &(*creators[k]) : nullptr); } + /// \ru Общее количество строителей. \en Total count of creators. + size_t GetCreatorsCount() const { return creators.size(); } + /// \ru Дать строитель. \en Get the creator. + const MbCreator * GetCreator( size_t k ) const { return ((k < creators.size()) ? &(*creators[k]) : nullptr); } + /// \ru Дать строитель. \en Get the creator. + MbCreator * SetCreator( size_t k ) { return ((k < creators.size()) ? &(*creators[k]) : nullptr); } + + /// \ru Собрать группы общих строителей тел. \en Collect groups of shared creators. + static size_t CollectSharedCreators( c3d::CreatorsSPtrVector & creators, c3d::IndicesVector & countNumbers, c3d::IndicesVector & sharedLinks ); -public: - /// \ru Собрать группы общих строителей тел. \en Collect groups of shared creators. - static size_t CollectSharedCreators( c3d::CreatorsSPtrVector & creators, c3d::IndicesVector & countNumbers, c3d::IndicesVector & sharedLinks ); private : - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbUnionSolid & ); + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbUnionSolid & ); DECLARE_PERSISTENT_CLASS_NEW_DEL( MbUnionSolid ) }; // MbUnionSolid IMPL_PERSISTENT_OPS( MbUnionSolid ) + //------------------------------------------------------------------------------ /** \brief \ru Создать оболочку булевой операции множества оболочек. \en Create a shell of Boolean operation of shell set. \~ diff --git a/C3d/Include/creator.h b/C3d/Include/creator.h index 334e21f..00753d1 100644 --- a/C3d/Include/creator.h +++ b/C3d/Include/creator.h @@ -424,7 +424,7 @@ public : \return \ru Выполнено ли построение. \en Whether the construction is performed. \~ */ - bool CreateWireFrame( SPtr & frame, MbeCopyMode sameShell ); + bool CreateWireFrame( SPtr & frame, MbeCopyMode sameShell ); /** \brief \ru Построить точечный каркас по исходным данным. \en Create a point-frame from the source data. \~ @@ -453,7 +453,7 @@ public : \return \ru Выполнено ли построение. \en Whether the construction is performed. \~ */ - bool CreatePointFrame( SPtr & frame, MbeCopyMode sameShell ); + bool CreatePointFrame( SPtr & frame, MbeCopyMode sameShell ); /** \brief \ru Создать полигональный объект по исходным данным. \en Create a polygonal object from the source data. \~ @@ -482,7 +482,7 @@ public : \return \ru Выполнено ли построение. \en Whether the construction is performed. \~ */ - bool CreateMesh( SPtr & mesh, MbeCopyMode sameShell ); + bool CreateMesh( SPtr & mesh, MbeCopyMode sameShell ); /// \ru Выдать свойства объекта. \en Get properties of the object. virtual void GetProperties( MbProperties & ); @@ -509,44 +509,45 @@ public : /// \ru Переместить/Изменить строитель. \en Displace/Change the creator. virtual bool Perform( MbCreator * ) const; - /// \ru Установить версию объектов. \en Set the objects version. + /// \ru Установить версию объектов. \en Set the objects version. virtual void SetYourVersion( VERSION version, bool forAll ); - /// \ru Выдать версию объекта. \en Get the object version. - VERSION GetYourVersion() const { return names->GetMathVersion(); } + /// \ru Выдать версию объекта. \en Get the object version. + VERSION GetYourVersion() const { return names->GetMathVersion(); } - /// \ru Выдать именователь объекта. \en Get the name-maker. - const MbSNameMaker & GetYourNameMaker() const { return *names; } - /// \ru Выдать именователь объекта для редактирования. \en Get the object's name-maker for editing. - MbSNameMaker & SetYourNameMaker() { return *names; } - /// \ru Установить именователь объекта. \en Set the object's name-maker. - void SetNameMaker( const MbSNameMaker & n ) { names->SetNameMaker( n ); } + /// \ru Выдать именователь объекта. \en Get the name-maker. + const MbSNameMaker & GetYourNameMaker() const { return *names; } + /// \ru Выдать именователь объекта для редактирования. \en Get the object's name-maker for editing. + MbSNameMaker & SetYourNameMaker() { return *names; } + /// \ru Установить именователь объекта. \en Set the object's name-maker. + void SetNameMaker( const MbSNameMaker & n ) { names->SetNameMaker( n ); } - /// \ru Выдать главное имя объекта. \en Get the main name of the object. - SimpleName GetMainName() const { return names->GetMainName(); } - /// \ru Установить главное имя объекта. \en Set the main name of the object. - void SetMainName( SimpleName n ) { names->SetMainName(n); } - /// \ru Выдать флаг состояния. \en Get the flag of state. - MbeProcessState GetStatus() const { return status; } - /// \ru Установить флаг состояния. \en Set the flag of state. - void SetStatus( MbeProcessState l ) { status = l; } + /// \ru Выдать главное имя объекта. \en Get the main name of the object. + SimpleName GetMainName() const { return names->GetMainName(); } + /// \ru Установить главное имя объекта. \en Set the main name of the object. + void SetMainName( SimpleName n ) { names->SetMainName(n); } + /// \ru Выдать флаг состояния. \en Get the flag of state. + MbeProcessState GetStatus() const { return status; } + /// \ru Установить флаг состояния. \en Set the flag of state. + void SetStatus( MbeProcessState l ) { status = l; } + + /** \brief \ru Регистрировать объект. + \en Register the object. \~ + \details \ru Регистрация объекта для предотвращения его многократной записи. + Другие объекты могут содержать указатель на данный объект. + Функция взводит флаг, который позволяет записывать объект один раз, а в остальных записях ссылаться на записанный экземпляр. + Чтение так же выполняется один раз, а в остальных случаях чтения подставляется адрес уже прочитанного объекта. + \en Object registration for preventing its multiple writing. + Other objects may contain a pointer to the given object. + The function sets a flag that allow to write the object once and to use the references to the recorded instance in the other records. + Reading is performed once too, in other cases of reading the address of the already read object is used. \~ + */ + void PrepareWrite() const { SetRegistrable( (GetUseCount() > 1) ? registrable : noRegistrable ); } - /** \brief \ru Регистрировать объект. - \en Register the object. \~ - \details \ru Регистрация объекта для предотвращения его многократной записи. - Другие объекты могут содержать указатель на данный объект. - Функция взводит флаг, который позволяет записывать объект один раз, а в остальных записях ссылаться на записанный экземпляр. - Чтение так же выполняется один раз, а в остальных случаях чтения подставляется адрес уже прочитанного объекта. - \en Object registration for preventing its multiple writing. - Other objects may contain a pointer to the given object. - The function sets a flag that allow to write the object once and to use the references to the recorded instance in the other records. - Reading is performed once too, in other cases of reading the address of the already read object is used. \~ - */ - void PrepareWrite() const { SetRegistrable( (GetUseCount() > 1) ? registrable : noRegistrable ); } /** \} */ private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию \en Declaration without implementation of the assignment operator to prevent an assignment by default - MbCreator & operator = ( const MbCreator & ); + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию \en Declaration without implementation of the assignment operator to prevent an assignment by default + MbCreator & operator = ( const MbCreator & ); DECLARE_PERSISTENT_CLASS( MbCreator ) }; // MbCreator diff --git a/C3d/Include/cur_arc.h b/C3d/Include/cur_arc.h index d578ec2..62ee054 100644 --- a/C3d/Include/cur_arc.h +++ b/C3d/Include/cur_arc.h @@ -392,7 +392,7 @@ public : void Refresh() override; // \ru Сбросить все временные данные \en Flush all the temporary data void PrepareIntegralData( const bool forced ) const override; // \ru Рассчитать временные (mutable) данные объекта. \en Calculate temporary (mutable) data of an object. bool IsVisibleInRect( const MbRect & r, bool exact = false ) const override; // \ru Виден ли объект в заданном прямоугольнике \en Whether the object is visible in the given rectangle - using MbCurve::IsVisibleInRect; + using MbCurve::IsVisibleInRect; bool IsCompleteInRect( const MbRect & r ) const override; // \ru Виден ли объект полностью в в заданном прямоугольнике \en Whether the object is completely visible in the given rectangle /** \} */ /** \ru \name Функции описания области определения кривой. @@ -434,7 +434,7 @@ public : \{ */ // \ru Вычислить значения точки и производных для заданного параметра. \en Calculate point and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - MbCartPoint & pnt, MbVector & fir, MbVector * sec, MbVector * thir ) const override; + MbCartPoint & pnt, MbVector & fir, MbVector * sec, MbVector * thir ) const override; /** \} */ /** \ru \name Функции движения по кривой \en \name Functions of moving along the curve @@ -454,8 +454,8 @@ public : // \ru Посчитать метрическую длину дуги от параметра t1 до t2. \en Calculate the metric length of the arc from parameter 't1' to 't2'. double CalculateLength( double t1, double t2 ) const override; // \ru Сдвинуть параметр t на расстояние len по направлению \en Shift the parameter t by the distance 'len' in the direction - virtual bool DistanceAlong( double & t, double len, int curveDir, double eps = Math::LengthEps, - VERSION version = Math::DefaultMathVersion() ) const override; + bool DistanceAlong( double & t, double len, int curveDir, double eps = Math::LengthEps, + VERSION version = Math::DefaultMathVersion() ) const override; double PointProjection( const MbCartPoint & pnt ) const override; // \ru Проекция точки на кривую \en Projection of a point onto the curve bool NearPointProjection( const MbCartPoint & pnt, double xEpsilon, double yEpsilon, @@ -517,7 +517,7 @@ public : \return \ru true - если операция прошла успешно. Иначе возвращает false. \en True - if the operation succeeded. Otherwise returns false. \~ */ - bool ModifyByPoint( size_t ind, const MbCartPoint & pnt ); // \ru Модификация по характерным точкам \en Modification by the characteristic points + bool ModifyByPoint( size_t ind, const MbCartPoint & pnt ); // \ru Модификация по характерным точкам \en Modification by the characteristic points bool GetSpecificPoint( const MbCartPoint & from, double & dmax, MbCartPoint & pnt ) const override; void Isoclinal( const MbVector & angle, SArray & tFind ) const override; // \ru Прямые, проходящие под углом к оси 0X и касательные к кривой \en Lines passing angularly to the 0X axis and tangent to the curve @@ -527,21 +527,21 @@ public : MbResultType Extend( const MbCurveExtensionParameters & parameters, c3d::PlaneCurveSPtr & resCurve ) const override; /// \ru Проверить с заданной точностью, является ли эллипс окружностью. \en Check whether the ellipse is a circle with a given tolerance. - bool IsCircle( double eps = PARAM_EPSILON ) const; + bool IsCircle( double eps = PARAM_EPSILON ) const; /** \} */ /** \ru \name Функции в локальной системе координат плейсмента объекта. \en \name Functions in the local coordinate system of object placement. \{ */ - /// \ru Выдать локальную систему координат объекта. \en Get the local coordinate system of an object. + /// \ru Выдать локальную систему координат объекта. \en Get the local coordinate system of an object. const MbPlacement & GetPlacement() const { return position; } - /// \ru Изменить локальную систему координат объекта. \en Modify the local coordinate system of the object. - void SetPlacement( const MbPlacement & pl ) { position = pl; Refresh(); } - /// \ru Определить, является ли локальная система координат ортонормированной. \en Determine whether the local coordinate system is orthonormalized. - bool IsPositionNormal() const { return ( position.IsNormal() ); } - /// \ru Определить, является ли локальная система координат ортогональной с равными по длине осями X,Y. \en Determine whether the local coordinate system is orthogonal with X and Y axes equal by length. - bool IsPositionCircular() const { return ( position.IsCircular() ); } - /// \ru Определить, является ли локальная система координат ортогональной и изотропной по осям. \en Determine whether the local coordinate system is orthogonal and isotropic by the axes. - bool IsPositionIsotropic() const { return ( position.IsIsotropic()); } + /// \ru Изменить локальную систему координат объекта. \en Modify the local coordinate system of the object. + void SetPlacement( const MbPlacement & pl ) { position = pl; Refresh(); } + /// \ru Определить, является ли локальная система координат ортонормированной. \en Determine whether the local coordinate system is orthonormalized. + bool IsPositionNormal() const { return ( position.IsNormal() ); } + /// \ru Определить, является ли локальная система координат ортогональной с равными по длине осями X,Y. \en Determine whether the local coordinate system is orthogonal with X and Y axes equal by length. + bool IsPositionCircular() const { return ( position.IsCircular() ); } + /// \ru Определить, является ли локальная система координат ортогональной и изотропной по осям. \en Determine whether the local coordinate system is orthogonal and isotropic by the axes. + bool IsPositionIsotropic() const { return ( position.IsIsotropic()); } /** \brief \ru Вычислить угол в локальной системе координат. \en Calculate the angle in the local coordinate system. \~ @@ -554,7 +554,7 @@ public : \return \ru Значение угла. \en Value of angle. \~ */ - double GetPositionAngle( const MbCartPoint & p ) const; // \ru Вычисление угла в локальной системе \en Calculation of angle in the local system + double GetPositionAngle( const MbCartPoint & p ) const; // \ru Вычисление угла в локальной системе \en Calculation of angle in the local system /** \brief \ru Инициализация параметров эллипса. \en Initialization of the ellipse parameters. \~ @@ -573,53 +573,53 @@ public : \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 ); // \ru Инициализация параметров по значениям углов в локальной системе \en Initialization of the parameters by values of angles in the local system /** \} */ /** \ru \name Функции для работы с данными. \en \name Functions for working with data. \{ */ - double GetR() const { return a; } ///< \ru Вернуть радиус или длину полуоси вдоль X для эллипса. \en Return the radius and the length of semiaxis along X for the ellipse - double GetRadiusA() const { return a; } ///< \ru Вернуть длину полуоси вдоль X. \en Return the length of semiaxis along X. - double GetRadiusB() const { return b; } ///< \ru Вернуть длину полуоси вдоль Y. \en Return the length of semiaxis along Y. - void SetRadiusA( double aa ) { a = aa; Refresh(); } ///< \ru Установить длину полуоси вдоль X. \en Set the length of semiaxis along X. - void SetRadiusB( double bb ) { b = bb; Refresh(); } ///< \ru Установить длину полуоси вдоль Y. \en Set the length of semiaxis along Y. - double GetAngle() const { return (trim2 - trim1); } ///< \ru Вернуть угол раствора дуги. \en Return the arc opening angle. - /// \ru Установить угол раствора дуги. Начальная точка дуги остается неизменной. \en Set the arc opening angle. The start point of the arc remains unchanged. - void SetAngle ( double ang ) { InitByPositionAngles( trim1, sense ? (trim1+ang) : (trim1-ang), sense ); } + double GetR() const { return a; } ///< \ru Вернуть радиус или длину полуоси вдоль X для эллипса. \en Return the radius and the length of semiaxis along X for the ellipse + double GetRadiusA() const { return a; } ///< \ru Вернуть длину полуоси вдоль X. \en Return the length of semiaxis along X. + double GetRadiusB() const { return b; } ///< \ru Вернуть длину полуоси вдоль Y. \en Return the length of semiaxis along Y. + void SetRadiusA( double aa ) { a = aa; Refresh(); } ///< \ru Установить длину полуоси вдоль X. \en Set the length of semiaxis along X. + void SetRadiusB( double bb ) { b = bb; Refresh(); } ///< \ru Установить длину полуоси вдоль Y. \en Set the length of semiaxis along Y. + double GetAngle() const { return (trim2 - trim1); } ///< \ru Вернуть угол раствора дуги. \en Return the arc opening angle. + /// \ru Установить угол раствора дуги. Начальная точка дуги остается неизменной. \en Set the arc opening angle. The start point of the arc remains unchanged. + void SetAngle ( double ang ) { InitByPositionAngles( trim1, sense ? (trim1+ang) : (trim1-ang), sense ); } - /// \ru Вычислить угол между осями OX локальной и глобальной системой координат. \en Calculate the angle between OX axes of the local and the global coordinate systems. - double GetMajorAxisAngle() const { return position.GetAxisX().DirectionAngle(); } + /// \ru Вычислить угол между осями OX локальной и глобальной системой координат. \en Calculate the angle between OX axes of the local and the global coordinate systems. + double GetMajorAxisAngle() const { return position.GetAxisX().DirectionAngle(); } - double GetTrim1() const { return trim1; } ///< \ru Вернуть параметр начальной точки. \en Return the parameter of the start point. - double GetTrim2() const { return trim2; } ///< \ru Вернуть параметр конечной точки. \en Return the parameter of the end point. - int GetSense() const { return trim2 > trim1 ? 1 : -1; } ///< \ru Определить флаг совпадения направления с направлением базовой кривой. \en Determine the flag of coincidence of the direction with the base curve direction. - void SetTrim1( double t ) { trim1 = t; InitByPositionAngles( trim1, trim2, sense ); } ///< \ru Установить параметр начальной точки. \en Set the parameter of the start point. - void SetTrim2( double t ) { trim2 = t; InitByPositionAngles( trim1, trim2, sense ); } ///< \ru Установить параметр конечной точки. \en Set the parameter of the end point. + double GetTrim1() const { return trim1; } ///< \ru Вернуть параметр начальной точки. \en Return the parameter of the start point. + double GetTrim2() const { return trim2; } ///< \ru Вернуть параметр конечной точки. \en Return the parameter of the end point. + int GetSense() const { return trim2 > trim1 ? 1 : -1; } ///< \ru Определить флаг совпадения направления с направлением базовой кривой. \en Determine the flag of coincidence of the direction with the base curve direction. + void SetTrim1( double t ) { trim1 = t; InitByPositionAngles( trim1, trim2, sense ); } ///< \ru Установить параметр начальной точки. \en Set the parameter of the start point. + void SetTrim2( double t ) { trim2 = t; InitByPositionAngles( trim1, trim2, sense ); } ///< \ru Установить параметр конечной точки. \en Set the parameter of the end point. - /// \ru Установить радиус дуги окружности. \en Set the radius of the circular arc. - void SetRadius( double rad ) { - a = rad; - b = rad; - Refresh(); - } - /// \ru Установить центр. \en Set the center. - void SetCentre( const MbCartPoint & c ) { - position.SetOrigin( c ); // \ru Установить центр \en Set the center - Refresh(); - } - /// \ru Установить направление дуги. \en Set the arc orientation. - void SetDirection( bool clockwise ) { - int newSense = clockwise ? - 1 : + 1; - if ( newSense != GetSense() ) { - InitByPositionAngles( trim1, trim2, newSense ); - } - } - /// \ru Инициализировать дуги эллипса заданной дугой. \en Initialize elliptical arcs with the given arc. - void Init( const MbArc & ); - /// \ru Инициализировать окружность по центру и радиусу \en Initialize a circle by the center and the radius - void Init( const MbCartPoint & pc, double rad ); - /// \ru Инициализировать дугу по начальному и конечному параметрам. \en Initialize arc by parameters for begin point and end point. - void Init( double t1, double t2 ); + /// \ru Установить радиус дуги окружности. \en Set the radius of the circular arc. + void SetRadius( double rad ) { + a = rad; + b = rad; + Refresh(); + } + /// \ru Установить центр. \en Set the center. + void SetCentre( const MbCartPoint & c ) { + position.SetOrigin( c ); // \ru Установить центр \en Set the center + Refresh(); + } + /// \ru Установить направление дуги. \en Set the arc orientation. + void SetDirection( bool clockwise ) { + int newSense = clockwise ? - 1 : + 1; + if ( newSense != GetSense() ) { + InitByPositionAngles( trim1, trim2, newSense ); + } + } + /// \ru Инициализировать дуги эллипса заданной дугой. \en Initialize elliptical arcs with the given arc. + void Init( const MbArc & ); + /// \ru Инициализировать окружность по центру и радиусу \en Initialize a circle by the center and the radius + void Init( const MbCartPoint & pc, double rad ); + /// \ru Инициализировать дугу по начальному и конечному параметрам. \en Initialize arc by parameters for begin point and end point. + void Init( double t1, double t2 ); /** \brief \ru Инициализировать дугу окружности. \en Initialize a circular arc. \~ @@ -638,7 +638,7 @@ public : \param[in] cl - \ru Признак замкнутости. \en Closedness attribute. \~ */ - void Init3Points( const MbCartPoint & p1, const MbCartPoint & p2, const MbCartPoint & p3, bool cl ); + void Init3Points( const MbCartPoint & p1, const MbCartPoint & p2, const MbCartPoint & p3, bool cl ); /** \brief \ru Инициализировать дугу окружности. \en Initialize a circular arc. \~ @@ -655,7 +655,7 @@ public : \param[in] p3 - \ru Конец дуги. \en End of the arc. \~ */ - void InitCircle( const MbCartPoint & p1, const MbCartPoint & p2, const MbCartPoint & p3 ); + void InitCircle( const MbCartPoint & p1, const MbCartPoint & p2, const MbCartPoint & p3 ); /** \brief \ru Инициализировать дугу окружности. \en Initialize a circular arc. \~ @@ -668,7 +668,7 @@ public : \param[in] p2 - \ru Конец дуги. \en End of the arc. \~ */ - void InitArc( MbCartPoint & pc, const MbCartPoint & p1, const MbCartPoint & p2 ); + void InitArc( MbCartPoint & pc, const MbCartPoint & p1, const MbCartPoint & p2 ); /** \brief \ru Инициализировать дугу окружности. \en Initialize a circular arc. \~ @@ -695,7 +695,7 @@ public : \en Direction. clockwise > 0 - moving counterclockwise, clockwise < 0 - clockwise. 'clockwise' can't be equal to zero. \~ */ - void Init( const MbCartPoint & pc, double rad, + void Init( const MbCartPoint & pc, double rad, const MbCartPoint & p1, const MbCartPoint & p2, bool clockwise ); // \ru Инициализация по центру и точке на дуге ( 360 градусов ) \en Initialization by the center and a point on the arc (360 degrees) @@ -710,7 +710,7 @@ public : \param[in] p - \ru Точка на окружности. \en Point on circle. \~ */ - void Init( const MbCartPoint & pc, const MbCartPoint & p ); + void Init( const MbCartPoint & pc, const MbCartPoint & p ); // \ru Первая точка, угол, радиус ( 360 градусов ) \en The first point, angle and radius (360 degrees) /** \brief \ru Инициализировать окружность. @@ -728,7 +728,7 @@ public : \param[in] rad - \ru Радиус. \en Radius. \~ */ - void Init( const MbCartPoint & p1, double angle, double rad ); + void Init( const MbCartPoint & p1, double angle, double rad ); // \ru центр, точка на окружности, начальный угол ( 360 градусов ) \en Center, a point on the circle, initial angle (360 degrees) /** \brief \ru Инициализировать окружность. @@ -744,7 +744,7 @@ public : \param[in] angle - \ru Начальный параметр. \en Get the start parameter. \~ */ - void Init( const MbCartPoint & pc, const MbCartPoint & pnt, double angle ); + void Init( const MbCartPoint & pc, const MbCartPoint & pnt, double angle ); // \ru Центр, угол первой точки, угол второй точки, радиус, направление \en Centre, angle of the first point, angle of the second point, radius, direction /** \brief \ru Инициализировать дугу окружность. @@ -770,7 +770,7 @@ public : \en Direction. clockwise > 0 - moving counterclockwise, clockwise < 0 - clockwise. 'clockwise' can't be equal to zero. \~ */ - void Init( const MbCartPoint & pc, double angle1, double angle2, double rad, bool clockwise ); + void Init( const MbCartPoint & pc, double angle1, double angle2, double rad, bool clockwise ); // \ru центр, точка, номер точки, угол другой точки, направление \en Center, point, index of point, angle of another point, direction /** \brief \ru Инициализировать дугу окружность. @@ -794,7 +794,7 @@ public : \en Direction. clockwise > 0 - moving counterclockwise, clockwise < 0 - clockwise. 'clockwise' can't be equal to zero. \~ */ - void Init( const MbCartPoint & pc, const MbCartPoint & pnt, bool firstPoint, double angle, bool clockwise ); + void Init( const MbCartPoint & pc, const MbCartPoint & pnt, bool firstPoint, double angle, bool clockwise ); // \ru центр, угол первой точки, вторая точка, радиус, направление \en Center, angle of the first point, the second point, radius, direction /** \brief \ru Инициализировать дугу окружность. @@ -818,7 +818,7 @@ public : \en Direction. clockwise > 0 - moving counterclockwise, clockwise < 0 - clockwise. initSense can't be equal to zero. \~ */ - void Init( const MbCartPoint & pc, double angle1, const MbCartPoint & p2, double rad, bool clockwise ); + void Init( const MbCartPoint & pc, double angle1, const MbCartPoint & p2, double rad, bool clockwise ); // \ru Окружность, первая точка, вторая точка, направление \en Circle, the first point, the second point, direction /** \brief \ru Инициализировать дугу окружность. @@ -842,7 +842,7 @@ public : \en Direction. initSense > 0 - counterclockwise, initSense < 0 - clockwise. initSense can't be equal to zero. \~ */ - void Init( MbArc * obj, const MbCartPoint & p1, const MbCartPoint & p2, int initSense ); + void Init( MbArc * obj, const MbCartPoint & p1, const MbCartPoint & p2, int initSense ); // \ru Первая точка, вторая точка, угол, номер угла, направление \en The first point, the second point, angle, index of angle, direction /** \brief \ru Инициализировать дугу окружность. @@ -868,9 +868,9 @@ public : \en Direction. clockwise > 0 - moving counterclockwise, clockwise < 0 - clockwise. 'clockwise' can't be equal to zero. \~ */ - void Init( const MbCartPoint & p1, const MbCartPoint & p2, double angle, bool firstAngle, bool clockwise ); + void Init( const MbCartPoint & p1, const MbCartPoint & p2, double angle, bool firstAngle, bool clockwise ); - // \ru Плавающий центр, угол первой точки, угол второй точки, точка, номер точки, направление \en Variable center, angle of the first point, angle of the second point, index of the point, direction + // \ru Плавающий центр, угол первой точки, угол второй точки, точка, номер точки, направление \en Variable center, angle of the first point, angle of the second point, index of the point, direction /** \brief \ru Инициализировать дугу окружность. \en Initialize a circular arc. \~ \details \ru В результате операции получаем дугу окружности, одним из концов которой является точка pnt. @@ -898,10 +898,10 @@ public : \en Direction. clockwise > 0 - moving counterclockwise, clockwise < 0 - clockwise. 'clockwise' can't be equal to zero. \~ */ - void Init( MbCartPoint & pc, double angle1, double angle2, - const MbCartPoint & pnt, bool firstPoint, bool clockwise ); + void Init( MbCartPoint & pc, double angle1, double angle2, + const MbCartPoint & pnt, bool firstPoint, bool clockwise ); - // \ru Плавающий центр, точка, номер точки, угол противоположной точки, радиус, направление \en Variable center, point, index of the point, angle of the opposite point, radius, direction + // \ru Плавающий центр, точка, номер точки, угол противоположной точки, радиус, направление \en Variable center, point, index of the point, angle of the opposite point, radius, direction /** \brief \ru Инициализировать дугу окружность. \en Initialize a circular arc. \~ \details \ru Исходный объект изменяется на дугу окружности с заданным радиусом и проходящую через точку p. @@ -925,8 +925,8 @@ public : \en Direction. clockwise > 0 - moving counterclockwise, clockwise < 0 - clockwise. 'clockwise' can't be equal to zero. \~ */ - void Init( MbCartPoint & pc, const MbCartPoint & p, bool firstPoint, - double angle, double rad, bool clockwise ); + void Init( MbCartPoint & pc, const MbCartPoint & p, bool firstPoint, + double angle, double rad, bool clockwise ); /** \brief \ru Инициализировать дугу окружность. \en Initialize a circular arc. \~ @@ -949,11 +949,11 @@ public : \en Direction. initSense > 0 - counterclockwise, initSense < 0 - clockwise. initSense can't be equal to zero. \~ */ - void Init( const MbCartPoint & pc, const MbCartPoint & p1, const MbCartPoint & p2, int initSense ); + void Init( const MbCartPoint & pc, const MbCartPoint & p1, const MbCartPoint & p2, int initSense ); - // \ru Инициализация по начальной и конечной точкам и 1/2 угла раствора дуги \en Initialization by the starting and end points and 1/2 of the arc opening angle - // \ru Если diskrData != nullptr, то округлить радиус и скорректировать первую \en If diskrData != nullptr, then round the radius and correct the first - // \ru Или вторую точку (зависит от correctFirstPnt) \en Or the second point (depends on correctFirstPnt) + // \ru Инициализация по начальной и конечной точкам и 1/2 угла раствора дуги \en Initialization by the starting and end points and 1/2 of the arc opening angle + // \ru Если diskrData != nullptr, то округлить радиус и скорректировать первую \en If diskrData != nullptr, then round the radius and correct the first + // \ru Или вторую точку (зависит от correctFirstPnt) \en Or the second point (depends on correctFirstPnt) /** \brief \ru Инициализировать дугу окружность. \en Initialize a circular arc. \~ \details \ru Инициализация происходит по начальной и конечной точкам и 1/2 угла раствора дуги. @@ -975,10 +975,11 @@ public : \en Determines which point to be corrected after the rounding. correctFirstPnt == true - the first point is to be corrected. \~ */ - void Init( double a2, MbCartPoint & p1, MbCartPoint & p2, - const DiskreteLengthData * diskrData = nullptr, - bool correctFirstPnt = true ); - // \ru Инициализация эллипса \en Ellipse initialization + void Init( double a2, MbCartPoint & p1, MbCartPoint & p2, + const DiskreteLengthData * diskrData = nullptr, + bool correctFirstPnt = true ); + + // \ru Инициализация эллипса \en Ellipse initialization /** \brief \ru Инициализировать эллипс. \en Initialize an ellipse. \~ \details \ru В результате операции получаем эллипс с заданными локальной системой координат и полуосями. @@ -990,7 +991,7 @@ public : \param[in] place - \ru Локальная система координат эллипса. \en The local coordinate system of the ellipse. \~ */ - void Init( double aa, double bb, const MbPlacement & place ); + void Init( double aa, double bb, const MbPlacement & place ); /** \brief \ru Инициализировать эллипс. \en Initialize an ellipse. \~ @@ -1011,7 +1012,7 @@ public : \param[in] ang - \ru Угол между осями OX локальной и текущей системами координат. \en An angle between OX axes of the local and the current coordinate systems. \~ */ - void Init( double aa, double bb, const MbCartPoint & pc, double ang ); + void Init( double aa, double bb, const MbCartPoint & pc, double ang ); // \ru Различные варианты построения эллипса \en Different variants of ellipse construction /** \brief \ru Инициализировать эллипс. @@ -1033,8 +1034,8 @@ public : \param[out] angle - \ru Угол между осями OX локальной и текущей системами координат. \en An angle between OX axes of the local and the current coordinate systems. \~ */ - void Init1( const MbCartPoint & c, const MbCartPoint & p1, - double & len, double & angle ); + void Init1( const MbCartPoint & c, const MbCartPoint & p1, + double & len, double & angle ); /** \brief \ru Инициализировать эллипс. \en Initialize an ellipse. \~ @@ -1055,8 +1056,8 @@ public : \param[out] lenB - \ru Длина полуоси вдоль Y. \en The length of semiaxis along Y. \~ */ - void Init2( const MbCartPoint & c, const MbCartPoint & p1, - MbCartPoint & p2, double & lenB ); + void Init2( const MbCartPoint & c, const MbCartPoint & p1, + MbCartPoint & p2, double & lenB ); /** \brief \ru Инициализировать эллипс. \en Initialize an ellipse. \~ \details \ru В результате операции получаем эллипс, вписанный в повернутый прямоугольник, @@ -1076,8 +1077,8 @@ public : \param[out] bb - \ru Длина полуоси вдоль Y. \en The length of semiaxis along Y. \~ */ - void Init3( const MbCartPoint & c0, const MbCartPoint & p1, - double angle, double & aa, double & bb ); + void Init3( const MbCartPoint & c0, const MbCartPoint & p1, + double angle, double & aa, double & bb ); /** \brief \ru Инициализировать эллипс. \en Initialize an ellipse. \~ @@ -1098,8 +1099,8 @@ public : \param[out] bb - \ru Длина полуоси вдоль Y. \en The length of semiaxis along Y. \~ */ - void Init4( const MbCartPoint & p1, const MbCartPoint & p2, - double angle, double & aa, double & bb ); + void Init4( const MbCartPoint & p1, const MbCartPoint & p2, + double angle, double & aa, double & bb ); /** \brief \ru Инициализировать эллипс. \en Initialize an ellipse. \~ @@ -1124,8 +1125,8 @@ public : \param[out] angle - \ru Угол между осями OX локальной и текущей системами координат. \en An angle between OX axes of the local and the current coordinate systems. \~ */ - void Init5( const MbCartPoint & c, const MbCartPoint & p1, const MbCartPoint & p2, - double & aa, double & bb, double & angle ); + void Init5( const MbCartPoint & c, const MbCartPoint & p1, const MbCartPoint & p2, + double & aa, double & bb, double & angle ); /** \brief \ru Инициализировать эллипс. \en Initialize an ellipse. \~ @@ -1148,8 +1149,8 @@ public : \param[out] angle - \ru Угол между осями OX локальной и текущей системами координат. \en An angle between OX axes of the local and the current coordinate systems. \~ */ - void Init6( const MbCartPoint & p1, const MbCartPoint & p2, const MbCartPoint & p3, - double & aa, double & bb, double & angle ); + void Init6( const MbCartPoint & p1, const MbCartPoint & p2, const MbCartPoint & p3, + double & aa, double & bb, double & angle ); /** \brief \ru Инициализировать эллипс. \en Initialize an ellipse. \~ @@ -1172,9 +1173,9 @@ public : \param[out] angle - \ru Угол между осями OX локальной и текущей системами координат. \en An angle between OX axes of the local and the current coordinate systems. \~ */ - void Init7( const MbCartPoint & pc, - MbCartPoint p1, MbCartPoint p2, MbCartPoint p3, - double & aa, double & bb, double & angle ); + void Init7( const MbCartPoint & pc, + MbCartPoint p1, MbCartPoint p2, MbCartPoint p3, + double & aa, double & bb, double & angle ); /** \brief \ru Инициализировать эллипс. \en Initialize an ellipse. \~ @@ -1199,10 +1200,10 @@ public : \param[out] angle - \ru Угол между осями OX локальной и текущей системами координат. \en An angle between OX axes of the local and the current coordinate systems. \~ */ - void Init8( const MbCartPoint & p1, const MbDirection & dir1, - const MbCartPoint & p2, const MbDirection & dir2, - const MbCartPoint & p3, - double & aa, double & bb, double & angle ); + void Init8( const MbCartPoint & p1, const MbDirection & dir1, + const MbCartPoint & p2, const MbDirection & dir2, + const MbCartPoint & p3, + double & aa, double & bb, double & angle ); // \ru Различные варианты построения дуги эллипса \en Different variants of elliptical arc construction /** \brief \ru Инициализировать дугу эллипса. \en Initialize an elliptical arc. \~ @@ -1229,8 +1230,8 @@ public : \en Direction. initSense > 0 - counterclockwise, initSense < 0 - clockwise. initSense can't be equal to zero. \~ */ - void Init( double aa, double bb, const MbPlacement & place, - double t1, double t2, int initSense ); + void Init( double aa, double bb, const MbPlacement & place, + double t1, double t2, int initSense ); /** \brief \ru Инициализировать дугу эллипса. \en Initialize an elliptical arc. \~ @@ -1259,12 +1260,12 @@ public : \en Direction. clockwise > 0 - moving counterclockwise, clockwise < 0 - clockwise. 'clockwise' can't be equal to zero. \~ */ - void Init( double aa, double bb, const MbPlacement & place, - const MbCartPoint & p1, const MbCartPoint & p2, bool clockwise ); + void Init( double aa, double bb, const MbPlacement & place, + const MbCartPoint & p1, const MbCartPoint & p2, bool clockwise ); - // \ru Эллипс вписан в прямоугольник, заданный двумя диагональными точками p1, p2, \en Ellipse is inscribed into the rectangle given by two diagonal points p1, p2, - // \ru проекции точек pB и pE на эллипс определяют начало и конец дуги, \en The projections of points pB and pE onto ellipse determine the start and the end of the arc, - // \ru clockwise определяет движение от начальноц точки к конечной по часовой стрелке или против \en 'clockwise' determines moving from the starting point to the end point clockwise or counterclockwise + // \ru Эллипс вписан в прямоугольник, заданный двумя диагональными точками p1, p2, \en Ellipse is inscribed into the rectangle given by two diagonal points p1, p2, + // \ru проекции точек pB и pE на эллипс определяют начало и конец дуги, \en The projections of points pB and pE onto ellipse determine the start and the end of the arc, + // \ru clockwise определяет движение от начальноц точки к конечной по часовой стрелке или против \en 'clockwise' determines moving from the starting point to the end point clockwise or counterclockwise /** \brief \ru Инициализировать дугу эллипса. \en Initialize an elliptical arc. \~ \details \ru Эллипс вписан в прямоугольник, заданный двумя диагональными точками p1, p2. @@ -1288,10 +1289,10 @@ public : \en Direction. clockwise > 0 - moving counterclockwise, clockwise < 0 - clockwise. 'clockwise' can't be equal to zero. \~ */ - void Init4( const MbCartPoint & p1, const MbCartPoint & p2, - const MbCartPoint & pB, const MbCartPoint & pE, bool clockwise = false ); + void Init4( const MbCartPoint & p1, const MbCartPoint & p2, + const MbCartPoint & pB, const MbCartPoint & pE, bool clockwise = false ); - bool OnSector( const MbCartPoint & pnt ) const; ///< \ru Определить, находится ли луч от центра до точки в секторе дуги. \en Determine whether the ray from the center to the point is in the arc's sector. + bool OnSector( const MbCartPoint & pnt ) const; ///< \ru Определить, находится ли луч от центра до точки в секторе дуги. \en Determine whether the ray from the center to the point is in the arc's sector. /** \brief \ru Определить попадание в сектор дуги. \en Determine whether the ray hits the arc's sector. \~ @@ -1304,7 +1305,7 @@ public : \result \ru true, если направление попадает в сектор дуги. \en True if the direction hits the arc's sector. \~ */ - bool OnSector( double angle ) const; // \ru Находится угол в секторе дуги ? \en Is the angle in the arc's sector? + bool OnSector( double angle ) const; // \ru Находится угол в секторе дуги ? \en Is the angle in the arc's sector? /** \brief \ru Заменить точку дуги. \en Replace the arc's point. \~ @@ -1315,9 +1316,10 @@ public : \param[in] pnt - \ru Новая точка. \en A new point. \~ */ - void SetLimitPoint( ptrdiff_t number, const MbCartPoint & pnt ); // \ru Заменить точку дуги \en Replace the arc point - /// \ru Вернуть направление дуги: true - по часовой стрелке; false - против часовой стрелки. \en Return the arc direction: true - clockwise, false - counterclockwise. - bool IsClockwise() const { return ( position.IsLeft() == (GetSense() > 0) ); } + void SetLimitPoint( ptrdiff_t number, const MbCartPoint & pnt ); // \ru Заменить точку дуги \en Replace the arc point + + /// \ru Вернуть направление дуги: true - по часовой стрелке; false - против часовой стрелки. \en Return the arc direction: true - clockwise, false - counterclockwise. + bool IsClockwise() const { return ( position.IsLeft() == (GetSense() > 0) ); } /** \brief \ru Вернуть угол крайней точки дуги. \en Return the angle of the end point. \~ @@ -1328,14 +1330,14 @@ public : \result \ru Угол между направлением от центра к крайней точке и осью OX текущей системы координат. \en The angle between the direction from the center to the end point and OX-axis of the current coordinate system. \~ */ - double GetLimitAngle( ptrdiff_t number ) const { - double ang = ( number == 1 ) ? trim1 : trim2; - if ( position.IsLeft() ) - ang = -ang; - ang += GetMajorAxisAngle(); // \ru Угол с осью X \en Angle with X axis - c3d::NormalizeAngle( ang); - return ang; - } + double GetLimitAngle( ptrdiff_t number ) const { + double ang = ( number == 1 ) ? trim1 : trim2; + if ( position.IsLeft() ) + ang = -ang; + ang += GetMajorAxisAngle(); // \ru Угол с осью X \en Angle with X axis + c3d::NormalizeAngle( ang); + return ang; + } /** \brief \ru Изменить граничный угол дуги. \en Modify the end angle of the arc. \~ @@ -1346,22 +1348,22 @@ public : \result \ru Угол между направлением от центра к крайней точке и осью OX текущей системы координат. \en The angle between the direction from the center to the end point and OX-axis of the current coordinate system. \~ */ - void SetLimitAngle( ptrdiff_t number, const MbCartPoint & pnt ) { - if ( number == 1 ) - InitByPositionAngles( GetPositionAngle(pnt), trim2, GetSense() ); - else - InitByPositionAngles( trim1, GetPositionAngle(pnt), GetSense() ); - Refresh(); - } + void SetLimitAngle( ptrdiff_t number, const MbCartPoint & pnt ) { + if ( number == 1 ) + InitByPositionAngles( GetPositionAngle(pnt), trim2, GetSense() ); + else + InitByPositionAngles( trim1, GetPositionAngle(pnt), GetSense() ); + Refresh(); + } inline double CheckParam( double & t ) const; ///< \ru Установить параметр в область допустимых значений. \en Set the parameter to the range of the allowable values. inline void ParamToAngle( double & t ) const; ///< \ru Перевести параметр кривой в угол. \en Convert the parameter of the curve to the angle. inline void AngleToParam( double & t ) const; ///< \ru Перевести угол кривой в параметр кривой. \en Convert the curve angle to the curve parameter. - void ParameterInto( double &t ) const { AngleToParam( t ); } ///< \ru Перевести параметр базовой кривой в локальный параметр. \en Convert parameter of the base curve to the local parameter. - void ParameterFrom( double &t ) const { ParamToAngle( t ); } ///< \ru Перевести локальный параметр в параметр базовой кривой. \en Convert the local parameter to the parameter of the base curve. - bool IsBaseParamOn( double t, double eps = Math::paramEpsilon ) const; ///< \ru Определить, находится ли параметр базовой кривой в диапазоне усеченной кривой. \en Determine whether the parameter of the base curve is in range of the trimmed curve. + void ParameterInto( double &t ) const { AngleToParam( t ); } ///< \ru Перевести параметр базовой кривой в локальный параметр. \en Convert parameter of the base curve to the local parameter. + void ParameterFrom( double &t ) const { ParamToAngle( t ); } ///< \ru Перевести локальный параметр в параметр базовой кривой. \en Convert the local parameter to the parameter of the base curve. + bool IsBaseParamOn( double t, double eps = Math::paramEpsilon ) const; ///< \ru Определить, находится ли параметр базовой кривой в диапазоне усеченной кривой. \en Determine whether the parameter of the base curve is in range of the trimmed curve. // \ru Работа с базовым эллипсом \en Work with the basic ellipse /** \brief \ru Вычислить точку на эллипсе. @@ -1373,7 +1375,7 @@ public : \param[out] pnt - \ru Искомая точка. \en The required point. \~ */ - void PointOnBaseEllipse( double & t, MbCartPoint & pnt ) const; // \ru Точка на базовом эллипсе \en A point on the base ellipse + void PointOnBaseEllipse( double & t, MbCartPoint & pnt ) const; // \ru Точка на базовом эллипсе \en A point on the base ellipse /** \brief \ru Найти проекцию точки на эллипс. \en Find the projection of a point onto the ellipse. \~ @@ -1384,10 +1386,10 @@ public : \result \ru Параметр, соответствующий точке проекции. \en Parameter corresponding to the projected point. \~ */ - double PointProjectionOnBaseEllipse( const MbCartPoint & pnt ) const; // \ru Проекция на базовом эллипсе \en Projection onto the base ellipse + double PointProjectionOnBaseEllipse( const MbCartPoint & pnt ) const; // \ru Проекция на базовом эллипсе \en Projection onto the base ellipse - void MakeAsBaseEllipse(); ///< \ru Инициализировать как полный эллипс. \en Initialize as complete ellipse. - void CopyBaseEllipse( const MbArc & init ); ///< \ru Cкопировать базовый эллипс. \en Copy the base ellipse. + void MakeAsBaseEllipse(); ///< \ru Инициализировать как полный эллипс. \en Initialize as complete ellipse. + void CopyBaseEllipse( const MbArc & init ); ///< \ru Cкопировать базовый эллипс. \en Copy the base ellipse. /** \brief \ru Определить, самопересекается ли эквидистанта от эллипса. \en Determine whether the ellipse offset has self-intersections. \~ @@ -1396,14 +1398,15 @@ public : \result \ru true, если самопересекается. \en True if it has self-intersections. \~ */ - bool IsSelfIntersectOffset( double d ) const; // \ru Есть ли самопересечения \en Whether there are self-intersections - // \ru Рассчитать коэффициенты неявного представления эллипса для IGES: Ax2 + Bxy + Cy2 + Dx + Ey + F = 0 \en Calculate coefficients of ellipse's implicit representation for IGES: Ax2 + Bxy + Cy2 + Dx + Ey + F = 0 - bool ParametricToCanonicConic( double & A, double & B, double & C, - double & D, double & E, double & F, - double & X1, double & Y1, double & X2, double & Y2 ) const; - bool Normalize(); ///< \ru Ортонормировать локальную систему координат. \en Orthonormalize the local coordinate system. - void GetControlPoints( SArray & points ); ///< \ru Заполнить массив контрольными точками. \en Fill the array with the control points. - void NormalizeTransform( const MbMatrix & mt ); ///< \ru Ортонормировать плейсмент при трансформировании. \en Orthonormalize the placement when transforming. + bool IsSelfIntersectOffset( double d ) const; // \ru Есть ли самопересечения \en Whether there are self-intersections + + // \ru Рассчитать коэффициенты неявного представления эллипса для IGES: Ax2 + Bxy + Cy2 + Dx + Ey + F = 0 \en Calculate coefficients of ellipse's implicit representation for IGES: Ax2 + Bxy + Cy2 + Dx + Ey + F = 0 + bool ParametricToCanonicConic( double & A, double & B, double & C, + double & D, double & E, double & F, + double & X1, double & Y1, double & X2, double & Y2 ) const; + bool Normalize(); ///< \ru Ортонормировать локальную систему координат. \en Orthonormalize the local coordinate system. + void GetControlPoints( SArray & points ); ///< \ru Заполнить массив контрольными точками. \en Fill the array with the control points. + void NormalizeTransform( const MbMatrix & mt ); ///< \ru Ортонормировать плейсмент при трансформировании. \en Orthonormalize the placement when transforming. /** \brief \ru Определить параметры пересечения прямой с эллипсом. \en Determine the parameters of intersection of a line with an ellipse. \~ @@ -1414,7 +1417,7 @@ public : \result \ru Количество точек пересечения. \en Count of intersection points. \~ */ - ptrdiff_t EllipticIntersect( const MbLine & pLine, double cross[2], double eps0 = PARAM_PRECISION ) const; + ptrdiff_t EllipticIntersect( const MbLine & pLine, double cross[2], double eps0 = PARAM_PRECISION ) const; const MbArc & operator = ( const MbArc & init ) { Init( init ); return *this; } ///< \ru Переопределяет оператор присваивания. \en Overrides the assignment operator. void GetProperties( MbProperties & properties ) override; // \ru Выдать свойства объекта \en Get properties of the object @@ -1423,12 +1426,12 @@ public : void SetBasisPoints( const MbControlData & ) override; // \ru Изменить объект по контрольным точкам. \en Change the object by control points. /** \} */ - void ReadAsCircle( reader & in ); // \ru Чтение. - void ReadAsEllipse( reader & in ); // \ru Чтение. - void ReadAsEllipseArc( reader & in ); // \ru Чтение. - void WriteAsCircle( writer & out ) const; // \ru Запись. - void WriteAsEllipse( writer & out ) const; // \ru Запись. - void WriteAsEllipseArc( writer & out ) const; // \ru Запись. + void ReadAsCircle( reader & in ); // \ru Чтение. + void ReadAsEllipse( reader & in ); // \ru Чтение. + void ReadAsEllipseArc( reader & in ); // \ru Чтение. + void WriteAsCircle( writer & out ) const; // \ru Запись. + void WriteAsEllipse( writer & out ) const; // \ru Запись. + void WriteAsEllipseArc( writer & out ) const; // \ru Запись. protected : // \ru Инициализация параметров по значениям углов эллипса \en Initialization of parameters by values of ellipse angles. @@ -1556,4 +1559,3 @@ MATH_FUNC (void) TrimmedWrite( writer & out, const MbTrimmedCurve * curve ); #endif // __CUR_ARC_H - diff --git a/C3d/Include/cur_arc3d.h b/C3d/Include/cur_arc3d.h index dbdfd63..757e29d 100644 --- a/C3d/Include/cur_arc3d.h +++ b/C3d/Include/cur_arc3d.h @@ -288,15 +288,15 @@ public : VISITING_CLASS( MbArc3D ); - 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 & ); + void Init( const MbPlacement3D &, double aa, double bb, double angle ); + void Init( const MbArc3D & init, double t1, double t2, int initSense ); /// \ru Инициализация окружности или дуги окружности по трем точкам, (n == 0) - окружность или дуга по центру и двум точкам, (n == 1) - окружность или дуга по трем точкам \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. - void Init( const MbCartPoint3D & p0, const MbCartPoint3D & p1, const MbCartPoint3D & p2, int n, bool closed ); + void Init( const MbCartPoint3D & p0, const MbCartPoint3D & p1, const MbCartPoint3D & p2, int n, bool closed ); /// \ru Инициализация дуги окружности по начальной и конечной точкам и 1/2 угла раствора дуги. \en Initialization of a circular arc by the starting and the end points and 1/2 of the arc opening angle. - void Init( double a_2, const MbCartPoint3D & p1, const MbCartPoint3D & p2, MbVector3D & vZ ); + void Init( double a_2, const MbCartPoint3D & p1, const MbCartPoint3D & p2, MbVector3D & vZ ); /// \ru Инициализация дуги окружности по 2D-дуге и локальной системе координат. \en Initialization of an arc by 2D-arc and local coordinate system. - void Init( const MbArc & ellipse, const MbPlacement3D & pos ); + void Init( const MbArc & ellipse, const MbPlacement3D & pos ); // \ru Общие функции математического объекта \en Common functions of the mathematical object /** \ru \name Общие функции геометрического объекта. @@ -357,7 +357,7 @@ public : \{ */ // \ru Вычислить значения точки и производных для заданного параметра. \en Calculate point and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const override; + MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const override; /** \} */ void Inverse( MbRegTransform * iReg = nullptr ) override; // \ru Изменить направление \en Change direction double Step ( double t, double sag ) const override; // \ru Вычисление шага по стрелке прогиба. \en Calculation of parameter step by the sag. @@ -381,9 +381,9 @@ public : void GetPointsByEvenLengthDelta( size_t n, std::vector & pnts ) const override; // \ru Выдать n точек кривой с равными интервалами по длине дуги \en Get n points of curves equally spaced by the arc length MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = nullptr, - VERSION version = Math::DefaultMathVersion(), bool * coincParams = nullptr ) const override; // \ru Дать плоскую проекцию кривой \en Get a planar projection of a curve + VERSION version = Math::DefaultMathVersion(), bool * coincParams = nullptr ) const override; // \ru Дать плоскую проекцию кривой \en Get a planar projection of a curve MbCurve * GetMapPsp( const MbMatrix3D &, double zNear, - MbRect1D * pRgn = nullptr ) const override; + MbRect1D * pRgn = nullptr ) const override; double GetRadius() 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 @@ -397,25 +397,25 @@ public : bool IsShift ( const MbSpaceItem &, MbVector3D &, bool & isSame, double accuracy = LENGTH_EPSILON ) const override; bool IsSimilarToCurve( const MbCurve3D & curve, double precision = METRIC_PRECISION ) const override; // \ru Подобные ли кривые для объединения (слива) \en Whether the curves for union (joining) are similar - void SetRadiusA( double aa ) { a = aa; Refresh(); } ///< \ru Установить большую полуось. \en Set the major semiaxis. - void SetRadiusB( double bb ) { b = bb; Refresh(); } ///< \ru Установить малую полуось. \en Set the minor semiaxis. - void SetRadius( double r ) { a = r; b = r; Refresh(); } ///< \ru Установить радиус окружности. \en Set circle radius. - double GetRadiusA() const { return a; } ///< \ru Получить большую полуось. \en Get the major semiaxis. - double GetRadiusB() const { return b; } ///< \ru Получить малую полуось. \en Get the minor semiaxis. + void SetRadiusA( double aa ) { a = aa; Refresh(); } ///< \ru Установить большую полуось. \en Set the major semiaxis. + void SetRadiusB( double bb ) { b = bb; Refresh(); } ///< \ru Установить малую полуось. \en Set the minor semiaxis. + void SetRadius( double r ) { a = r; b = r; Refresh(); } ///< \ru Установить радиус окружности. \en Set circle radius. + double GetRadiusA() const { return a; } ///< \ru Получить большую полуось. \en Get the major semiaxis. + double GetRadiusB() const { return b; } ///< \ru Получить малую полуось. \en Get the minor semiaxis. - void SetLimitPoint( ptrdiff_t number, const MbCartPoint3D & ); ///< \ru Заменить начальную (1) или конечную (2) точку дуги. \en Replace a start (1) or end (2) point of the arc. - double GetAngle() const { return (trim2 - trim1); } ///< \ru Выдать граничный угол дуги \en Get the end angle of the arc. - void SetAngle ( double ang ) { trim2 = trim1 + ang; CheckClosed(); Refresh(); } ///< \ru Изменить граничный угол дуги. \en Change the end angle of the arc. + void SetLimitPoint( ptrdiff_t number, const MbCartPoint3D & ); ///< \ru Заменить начальную (1) или конечную (2) точку дуги. \en Replace a start (1) or end (2) point of the arc. + double GetAngle() const { return (trim2 - trim1); } ///< \ru Выдать граничный угол дуги \en Get the end angle of the arc. + void SetAngle ( double ang ) { trim2 = trim1 + ang; CheckClosed(); Refresh(); } ///< \ru Изменить граничный угол дуги. \en Change the end angle of the arc. - bool IsCircle( double eps = Math::metricRegion ) const; ///< \ru Является ли дуга эллипса дугой окружности. \en Whether the arc of an ellipse is an arc of a circle. + bool IsCircle( double eps = Math::metricRegion ) const; ///< \ru Является ли дуга эллипса дугой окружности. \en Whether the arc of an ellipse is an arc of a circle. inline double CheckParam( double & t ) const; ///< \ru Установить параметр в область допустимых значений \en Set the parameter into the region of the legal values inline void ParamToAngle( double & t ) const; ///< \ru Перевод параметра кривой в угол. \en Convert parameter of curve to the angle. inline void AngleToParam( double & t ) const; ///< \ru Перевод угла кривой в параметр кривой. \en Convert an angle of curve to a parameter of curve. inline double GetTrim1() const { return trim1; } ///< \ru Параметры начальной точки. \en Parameters of start point. inline double GetTrim2() const { return trim2; } ///< \ru Параметры конечной точки. \en Parameters of end point. - bool MakeTrimmed( double t1, double t2 ); ///< \ru Установка параметров усечения с сохранением направления кривой. \en Setting of the parameters of trimming with keeping the curve direction. - void AlignXAxis(); ///< \ru Повернуть плейсмент круговой дуги так, чтобы ось ox указывала в начальную точку дуги. \en Rotate the placement of a circular arc so as the ox-axis points to the start point of the arc. + bool MakeTrimmed( double t1, double t2 ); ///< \ru Установка параметров усечения с сохранением направления кривой. \en Setting of the parameters of trimming with keeping the curve direction. + void AlignXAxis(); ///< \ru Повернуть плейсмент круговой дуги так, чтобы ось ox указывала в начальную точку дуги. \en Rotate the placement of a circular arc so as the ox-axis points to the start point of the arc. /// \ru Является ли кривая плоской? \en Whether the curve is planar? bool IsPlanar( double accuracy = METRIC_EPSILON ) const override; @@ -432,24 +432,25 @@ public : // \ru Продлить кривую. \en Extend the curve. \~ MbResultType Extend( const MbCurveExtensionParameters & parameters, c3d::SpaceCurveSPtr & resCurve ) const override; - bool Normalize(); ///< \ru Ортонормировать локальную систему координат. \en Orthonormalize the local coordinate system. - bool IsPositionNormal() const { return ( !position.IsAffine() ); } - bool IsPositionCircular() const { return ( position.IsCircular() ); } - bool IsPositionIsotropic() const { return ( position.IsIsotropic()); } + bool Normalize(); ///< \ru Ортонормировать локальную систему координат. \en Orthonormalize the local coordinate system. + bool IsPositionNormal() const { return ( !position.IsAffine() ); } + bool IsPositionCircular() const { return ( position.IsCircular() ); } + bool IsPositionIsotropic() const { return ( position.IsIsotropic()); } const MbCartPoint3D & GetCentre() const { return position.GetOrigin(); } private: - void CheckClosed(); ///< \ru Проверить и установить признак замкнутости кривой. \en Check and set attribute of curve closedness. + void CheckClosed(); ///< \ru Проверить и установить признак замкнутости кривой. \en Check and set attribute of curve closedness. private: - void operator = ( const MbArc3D & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbArc3D & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbArc3D ) }; IMPL_PERSISTENT_OPS( MbArc3D ) + //------------------------------------------------------------------------------ // \ru Установить параметр в область допустимых значений \en Set the parameter into the region of the legal values // --- diff --git a/C3d/Include/cur_b_spline.h b/C3d/Include/cur_b_spline.h index 8454245..0e54402 100644 --- a/C3d/Include/cur_b_spline.h +++ b/C3d/Include/cur_b_spline.h @@ -81,7 +81,7 @@ public: void ThirdDer ( double &t, MbVector3D &td ) const override; // \ru Третья производная по t \en Third derivative with respect to t // \ru Вычислить значения точки и производных для заданного параметра. \en Calculate point and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const override; + MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const override; double Step( double t, double sag ) const override; // \ru Вычисление шага аппроксимации \en Calculate step of approximation @@ -89,20 +89,22 @@ public: void Inverse( MbRegTransform * iReg = nullptr ) override; // \ru Изменить направление \en Change direction - void CalculateOnePolygon( size_t i, const MbStepData & stepData, MbPolygon3D * polygon ) const; // \ru Pассчитать полигон по параметру T \en Calculate polygon of the parameter T - // \ru Расчет весовых функций и их первых, вторых и третьих производных \en Calculation of the weight functions and their first, second and third derivatives - ptrdiff_t CalculateFunctions( double x, double * m, - double * mm0, double * mm1, double * mm2, double * mm3 ) const; - ptrdiff_t CalculateParam( double & t, double & x ) const; // \ru Расчет параметра и номера сплайна \en Calculation of the parameter and spline number - void GetWeightFunctions( double t, double * m, - double * mm0, double * mm1, double * mm2, double * mm3 ) const; // \ru Определение В-сплайнов \en Definition of B-splines + void CalculateOnePolygon( size_t i, const MbStepData & stepData, MbPolygon3D * polygon ) const; // \ru Pассчитать полигон по параметру T \en Calculate polygon of the parameter T + // \ru Расчет весовых функций и их первых, вторых и третьих производных \en Calculation of the weight functions and their first, second and third derivatives + ptrdiff_t CalculateFunctions( double x, double * m, + double * mm0, double * mm1, double * mm2, double * mm3 ) const; + ptrdiff_t CalculateParam( double & t, double & x ) const; // \ru Расчет параметра и номера сплайна \en Calculation of the parameter and spline number + void GetWeightFunctions( double t, double * m, + double * mm0, double * mm1, double * mm2, double * mm3 ) const; // \ru Определение В-сплайнов \en Definition of B-splines private: - void operator = ( const MbBSpline & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbBSpline & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbBSpline ) + }; // MbBSpline IMPL_PERSISTENT_OPS( MbBSpline ) + #endif // __CUR_B_SPLINE_H diff --git a/C3d/Include/cur_bezier.h b/C3d/Include/cur_bezier.h index ca48c6a..f9feb69 100644 --- a/C3d/Include/cur_bezier.h +++ b/C3d/Include/cur_bezier.h @@ -240,7 +240,7 @@ public : \param[in] cls - \ru Замкнутость кривой. \en A curve closedness. \~ */ - void Init( const SArray & initList, bool cls ); + void Init( const SArray & initList, bool cls ); /** \brief \ru Инициировать кривую по заданной кривой Безье. \en Initialize a curve by a given Bezier curve. \~ @@ -249,7 +249,7 @@ public : \param[in] initCurve - \ru Заданная кривая. \en A given curve. \~ */ - void Init( const MbBezier & initCurve ); + void Init( const MbBezier & initCurve ); /** \brief \ru Инициировать кривую по дуге окружности. \en Initialize a curve by a circle arc. \~ @@ -258,7 +258,7 @@ public : \param[in] arc - \ru Дуга окружности. \en Circle arc. \~ */ - void Init( const MbArc & arc ); // \ru Инициализация по дуге окружности \en Initialization by a circle arc + void Init( const MbArc & arc ); // \ru Инициализация по дуге окружности \en Initialization by a circle arc /** \brief \ru Инициировать кривую по контрольным точкам. \en Initialize a curve by control points. \~ @@ -269,7 +269,7 @@ public : \param[in] initList - \ru Массив контрольных точек кривой. \en An array of control points of curve. \~ */ - void InitCtrlPoints( const SArray & initList ); + void InitCtrlPoints( const SArray & initList ); /** \} */ /** \ru \name Функции описания области определения кривой. \en \name Functions for curve domain description. @@ -316,8 +316,7 @@ public : void GetProperties( MbProperties & properties ) override; // \ru Выдать свойства объекта \en Get properties of the object void SetProperties( const MbProperties & properties ) override; // \ru Записать свойства объекта \en Set properties of the object - /// \ru Получить границы участков кривой, которые описываются одной аналитической функцией. - /// \en Get the boundaries of the curve sections that are described by one analytical function. \~ + /// \ru Получить границы участков кривой, которые описываются одной аналитической функцией. \en Get the boundaries of the curve sections that are described by one analytical function. \~ void GetAnalyticalFunctionsBounds( std::vector & params ) const override; @@ -335,9 +334,9 @@ public : void Rebuild() override; // \ru Пересчитать Безье кривую \en Recalculate Bezier curve void SetClosed( bool cls ) override; - // \ru BEG: для библиотеки (хорошо бы избавиться) \en BEG: for the library (it would be good to get rid of this) - void LtSetClosed( bool cls ); // \ru Установить признак замкнутости. \en Set the closedness attribute. - // \ru END: для библиотеки (хорошо бы избавиться) \en END: for the library (it would be good to get rid of this) + // \ru BEG: для библиотеки (хорошо бы избавиться) \en BEG: for the library (it would be good to get rid of this) + void LtSetClosed( bool cls ); // \ru Установить признак замкнутости. \en Set the closedness attribute. + // \ru END: для библиотеки (хорошо бы избавиться) \en END: for the library (it would be good to get rid of this) void RemovePoint( ptrdiff_t index ) override; // \ru Удалить точку \en Remove the point. void RemovePoints() override; // \ru Удалить все точки \en Remove all points @@ -367,7 +366,7 @@ public : \param[in] rightPnt- \ru Точка справа от характерной точки. \en Point to the right of the characteristic point. \~ */ - void InsertPolePoints( size_t index, const MbCartPoint & leftPnt, const MbCartPoint & basePnt, const MbCartPoint & rightPnt ); + void InsertPolePoints( size_t index, const MbCartPoint & leftPnt, const MbCartPoint & basePnt, const MbCartPoint & rightPnt ); /** \brief \ru Заменить полюс. \en Replace the pole. \~ @@ -411,7 +410,7 @@ public : \param[in] angle - \ru Угол между направлением касательной и осью OX текущей системы координат. \en The angle between the direction of the tangent and the OX-axis of the current coordinate system. \~ */ - void AddPoint( MbCartPoint & pnt, double dl, double dr, double angle ); + void AddPoint( MbCartPoint & pnt, double dl, double dr, double angle ); /** \brief \ru Определить выпуклую оболочку сегмента кривой. \en Determine the convex hull of the curve segment. \~ @@ -422,17 +421,17 @@ public : \param[out] poly - \ru Массив точек, составляющих выпуклую оболочку сегмента. \en Array of points which constitute the convex hull of the segment. \~ */ - void ConvexHull( ptrdiff_t seg, SArray & poly ) const; - // \ru Определение особых точек офсетной кривой \en Determination of singular points of the offset curve + void ConvexHull( ptrdiff_t seg, SArray & poly ) const; + /// \ru Определение особых точек офсетной кривой \en Determination of singular points of the offset curve void OffsetCuspPoint( SArray & tCusps, double dist ) const override; - /// \ru Вернуть массив отдельных сегментов Bezier-кривой. \en Return an array of separate segments of the Bezier-curve. - void GetSegments( RPArray & segments ) const; - /// \ru Удалить совпадающие точки. \en Delete coincident points. - void ExeptEqualPoints(); + /// \ru Вернуть массив отдельных сегментов Bezier-кривой. \en Return an array of separate segments of the Bezier-curve. + void GetSegments( RPArray & segments ) const; + /// \ru Удалить совпадающие точки. \en Delete coincident points. + void ExeptEqualPoints(); bool IsDegenerate( double eps = Math::LengthEps ) const override; // \ru Проверка вырожденности кривой \en Check for curve degeneracy - /// \ru Сделать контур из NURBS-кривой. \en Create a contour from the NURBS curve. - MbContour * CreateContour() const; + /// \ru Сделать контур из NURBS-кривой. \en Create a contour from the NURBS curve. + MbContour * CreateContour() const; // \ru Функции только Bezier кривой \en Functions for Bezier curve @@ -449,11 +448,11 @@ public : \result \ru true - если построение прошло успешно. \en True - if construction has been successfully. \~ */ - bool Break( MbBezier & trimPart, double t1, double t2 ) 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. - ptrdiff_t GetSplinesCount() const { return splinesCount; } ///< \ru Количество сплайнов \en The number of splines + bool Break( MbBezier & trimPart, double t1, double t2 ) 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. + ptrdiff_t GetSplinesCount() const { return splinesCount; } ///< \ru Количество сплайнов \en The number of splines /** \brief \ru Выделить часть кривой Безье. \en Break a part of the Bezier curve. \~ @@ -468,7 +467,7 @@ public : \param[in] sense - \ru Совпадает ли направление полученной кривой с направлением исходной кривой. \en Whether the direction of the resulting curve coincides with the direction of the original curve. \~ */ - void Trimm( MbBezier & trimm, double t1, double t2, int sense ) const; + void Trimm( MbBezier & trimm, double t1, double t2, int sense ) const; bool DistanceToPointIfLess( const MbCartPoint & to, double &d ) const override; // \ru Расстояние до точки, если оно меньше d \en Distance to the point if it is less than d @@ -489,13 +488,13 @@ public : \result \ru true - если операция прошла успешно. \en True - if operation has been successfully. \~ */ - bool BasicFunctions( double & t, CcArray & values, ptrdiff_t & left ) const; + bool BasicFunctions( double & t, CcArray & values, ptrdiff_t & left ) const; // \ru Посчитать метрическую длину \en Calculate the metric length double CalculateMetricLength() const override; // \ru Сдвинуть параметр t на расстояние len. \en Move parameter t on the metric distance len. - virtual bool DistanceAlong( double & t, double len, int curveDir, double eps = Math::LengthEps, - VERSION version = Math::DefaultMathVersion() ) const override; + bool DistanceAlong( double & t, double len, int curveDir, double eps = Math::LengthEps, + VERSION version = Math::DefaultMathVersion() ) const override; bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = nullptr, double epsilon = EPSILON ) const override; // \ru Непрерывна ли первая производная? \en Have the first derivative the continuous? // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. @@ -506,18 +505,19 @@ public : protected: bool CanChangeClosed() const override; // \ru Можно ли поменять признак замкнутости \en Whether it is possible to change the attribute of closedness private : - void CheckData( double & t ) const; - void EvaluateSlope ( ptrdiff_t index ); // \ru Рассчитать производные в полюсе index \en Calculate derivatives at the pole "index" - void EvaluateSlope0 ( ptrdiff_t index ); // \ru Рассчитать производные в полюсе index для 0-ой формы \en Calculate derivatives at the pole "index" for 0-th form - void EvaluateSlope1 ( ptrdiff_t index ); // \ru Рассчитать производные в полюсе index для 1-ой формы \en Calculate derivatives at the pole "index" for 1-th form - void SetDerives(); // \ru Рассчитать все производные \en Calculate all derivatives - void SetDerives ( ptrdiff_t index ); // \ru Рассчитать производные в полюсах при изменении полюса index. \en Calculate derivatives at poles when changing the pole "index". + void CheckData( double & t ) const; + void EvaluateSlope ( ptrdiff_t index ); // \ru Рассчитать производные в полюсе index \en Calculate derivatives at the pole "index" + void EvaluateSlope0 ( ptrdiff_t index ); // \ru Рассчитать производные в полюсе index для 0-ой формы \en Calculate derivatives at the pole "index" for 0-th form + void EvaluateSlope1 ( ptrdiff_t index ); // \ru Рассчитать производные в полюсе index для 1-ой формы \en Calculate derivatives at the pole "index" for 1-th form + void SetDerives(); // \ru Рассчитать все производные \en Calculate all derivatives + void SetDerives ( ptrdiff_t index ); // \ru Рассчитать производные в полюсах при изменении полюса index. \en Calculate derivatives at poles when changing the pole "index". - void operator = ( const MbBezier & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbBezier & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbBezier ) }; IMPL_PERSISTENT_OPS( MbBezier ) + #endif // __CUR_BEZIER_H diff --git a/C3d/Include/cur_bezier3d.h b/C3d/Include/cur_bezier3d.h index 67f3c67..8513067 100644 --- a/C3d/Include/cur_bezier3d.h +++ b/C3d/Include/cur_bezier3d.h @@ -104,40 +104,40 @@ public : public : VISITING_CLASS( MbBezier3D ); - void Init( const SArray & initList, bool cls ); - void Init( const MbBezier3D & ); - void Init( const MbBezier &, const MbPlacement3D & ); - void Init( MbArc3D & ); + void Init( const SArray & initList, bool cls ); + void Init( const MbBezier3D & ); + void Init( const MbBezier &, const MbPlacement3D & ); + void Init( MbArc3D & ); // \ru Общие функции математического объекта \en The common functions of the mathematical object MbeSpaceType IsA() const override; // \ru Тип элемента \en A type of element MbSpaceItem & Duplicate( MbRegDuplicate * = nullptr ) const override; // \ru Сделать копию элемента \en Create a copy of the element - bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const override; - bool SetEqual ( const MbSpaceItem & ) 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 Rotation + bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const override; + bool SetEqual ( const MbSpaceItem & ) 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 Rotation - void GetProperties( MbProperties & ) override; // \ru Выдать свойства объекта \en Get properties of the object - void SetProperties( const MbProperties & ) override; // \ru Записать свойства объекта \en Set properties of the object + 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 Common functions of curve - double GetTMax() const override; // \ru Вернуть максимальное значение параметра \en Get the maximum value of parameter - double GetTMin() const override; // \ru Вернуть минимальное значение параметра \en Get the minimum value of parameter + double GetTMax() const override; // \ru Вернуть максимальное значение параметра \en Get the maximum value of parameter + double GetTMin() const override; // \ru Вернуть минимальное значение параметра \en Get the minimum value of parameter // \ru Функции для работы внутри области определения кривой. \en Functions for working inside of the curve domain. \~ - void PointOn ( double & t, MbCartPoint3D & ) const override; // \ru Точка на кривой \en The point on the curve - void FirstDer ( double & t, MbVector3D & ) const override; // \ru Первая производная \en First derivative - void SecondDer( double & t, MbVector3D & ) const override; // \ru Вторая производная \en Second derivative - void ThirdDer ( double & t, MbVector3D & ) const override; // \ru Третья производная \en Third derivative + void PointOn ( double & t, MbCartPoint3D & ) const override; // \ru Точка на кривой \en The point on the curve + void FirstDer ( double & t, MbVector3D & ) const override; // \ru Первая производная \en First derivative + void SecondDer( double & t, MbVector3D & ) const override; // \ru Вторая производная \en Second derivative + void ThirdDer ( double & t, MbVector3D & ) const override; // \ru Третья производная \en Third derivative // \ru Вычислить значения точки и производных для заданного параметра. \en Calculate point and derivatives of object for given parameter. \~ - void Explore( double & t, bool ext, - MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const override; + void Explore( double & t, bool ext, + MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const override; - double Step( double t, double sag ) const override; // \ru Вычисление шага аппроксимации \en Calculate step of approximation - double DeviationStep( double t, double angle ) const override; - void Inverse( MbRegTransform * iReg = nullptr ) override; // \ru Изменить направление \en Change direction + double Step( double t, double sag ) const override; // \ru Вычисление шага аппроксимации \en Calculate step of approximation + double DeviationStep( double t, double angle ) const override; + void Inverse( MbRegTransform * iReg = nullptr ) override; // \ru Изменить направление \en Change direction virtual bool Break( MbBezier3D &, double t1, double t2 ) const; // \ru Разбить на две части \en Split into two parts @@ -147,68 +147,69 @@ public : MbCurve3D * Trimmed( double t1, double t2, int sense ) const override; // \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; + bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place, bool saveParams, PlanarCheckParams params = PlanarCheckParams() ) const override; /// \ru Получить границы участков кривой, которые описываются одной аналитической функцией. /// \en Get the boundaries of the curve sections that are described by one analytical function. \~ - void GetAnalyticalFunctionsBounds( std::vector & params ) const override; + void GetAnalyticalFunctionsBounds( std::vector & params ) const override; // \ru Общие функции полигональной кривой \en Common functions of a polygonal curve - void Rebuild() override; // \ru Пересчитать Безье кривую \en Recalculate Bezier curve - void SetClosed ( bool cls ) override; // \ru Установить признак замкнутости \en Set the closedness attribute. - void AddPoint ( const MbCartPoint3D & ) override; // \ru Добавить точку в конец массива \en Add a point to the end of array - void InsertPoint( ptrdiff_t index, const MbCartPoint3D & ) override; // \ru Добавить точку \en Add a point - void InsertPoint( double t, const MbCartPoint3D &, double ) override; // \ru Добавить точку \en Add a point - void RemovePoint( ptrdiff_t index ) override; // \ru Удалить точку \en Remove a point - bool ChangePoint( ptrdiff_t index, const MbCartPoint3D & ) override; // \ru Заменить точку \en Replace a point - void ChangePole ( ptrdiff_t index, const MbCartPoint3D & override); // \ru Заменить полюс \en Replace a pole - bool CheckParam ( double & t, ptrdiff_t & i0, ptrdiff_t & i1, double & t0, double & t1 ) const override; // \ru Загнать параметр получить локальный индексы и параметры \en Move parameter, get local indices and parameters - double GetParam( ptrdiff_t i ) const override; // \ru Выдать параметр для точки с номером \en Get a parameter for point with number - size_t GetPointsCount() const override; // \ru Выдать количество точек \en Get the number of points - void GetPoint ( ptrdiff_t index, MbCartPoint3D & ) const override; // \ru Выдать точку \en Get a point - ptrdiff_t GetNearPointIndex ( const MbCartPoint3D & ) const override; // \ru Выдать индекс точки, ближайшей к заданной \en Get the point index which is nearest to the given - void GetRuleInterval ( ptrdiff_t index, double & t1, double & t2 ) const override; // \ru Выдать интервал влияния точки \en Get the interval of point influence + void Rebuild() override; // \ru Пересчитать Безье кривую \en Recalculate Bezier curve + void SetClosed ( bool cls ) override; // \ru Установить признак замкнутости \en Set the closedness attribute. + void AddPoint ( const MbCartPoint3D & ) override; // \ru Добавить точку в конец массива \en Add a point to the end of array + void InsertPoint( ptrdiff_t index, const MbCartPoint3D & ) override; // \ru Добавить точку \en Add a point + void InsertPoint( double t, const MbCartPoint3D &, double ) override; // \ru Добавить точку \en Add a point + void RemovePoint( ptrdiff_t index ) override; // \ru Удалить точку \en Remove a point + bool ChangePoint( ptrdiff_t index, const MbCartPoint3D & ) override; // \ru Заменить точку \en Replace a point + void ChangePole ( ptrdiff_t index, const MbCartPoint3D & override); // \ru Заменить полюс \en Replace a pole + bool CheckParam ( double & t, ptrdiff_t & i0, ptrdiff_t & i1, double & t0, double & t1 ) const override; // \ru Загнать параметр получить локальный индексы и параметры \en Move parameter, get local indices and parameters + double GetParam( ptrdiff_t i ) const override; // \ru Выдать параметр для точки с номером \en Get a parameter for point with number + size_t GetPointsCount() const override; // \ru Выдать количество точек \en Get the number of points + void GetPoint ( ptrdiff_t index, MbCartPoint3D & ) const override; // \ru Выдать точку \en Get a point + ptrdiff_t GetNearPointIndex ( const MbCartPoint3D & ) const override; // \ru Выдать индекс точки, ближайшей к заданной \en Get the point index which is nearest to the given + void GetRuleInterval ( ptrdiff_t index, double & t1, double & t2 ) const override; // \ru Выдать интервал влияния точки \en Get the interval of point influence - MbNurbs3D * Trimm( double t1, double t2, int sense ) const; - void Trimm( MbBezier3D &, double t1, double t2, int sense ) const; + MbNurbs3D * Trimm( double t1, double t2, int sense ) const; + void Trimm( MbBezier3D &, double t1, double t2, int sense ) const; - void InitCtrlPoints( const SArray & ); - void SetBezierSplines(); // \ru Вычислить параметры кривой-Bezier \en Calculate parameters of the Bezier curve - int GetFormType() const { return form; } // \ru Форма сплайна \en The spline form - void SetFormType( int newForm ); - ptrdiff_t GetSplinesCount() const { return splinesCount; } // \ru Количество сплайнов \en The number of splines + void InitCtrlPoints( const SArray & ); + void SetBezierSplines(); // \ru Вычислить параметры кривой-Bezier \en Calculate parameters of the Bezier curve + int GetFormType() const { return form; } // \ru Форма сплайна \en The spline form + void SetFormType( int newForm ); + ptrdiff_t GetSplinesCount() const { return splinesCount; } // \ru Количество сплайнов \en The number of splines // \ru Функции только 3D кривой \en Function for 3D-curve - MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = nullptr, - VERSION version = Math::DefaultMathVersion(), bool * coincParams = nullptr ) const override; // \ru Дать плоскую проекцию кривой \en Get a planar projection of curve + MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = nullptr, + VERSION version = Math::DefaultMathVersion(), bool * coincParams = nullptr ) const override; // \ru Дать плоскую проекцию кривой \en Get a planar projection of curve - size_t GetCount() const override; + size_t GetCount() const override; // \ru Посчитать метрическую длину \en Calculate the metric length - double CalculateMetricLength() const override; + double CalculateMetricLength() const override; // \ru Сдвинуть параметр t на расстояние len. \en Move parameter t on the metric distance len. - bool DistanceAlong( double & t, double len, int curveDir, double eps = Math::metricPrecision, - VERSION version = Math::DefaultMathVersion() ) const override; + bool DistanceAlong( double & t, double len, int curveDir, double eps = Math::metricPrecision, + VERSION version = Math::DefaultMathVersion() ) const override; - bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = nullptr, double epsilon = EPSILON ) const override; // \ru Непрерывна ли первая производная? \en Have the first derivative the continuous? + bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = nullptr, double epsilon = EPSILON ) const override; // \ru Непрерывна ли первая производная? \en Have the first derivative the continuous? // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. - bool SetContinuousDerivativeLength( VERSION version, double epsilon = EPSILON ) override; + bool SetContinuousDerivativeLength( VERSION version, double epsilon = EPSILON ) override; private : - void CheckBezierClosed(); // \ru Проверка признака замкнутости. \en Check closed. - void EvaluateSlope ( ptrdiff_t index ); // \ru Рассчитать производные в полюсе index \en Calculate derivatives at the pole "index" - void EvaluateSlope0( ptrdiff_t index ); // \ru Рассчитать производные в полюсе index для 0-ой формы \en Calculate derivatives at the pole "index" for 0-th form - void EvaluateSlope1( ptrdiff_t index ); // \ru Рассчитать производные в полюсе index для 1-ой формы \en Calculate derivatives at the pole "index" for 1-th form - void SetDerives (); // \ru Рассчитать все производные \en Calculate all derivatives - void SetDerives ( ptrdiff_t index ); // \ru Рассчитать производные в полюсах при изменении полюса index \en Calculate derivatives at poles when changing the pole "index" + void CheckBezierClosed(); // \ru Проверка признака замкнутости. \en Check closed. + void EvaluateSlope ( ptrdiff_t index ); // \ru Рассчитать производные в полюсе index \en Calculate derivatives at the pole "index" + void EvaluateSlope0( ptrdiff_t index ); // \ru Рассчитать производные в полюсе index для 0-ой формы \en Calculate derivatives at the pole "index" for 0-th form + void EvaluateSlope1( ptrdiff_t index ); // \ru Рассчитать производные в полюсе index для 1-ой формы \en Calculate derivatives at the pole "index" for 1-th form + void SetDerives (); // \ru Рассчитать все производные \en Calculate all derivatives + void SetDerives ( ptrdiff_t index ); // \ru Рассчитать производные в полюсах при изменении полюса index \en Calculate derivatives at poles when changing the pole "index" private: - void operator = ( const MbBezier3D & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbBezier3D & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbBezier3D ) }; IMPL_PERSISTENT_OPS( MbBezier3D ) + #endif // __CUR_BEZIER3D_H diff --git a/C3d/Include/cur_bridge3d.h b/C3d/Include/cur_bridge3d.h index 9ad0d2e..23929f2 100644 --- a/C3d/Include/cur_bridge3d.h +++ b/C3d/Include/cur_bridge3d.h @@ -60,7 +60,7 @@ public: public: VISITING_CLASS( MbBridgeCurve3D ); - void Init( MbCurve3D & c1, double t1, bool s1, + void Init( MbCurve3D & c1, double t1, bool s1, MbCurve3D & c2, double t2, bool s2, double _tmin, double _tmax ); @@ -95,7 +95,7 @@ public: void ThirdDer ( double & t, MbVector3D & ) const override; // \ru Третья производная по t \en The third derivative with respect to t // \ru Вычислить значения точки и производных для заданного параметра. \en Calculate point and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const override; + MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const override; void Inverse ( MbRegTransform * iReg = nullptr ) override; // \ru Изменить направление \en Change direction double Step ( double t, double sag ) const override; // \ru Вычисление шага аппроксимации \en Calculation of the approximation step @@ -109,9 +109,9 @@ public: private: inline void CheckParam ( double & t ) const; // \ru Проверка параметра \en Check parameter inline void LocalParams ( const double & t, double & quota1, double & quota2 ) const; // \ru Вычисление локальных данных по параметру \en Calculation of local data by the parameter - void LocalData (); // \ru Определение значений точек и производных на концах \en Determination of values of points and derivatives at the ends - void ChangeCurves( MbCurve3D & c1, MbCurve3D & c2 ); - void operator = ( const MbBridgeCurve3D & ); // \ru Не реализовано. \en Not implemented. + void LocalData (); // \ru Определение значений точек и производных на концах \en Determination of values of points and derivatives at the ends + void ChangeCurves( MbCurve3D & c1, MbCurve3D & c2 ); + void operator = ( const MbBridgeCurve3D & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbBridgeCurve3D ) }; diff --git a/C3d/Include/cur_character_curve.h b/C3d/Include/cur_character_curve.h index 96e51a6..a63fa6d 100644 --- a/C3d/Include/cur_character_curve.h +++ b/C3d/Include/cur_character_curve.h @@ -92,7 +92,7 @@ public: void ThirdDer( double & t, MbVector & ) const override; // \ru Третья производная по t \en The third derivative with respect to t // \ru Вычислить значения точки и производных для заданного параметра. \en Calculate point and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - MbCartPoint & pnt, MbVector & fir, MbVector * sec, MbVector * thir ) const override; + MbCartPoint & pnt, MbVector & fir, MbVector * sec, MbVector * thir ) const override; double Step ( double t, double sag ) const override; // \ru Вычисление шага параметра по величине прогиба кривой \en Calculation of parameter step by value of sag of the curve double DeviationStep ( double t, double ang ) const override; // \ru Вычисление шага параметра по углу отклонения касательной \en Calculation of parameter by the angle of tangent deviation @@ -117,36 +117,38 @@ public: void GetProperties ( MbProperties & ) override; // \ru Выдать свойства объекта \en Get properties of the object void SetProperties ( const MbProperties & ) override; // \ru Записать свойства объекта \en Set properties of the object - void CheckParam ( double & t ) const; - void CalculateParam( double t, MbCartPoint & point, - MbVector & firstDer, MbVector & secondDer, MbVector & thirdDer ) const; + void CheckParam ( double & t ) const; + void CalculateParam( double t, MbCartPoint & point, + MbVector & firstDer, MbVector & secondDer, MbVector & thirdDer ) const; const MbFunction * GetX() const { return xFunction; } const MbFunction * GetY() const { return yFunction; } const MbMatrix & GetMatrix() const { return transform; } const MbPlacement & GetPlacement() const { return position; } MbeLocalSystemType GetCoordinateType() const { return coordinateType; } - void GetSpecialParams( std::vector & params ) const; + void GetSpecialParams( std::vector & params ) const; protected: - double ApproximationStep( double t, bool isAngle, double sag ) const; - void ConvertParamsInd( size_t componentIndex, - const std::vector & tComponent, - std::vector & tCrv ) const; - void ConvertParams( const double tCrv, - double (&tComponents) [2], - double (&proportionFactors)[2]) const; + double ApproximationStep( double t, bool isAngle, double sag ) const; + void ConvertParamsInd( size_t componentIndex, + const std::vector & tComponent, + std::vector & tCrv ) const; + void ConvertParams( const double tCrv, + double (&tComponents) [2], + double (&proportionFactors)[2]) const; private: - // \ru Проверить и установить признак замкнутости. \en Check and set the flag of closedness. - void CheckClosed(); + + // \ru Проверить и установить признак замкнутости. \en Check and set the flag of closedness. + void CheckClosed(); private: - void operator = ( const MbCharacterCurve & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbCharacterCurve & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCharacterCurve ) }; IMPL_PERSISTENT_OPS( MbCharacterCurve ) + #endif // __CUR_CHARACTER_CURVE_H diff --git a/C3d/Include/cur_character_curve3d.h b/C3d/Include/cur_character_curve3d.h index f4bb865..997dc72 100644 --- a/C3d/Include/cur_character_curve3d.h +++ b/C3d/Include/cur_character_curve3d.h @@ -105,7 +105,7 @@ public: void ThirdDer ( double & t, MbVector3D & ) const override; // \ru Третья производная по t \en The third derivative with respect to t // \ru Вычислить значения точки и производных для заданного параметра. \en Calculate point and derivatives of object for given parameter. \~ void Explore ( double & t, bool ext, - MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const override; + MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const override; double Step ( double t, double sag ) const override; ///< \ru Вычисление шага параметра по величине прогиба кривой \en Calculation of parameter step by value of sag of the curve double DeviationStep( double t, double ang ) const override; ///< \ru Вычисление шага параметра по углу отклонения касательной \en Calculation of parameter by the angle of tangent deviation @@ -119,14 +119,14 @@ public: // \ru Дать плоскую кривую и плейсмент, если пространственная кривая плоская (после использования вызывать DeleteItem на двумерную кривую) \en Get a planar curve and placement, if the spatial curve is planar (after using the DeleteItem must be called on a three-dimensional curve) bool GetPlaneCurve ( MbCurve *& curve2d, MbPlacement3D & place, bool saveParams, PlanarCheckParams params = PlanarCheckParams() ) const override; MbCurve * GetMap( const MbMatrix3D & into, MbRect1D * pRegion = nullptr, - VERSION version = Math::DefaultMathVersion(), bool * coincParams = nullptr ) const override; // \ru Дать плоскую проекцию кривой \en Get a planar projection of curve + VERSION version = Math::DefaultMathVersion(), bool * coincParams = nullptr ) const override; // \ru Дать плоскую проекцию кривой \en Get a planar projection of curve // \ru Определить количество разбиений для прохода в операциях. \en Define the number of splittings for one passage in operations. size_t GetCount() const override; MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & ) const override; - void CheckParam ( double & t ) const; - void CalculateParam( double t, MbCartPoint3D & point, - MbVector3D & firstDer, MbVector3D & secondDer, MbVector3D & thirdDer ) const; + void CheckParam ( double & t ) const; + void CalculateParam( double t, MbCartPoint3D & point, + MbVector3D & firstDer, MbVector3D & secondDer, MbVector3D & thirdDer ) const; const MbFunction * GetX() const { return xFunction; } const MbFunction * GetY() const { return yFunction; } @@ -136,25 +136,26 @@ public: MbeLocalSystemType3D GetCoordinateType() const { return coordinateType; } protected: -// void GetSpecialParams( std::vector & params ) const; - double ApproximationStep( double t, bool isAngle, double constraint ) const; - void ConvertParamsInd( size_t componentIndex, - const std::vector & tComponent, - std::vector & tCrv ) const; - void ConvertParams( const double tCrv, - double (&tComponents)[3], - double (&proportionFactors)[3]) const; +// void GetSpecialParams( std::vector & params ) const; + double ApproximationStep( double t, bool isAngle, double constraint ) const; + void ConvertParamsInd( size_t componentIndex, + const std::vector & tComponent, + std::vector & tCrv ) const; + void ConvertParams( const double tCrv, + double (&tComponents)[3], + double (&proportionFactors)[3]) const; private: - // \ru Проверить и установить признак замкнутости. \en Check and set the flag of closedness. - void CheckClosed(); + // \ru Проверить и установить признак замкнутости. \en Check and set the flag of closedness. + void CheckClosed(); private: - void operator = ( const MbCharacterCurve3D & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbCharacterCurve3D & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCharacterCurve3D ) }; IMPL_PERSISTENT_OPS( MbCharacterCurve3D ) + #endif // __CUR_CHARCTER_CURVE3D_H diff --git a/C3d/Include/cur_cone_spiral.h b/C3d/Include/cur_cone_spiral.h index 741b150..2b96671 100644 --- a/C3d/Include/cur_cone_spiral.h +++ b/C3d/Include/cur_cone_spiral.h @@ -185,14 +185,14 @@ public: public: VISITING_CLASS( MbConeSpiral ); - /// \ru Инициализация конической спирали по конической спирали. \en Initialization of conical spiral by conical spiral. - void Init( const MbConeSpiral & ); - /// \ru Инициализация цилиндрической спирали по основанию. \en Initialization of cylindrical spiral by base. - bool Init( const MbPlacement3D &, bool resetToCylindrical ); - /// \ru Инициализация конической спирали по радиусам оснований, высоте и шагу. \en Initialization of conical spiral by bottom radii, height and step. - bool Init( double radius1, double radius2, double height, double st ); - /// \ru Инициализация конической спирали по основанию, радиусам оснований, и высоте с шагом. \en Initialization of conical spiral by the base, radii of bases and height with step. - bool Init( const MbPlacement3D & place, double radius1, double radius2, double height, double st ); + /// \ru Инициализация конической спирали по конической спирали. \en Initialization of conical spiral by conical spiral. + void Init( const MbConeSpiral & ); + /// \ru Инициализация цилиндрической спирали по основанию. \en Initialization of cylindrical spiral by base. + bool Init( const MbPlacement3D &, bool resetToCylindrical ); + /// \ru Инициализация конической спирали по радиусам оснований, высоте и шагу. \en Initialization of conical spiral by bottom radii, height and step. + bool Init( double radius1, double radius2, double height, double st ); + /// \ru Инициализация конической спирали по основанию, радиусам оснований, и высоте с шагом. \en Initialization of conical spiral by the base, radii of bases and height with step. + bool Init( const MbPlacement3D & place, double radius1, double radius2, double height, double st ); public: // \ru Общие функции математического объекта. \en The common functions of the mathematical object. @@ -217,14 +217,14 @@ public: void _ThirdDer ( double t, MbVector3D & td ) const override; // \ru Третья производная по t. \en The third derivative with respect to t. // \ru Вычислить значения точки и производных для заданного параметра. \en Calculate point and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const override; + MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const override; double Step ( double t, double sag ) const override; // \ru Вычисление шага по стрелке прогиба. \en Calculation of parameter step by the sag. double DeviationStep( double t, double angle ) const override; // \ru Вычисление шага по углу отклонения нормали. \en Calculation of parameter step by the deviation angle. double MetricStep ( double t, double length ) const override; // \ru Вычисление шага параметра по длине. \en Calculation of parameter step by the given length. MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = nullptr, - VERSION version = Math::DefaultMathVersion(), bool * coincParams = nullptr ) const override; + VERSION version = Math::DefaultMathVersion(), bool * coincParams = nullptr ) const override; MbCurve3D * Trimmed( double t1, double t2, int sense ) const override; // \ru Создание усеченной кривой. \en Creation of a trimmed curve. @@ -244,34 +244,35 @@ public: // \ru Дать поверхностную кривую, если пространственная кривая поверхностная (после использования вызывать DeleteItem на аргументы) \en Get a surface curve if spatial curve is lying on the surface (after the using call DeleteItem for arguments) bool GetSurfaceCurve( MbCurve *& curve2d, MbSurface *& surface, VERSION version = Math::DefaultMathVersion() ) const override; - double GetAlpha() const { return ::atan( tgAlpha ); } - double GetTgAlpha() const { return tgAlpha; } - void SetAlpha( double a ) { tgAlpha = ::tan( a ); Refresh(); } + double GetAlpha() const { return ::atan( tgAlpha ); } + double GetTgAlpha() const { return tgAlpha; } + void SetAlpha( double a ) { tgAlpha = ::tan( a ); Refresh(); } - double GetR() const { return radius; } - void FastInverse(); - double GetStepD2PI() const { return stepd2pi; } - void GetSpiralDir( MbVector3D & dir ) const; + double GetR() const { return radius; } + void FastInverse(); + double GetStepD2PI() const { return stepd2pi; } + void GetSpiralDir( MbVector3D & dir ) const; - /// \ru Узнать тип конической спирали \en Learn the type of conical spiral. - ConeSpiralType GetType() const { return type; } + /// \ru Узнать тип конической спирали \en Learn the type of conical spiral. + ConeSpiralType GetType() const { return type; } private: - /// \ru Усеченное значение tmax для случая закручивающихся в точку плоской или конической спиралей. \en Trimmed value tmax for the case of planar or conical spirals trailing to the point. - void CalConeTMax(); - /// \ru Текущий радиус. \en The current radius. - double GetR( double t ) const; - /// \ru Производная текущего радиуса. \en The derivative of the current radius. - double GetRDerive( double t ) const; - /// \ru Ближайшая проекция точки на плоскую спираль. \en The nearest point projection on the planar spiral. - bool PlaneProjection( const MbCartPoint3D & pSpace, double & tProj, bool ext, MbRect1D * tRange ) const; - /// \ru Ближайшая проекция точки на цилиндрическую спираль. \en The nearest point projection on the cylindrical spiral. - bool CylindricalProjection( const MbCartPoint3D & pSpace, double & tProj, bool ext, MbRect1D * tRange ) const; + /// \ru Усеченное значение tmax для случая закручивающихся в точку плоской или конической спиралей. \en Trimmed value tmax for the case of planar or conical spirals trailing to the point. + void CalConeTMax(); + /// \ru Текущий радиус. \en The current radius. + double GetR( double t ) const; + /// \ru Производная текущего радиуса. \en The derivative of the current radius. + double GetRDerive( double t ) const; + /// \ru Ближайшая проекция точки на плоскую спираль. \en The nearest point projection on the planar spiral. + bool PlaneProjection( const MbCartPoint3D & pSpace, double & tProj, bool ext, MbRect1D * tRange ) const; + /// \ru Ближайшая проекция точки на цилиндрическую спираль. \en The nearest point projection on the cylindrical spiral. + bool CylindricalProjection( const MbCartPoint3D & pSpace, double & tProj, bool ext, MbRect1D * tRange ) const; private: // \ru Объявление (перегрузка) оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en Declaration (overload) of the assignment operator without its implementation, to prevent the default assignment. MbConeSpiral & operator = ( const MbConeSpiral & ); -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbConeSpiral ) + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbConeSpiral ) + }; IMPL_PERSISTENT_OPS( MbConeSpiral ) diff --git a/C3d/Include/cur_contour.h b/C3d/Include/cur_contour.h index 388b9a8..2f32243 100644 --- a/C3d/Include/cur_contour.h +++ b/C3d/Include/cur_contour.h @@ -137,15 +137,15 @@ 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() ) CalculateGabarit( rect ); return rect; } + const MbRect & GetCube() const { if ( rect.IsEmpty() ) CalculateGabarit( rect ); return rect; } - /// \ru Сбросить рассчитанный габарит контура. \en Reset the calculated contour bounding box. - void SetDirtyGabarit() const { 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? - bool IsGabaritEmpty() const { return rect.IsEmpty(); } + /// \ru Сбросить рассчитанный габарит контура. \en Reset the calculated contour bounding box. + void SetDirtyGabarit() const { 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? + bool IsGabaritEmpty() const { return rect.IsEmpty(); } double DistanceToPoint( const MbCartPoint & ) const override; // \ru Расстояние до точки \en Distance to a point. @@ -205,7 +205,7 @@ public: \{ */ // \ru Вычислить значения точки и производных для заданного параметра. \en Calculate point and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - MbCartPoint & pnt, MbVector & fir, MbVector * sec, MbVector * thir ) const override; + MbCartPoint & pnt, MbVector & fir, MbVector * sec, MbVector * thir ) const override; /** \} */ /** \ru \name Функции движения по кривой @@ -223,103 +223,106 @@ public: double GetLengthEvaluation() const override; // \ru Оценка метрической длины кривой \en Evaluation of the metric length of the curve. double CalculateMetricLength() const override; // \ru Посчитать метрическую длину \en Calculate the metric length - double GetParamLength() const { return paramLength; } - double CalculateParamLength(); // \ru Посчитать параметрическую длину \en Calculate the parametric length + double GetParamLength() const { return paramLength; } + double CalculateParamLength(); // \ru Посчитать параметрическую длину \en Calculate the parametric length - /// \ru Вычисление площади контура, если контур замкнут. \en Calculation of contour area if contour is closed. - double GetArea( double sag = Math::deviateSag ) const - { - sag = ::fabs(sag); - if ( ::fabs( areaSign.first - sag ) > EXTENT_EPSILON ) - return CalculateArea( sag ); - return areaSign.second; - } + /// \ru Вычисление площади контура, если контур замкнут. \en Calculation of contour area if contour is closed. + double GetArea( double sag = Math::deviateSag ) const + { + sag = ::fabs(sag); + if ( ::fabs( areaSign.first - sag ) > EXTENT_EPSILON ) + return CalculateArea( sag ); + return areaSign.second; + } MbNurbs * NurbsCurve( const MbCurveIntoNurbsInfo & ) const override; MbContour * NurbsContour() const override; - void SetClosed(); ///< \ru Установить признак замкнутости контура. \en Set the closedness attribute of contour. - void CheckClosed( double closedEps ); ///< \ru Установить признак замкнутости контура. \en Set the closedness attribute of contour. - void InitClosed( bool c ) { closed = c; } ///< \ru Установить признак замкнутости контура. \en Set the closedness attribute of contour. + void SetClosed(); ///< \ru Установить признак замкнутости контура. \en Set the closedness attribute of contour. + void CheckClosed( double closedEps ); ///< \ru Установить признак замкнутости контура. \en Set the closedness attribute of contour. + void InitClosed( bool c ) { closed = c; } ///< \ru Установить признак замкнутости контура. \en Set the closedness attribute of contour. - /** \brief \ru Проверить замкнутость и непрерывность точек контура. - \en Check for closedness and continuity of contour points. \~ - \details \ru Проверить замкнутость и непрерывность точек контура. - Проверяется совпадение первой и последней точки контура, - совпадение последней точки каждого сегмента с первой точкой следующего сегмента. - Равенство точек проверяется по умолчанию грубо - с точностью, равной 5 * PARAM_NEAR. - \en Check for closedness and continuity of contour points. - Checking for coincidence of first and last points of the contour, - coincidence of the last point of each segment with the first point of the next segment. - Equality of points is checked roughly by default - with tolerance is equal to 5* PARAM_NEAR. \~ - \return \ru true, если контур замкнутый и непрерывный. - \en true, if contour is closed and continuous. \~ - */ - bool IsClosedContinuousC0( double eps = 5.0 * PARAM_NEAR ) const; + /** \brief \ru Проверить замкнутость и непрерывность точек контура. + \en Check for closedness and continuity of contour points. \~ + \details \ru Проверить замкнутость и непрерывность точек контура. + Проверяется совпадение первой и последней точки контура, + совпадение последней точки каждого сегмента с первой точкой следующего сегмента. + Равенство точек проверяется по умолчанию грубо - с точностью, равной 5 * PARAM_NEAR. + \en Check for closedness and continuity of contour points. + Checking for coincidence of first and last points of the contour, + coincidence of the last point of each segment with the first point of the next segment. + Equality of points is checked roughly by default - with tolerance is equal to 5* PARAM_NEAR. \~ + \return \ru true, если контур замкнутый и непрерывный. + \en true, if contour is closed and continuous. \~ + */ + bool IsClosedContinuousC0( double eps = 5.0 * PARAM_NEAR ) const; - void CloseByLineSeg( bool calcInternalData ); ///< \ru Замкнуть контур отрезком. \en Close the contour by segment. + void CloseByLineSeg( bool calcInternalData ); ///< \ru Замкнуть контур отрезком. \en Close the contour by segment. // \ru Посчитать метрическую длину разомкнутой кривой с заданной точностью \en Calculate the metric length of unclosed curve within the given tolerance double CalculateLength( double t1, double t2 ) const override; // \ru Сдвинуть параметр t на расстояние len \en Move parameter t on the distance len bool DistanceAlong( double & t, double len, int curveDir, double eps = Math::LengthEps, - VERSION version = Math::DefaultMathVersion() ) const override; - /// \ru Cбросить переменные кэширования. \en Reset variables caching. - void Clear( bool calculateParamLength = true ) - { - if ( calculateParamLength ) - CalculateParamLength(); // \ru Параметрическая длина контура \en Parametric length of a contour - metricLength = -1; // \ru Метрическая длина кривой \en Metric length of a curve - rect.SetEmpty(); - areaSign.first = -1.0; - } - /** \brief \ru Найти сегмент контура. - \en Find a contour segment. \~ - \details \ru Найти сегмент контура по параметру контура. \n - \en Find a contour segment by parameter on contour. \n \~ - \param[in,out] t - \ru Параметр контура. - \en Contour parameter. \~ - \param[out] tSeg - \ru Параметр сегмента контура. - \en Contour segment parameter. \~ - \return \ru Возвращает номер сегмента в случае успешного выполнения или -1. - \en Returns the segment number in case of successful execution or -1. \~ - */ - ptrdiff_t FindSegment( double & t, double & tSeg ) const; + VERSION version = Math::DefaultMathVersion() ) const override; + /// \ru Cбросить переменные кэширования. \en Reset variables caching. + void Clear( bool calculateParamLength = true ) + { + if ( calculateParamLength ) + CalculateParamLength(); // \ru Параметрическая длина контура \en Parametric length of a contour + metricLength = -1; // \ru Метрическая длина кривой \en Metric length of a curve + rect.SetEmpty(); + areaSign.first = -1.0; + } + /** \brief \ru Найти сегмент контура. + \en Find a contour segment. \~ + \details \ru Найти сегмент контура по параметру контура. \n + \en Find a contour segment by parameter on contour. \n \~ + \param[in,out] t - \ru Параметр контура. + \en Contour parameter. \~ + \param[out] tSeg - \ru Параметр сегмента контура. + \en Contour segment parameter. \~ + \return \ru Возвращает номер сегмента в случае успешного выполнения или -1. + \en Returns the segment number in case of successful execution or -1. \~ + */ + ptrdiff_t FindSegment( double & t, double & tSeg ) const; - size_t GetSegmentsCount() const { return segments.size(); } ///< \ru Выдать количество сегментов контура. \en Get the number of contour segments. + size_t GetSegmentsCount() const { return segments.size(); } ///< \ru Выдать количество сегментов контура. \en Get the number of contour segments. const MbCurve * GetSegment( size_t ind ) const { return segments[ind]; } ///< \ru Выдать сегмент контура по индексу. \en Get contour segment by the index. MbCurve * SetSegment( size_t ind ) { return segments[ind]; } ///< \ru Выдать сегмент контура по индексу. \en Get contour segment by the index. - // \ru Положение точки относительно кривой. \en The point position relative to the curve. - // \ru iloc_InItem = 1 - точка находится слева от контура, \en Iloc_InItem = 1 - point is located to the left of the contour, - // \ru iloc_OnItem = 0 - точка находится на контуре, \en Iloc_OnItem = 0 - point is located on the contour, - // \ru iloc_OutOfItem = -1 - точка находится справа от контура. \en Iloc_OutOfItem = -1 - point is located to the right of the contour. + // \ru Положение точки относительно кривой. \en The point position relative to the curve. + // \ru iloc_InItem = 1 - точка находится слева от контура, \en Iloc_InItem = 1 - point is located to the left of the contour, + // \ru iloc_OnItem = 0 - точка находится на контуре, \en Iloc_OnItem = 0 - point is located on the contour, + // \ru iloc_OutOfItem = -1 - точка находится справа от контура. \en Iloc_OutOfItem = -1 - point is located to the right of the contour. MbeItemLocation PointRelative( const MbCartPoint & pnt, double eps = Math::LengthEps ) const override; - // \ru Положение точки относительно кривой. \en The point position relative to the curve. + // \ru Положение точки относительно кривой. \en The point position relative to the curve. MbeLocation PointLocation( const MbCartPoint & pnt, double eps = Math::LengthEps ) const override; double PointProjection( const MbCartPoint & ) const override; // \ru Проекция точки на кривую \en Point projection on the curve bool NearPointProjection( const MbCartPoint &, double xEpsilon, double yEpsilon, - double & t, bool ext, MbRect1D * tRange = nullptr ) const override; // \ru Проекция точки на кривую или её продолжение в области поиска проекции \en Point projection on the curve or its extension in the projection search area + double & t, bool ext, MbRect1D * tRange = nullptr ) const override; // \ru Проекция точки на кривую или её продолжение в области поиска проекции \en Point projection on the curve or its extension in the projection search area - /** \brief \ru Параметрическое расстояние до ближайшей границы. - \en Parametric distance to the nearest boundary. - \details \ru Параметрическое расстояние до ближайшей границы. \n - \en Parametric distance to the nearest boundary. \n \~ - \param[in] pnt - \ru Тестируемая точка. - \en A testing point. \~ - \param[in] eps - \ru Точность. - \en Accuracy. \~ - \return \ru Расстояние до ближайшей границы. - \en Distance to the nearest boundary. \~ - */ - double DistanceToBorder( const MbCartPoint & pnt, double eps = Math::paramRegion ) const; + /** \brief \ru Параметрическое расстояние до ближайшей границы. + \en Parametric distance to the nearest boundary. + \details \ru Параметрическое расстояние до ближайшей границы. \n + \en Parametric distance to the nearest boundary. \n \~ + \param[in] pnt - \ru Тестируемая точка. + \en A testing point. \~ + \param[in] eps - \ru Точность. + \en Accuracy. \~ + \return \ru Расстояние до ближайшей границы. + \en Distance to the nearest boundary. \~ + */ + double DistanceToBorder( const MbCartPoint & pnt, double eps = Math::paramRegion ) const; - void Trimm( double t1, double t2 ); ///< \ru Выделить часть контура. \en Trim a part of the contour. + void Trimm( double t1, double t2 ); ///< \ru Выделить часть контура. \en Trim a part of the contour. - // \ru Вычисление всех перпендикуляров к кривой из данной точки \en Calculation of all perpendiculars to the curve from a given point + // \ru Продлить кривую. \en Extend the curve. \~ + MbResultType Extend( const MbCurveExtensionParameters & parameters, c3d::PlaneCurveSPtr & resCurve ) const override; + + // \ru Вычисление всех перпендикуляров к кривой из данной точки \en Calculation of all perpendiculars to the curve from a given point void PerpendicularPoint( const MbCartPoint &, SArray & tFind ) const override; - // \ru Вычисление всех касательных к кривой из данной точки \en Calculation of all tangents to the curve from a given point + // \ru Вычисление всех касательных к кривой из данной точки \en Calculation of all tangents to the curve from a given point void TangentPoint( const MbCartPoint &, SArray & tFind ) const override; @@ -327,126 +330,126 @@ public: void IntersectVertical ( double x, SArray & ) const override; // \ru Пересечение с вертикальной прямой \en Intersection with the vertical line void SelfIntersect( SArray &, double metricEps = Math::LengthEps ) const override; // \ru Самопересечение контура \en Self-intersection of the contour - /** \brief \ru Есть ли самопересечения контура? - \en Is it a contour with self-intersections? \~ - \details \ru Есть ли самопересечения контура? - \en Is it a contour with self-intersections? \~ - \param[in] metricEps - \ru Точность (по умолчанию рекомендуется использовать Math::LengthEps). - \en Accuracy (it's recommended to use Math::LengthEps). \~ - \param[in] considerPartialCoincidence - \ru Считать частичное совпадение соседних сегментов самопересечением (true - по умолчанию). - \en Consider partial coincidence of neighboring segments as self-intersection (true - by default). \~ - */ - bool IsSelfIntersect( double metricEps, bool considerPartialCoincidence ) const; + /** \brief \ru Есть ли самопересечения контура? + \en Is it a contour with self-intersections? \~ + \details \ru Есть ли самопересечения контура? + \en Is it a contour with self-intersections? \~ + \param[in] metricEps - \ru Точность (по умолчанию рекомендуется использовать Math::LengthEps). + \en Accuracy (it's recommended to use Math::LengthEps). \~ + \param[in] considerPartialCoincidence - \ru Считать частичное совпадение соседних сегментов самопересечением (true - по умолчанию). + \en Consider partial coincidence of neighboring segments as self-intersection (true - by default). \~ + */ + bool IsSelfIntersect( double metricEps, bool considerPartialCoincidence ) const; - // \ru Функции находятся в файле equcntr.cpp \en Functions are in the file equcntr.cpp + // \ru Функции находятся в файле equcntr.cpp \en Functions are in the file equcntr.cpp - /// \ru Скругление двух соседних элементов с информацией об удалении \en Fillet of two neighboring elements with information about removal - bool FilletTwoSegments( ptrdiff_t & index, double rad, bool & del1, bool & del2 ); - /// \ru Скругление двух соседних элементов \en Fillet of two neighboring elements - bool FilletTwoSegments( ptrdiff_t & index, double rad ); - /// \ru Вставка фаски между двумя соседними элементами с информацией об удалении \en Insertion of chamfer between two neighboring elements with information about removal - bool ChamferTwoSegments( ptrdiff_t & index, double len, double angle, - bool type, bool firstSeg, bool & del1, bool & del2 ); - /// \ru Вставка фаски между двумя соседними элементами \en Insertion of chamfer between two neighboring elements - bool ChamferTwoSegments( ptrdiff_t & index, double len, double angle, - bool type, bool firstSeg = true ); - bool Fillet( double rad ); ///< \ru Скругление контура \en Fillet of contour - bool Chamfer( double len, double angle, bool type ); ///< \ru Вставка фаски \en Insertion of the chamfer - MbeState RemoveFilletOrChamfer( const MbCartPoint & pnt ); ///< \ru Удалить скругление или фаску контура \en Remove fillet or contour chamfer - /// \ru Разбить контур на непересекающиеся сегменты. \en Split contour into non-overlapping segments. - bool InsertCrossPoints(); - /// \ru Разбиение сегментов контура в точках пересечения. \en Splitting of contour segments at the points of intersection. - void BreakSegment( ptrdiff_t & index, ptrdiff_t firtsIdx, - SArray & cross, bool firstCurve = true ); + /// \ru Скругление двух соседних элементов с информацией об удалении \en Fillet of two neighboring elements with information about removal + bool FilletTwoSegments( ptrdiff_t & index, double rad, bool & del1, bool & del2 ); + /// \ru Скругление двух соседних элементов \en Fillet of two neighboring elements + bool FilletTwoSegments( ptrdiff_t & index, double rad ); + /// \ru Вставка фаски между двумя соседними элементами с информацией об удалении \en Insertion of chamfer between two neighboring elements with information about removal + bool ChamferTwoSegments( ptrdiff_t & index, double len, double angle, + bool type, bool firstSeg, bool & del1, bool & del2 ); + /// \ru Вставка фаски между двумя соседними элементами \en Insertion of chamfer between two neighboring elements + bool ChamferTwoSegments( ptrdiff_t & index, double len, double angle, + bool type, bool firstSeg = true ); + bool Fillet( double rad ); ///< \ru Скругление контура \en Fillet of contour + bool Chamfer( double len, double angle, bool type ); ///< \ru Вставка фаски \en Insertion of the chamfer + MbeState RemoveFilletOrChamfer( const MbCartPoint & pnt ); ///< \ru Удалить скругление или фаску контура \en Remove fillet or contour chamfer + /// \ru Разбить контур на непересекающиеся сегменты. \en Split contour into non-overlapping segments. + bool InsertCrossPoints(); + /// \ru Разбиение сегментов контура в точках пересечения. \en Splitting of contour segments at the points of intersection. + void BreakSegment( ptrdiff_t & index, ptrdiff_t firtsIdx, + SArray & cross, bool firstCurve = true ); - bool CheckConnection( double eps = Math::LengthEps ) const; ///< \ru Проверка непрерывности контура \en Check for contour continuity. - bool CheckConnection( double xEps, double yEps ) const; ///< \ru Проверка непрерывности контура \en Check for contour continuity. + bool CheckConnection( double eps = Math::LengthEps ) const; ///< \ru Проверка непрерывности контура \en Check for contour continuity. + bool CheckConnection( double xEps, double yEps ) const; ///< \ru Проверка непрерывности контура \en Check for contour continuity. - /// \ru Скругление двух соседних элементов дугой нулевого радиуса. \en Rounding two neighboring elements by arc of zero radius. - void FilletTwoSegmentsZero( ptrdiff_t & index, int defaultSense, bool fullInsert ); - /// \ru Скругление контура дугой нулевого радиуса. \en Rounding contour by arc of zero radius. - void FilletZero( int defaultSense, bool fullInsert = false ); - /// \ru Вставка фаски между двумя соседними элементами для построения эквидистанты. \en Insertion of chamfer between two neighboring elements for construction of the offset. - void ChamferTwoSegmentsZero( ptrdiff_t & index, double rad ); - /// \ru Вставка фаски для построения эквидистанты. \en Insertion of chamfer for construction of the offset. - void ChamferZero( double rad ); - /// \ru Удаление вырожденных сегментов контура. \en Removal of degenerate contour segments. - void DeleteDegenerateSegments( double radius, MbCurve * curve, bool mode ); + /// \ru Скругление двух соседних элементов дугой нулевого радиуса. \en Rounding two neighboring elements by arc of zero radius. + void FilletTwoSegmentsZero( ptrdiff_t & index, int defaultSense, bool fullInsert ); + /// \ru Скругление контура дугой нулевого радиуса. \en Rounding contour by arc of zero radius. + void FilletZero( int defaultSense, bool fullInsert = false ); + /// \ru Вставка фаски между двумя соседними элементами для построения эквидистанты. \en Insertion of chamfer between two neighboring elements for construction of the offset. + void ChamferTwoSegmentsZero( ptrdiff_t & index, double rad ); + /// \ru Вставка фаски для построения эквидистанты. \en Insertion of chamfer for construction of the offset. + void ChamferZero( double rad ); + /// \ru Удаление вырожденных сегментов контура. \en Removal of degenerate contour segments. + void DeleteDegenerateSegments( double radius, MbCurve * curve, bool mode ); - /** \brief \ru Построение эквидистанты к контуру. - \en Construction of offset to contour. \~ - \details \ru Построение эквидистанты к контуру справа и слева. - Имя каждого эквидистантного контура совпадает с именем исходного. - \en Construction of offset to contour of the left and right. - A name of every offset contour matches with the name of the initial one. \~ - \param[in] radLeft - \ru Радиус эквидистанты слева по направлению. - \en The equidistance radius on the left by direction. \~ - \param[in] radRight - \ru Радиус эквидистанты справа по направлению. - \en The equidistance radius on the right by direction. \~ - \param[in] side - \ru Признак, с какой стороны строить:\n - 0 - слева по направлению,\n - 1 - справа по направлению,\n - 2 - с двух сторон. - \en Attribute defining the side to construct:\n - 0 - on the left by direction,\n - 1 - on the right by direction,\n - 2 - on the both sides. \~ - \param[in] mode - \ru Cпособ обхода углов:\n - true - дугой, - false - срезом. - \en The way of traverse of angles:\n - true - by arc, - false - by section. \~ - \param[out] equLeft - \ru Массив контуров слева. - \en The array of contours on the left side. \~ - \param[out] equRight - \ru Массив контуров справа. - \en The array of contours on the right side. \~ - */ - void Equid( double radLeft, double radRight, int side, bool mode, - PArray & equLeft, PArray & equRight ); + /** \brief \ru Построение эквидистанты к контуру. + \en Construction of offset to contour. \~ + \details \ru Построение эквидистанты к контуру справа и слева. + Имя каждого эквидистантного контура совпадает с именем исходного. + \en Construction of offset to contour of the left and right. + A name of every offset contour matches with the name of the initial one. \~ + \param[in] radLeft - \ru Радиус эквидистанты слева по направлению. + \en The equidistance radius on the left by direction. \~ + \param[in] radRight - \ru Радиус эквидистанты справа по направлению. + \en The equidistance radius on the right by direction. \~ + \param[in] side - \ru Признак, с какой стороны строить:\n + 0 - слева по направлению,\n + 1 - справа по направлению,\n + 2 - с двух сторон. + \en Attribute defining the side to construct:\n + 0 - on the left by direction,\n + 1 - on the right by direction,\n + 2 - on the both sides. \~ + \param[in] mode - \ru Cпособ обхода углов:\n + true - дугой, + false - срезом. + \en The way of traverse of angles:\n + true - by arc, + false - by section. \~ + \param[out] equLeft - \ru Массив контуров слева. + \en The array of contours on the left side. \~ + \param[out] equRight - \ru Массив контуров справа. + \en The array of contours on the right side. \~ + */ + void Equid( double radLeft, double radRight, int side, bool mode, + PArray & equLeft, PArray & equRight ); - /// \ru Построение новых контуров из эквидистанты. \en Construction of new contours from equidistance. - void CreateNewContours( RPArray & ); + /// \ru Построение новых контуров из эквидистанты. \en Construction of new contours from equidistance. + void CreateNewContours( RPArray & ); - /// \ru Вычисление площади контура, если контур замкнут. \en Calculation of contour area if contour is closed. - double CalculateArea( double sag = Math::deviateSag ) const; - /// \ru Определение направления обхода контура, если контур замкнут. \en Determination of traverse direction if contour is closed. - int GetSense() const; - /// \ru Установить направление обхода контура. \en Set the traverse direction of the contour. - void SetSense( int sense ); + /// \ru Вычисление площади контура, если контур замкнут. \en Calculation of contour area if contour is closed. + double CalculateArea( double sag = Math::deviateSag ) const; + /// \ru Определение направления обхода контура, если контур замкнут. \en Determination of traverse direction if contour is closed. + int GetSense() const; + /// \ru Установить направление обхода контура. \en Set the traverse direction of the contour. + void SetSense( int sense ); // \ru Изменить направление обхода контура \en Change the traverse direction of the contour void Inverse( MbRegTransform * = nullptr ) override; - // \ru Согласовать параметризацию сегментов, если до инвертации она была согласованной. \en Agree on segment parameterization, if it was consistent before inversion. - bool NormalizeReparametrization(); + // \ru Согласовать параметризацию сегментов, если до инвертации она была согласованной. \en Agree on segment parameterization, if it was consistent before inversion. + bool NormalizeReparametrization(); size_t GetCount() const override; // \ru Количество разбиений для прохода в операциях \en The number of partitions for passage in the operations - // \ru Выдать характерную точку ограниченной кривой если она ближе чем dmax \en Get characteristic point of bounded curve if it is closer than dmax + // \ru Выдать характерную точку ограниченной кривой если она ближе чем dmax \en Get characteristic point of bounded curve if it is closer than dmax bool DistanceToPointIfLess( const MbCartPoint & toP, double & d ) const override; // \ru Расстояние до точки, если оно меньше d \en Distance to the point if it is less than d bool GetSpecificPoint( const MbCartPoint & from, double & dmax, MbCartPoint & pnt ) const override; - /// \ru Выдать среднюю точку сегмента контура. \en Get a mid-point of the contour segment. - bool GetSegmentMiddlePoint( const MbCartPoint & from, MbCartPoint & midPoint ) const; - /// \ru Выдать линейный сегмент контура. \en Get the linear segment of contour. - bool GetLinearSegment( const MbCartPoint & from, double maxDist, MbCartPoint & p1, MbCartPoint & p2, double & d ) const; - /// \ru Выдать дуговой сегмент контура. \en Get the arc segment of contour. - MbArc * GetArcSegment( const MbCartPoint & from, double maxDist, double & d ) const; - /// \ru Выдать длину сегмента контура. \en Get the contour segment length. - bool GetSegmentLength( const MbCartPoint & from, double & length ) const; + /// \ru Выдать среднюю точку сегмента контура. \en Get a mid-point of the contour segment. + bool GetSegmentMiddlePoint( const MbCartPoint & from, MbCartPoint & midPoint ) const; + /// \ru Выдать линейный сегмент контура. \en Get the linear segment of contour. + bool GetLinearSegment( const MbCartPoint & from, double maxDist, MbCartPoint & p1, MbCartPoint & p2, double & d ) const; + /// \ru Выдать дуговой сегмент контура. \en Get the arc segment of contour. + MbArc * GetArcSegment( const MbCartPoint & from, double maxDist, double & d ) const; + /// \ru Выдать длину сегмента контура. \en Get the contour segment length. + bool GetSegmentLength( const MbCartPoint & from, double & length ) const; bool GetWeightCentre( MbCartPoint & ) const override; // \ru Выдать центр тяжести контура \en Get gravity center of contour bool GetCentre ( MbCartPoint & ) const override; // \ru Выдать центр кривой \en Get the center of curve - /// \ru Найти ближайший к точке узел контура. \en Find the nearest node of contour to point. - ptrdiff_t FindNearestNode( const MbCartPoint & to ) const; - /// \ru Найти ближайший к точке сегмент контура. \en Find the nearest segment of contour to point. - ptrdiff_t FindNearestSegment( const MbCartPoint & to ) const; + /// \ru Найти ближайший к точке узел контура. \en Find the nearest node of contour to point. + ptrdiff_t FindNearestNode( const MbCartPoint & to ) const; + /// \ru Найти ближайший к точке сегмент контура. \en Find the nearest segment of contour to point. + ptrdiff_t FindNearestSegment( const MbCartPoint & to ) const; - // \ru Определение особых точек офсетной кривой \en Determination of singular points of the offset curve + // \ru Определение особых точек офсетной кривой \en Determination of singular points of the offset curve void OffsetCuspPoint( SArray & tCusps, double dist ) const override; double GetRadius() const override; // \ru Дать физический радиус объекта или ноль, если это невозможно. \en Get the physical radius of the object or null if it impossible. bool GetAxisPoint( MbCartPoint & ) const override; // \ru Выдать центр оси кривой. \en Give the curve axis center. - void CombineNurbsSegments(); ///< \ru Объединить NURBS кривые в контуре. \en Unite NURBS curves into the contour. + void CombineNurbsSegments(); ///< \ru Объединить NURBS кривые в контуре. \en Unite NURBS curves into the contour. void GetProperties( MbProperties & ) override; // \ru Выдать свойства объекта \en Get properties of the object void SetProperties( const MbProperties & ) override; // \ru Записать свойства объекта \en Set properties of the object @@ -487,157 +490,158 @@ public: \en \name Function for working with segments of contour \{ */ - bool Init( List & ); ///< \ru Инициализация по списку кривых. \en Initialization by list of curves. - void Init( const MbContour & ); ///< \ru Инициализация по контуру. \en Initialization by a contour. + bool Init( List & ); ///< \ru Инициализация по списку кривых. \en Initialization by list of curves. + void Init( const MbContour & ); ///< \ru Инициализация по контуру. \en Initialization by a contour. - /** \brief \ru Инициализация по массиву кривых. - \en Initialization by array of curves. \~ - \details \ru Инициализация по массиву кривых. \n - \en Initialization by array of curves. \n \~ - \param[in] curves - \ru Кривые. - \en Curves. \~ - \param[in] sameCurves - \ru Использовать оригиналы кривых (true) или их копии (false). - \en Use original curves (true) or copies thereof (false). \~ - \return \ru Возвращает true, если кривые были добавлена. - \en Returns true if curves were added. \~ - */ - template - bool Init( Curves & curves, bool sameCurves ); - /// \ru Инициализация по массиву точек (замкнутый контур). \en Initialization by array of points (closed contour). - template - bool InitByPoints( const Points & ); + /** \brief \ru Инициализация по массиву кривых. + \en Initialization by array of curves. \~ + \details \ru Инициализация по массиву кривых. \n + \en Initialization by array of curves. \n \~ + \param[in] curves - \ru Кривые. + \en Curves. \~ + \param[in] sameCurves - \ru Использовать оригиналы кривых (true) или их копии (false). + \en Use original curves (true) or copies thereof (false). \~ + \return \ru Возвращает true, если кривые были добавлена. + \en Returns true if curves were added. \~ + */ + template + bool Init( Curves & curves, bool sameCurves ); + /// \ru Инициализация по массиву точек (замкнутый контур). \en Initialization by array of points (closed contour). + template + bool InitByPoints( const Points & ); - bool InitAsRectangle( const MbCartPoint * ); ///< \ru Инициализация как прямоугольника ( приходит 4 точки ) \en Initialization as rectangle (4 points are given). - bool InitByRectangle( const MbRect & ); ///< \ru Инициализация по прямоугольнику габарита. \en Initialization by rectangle of bounding box. + bool InitAsRectangle( const MbCartPoint * ); ///< \ru Инициализация как прямоугольника ( приходит 4 точки ) \en Initialization as rectangle (4 points are given). + bool InitByRectangle( const MbRect & ); ///< \ru Инициализация по прямоугольнику габарита. \en Initialization by rectangle of bounding box. - bool AddSegment ( MbCurve * ); ///< \ru Добавить сегмент в контур. \en Add a segment to the contour. - bool AddSegmentOrDeleteCurve( MbCurve * ); ///< \ru Добавить кривую как сегмент или удалить ее. \en Add a curve as segment or remove its. + bool AddSegment ( MbCurve * ); ///< \ru Добавить сегмент в контур. \en Add a segment to the contour. + bool AddSegmentOrDeleteCurve( MbCurve * ); ///< \ru Добавить кривую как сегмент или удалить ее. \en Add a curve as segment or remove its. - /** \brief \ru Добавить (усеченную) копию сегмента в конец контура. - \en Add a (truncated) segment copy to the end of the contour. \~ - \details \ru Добавить (усеченную) копию сегмента в конец контура. \n - \en Add a (truncated) segment copy to the end of the contour. \n \~ - \param[in] pBasis- \ru Исходная кривая. - \en Initial curve. \~ - \param[in] t1 - \ru Начальный параметр усечения. - \en Truncation starting parameter. \~ - \param[in] t2 - \ru Конечный параметр усечения. - \en Truncation ending parameter. \~ - \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. \~ - \return \ru Возвращает в случае успешного выполнения ненулевой указатель на добавленную кривую. - \en Returns, if successful, a non-zero pointer to the added curve. \~ - */ - MbCurve * AddSegment( const MbCurve * pBasis, double t1, double t2, int sense = 1 ); + /** \brief \ru Добавить (усеченную) копию сегмента в конец контура. + \en Add a (truncated) segment copy to the end of the contour. \~ + \details \ru Добавить (усеченную) копию сегмента в конец контура. \n + \en Add a (truncated) segment copy to the end of the contour. \n \~ + \param[in] pBasis- \ru Исходная кривая. + \en Initial curve. \~ + \param[in] t1 - \ru Начальный параметр усечения. + \en Truncation starting parameter. \~ + \param[in] t2 - \ru Конечный параметр усечения. + \en Truncation ending parameter. \~ + \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. \~ + \return \ru Возвращает в случае успешного выполнения ненулевой указатель на добавленную кривую. + \en Returns, if successful, a non-zero pointer to the added curve. \~ + */ + MbCurve * AddSegment( const MbCurve * pBasis, double t1, double t2, int sense = 1 ); - bool AddAtSegment ( MbCurve * newSegment, size_t index ); ///< \ru Вставить сегмент перед сегментом контура с индексом index. \en Insert a segment before the contour segment with the index "index". - bool AddAfterSegment( MbCurve * newSegment, size_t index ); ///< \ru Вставить сегмент после сегмента контура с индексом index. \en Insert a segment after the contour segment with the index "index". + bool AddAtSegment ( MbCurve * newSegment, size_t index ); ///< \ru Вставить сегмент перед сегментом контура с индексом index. \en Insert a segment before the contour segment with the index "index". + bool AddAfterSegment( MbCurve * newSegment, size_t index ); ///< \ru Вставить сегмент после сегмента контура с индексом index. \en Insert a segment after the contour segment with the index "index". - /** \brief \ru Добавить новый элемент в начало или конец контура. - \en Add the new element to the beginning or end of contour. \~ - \details \ru Добавить новый элемент в начало или конец контура. \n - \en Add the new element to the beginning or end of contour. \n \~ - \param[in] curve - \ru Добавляемая кривая. - \en Added curve. \~ - \param[in] absEps - \ru Точность проверки совпадения концов кривых (1e-8 - 1e-4). - \en Accuracy of verification of curve end coincidence (1e-8 - 1e-4). \~ - \param[in] toEndOnly - \ru Добавлять кривую только в конец контура. - \en Add the curve only at the end of the contour. \~ - \param[in] checkSame - \ru Проверять наличие такой же (добавляемой) кривой в контуре. - \en Check a presence of the same curve in the contour. \~ - \param[in] version - \ru Версия. - \en Version. \~ - \return \ru Возвращает true, если кривая была добавлена. - \en Returns true if the curve was added. \~ - */ - bool AddCurveWithRuledCheck( MbCurve & newCur, double absEps, bool toEndOnly = false, bool checkSame = true, - VERSION version = Math::DefaultMathVersion() ); + /** \brief \ru Добавить новый элемент в начало или конец контура. + \en Add the new element to the beginning or end of contour. \~ + \details \ru Добавить новый элемент в начало или конец контура. \n + \en Add the new element to the beginning or end of contour. \n \~ + \param[in] curve - \ru Добавляемая кривая. + \en Added curve. \~ + \param[in] absEps - \ru Точность проверки совпадения концов кривых (1e-8 - 1e-4). + \en Accuracy of verification of curve end coincidence (1e-8 - 1e-4). \~ + \param[in] toEndOnly - \ru Добавлять кривую только в конец контура. + \en Add the curve only at the end of the contour. \~ + \param[in] checkSame - \ru Проверять наличие такой же (добавляемой) кривой в контуре. + \en Check a presence of the same curve in the contour. \~ + \param[in] version - \ru Версия. + \en Version. \~ + \return \ru Возвращает true, если кривая была добавлена. + \en Returns true if the curve was added. \~ + */ + bool AddCurveWithRuledCheck( MbCurve & newCur, double absEps, bool toEndOnly = false, bool checkSame = true, + VERSION version = Math::DefaultMathVersion() ); - void DeleteSegments(); ///< \ru Удалить все сегменты в контуре. \en Remove all segments from contour. - void DeleteSegment( size_t ind ); ///< \ru Удалить сегмент в контуре. \en Remove a segment from contour. - void DetachSegments(); ///< \ru Отцепить все сегменты от контура без удаления. \en Detach all segments from the contour without removing. - MbCurve * DetachSegment( size_t ind ); ///< \ru Отцепить сегмент от контура и вернуть его. \en Detach a segment from contour return it. - template - void DetachSegments( CurvesVector & segms ); ///< \ru Отцепить все сегменты от контура без удаления. \en Detach all segments from the contour without removing. + void DeleteSegments(); ///< \ru Удалить все сегменты в контуре. \en Remove all segments from contour. + void DeleteSegment( size_t ind ); ///< \ru Удалить сегмент в контуре. \en Remove a segment from contour. + void DetachSegments(); ///< \ru Отцепить все сегменты от контура без удаления. \en Detach all segments from the contour without removing. + MbCurve * DetachSegment( size_t ind ); ///< \ru Отцепить сегмент от контура и вернуть его. \en Detach a segment from contour return it. - void SetSegment( MbCurve & newSegment, size_t ind ); ///< \ru Заменить сегмент в контуре. \en Replace a segment in the contour. - void SegmentsAdd( MbCurve & newSegment, bool calculateParamLength = true ); ///< \ru Добавить сегмент в контур без проверки. \en Add a segment to the contour without checking. - void SegmentsInsert( size_t ind, MbCurve & newSegment ); ///< \ru Вставить сегмент в контур перед индексом без проверки. \en Insert a segment into contour before an index without checking. - void SegmentsRemove( size_t ind ); ///< \ru Удалить сегмент без проверки. \en Remove a segment without checking. - void SegmentsDetach( size_t ind ); ///< \ru Отцепить сегмент без проверки. \en Detach a segment without checking. + template + void DetachSegments( CurvesVector & segms ); ///< \ru Отцепить все сегменты от контура без удаления. \en Detach all segments from the contour without removing. - void Calculate( bool calcArea = false ); ///< \ru Рассчитать параметры: rect, paramLength, metricLength, closed. \en Calculate parameters: rect, paramLength, metricLength, closed. + void SetSegment( MbCurve & newSegment, size_t ind ); ///< \ru Заменить сегмент в контуре. \en Replace a segment in the contour. + void SegmentsAdd( MbCurve & newSegment, bool calculateParamLength = true ); ///< \ru Добавить сегмент в контур без проверки. \en Add a segment to the contour without checking. + void SegmentsInsert( size_t ind, MbCurve & newSegment ); ///< \ru Вставить сегмент в контур перед индексом без проверки. \en Insert a segment into contour before an index without checking. + void SegmentsRemove( size_t ind ); ///< \ru Удалить сегмент без проверки. \en Remove a segment without checking. + void SegmentsDetach( size_t ind ); ///< \ru Отцепить сегмент без проверки. \en Detach a segment without checking. - // \ru Управление распределением памяти в массиве segments \en Control of memory allocation in the array "segments" - void SegmentsReserve( size_t additionalSpace ) { segments.Reserve( additionalSpace ); } ///< \ru Зарезервировать место под столько элементов. \en Reserve memory for this number of elements. - void SegmentsAdjust () { segments.Adjust(); } ///< \ru Удалить лишнюю память. \en Free the unnecessary memory. + void Calculate( bool calcArea = false ); ///< \ru Рассчитать параметры: rect, paramLength, metricLength, closed. \en Calculate parameters: rect, paramLength, metricLength, closed. + + // \ru Управление распределением памяти в массиве segments \en Control of memory allocation in the array "segments" + void SegmentsReserve( size_t additionalSpace ) { segments.Reserve( additionalSpace ); } ///< \ru Зарезервировать место под столько элементов. \en Reserve memory for this number of elements. + void SegmentsAdjust () { segments.Adjust(); } ///< \ru Удалить лишнюю память. \en Free the unnecessary memory. template - bool GetSegments( CurvesVector & segms ) const; ///< \ru Получить сегменты контура. \en Get contour segments. + bool GetSegments( CurvesVector & segms ) const; ///< \ru Получить сегменты контура. \en Get contour segments. - void SetMetricLength( double len ) const { 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. - void ReplaceContoursAndPolylines(); - void GetPolygon( double sag, SArray & poly, double eps ) const; ///< \ru Дать точки полигона. \en Get points of polygon. + void SetMetricLength( double len ) const { 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. + void ReplaceContoursAndPolylines(); + void GetPolygon( double sag, SArray & poly, double eps ) const; ///< \ru Дать точки полигона. \en Get points of polygon. - bool IsAnyCurvilinear() const; ///< \ru Есть ли в контуре криволинейный сегмент. \en Whether the contour has a curved segment. - bool IsSameSegments( const MbContour &, double accuracy = PARAM_PRECISION ) const; ///< \ru Содержат ли контура идентичные сегменты. \en Whether contours contains identical segments. - bool GetBegSegmentPoint( size_t i, MbCartPoint & ) const; ///< \ru Дать начальную точку i-го сегмента. \en Get the start point of i-th segment. - bool GetEndSegmentPoint( size_t i, MbCartPoint & ) const; ///< \ru Дать конечную точку i-го сегмента. \en Get the end point of i-th segment. + bool IsAnyCurvilinear() const; ///< \ru Есть ли в контуре криволинейный сегмент. \en Whether the contour has a curved segment. + bool IsSameSegments( const MbContour &, double accuracy = PARAM_PRECISION ) const; ///< \ru Содержат ли контура идентичные сегменты. \en Whether contours contains identical segments. + bool GetBegSegmentPoint( size_t i, MbCartPoint & ) const; ///< \ru Дать начальную точку i-го сегмента. \en Get the start point of i-th segment. + bool GetEndSegmentPoint( size_t i, MbCartPoint & ) const; ///< \ru Дать конечную точку i-го сегмента. \en Get the end point of i-th segment. - /** \brief \ru Нормаль по параметру, учитывая стыки сегментов. - \en Normal by parameter with consideration of segments joints \~ - \details \ru Нормаль по параметру, учитывая стыки сегментов.\n - \en Normal by parameter with consideration of segments joints \n \~ - \param[in] t - \ru Параметр на контуре - \en Parameter on the contour \~ - \param[out] norm - \ru Единичный вектор нормали, если не попали на стык сегментов\n - если попали на стык сегментов - вектор, направленный, - как сумма двух нормалей на сегментах в точке стыка, - с длиной, равной 1, деленной на синус половинного угла между сегментами - \en Unit vector of normal if not hit on the joint of segments \n - if we got on the joint of segments then the vector is directed, - as the sum of two normals on segments in joint, - with length which is equal to 1 divided by the sine of half angle between the segments \~ - \return \ru true, если попали на стык сегментов - \en true, if got on the joint of segments \~ - */ - bool CornerNormal( double t, MbVector & norm ) const; + /** \brief \ru Нормаль по параметру, учитывая стыки сегментов. + \en Normal by parameter with consideration of segments joints \~ + \details \ru Нормаль по параметру, учитывая стыки сегментов.\n + \en Normal by parameter with consideration of segments joints \n \~ + \param[in] t - \ru Параметр на контуре + \en Parameter on the contour \~ + \param[out] norm - \ru Единичный вектор нормали, если не попали на стык сегментов\n + если попали на стык сегментов - вектор, направленный, + как сумма двух нормалей на сегментах в точке стыка, + с длиной, равной 1, деленной на синус половинного угла между сегментами + \en Unit vector of normal if not hit on the joint of segments \n + if we got on the joint of segments then the vector is directed, + as the sum of two normals on segments in joint, + with length which is equal to 1 divided by the sine of half angle between the segments \~ + \return \ru true, если попали на стык сегментов + \en true, if got on the joint of segments \~ + */ + bool CornerNormal( double t, MbVector & norm ) const; - /** \brief \ru Параметры стыков сегментов. - \en Parameters of segments joints. \~ - \details \ru Параметры стыков сегментов кроме минимального - и максимального параметров контура. - \en Parameters of segments joints without minimal - and maximal contour parameter. \~ - \param[out] params - \ru Набор параметров. - \en Set of parameters. \~ - */ - template - void GetCornerParams( Params & params ) const; - // \ru Вычисление всех касательных к кривой из данной точки \en Calculation of all tangents to the curve from a given point + /** \brief \ru Параметры стыков сегментов. + \en Parameters of segments joints. \~ + \details \ru Параметры стыков сегментов кроме минимального + и максимального параметров контура. + \en Parameters of segments joints without minimal + and maximal contour parameter. \~ + \param[out] params - \ru Набор параметров. + \en Set of parameters. \~ + */ + template + void GetCornerParams( Params & params ) const; + // \ru Вычисление всех касательных к кривой из данной точки \en Calculation of all tangents to the curve from a given point - /** \brief \ru Вычисление двух касательных (для параметров стыков). - \en Calculation of two tangents (for parameters of joints). \~ - \details \ru Вычисление двух касательных для параметра стыка по соответствующим сегментам. - Если параметр не стыковой, то касательные равны. - \en Calculation of two tangents for parameter of segments joint corresponding to the segments. - If parameter is not one of parameters of segments joints tangents are equal. - and maximal contour parameter. \~ - \param[in] t - \ru Параметр. - \en A parameter. \~ - \param[out] tan1 - \ru Первая касательная. - \en First tangent. \~ - \param[out] tan2 - \ru Вторая касательная. - \en Second tangent. \~ - */ - bool GetTwoTangents( double t, MbVector & tan1, MbVector & tan2 ) const; + /** \brief \ru Вычисление двух касательных (для параметров стыков). + \en Calculation of two tangents (for parameters of joints). \~ + \details \ru Вычисление двух касательных для параметра стыка по соответствующим сегментам. + Если параметр не стыковой, то касательные равны. + \en Calculation of two tangents for parameter of segments joint corresponding to the segments. + If parameter is not one of parameters of segments joints tangents are equal. + and maximal contour parameter. \~ + \param[in] t - \ru Параметр. + \en A parameter. \~ + \param[out] tan1 - \ru Первая касательная. + \en First tangent. \~ + \param[out] tan2 - \ru Вторая касательная. + \en Second tangent. \~ + */ + bool GetTwoTangents( double t, MbVector & tan1, MbVector & tan2 ) const; /** \} */ /** \ru \name Функции работы с именами контура. @@ -651,7 +655,7 @@ public: \param[out] names - \ru Имена сегментов. \en Names of segments \~ */ - void GetSegmentsNames( SimpleNameArray & names ) const; + void GetSegmentsNames( SimpleNameArray & names ) const; /** \brief \ru Установить имена сегментов. \en Set names of segments. \~ @@ -660,12 +664,12 @@ public: \param[in] names - \ru Набор имен. \en A set of names. \~ */ - void SetSegmentsNames( const SimpleNameArray & names ); + void SetSegmentsNames( const SimpleNameArray & names ); /** \} */ private: - ptrdiff_t _FindSegment( double & t, double & tSeg ) const; // \ru Нахождение сегмента контура \en Finding of a contour segment + ptrdiff_t _FindSegment( double & t, double & tSeg ) const; // \ru Нахождение сегмента контура \en Finding of a contour segment MbContour & operator = ( const MbContour & initContour ); DECLARE_PERSISTENT_CLASS_NEW_DEL( MbContour ) @@ -702,6 +706,7 @@ MbContour::MbContour( const Curves & initCurves, bool same ) SetClosed(); // установить признак замкнутости контура } + //------------------------------------------------------------------------------ // \ru Инициализация по массиву точек (замкнутый контур). \en Initialization by array of points (closed contour). // --- @@ -725,6 +730,7 @@ bool MbContour::InitByPoints( const Points & points ) return false; } + //------------------------------------------------------------------------------ // \ru Инициализация по массиву кривых. \en Initialization by array of curves. // --- @@ -753,6 +759,7 @@ bool MbContour::Init( Curves & curves, bool same ) return res; } + //------------------------------------------------------------------------------ // \ru Получить сегменты контура. \en Get contour segments. // --- @@ -771,6 +778,7 @@ bool MbContour::GetSegments( CurvesVector & segms ) const return res; } + //------------------------------------------------------------------------------ // \ru Отцепить все сегменты от контура без удаления. \en Detach all segments from the contour without removing. // --- diff --git a/C3d/Include/cur_contour3d.h b/C3d/Include/cur_contour3d.h index 7f24c67..97532c3 100644 --- a/C3d/Include/cur_contour3d.h +++ b/C3d/Include/cur_contour3d.h @@ -152,7 +152,7 @@ public: \{ */ // \ru Вычислить значения точки и производных для заданного параметра. \en Calculate point and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const override; + MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const override; /** \} */ /** \ru \name Функции движения по кривой @@ -171,10 +171,14 @@ public: // \ru Преобразование в NURBS кривую \en Transform to NURBS-curve MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & ) const override; MbCurve3D * Trimmed( double t1, double t2, int sense ) const override; // \ru Создание усеченной кривой \en Creation of a trimmed curve + + // \ru Продлить кривую. \en Extend the curve. \~ + MbResultType Extend( const MbCurveExtensionParameters & parameters, c3d::SpaceCurveSPtr & resCurve ) const override; + // \ru Изменить направление \en Change direction void Inverse( MbRegTransform * iReg = nullptr ) override; // \ru Согласовать параметризацию сегментов, если до инвертации она была согласованной. \en Agree on segment parameterization, if it was consistent before inversion. - bool NormalizeReparametrization(); + bool NormalizeReparametrization(); /// \ru Подобные ли кривые для объединения (слива). \en Whether the curves to union (joining) are similar. bool IsSimilarToCurve( const MbCurve3D & other, double precision = METRIC_PRECISION ) const override; @@ -185,13 +189,13 @@ public: double CalculateMetricLength() const override; // \ru Посчитать метрическую длину \en Calculate the metric length double CalculateLength( double t1, double t2 ) const override; bool DistanceAlong( double & t, double len, int curveDir, double eps = Math::metricPrecision, - VERSION version = Math::DefaultMathVersion() ) const override; + VERSION version = Math::DefaultMathVersion() ) const override; void CalculateLocalGabarit( const MbMatrix3D &, MbCube & ) const override; // \ru Рассчитать габарит относительно л.с.к. \en Calculate bounding box relative to the local coordinate system. void CalculateGabarit( MbCube & ) const override; // \ru Вычислить габарит кривой \en Calculate the bounding box of curve MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = nullptr, - VERSION version = Math::DefaultMathVersion(), bool * coincParams = nullptr ) const override; // \ru Дать плоскую проекцию кривой \en Get a planar projection of curve + VERSION version = Math::DefaultMathVersion(), bool * coincParams = nullptr ) const override; // \ru Дать плоскую проекцию кривой \en Get a planar projection of curve MbCurve * GetProjection( const MbPlacement3D & place, VERSION version ) const override; // \ru Дать проекцию ребра на плоскость. \en Get the edge projection onto plane. size_t GetCount() const override; @@ -256,107 +260,107 @@ public: \en \name Function for working with segments of contour \{ */ - /// \ru Инициализация по набору кривых (sameCurves - кривые или их копии). \en Initialize by curves (sameCurves - curves or their copies). - template - bool Init( const CurvesVector & initSegments, bool sameCurves, bool cls ); - /// \ru Инициализация по набору точек. \en Initialize by points. - template - bool Init( const PointsVector & points, bool doClosed = true ); + /// \ru Инициализация по набору кривых (sameCurves - кривые или их копии). \en Initialize by curves (sameCurves - curves or their copies). + template + bool Init( const CurvesVector & initSegments, bool sameCurves, bool cls ); + /// \ru Инициализация по набору точек. \en Initialize by points. + template + bool Init( const PointsVector & points, bool doClosed = true ); - /** \brief \ru Найти сегмент контура. - \en Find a contour segment. \~ - \details \ru Найти сегмент контура по параметру контура. \n - \en Find a contour segment by parameter on contour. \n \~ - \param[in,out] t - \ru Параметр контура. - \en Contour parameter. \~ - \param[out] tSeg - \ru Параметр сегмента контура. - \en Contour segment parameter. \~ - \return \ru Возвращает номер сегмента в случае успешного выполнения или -1. - \en Returns the segment number in case of successful execution or -1. \~ - */ - ptrdiff_t FindSegment( double & t, double & tSeg ) const; + /** \brief \ru Найти сегмент контура. + \en Find a contour segment. \~ + \details \ru Найти сегмент контура по параметру контура. \n + \en Find a contour segment by parameter on contour. \n \~ + \param[in,out] t - \ru Параметр контура. + \en Contour parameter. \~ + \param[out] tSeg - \ru Параметр сегмента контура. + \en Contour segment parameter. \~ + \return \ru Возвращает номер сегмента в случае успешного выполнения или -1. + \en Returns the segment number in case of successful execution or -1. \~ + */ + ptrdiff_t FindSegment( double & t, double & tSeg ) const; - size_t GetSegmentsCount() const { return segments.size(); } ///< \ru Выдать количество сегментов контура. \en Get the number of contour segments. - template - void GetSegments( CurvesVector & curves ) const; ///< \ru Получить кривые контура. \en Get contour segments. + size_t GetSegmentsCount() const { return segments.size(); } ///< \ru Выдать количество сегментов контура. \en Get the number of contour segments. + template + void GetSegments( CurvesVector & curves ) const; ///< \ru Получить кривые контура. \en Get contour segments. - void DetachSegments(); ///< \ru Отцепить все сегменты контура. \en Detach all segments of contour. - void DeleteSegments(); ///< \ru Отсоединить используемые сегменты и удалить остальные. \en Delete used segments and remove other segments. + void DetachSegments(); ///< \ru Отцепить все сегменты контура. \en Detach all segments of contour. + void DeleteSegments(); ///< \ru Отсоединить используемые сегменты и удалить остальные. \en Delete used segments and remove other segments. - void DeleteSegment( size_t ind ); ///< \ru Удалить сегмент контура. \en Delete the segment of contour. - MbCurve3D * DetachSegment( size_t ind ); ///< \ru Отцепить сегмент контура. \en Detach the segment of contour. + void DeleteSegment( size_t ind ); ///< \ru Удалить сегмент контура. \en Delete the segment of contour. + MbCurve3D * DetachSegment( size_t ind ); ///< \ru Отцепить сегмент контура. \en Detach the segment of contour. const MbCurve3D * GetSegment( size_t ind ) const { return segments[ind]; } ///< \ru Выдать сегмент контура по индексу. \en Get contour segment by the index. MbCurve3D * SetSegment( size_t ind ) { return segments[ind]; } ///< \ru Выдать сегмент контура по индексу. \en Get contour segment by the index. - void SetSegment ( MbCurve3D & newSegment, size_t ind, bool same ); ///< \ru Заменить сегмент в контуре. \en Replace a segment in the contour. - void AddSegment ( MbCurve3D & newSegment, bool same ); ///< \ru Добавить сегмент в контур. \en Add a segment to the contour. - void AddAtSegment ( MbCurve3D & newSegment, size_t ind, bool same ); ///< \ru Добавить сегмент в контур перед сегментом с индексом ind. \en Add a segment to the contour before the segment with index ind. - void AddAfterSegment( MbCurve3D & newSegment, size_t ind, bool same ); ///< \ru Добавить сегмент в контур после сегмента с индексом ind. \en Add a segment to the contour after the segment with index ind. + void SetSegment ( MbCurve3D & newSegment, size_t ind, bool same ); ///< \ru Заменить сегмент в контуре. \en Replace a segment in the contour. + void AddSegment ( MbCurve3D & newSegment, bool same ); ///< \ru Добавить сегмент в контур. \en Add a segment to the contour. + void AddAtSegment ( MbCurve3D & newSegment, size_t ind, bool same ); ///< \ru Добавить сегмент в контур перед сегментом с индексом ind. \en Add a segment to the contour before the segment with index ind. + void AddAfterSegment( MbCurve3D & newSegment, size_t ind, bool same ); ///< \ru Добавить сегмент в контур после сегмента с индексом ind. \en Add a segment to the contour after the segment with index ind. - /** \brief \ru Добавить (усеченную) копию сегмента в конец контура. - \en Add a (truncated) segment copy to the end of the contour. \~ - \details \ru Добавить (усеченную) копию сегмента в конец контура. \n - \en Add a (truncated) segment copy to the end of the contour. \n \~ - \param[in] pBasis- \ru Исходная кривая. - \en Initial curve. \~ - \param[in] t1 - \ru Начальный параметр усечения. - \en Truncation starting parameter. \~ - \param[in] t2 - \ru Конечный параметр усечения. - \en Truncation ending parameter. \~ - \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. \~ - \return \ru Возвращает в случае успешного выполнения ненулевой указатель на добавленную кривую. - \en Returns, if successful, a non-zero pointer to the added curve. \~ - */ - MbCurve3D * AddSegment( MbCurve3D & pBasis, double t1, double t2, int sense ); + /** \brief \ru Добавить (усеченную) копию сегмента в конец контура. + \en Add a (truncated) segment copy to the end of the contour. \~ + \details \ru Добавить (усеченную) копию сегмента в конец контура. \n + \en Add a (truncated) segment copy to the end of the contour. \n \~ + \param[in] pBasis- \ru Исходная кривая. + \en Initial curve. \~ + \param[in] t1 - \ru Начальный параметр усечения. + \en Truncation starting parameter. \~ + \param[in] t2 - \ru Конечный параметр усечения. + \en Truncation ending parameter. \~ + \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. \~ + \return \ru Возвращает в случае успешного выполнения ненулевой указатель на добавленную кривую. + \en Returns, if successful, a non-zero pointer to the added curve. \~ + */ + MbCurve3D * AddSegment( MbCurve3D & pBasis, double t1, double t2, int sense ); - void SegmentsAdd( MbCurve3D & newSegment, bool calculateParamLength = true ); ///< \ru Добавить сегмент в контур без проверки. \en Add a segment to the contour without checking. - bool GetCornerAngle( size_t index, MbCartPoint3D & origin, MbVector3D & axis, MbVector3D & tau, double & angle, - double angleEps ) const; - /// \ru Cбросить переменные кэширования. \en Reset variables caching. - void Clear() { - CalculateParamLengthAndClosed(); // \ru Параметрическая длина контура. \en Parametric length of a contour. - } - bool IsSimple() const; ///< \ru Состоит ли контур из отрезков и дуг? \en Whether the contour consists of the segments and arcs? - /// \ru Управление распределением памяти в массиве segments. \en Control of memory allocation in the array "segments". - void SegmentsReserve( size_t additionalSpace ) { segments.Reserve( additionalSpace ); } ///< \ru Зарезервировать место. \en Reserve space. - void SegmentsAdjust () { segments.Adjust(); } ///< \ru Удалить лишнюю память. \en Free the unnecessary memory. + void SegmentsAdd( MbCurve3D & newSegment, bool calculateParamLength = true ); ///< \ru Добавить сегмент в контур без проверки. \en Add a segment to the contour without checking. + bool GetCornerAngle( size_t index, MbCartPoint3D & origin, MbVector3D & axis, MbVector3D & tau, double & angle, + double angleEps ) const; + /// \ru Cбросить переменные кэширования. \en Reset variables caching. + void Clear() { + CalculateParamLengthAndClosed(); // \ru Параметрическая длина контура. \en Parametric length of a contour. + } + bool IsSimple() const; ///< \ru Состоит ли контур из отрезков и дуг? \en Whether the contour consists of the segments and arcs? + /// \ru Управление распределением памяти в массиве segments. \en Control of memory allocation in the array "segments". + void SegmentsReserve( size_t additionalSpace ) { segments.Reserve( additionalSpace ); } ///< \ru Зарезервировать место. \en Reserve space. + void SegmentsAdjust () { segments.Adjust(); } ///< \ru Удалить лишнюю память. \en Free the unnecessary memory. - /** \brief \ru Добавить новый элемент в начало или конец контура. - \en Add the new element to the beginning or end of contour. \~ - \details \ru Добавить новый элемент в начало или конец контура. \n - \en Add the new element to the beginning or end of contour. \n \~ - \param[in] curve - \ru Добавляемая кривая. - \en Added curve. \~ - \param[in] absEps - \ru Точность проверки совпадения концов кривых (1e-8 - 1e-4). - \en Accuracy of verification of curve end coincidence (1e-8 - 1e-4). \~ - \param[in] toEndOnly - \ru Добавлять кривую только в конец контура. - \en Add the curve only at the end of the contour. \~ - \param[in] checkSame - \ru Проверять наличие такой же (добавляемой) кривой в контуре. - \en Check a presence of the same curve in the contour. \~ - \param[in] checkSame - \ru Версия. - \en Version. \~ - \return \ru Возвращает true, если кривая была добавлена. - \en Returns true if the curve was added. \~ - */ - bool AddCurveWithRuledCheck( MbCurve3D & curve, double absEps, bool toEndOnly = false, bool checkSame = true, - VERSION version = Math::DefaultMathVersion() ); + /** \brief \ru Добавить новый элемент в начало или конец контура. + \en Add the new element to the beginning or end of contour. \~ + \details \ru Добавить новый элемент в начало или конец контура. \n + \en Add the new element to the beginning or end of contour. \n \~ + \param[in] curve - \ru Добавляемая кривая. + \en Added curve. \~ + \param[in] absEps - \ru Точность проверки совпадения концов кривых (1e-8 - 1e-4). + \en Accuracy of verification of curve end coincidence (1e-8 - 1e-4). \~ + \param[in] toEndOnly - \ru Добавлять кривую только в конец контура. + \en Add the curve only at the end of the contour. \~ + \param[in] checkSame - \ru Проверять наличие такой же (добавляемой) кривой в контуре. + \en Check a presence of the same curve in the contour. \~ + \param[in] checkSame - \ru Версия. + \en Version. \~ + \return \ru Возвращает true, если кривая была добавлена. + \en Returns true if the curve was added. \~ + */ + bool AddCurveWithRuledCheck( MbCurve3D & curve, double absEps, bool toEndOnly = false, bool checkSame = true, + VERSION version = Math::DefaultMathVersion() ); - /// \ru Проверка непрерывности контура. \en Check for contour continuity. - bool CheckConnection( double eps = METRIC_PRECISION ) const; - void CalculateParamLength(); ///< \ru Рассчитать параметрическую длину. \en Calculate parametric length. - void CheckClosed( double /*closedEps*/ ); ///< \ru Установить признак замкнутости контура. \en Set the closedness attribute of contour. - /// \ru Содержат ли контура идентичные сегменты. \en Whether contours contains identical segments. - bool IsSameSegments( const MbContour3D &, double accuracy = METRIC_PRECISION ) const; - /// \ru Нахождение точки сегмента контура по индексу сегмента. \en Finding the point of a contour segment by segment index. - void FindCorner( size_t index, MbCartPoint3D & ) const; - /// \ru Установить начальную (конечную) точку для замкнутого контура. \en Set the start (end) point for closed contour. - bool SetBegEndPoint( double t ); + /// \ru Проверка непрерывности контура. \en Check for contour continuity. + bool CheckConnection( double eps = METRIC_PRECISION ) const; + void CalculateParamLength(); ///< \ru Рассчитать параметрическую длину. \en Calculate parametric length. + void CheckClosed( double /*closedEps*/ ); ///< \ru Установить признак замкнутости контура. \en Set the closedness attribute of contour. + /// \ru Содержат ли контура идентичные сегменты. \en Whether contours contains identical segments. + bool IsSameSegments( const MbContour3D &, double accuracy = METRIC_PRECISION ) const; + /// \ru Нахождение точки сегмента контура по индексу сегмента. \en Finding the point of a contour segment by segment index. + void FindCorner( size_t index, MbCartPoint3D & ) const; + /// \ru Установить начальную (конечную) точку для замкнутого контура. \en Set the start (end) point for closed contour. + bool SetBegEndPoint( double t ); /** \} */ /** \ru \name Функции работы с именами контура. @@ -370,7 +374,7 @@ public: \param[out] names - \ru Имена сегментов. \en Names of segments \~ */ - void GetSegmentsNames( SimpleNameArray & names ) const; + void GetSegmentsNames( SimpleNameArray & names ) const; /** \brief \ru Установить имена сегментов. \en Set names of segments. \~ @@ -379,20 +383,20 @@ public: \param[in] names - \ru Набор имен. \en A set of names. \~ */ - void SetSegmentsNames( const SimpleNameArray & names ); + void SetSegmentsNames( const SimpleNameArray & names ); /** \} */ private: - void SetClosed(); // \ru Проверить и установить признак замкнутости контура. \en Check and set closedness attribute of contour. - void CalculateParamLengthAndClosed(); // \ru Посчитать параметрическую длину и признак замкнутости \en Calculate parametric length and closedness attribute - ptrdiff_t _FindSegment( double & t, double & tSeg ) const; // \ru Нахождение сегмента контура \en Finding of a contour segment + void SetClosed(); // \ru Проверить и установить признак замкнутости контура. \en Check and set closedness attribute of contour. + void CalculateParamLengthAndClosed(); // \ru Посчитать параметрическую длину и признак замкнутости \en Calculate parametric length and closedness attribute + ptrdiff_t _FindSegment( double & t, double & tSeg ) const; // \ru Нахождение сегмента контура \en Finding of a contour segment + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbContour3D ) + OBVIOUS_PRIVATE_COPY( MbContour3D ) -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbContour3D ) -OBVIOUS_PRIVATE_COPY( MbContour3D ) }; // MbContour3D - IMPL_PERSISTENT_OPS( MbContour3D ) diff --git a/C3d/Include/cur_contour_on_plane.h b/C3d/Include/cur_contour_on_plane.h index 8182ed2..4b1d9ca 100644 --- a/C3d/Include/cur_contour_on_plane.h +++ b/C3d/Include/cur_contour_on_plane.h @@ -131,6 +131,10 @@ public : /// \ru Инвертировать нормаль плоскости. \en Invert the normal of plane. void InvertNormal( MbRegTransform * = nullptr ); + /// \ru Продлить кривую. \en Extend the curve. \~ + MbResultType Extend( const MbCurveExtensionParameters & parameters, c3d::SpaceCurveSPtr & resCurve ) const override; + + private: void operator = ( const MbContourOnPlane & ); // \ru Не реализовано !!! \en Not implemented !!! diff --git a/C3d/Include/cur_cosinusoid.h b/C3d/Include/cur_cosinusoid.h index 1c1a5ea..ac76c7f 100644 --- a/C3d/Include/cur_cosinusoid.h +++ b/C3d/Include/cur_cosinusoid.h @@ -120,7 +120,7 @@ public: void _ThirdDer ( double t, MbVector & v ) const override; // \ru Вычислить значения точки и производных для заданного параметра. \en Calculate point and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - MbCartPoint & pnt, MbVector & fir, MbVector * sec, MbVector * thir ) const override; + MbCartPoint & pnt, MbVector & fir, MbVector * sec, MbVector * thir ) const override; bool HasLength ( double & length ) const override; double GetMetricLength() const override; // \ru Метрическая длина \en The metric length @@ -140,7 +140,7 @@ public: double PointProjection( const MbCartPoint & pnt ) const override; // \ru Проекция точки на кривую \en Point projection on the curve bool NearPointProjection( const MbCartPoint & pnt, double xEpsilon, double yEpsilon, - double & t, bool ext, MbRect1D * tRange = nullptr ) const override; // \ru Проекция точки на кривую или её продолжение в области поиска проекции \en Point projection on the curve or its extension in the projection search area + double & t, bool ext, MbRect1D * tRange = nullptr ) const override; // \ru Проекция точки на кривую или её продолжение в области поиска проекции \en Point projection on the curve or its extension in the projection search area void GetProperties( MbProperties & properties ) override; // \ru Выдать свойства объекта \en Get properties of the object void SetProperties( const MbProperties & properties ) override; // \ru Записать свойства объекта \en Set properties of the object @@ -151,46 +151,47 @@ public: const MbPlacement & GetPlacement() const { return position; } MbPlacement & SetPlacement() { return position; } - double GetFrequency() const { return frequency; } - double GetPhase() const { return phase; } - double GetAmplitude() const { return amplitude; } - double GetOwnTMin() const { return tmin; } - double GetOwnTMax() const { return tmax; } - void SetPlacement( const MbPlacement &pos ); - void SetFrequency( double f ); - void SetPhase ( double p ); - void SetAmplitude( double a ); - void SetOwnTMin ( double t ); - void SetOwnTMax ( double t ); + double GetFrequency() const { return frequency; } + double GetPhase() const { return phase; } + double GetAmplitude() const { return amplitude; } + double GetOwnTMin() const { return tmin; } + double GetOwnTMax() const { return tmax; } + void SetPlacement( const MbPlacement &pos ); + void SetFrequency( double f ); + void SetPhase ( double p ); + void SetAmplitude( double a ); + void SetOwnTMin ( double t ); + void SetOwnTMax ( double t ); inline void CheckParam( double & t ) const; - bool IsHorizontal( double eps = Math::AngleEps ) const; // \ru Проверка горизонтальности \en Check for horizontality - bool IsVertical ( double eps = Math::AngleEps ) const; // \ru Проверка вертикальности \en Check for verticality + bool IsHorizontal( double eps = Math::AngleEps ) const; // \ru Проверка горизонтальности \en Check for horizontality + bool IsVertical ( double eps = Math::AngleEps ) const; // \ru Проверка вертикальности \en Check for verticality - void Init ( const MbCosinusoid & ); - void Init ( double t1, double t2 ); - void Init ( const MbPlacement & pos, double am, double ph, double af ); - void Init1( CosinusoidPar & par, MbCartPoint & p1, MbCartPoint & p2, double & len, double & angle ); - void Init2( CosinusoidPar & par, const MbCartPoint & p1, MbCartPoint & p2, const double & len, double & angle ); - void Init3( CosinusoidPar & par, const MbCartPoint & p1, MbCartPoint & p2, double & len, const double & angle, - const DiskreteLengthData * = nullptr ); - void Init4( CosinusoidPar & par, MbCartPoint & p1, const MbCartPoint & p2, const double & len, double & angle ); - void Init5( CosinusoidPar & par, MbCartPoint & p1, const MbCartPoint & p2, double & len, const double & angle, - const DiskreteLengthData * = nullptr ); - void Init6( CosinusoidPar & par, const MbCartPoint & p1, MbCartPoint & p2, const double & len, const double & angle ); - void Init7( CosinusoidPar & par, MbCartPoint & p1, const MbCartPoint & p2, const double & len, const double & angle ); - void Init8( CosinusoidPar & par, MbCartPoint & p1, MbCartPoint & p2, double & len, double & angle, - const DiskreteLengthData & diskrData, bool correctP1 ); - void SpecInit( const CosinusoidPar &, const MbCartPoint & p1, double angle, double len ); + void Init ( const MbCosinusoid & ); + void Init ( double t1, double t2 ); + void Init ( const MbPlacement & pos, double am, double ph, double af ); + void Init1( CosinusoidPar & par, MbCartPoint & p1, MbCartPoint & p2, double & len, double & angle ); + void Init2( CosinusoidPar & par, const MbCartPoint & p1, MbCartPoint & p2, const double & len, double & angle ); + void Init3( CosinusoidPar & par, const MbCartPoint & p1, MbCartPoint & p2, double & len, const double & angle, + const DiskreteLengthData * = nullptr ); + void Init4( CosinusoidPar & par, MbCartPoint & p1, const MbCartPoint & p2, const double & len, double & angle ); + void Init5( CosinusoidPar & par, MbCartPoint & p1, const MbCartPoint & p2, double & len, const double & angle, + const DiskreteLengthData * = nullptr ); + void Init6( CosinusoidPar & par, const MbCartPoint & p1, MbCartPoint & p2, const double & len, const double & angle ); + void Init7( CosinusoidPar & par, MbCartPoint & p1, const MbCartPoint & p2, const double & len, const double & angle ); + void Init8( CosinusoidPar & par, MbCartPoint & p1, MbCartPoint & p2, double & len, double & angle, + const DiskreteLengthData & diskrData, bool correctP1 ); + void SpecInit( const CosinusoidPar &, const MbCartPoint & p1, double angle, double len ); private: - void operator = ( const MbCosinusoid & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbCosinusoid & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCosinusoid ) }; // MbCosinusoid IMPL_PERSISTENT_OPS( MbCosinusoid ) + //------------------------------------------------------------------------------- // \ru Проверка параметра \en Check parameter // --- diff --git a/C3d/Include/cur_crooked_spiral.h b/C3d/Include/cur_crooked_spiral.h index a08b068..005404f 100644 --- a/C3d/Include/cur_crooked_spiral.h +++ b/C3d/Include/cur_crooked_spiral.h @@ -76,16 +76,16 @@ public: public : VISITING_CLASS( MbCrookedSpiral ); - /// \ru Инициализация спирали по спирали. \en Spiral initialization by spiral. - void Init( const MbCrookedSpiral & ); - /// \ru Инициализация спирали по основанию (локальной системе координат). \en Spiral initialization by base (local coordinate system). - void Init( const MbPlacement3D & ); + /// \ru Инициализация спирали по спирали. \en Spiral initialization by spiral. + void Init( const MbCrookedSpiral & ); + /// \ru Инициализация спирали по основанию (локальной системе координат). \en Spiral initialization by base (local coordinate system). + void Init( const MbPlacement3D & ); // \ru Общие функции математического объекта \en Common functions of the mathematical object MbeSpaceType IsA() const override; // \ru Тип элемента \en Type of element MbSpaceItem & Duplicate( MbRegDuplicate * = nullptr ) const override; // \ru Сделать копию элемента \en Create a copy of the element - bool IsSame( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const override; + bool IsSame( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const override; bool SetEqual( const MbSpaceItem & init ) override; // \ru Сделать равным \en Make equal void GetProperties( MbProperties & ) override; // \ru Выдать свойства объекта \en Get properties of the object @@ -106,7 +106,7 @@ public : void _ThirdDer ( double t, MbVector3D & td ) const override; // \ru Третья производная по t \en Third derivative with respect to t // \ru Вычислить значения точки и производных для заданного параметра. \en Calculate point and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const override; + MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const override; void Inverse( MbRegTransform * iReg = nullptr ) override; // \ru Изменить направление \en Change direction @@ -120,32 +120,34 @@ public : double GetSpiralRadius( double t ) const override; // \ru Выдать физический радиус спирали \en Get physical radius of spiral const MbCurve & GetAxisCurve() const { return *curve; } ///< \ru Выдать осевую кривую. \en Get axial curve. - double GetSpiralRadius() const { return radius; } ///< \ru Выдать радиус. \en Get radius. - void SetSpiralRadius( double r ) { radius = r; }; ///< \ru Изменить радиус. \en Change radius. - bool GetCurveSense () const { return curveSense; } ///< \ru Выдать признак совпадения направления на спирали и оси (кривой). \en Get attribute of coincidence of the direction on the spiral and axis (curve). + double GetSpiralRadius() const { return radius; } ///< \ru Выдать радиус. \en Get radius. + void SetSpiralRadius( double r ) { radius = r; }; ///< \ru Изменить радиус. \en Change radius. + bool GetCurveSense () const { return curveSense; } ///< \ru Выдать признак совпадения направления на спирали и оси (кривой). \en Get attribute of coincidence of the direction on the spiral and axis (curve). private: - void GetFirstDerNormW ( const MbVector & fDerW, const MbVector & sDerW, MbVector & fdNormW ) const; // \ru Выдать первую производную нормали по параметру кривой оси \en Get the first derivative of normal vector with respect to parameter of axis curve - void GetSecondDerNormW ( const MbVector & fDerW, const MbVector & sDerW, const MbVector & tDerW, MbVector & sdNormW ) const; // \ru Выдать вторую производную нормали по параметру кривой оси \en Get the second derivative of normal vector with respect to parameter of axis curve - void GetThirdDerNormW ( const MbVector & fDerW, const MbVector & sDerW, const MbVector & tDerW, MbVector & tdNormW ) const; // \ru Выдать третью производную нормали по параметру кривой оси \en Get the third derivative of normal vector with respect to parameter of axis curve - void GetFirstDerNormT ( const MbVector & fDerW, const MbVector & sDerW, MbVector & fdNorm ) const; // \ru Выдать первую производную нормали по параметру спирали \en Get the first derivative of normal vector with respect to parameter of the spiral - void GetSecondDerNormT ( const MbVector & fDerW, const MbVector & sDerW, const MbVector & tDerW, MbVector & sdNorm ) const; // \ru Выдать вторую производную нормали по параметру спирали \en Get the second derivative of normal vector with respect to parameter of the spiral - void GetThirdDerNormT ( const MbVector & fDerW, const MbVector & sDerW, const MbVector & tDerW, MbVector & tdNorm ) const; // \ru Выдать третью производную нормали по параметру спирали \en Get the third derivative of normal vector with respect to parameter of the spiral - void GetFirstDerT ( const MbVector & fDerW, MbVector & fd ) const; // \ru Выдать первую производную кривой оси по параметру спирали \en Get the first derivative of axis curve with respect to parameter of the spiral - void GetSecondDerT ( const MbVector & fDerW, const MbVector & sDerW, MbVector & sd ) const; // \ru Выдать вторую производную кривой оси по параметру спирали \en Get the second derivative of axis curve with respect to parameter of the spiral - void GetThirdDerT ( const MbVector & fDerW, const MbVector & sDerW, const MbVector & tDerW, MbVector & td ) const; // \ru Выдать третью производную кривой оси по параметру спирали \en Get the third derivative of axis curve with respect to parameter of the spiral - double GetFirstDerParamT ( const MbVector & fDerW ) const; // \ru Выдать первую производную параметра кривой оси по параметру спирали \en Get the first derivative of axis curve parameter with respect to parameter of the spiral - double GetSecondDerParamT( const MbVector & fDerW, const MbVector & sDerW ) const; // \ru Выдать вторую производную параметра кривой оси по параметру спирали \en Get the second derivative of axis curve parameter with respect to parameter of the spiral - double GetThirdDerParamT ( const MbVector & fDerW, const MbVector & sDerW, const MbVector & tDerW ) const; // \ru Выдать третью производную параметра кривой оси по параметру спирали \en Get the third derivative of axis curve parameter with respect to parameter of the spiral - void GetCurveParams ( double tSense, MbCartPoint & point, MbDirection & normal, - MbVector & fDerW, MbVector & sDerW, MbVector & tDerW ) const; // \ru Параметры кривой оси, соответствующие параметру спирали t \en Parameters of axis curve corresponding to the parameter t of the spiral - void CalculateParams (); // \ru Посчитать параметры спирали (параметрические сдвиги от начала кривой) и параметры кривой. \en Calculate parameters of spiral (parametric shifts from the beginning of the curve) and parameters of "curve". - bool NearestLeftParams ( double tSense, c3d::DoublePair & paramPair ) const; // \ru Ближайшая слева пара параметров спирали и кривой. \en Nearest left parameters pair of spiral and "curve". + void GetFirstDerNormW ( const MbVector & fDerW, const MbVector & sDerW, MbVector & fdNormW ) const; // \ru Выдать первую производную нормали по параметру кривой оси \en Get the first derivative of normal vector with respect to parameter of axis curve + void GetSecondDerNormW ( const MbVector & fDerW, const MbVector & sDerW, const MbVector & tDerW, MbVector & sdNormW ) const; // \ru Выдать вторую производную нормали по параметру кривой оси \en Get the second derivative of normal vector with respect to parameter of axis curve + void GetThirdDerNormW ( const MbVector & fDerW, const MbVector & sDerW, const MbVector & tDerW, MbVector & tdNormW ) const; // \ru Выдать третью производную нормали по параметру кривой оси \en Get the third derivative of normal vector with respect to parameter of axis curve + void GetFirstDerNormT ( const MbVector & fDerW, const MbVector & sDerW, MbVector & fdNorm ) const; // \ru Выдать первую производную нормали по параметру спирали \en Get the first derivative of normal vector with respect to parameter of the spiral + void GetSecondDerNormT ( const MbVector & fDerW, const MbVector & sDerW, const MbVector & tDerW, MbVector & sdNorm ) const; // \ru Выдать вторую производную нормали по параметру спирали \en Get the second derivative of normal vector with respect to parameter of the spiral + void GetThirdDerNormT ( const MbVector & fDerW, const MbVector & sDerW, const MbVector & tDerW, MbVector & tdNorm ) const; // \ru Выдать третью производную нормали по параметру спирали \en Get the third derivative of normal vector with respect to parameter of the spiral + void GetFirstDerT ( const MbVector & fDerW, MbVector & fd ) const; // \ru Выдать первую производную кривой оси по параметру спирали \en Get the first derivative of axis curve with respect to parameter of the spiral + void GetSecondDerT ( const MbVector & fDerW, const MbVector & sDerW, MbVector & sd ) const; // \ru Выдать вторую производную кривой оси по параметру спирали \en Get the second derivative of axis curve with respect to parameter of the spiral + void GetThirdDerT ( const MbVector & fDerW, const MbVector & sDerW, const MbVector & tDerW, MbVector & td ) const; // \ru Выдать третью производную кривой оси по параметру спирали \en Get the third derivative of axis curve with respect to parameter of the spiral + double GetFirstDerParamT ( const MbVector & fDerW ) const; // \ru Выдать первую производную параметра кривой оси по параметру спирали \en Get the first derivative of axis curve parameter with respect to parameter of the spiral + double GetSecondDerParamT( const MbVector & fDerW, const MbVector & sDerW ) const; // \ru Выдать вторую производную параметра кривой оси по параметру спирали \en Get the second derivative of axis curve parameter with respect to parameter of the spiral + double GetThirdDerParamT ( const MbVector & fDerW, const MbVector & sDerW, const MbVector & tDerW ) const; // \ru Выдать третью производную параметра кривой оси по параметру спирали \en Get the third derivative of axis curve parameter with respect to parameter of the spiral + void GetCurveParams ( double tSense, MbCartPoint & point, MbDirection & normal, + MbVector & fDerW, MbVector & sDerW, MbVector & tDerW ) const; // \ru Параметры кривой оси, соответствующие параметру спирали t \en Parameters of axis curve corresponding to the parameter t of the spiral + void CalculateParams (); // \ru Посчитать параметры спирали (параметрические сдвиги от начала кривой) и параметры кривой. \en Calculate parameters of spiral (parametric shifts from the beginning of the curve) and parameters of "curve". + bool NearestLeftParams ( double tSense, c3d::DoublePair & paramPair ) const; // \ru Ближайшая слева пара параметров спирали и кривой. \en Nearest left parameters pair of spiral and "curve". + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCrookedSpiral ) + OBVIOUS_PRIVATE_COPY( MbCrookedSpiral ) -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCrookedSpiral ) -OBVIOUS_PRIVATE_COPY( MbCrookedSpiral ) }; // MbCrookedSpiral IMPL_PERSISTENT_OPS( MbCrookedSpiral ) + #endif // __CUR_CROOKET_SPIRAL_H diff --git a/C3d/Include/cur_cubic_spline.h b/C3d/Include/cur_cubic_spline.h index e226493..233d175 100644 --- a/C3d/Include/cur_cubic_spline.h +++ b/C3d/Include/cur_cubic_spline.h @@ -171,22 +171,22 @@ public : /** \ru \name Функции инициализации сплайна. \en \name Spline initialization functions. \{ */ - /// \ru Инициализатор по заданной кривой. \en Initializer by a given curve. - bool Init( const MbCurve &, VERSION version ); - /// \ru Инициализатор по точкам и признаку замкнутости. \en Initializer by points and an attribute of closedness. - bool Init( const SArray &, bool ); - /// \ru Инициализатор по точкам, вторым производным и признаку замкнутости. \en Initializer by points, second derivatives and closedness attribute. - bool Init( const SArray &, - const SArray &, bool ); - /// \ru Инициализатор по точкам, параметрам и признаку замкнутости. \en Initializer by points, parameters and closedness attribute. - bool Init( const SArray &, - const SArray &, bool ); - /// \ru Инициализатор по точкам, вторым производным, параметрам и признаку замкнутости. \en Initializer by points, second derivatives, parameters and closedness attribute. - bool Init( const SArray &, - const SArray &, - const SArray &, bool ); - /// \ru Дублирующий инициализатор. \en Duplicating initializer. - void InitC( const MbCubicSpline & ); + /// \ru Инициализатор по заданной кривой. \en Initializer by a given curve. + bool Init( const MbCurve &, VERSION version ); + /// \ru Инициализатор по точкам и признаку замкнутости. \en Initializer by points and an attribute of closedness. + bool Init( const SArray &, bool ); + /// \ru Инициализатор по точкам, вторым производным и признаку замкнутости. \en Initializer by points, second derivatives and closedness attribute. + bool Init( const SArray &, + const SArray &, bool ); + /// \ru Инициализатор по точкам, параметрам и признаку замкнутости. \en Initializer by points, parameters and closedness attribute. + bool Init( const SArray &, + const SArray &, bool ); + /// \ru Инициализатор по точкам, вторым производным, параметрам и признаку замкнутости. \en Initializer by points, second derivatives, parameters and closedness attribute. + bool Init( const SArray &, + const SArray &, + const SArray &, bool ); + /// \ru Дублирующий инициализатор. \en Duplicating initializer. + void InitC( const MbCubicSpline & ); /** \} */ /** \ru \name Общие функции геометрического объекта. @@ -228,10 +228,10 @@ public : \{ */ // \ru Вычислить значения точки и производных для заданного параметра. \en Calculate point and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - MbCartPoint & pnt, MbVector & fir, MbVector * sec, MbVector * thir ) const override; + MbCartPoint & pnt, MbVector & fir, MbVector * sec, MbVector * thir ) const override; - void FourDer ( double &, MbVector & ) const; ///< \ru Оценить четвертую производную. \en Estimate the fourth derivative. - void PointOnLine( double &, MbCartPoint & ) const; ///< \ru Вычислить точку на кривой при линейной аппроксимации. \en Calculate a point on the curve with a linear approximation. + void FourDer ( double &, MbVector & ) const; ///< \ru Оценить четвертую производную. \en Estimate the fourth derivative. + void PointOnLine( double &, MbCartPoint & ) const; ///< \ru Вычислить точку на кривой при линейной аппроксимации. \en Calculate a point on the curve with a linear approximation. /** \} */ /** \ru \name Функции движения по кривой @@ -268,7 +268,7 @@ public : \en A constructed trimmed curve. \~ */ MbCurve * Trimmed ( double t1, double t2, int sense ) const override; // \ru Усечь кривую \en Trim a curve - MbCurve * TrimmedBreak( double t1, double t2, int sense ) const; // \ru Усечь кривую с разрывом \en Trim a curve with a break + MbCurve * TrimmedBreak( double t1, double t2, int sense ) const; // \ru Усечь кривую с разрывом \en Trim a curve with a break MbNurbs * NurbsCurve( const MbCurveIntoNurbsInfo & ) const override; MbCurve * NurbsCurve( const MbNurbsParameters & ) const override; @@ -287,7 +287,7 @@ public : double CalculateMetricLength() const override; // \ru Сдвинуть параметр t на расстояние len. \en Move parameter t on the metric distance len. bool DistanceAlong( double & t, double len, int curveDir, double eps = Math::LengthEps, - VERSION version = Math::DefaultMathVersion() ) const override; + VERSION version = Math::DefaultMathVersion() ) const override; /// \ru Получить границы участков кривой, которые описываются одной аналитической функцией. /// \en Get the boundaries of the curve sections that are described by one analytical function. \~ void GetAnalyticalFunctionsBounds( std::vector & params ) const override; @@ -336,56 +336,57 @@ public : If a curve is not closed and "black" is true then the system has a solution when knot is absent. \~ */ - void InitCreate ( MbVector &, MbVector &, SArray &, double &, - double &, double &, double &, bool black = false ); - /// \ru Решить систему методом исключения Гаусса. \en Solve the system by Gaussian elimination method. - void Create ( MbVector &, MbVector &, bool black = false ); - /// \ru Вычислить производные на концах в случае незамкнутости сплайна. \en Calculate derivatives at the ends if the spline is not closed. - void CreateEndS ( MbVector &, MbVector & ); - /// \ru Построить сплайн если необходимо. \en Create a spline if necessary. - void Create (); - /// \ru Очистить кривую. \en Clear the curve. - void Delete (); - /// \ru Установить область изменения параметра: первый - минимальный, второй - максимальный. \en Set the range of parameter: the first is minimum, the second is maximum. - bool SetLimitParam( double newTMin, double newTMax ); - /// \ru Преобразовать в замкнутую кривую, если кривая разомкнута но концы кривой гладко стыкуются. \en Convert to a closed curve if the curve is unclosed but the ends of the curve are connected smoothly. - bool ConvertToClosed(); + void InitCreate ( MbVector &, MbVector &, SArray &, double &, + double &, double &, double &, bool black = false ); + /// \ru Решить систему методом исключения Гаусса. \en Solve the system by Gaussian elimination method. + void Create ( MbVector &, MbVector &, bool black = false ); + /// \ru Вычислить производные на концах в случае незамкнутости сплайна. \en Calculate derivatives at the ends if the spline is not closed. + void CreateEndS ( MbVector &, MbVector & ); + /// \ru Построить сплайн если необходимо. \en Create a spline if necessary. + void Create (); + /// \ru Очистить кривую. \en Clear the curve. + void Delete (); + /// \ru Установить область изменения параметра: первый - минимальный, второй - максимальный. \en Set the range of parameter: the first is minimum, the second is maximum. + bool SetLimitParam( double newTMin, double newTMax ); + /// \ru Преобразовать в замкнутую кривую, если кривая разомкнута но концы кривой гладко стыкуются. \en Convert to a closed curve if the curve is unclosed but the ends of the curve are connected smoothly. + bool ConvertToClosed(); void SetBegEndDerivesEqual() override; // \ru Установить равные производные на краях \en Set equal derivatives at the edges void ClosedBreak() override; // \ru Сделать незамкнутой, оставив совпадающими начало и конец \en Make unclosed, leave coinciding start and end - /// \ru Вычисление шага аппроксимации. \en Calculation of a step of approximation. - double StepD( double &t, double sag, bool bfirst, double ang = 0.35 ) const; + /// \ru Вычисление шага аппроксимации. \en Calculation of a step of approximation. + double StepD( double &t, double sag, bool bfirst, double ang = 0.35 ) const; - /// \ru Вернуть количество элементов в массиве векторов производных. \en Get the number of elements in array of derivative vectors. - ptrdiff_t GetVectorListCount() const { return (ptrdiff_t)/*OV_x64 (int)*/vectorList.Count(); } - /// \ru Вернуть массив вторых призводных в контрольных точках. \en Get the array of second derivatives at the control points. - void GetVectorList( SArray & vectors ) const { vectors = vectorList; } - /// \ru Выдать вектор второй производной с индексов i. \en Get the vector of the second derivative with index i. + /// \ru Вернуть количество элементов в массиве векторов производных. \en Get the number of elements in array of derivative vectors. + ptrdiff_t GetVectorListCount() const { return (ptrdiff_t)/*OV_x64 (int)*/vectorList.Count(); } + /// \ru Вернуть массив вторых призводных в контрольных точках. \en Get the array of second derivatives at the control points. + void GetVectorList( SArray & vectors ) const { vectors = vectorList; } + /// \ru Выдать вектор второй производной с индексов i. \en Get the vector of the second derivative with index i. const MbVector & GetVectorList( size_t i ) const { return vectorList[i]; } - /// \ru Выдать вектор второй производной с индексов i. \en Get the vector of the second derivative with index i. - MbVector & SetVectorList( size_t i ) { return vectorList[i]; } + /// \ru Выдать вектор второй производной с индексов i. \en Get the vector of the second derivative with index i. + MbVector & SetVectorList( size_t i ) { return vectorList[i]; } - /// \ru Вернуть количество параметров в узлах. \en Get the number of parameters in knots. - ptrdiff_t GetTListCount() const { return tList.Count(); } - /// \ru Вернуть массив параметров в узлах. \en Get the array of parameters in knots. + /// \ru Вернуть количество параметров в узлах. \en Get the number of parameters in knots. + ptrdiff_t GetTListCount() const { return tList.Count(); } + /// \ru Вернуть массив параметров в узлах. \en Get the array of parameters in knots. void GetTList( SArray & params ) const override { params = tList; } - /// \ru Вернуть значение параметра для точки с индексом i. \en Get the value of parameter for the point with index i. + /// \ru Вернуть значение параметра для точки с индексом i. \en Get the value of parameter for the point with index i. const double & GetTList( size_t i ) const { return tList[i]; } - /// \ru Вернуть число сегментов сплайна. \en Get the number of spline segments. - ptrdiff_t GetUppParam() const { return splinesCount; } - /// \ru Определение максимального индекса массива параметров слева. \en Determination of the maximum index of parameter array on the left. - ptrdiff_t GetIndex( double t ) const; + /// \ru Вернуть число сегментов сплайна. \en Get the number of spline segments. + ptrdiff_t GetUppParam() const { return splinesCount; } + /// \ru Определение максимального индекса массива параметров слева. \en Determination of the maximum index of parameter array on the left. + ptrdiff_t GetIndex( double t ) const; /** \} */ private: - // \ru Найти узел в положительном направлении \en Find a knot in the positive direction - void AddKnot( ptrdiff_t &, double &, ptrdiff_t &, double &, ptrdiff_t &, double & ) const; - void CheckSpline(); // \ru Проверить корректность расчета сплайна \en Check correctness of the spline calculation - void operator = ( const MbCubicSpline & ); // \ru Не реализовано. \en Not implemented. + // \ru Найти узел в положительном направлении \en Find a knot in the positive direction + void AddKnot( ptrdiff_t &, double &, ptrdiff_t &, double &, ptrdiff_t &, double & ) const; + void CheckSpline(); // \ru Проверить корректность расчета сплайна \en Check correctness of the spline calculation + void operator = ( const MbCubicSpline & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCubicSpline ) }; IMPL_PERSISTENT_OPS( MbCubicSpline ) + //------------------------------------------------------------------------------ /// \ru Используется в трехмерном кубическом сплайне \en It is used in the three-dimensional cubic spline // --- diff --git a/C3d/Include/cur_cubic_spline3d.h b/C3d/Include/cur_cubic_spline3d.h index a99c352..2962878 100644 --- a/C3d/Include/cur_cubic_spline3d.h +++ b/C3d/Include/cur_cubic_spline3d.h @@ -228,23 +228,23 @@ public: VISITING_CLASS( MbCubicSpline3D ); // \ru Инициализатор по точкам и признаку замкнутости \en Initializer by points and an attribute of closedness - bool Init( const SArray &, bool cls, VERSION version = Math::DefaultMathVersion() ); + bool Init( const SArray &, bool cls, VERSION version = Math::DefaultMathVersion() ); // \ru Инициализатор по точкам вторым производным и признаку замкнутости \en Initializer by points, second derivatives and closedness attribute - bool Init( const SArray &, const SArray &, bool cls, VERSION version = Math::DefaultMathVersion() ); + bool Init( const SArray &, const SArray &, bool cls, VERSION version = Math::DefaultMathVersion() ); // \ru Инициализатор по точкам параметрам и признаку замкнутости \en Initializer by points, parameters and an attribute of closedness - bool Init( const SArray &, const SArray &, bool ); + bool Init( const SArray &, const SArray &, bool ); // \ru Инициализатор по точкам вторым производным параметрам и признаку замкнутости \en Initializer by points, second derivatives, parameters and an attribute of closedness - bool Init( const SArray &, const SArray &, + bool Init( const SArray &, const SArray &, const SArray &, bool ); // \ru Инициализация по точкам и краевым производным \en Initialization by points and boundary derivatives - bool Init( const SArray &, const MbVector3D &, const MbVector3D &, bool, bool ); + bool Init( const SArray &, const MbVector3D &, const MbVector3D &, bool, bool ); // \ru Инициализация по точкам, параметрам и краевым производным \en Initialization by points, parameters and boundary derivatives - bool Init( const SArray &, const SArray &, + bool Init( const SArray &, const SArray &, const MbVector3D &, const MbVector3D &, bool, bool ); - bool Init( const MbCurve3D &, VERSION version ); // \ru Инициализатор по другой кривой \en Initializer by another curve - void InitC( const MbCubicSpline3D & ); // \ru Дублирующий инициализатор \en Duplicating initializer + bool Init( const MbCurve3D &, VERSION version ); // \ru Инициализатор по другой кривой \en Initializer by another curve + void InitC( const MbCubicSpline3D & ); // \ru Дублирующий инициализатор \en Duplicating initializer // \ru Инициализатор по двумерному сплайну на плоскости \en Initializer by a two-dimensional spline on the plane - void Init( const MbCubicSpline &, const MbPlacement3D & ); + void Init( const MbCubicSpline &, const MbPlacement3D & ); // \ru Общие функции математического объекта \en Common functions of the mathematical object MbSpaceItem & Duplicate( MbRegDuplicate * = nullptr ) const override; // \ru Сделать копию элемента \en Create a copy of the element @@ -269,9 +269,9 @@ public: void ThirdDer ( double &, MbVector3D & ) const override; // \ru Третья производная \en Third derivative // \ru Вычислить значения точки и производных для заданного параметра. \en Calculate point and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const override; + MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const override; - void FourDer( double &, MbVector3D & ) const; ///< \ru Оценить четвертую производную. \en Estimate the fourth derivative. + void FourDer( double &, MbVector3D & ) const; ///< \ru Оценить четвертую производную. \en Estimate the fourth derivative. // \ru Построить NURBS-копию кривой \en Create a NURBS-copy of the curve MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & ) const override; @@ -284,7 +284,7 @@ public: bool IsDegenerate( double eps = METRIC_PRECISION ) const override; MbCurve3D * Trimmed( double t1, double t2, int sense ) const override; // \ru Создать усеченную кривую \en Create the trimmed curve MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = nullptr, - VERSION version = Math::DefaultMathVersion(), bool * coincParams = nullptr ) const override; + VERSION version = Math::DefaultMathVersion(), bool * coincParams = nullptr ) const override; bool IsPlanar ( double accuracy = METRIC_EPSILON ) const override; // \ru Является ли кривая плоской \en Whether a curve is planar bool GetPlacement( MbPlacement3D & place, PlanarCheckParams params = PlanarCheckParams() ) const override; // \ru Заполнить плейсемент, ести кривая плоская \en Fill the placement if curve is planar @@ -295,7 +295,7 @@ public: double CalculateMetricLength() const override; // \ru Сдвинуть параметр t на расстояние len. \en Move parameter t on the metric distance len. bool DistanceAlong( double & t, double len, int curveDir, double eps = Math::metricPrecision, - VERSION version = Math::DefaultMathVersion() ) const override; + VERSION version = Math::DefaultMathVersion() ) const override; /// \ru Получить границы участков кривой, которые описываются одной аналитической функцией. /// \en Get the boundaries of the curve sections that are described by one analytical function. \~ @@ -316,56 +316,56 @@ public: double DeviationStep( double t, double angle ) const override; // \ru Периодичность \en Periodicity bool IsPointsPeriodic( ptrdiff_t & begPointNumber, // \ru Номер первой точки \en Number of the first point - ptrdiff_t & endPointNumber, // \ru Номер последней точки \en Number of the last point - ptrdiff_t & period ) const override; // \ru Количество точек в периоде \en The number of points in the period + ptrdiff_t & endPointNumber, // \ru Номер последней точки \en Number of the last point + ptrdiff_t & period ) const override; // \ru Количество точек в периоде \en The number of points in the period - void Delete(); // \ru Очистить данные \en Clear data + void Delete(); // \ru Очистить данные \en Clear data // \ru Подготовить вычисление сплайна \en Prepare the calculation of the spline - void InitCreate( MbVector3D &, MbVector3D &, SArray &, + void InitCreate( MbVector3D &, MbVector3D &, SArray &, double &, double &, double &, double &, bool black = false ); // \ru Решить систему методом исключения гауса \en Solve the system by Gaussian elimination method // \ru Если кривая не замкнута и black = true система решается \en If a curve is non-closed and black is true then the system is solved // \ru При условии отсутствия узла Де Бор К. "Практическое руководство по сплайнам" \en If knot is not (Carl de Boor - "A Practical Guide to Splines") // \ru 1985, М.: Радио и связь, стр. 52. \en 2001, Springer 52. - void Create ( MbVector3D &, MbVector3D &, bool black = false ); - void CreateEndS( MbVector3D &, MbVector3D & ) const; - void Create (); // \ru Построить сплайн \en Create a spline + void Create ( MbVector3D &, MbVector3D &, bool black = false ); + void CreateEndS( MbVector3D &, MbVector3D & ) const; + void Create (); // \ru Построить сплайн \en Create a spline - void Create ( const MbVector3D &, const MbVector3D &, bool , bool ); + void Create ( const MbVector3D &, const MbVector3D &, bool , bool ); // \ru Вычислить параметры сплайна \en Calculate parameters of the spline - void CreateVects( const MbVector3D & startS, bool startFirst, + void CreateVects( const MbVector3D & startS, bool startFirst, const MbVector3D & endS, bool endFirst ); // \ru Установить область изменения параметра первый минимальный второй максимальный \en Set the range of the parameter: first minimum and second maximum - bool SetLimitParam( double, double ); - bool ConvertToClosed(); // \ru Преобразовать в замкнутую кривую если кривая разомкнута \en Convert to a closed curve if the curve is open + bool SetLimitParam( double, double ); + bool ConvertToClosed(); // \ru Преобразовать в замкнутую кривую если кривая разомкнута \en Convert to a closed curve if the curve is open // \ru Но концы кривой гладко стыкуются \en But the ends of the curve are connected smoothly - double StepD( double t, double sag, bool bfirst, double angle = Math::lowRenderAng ) const; // \ru Вычисление шага аппроксимации \en Calculation of approximation step + double StepD( double t, double sag, bool bfirst, double angle = Math::lowRenderAng ) const; // \ru Вычисление шага аппроксимации \en Calculation of approximation step - ptrdiff_t GetVectorListCount() const { return (ptrdiff_t)vectorList.Count(); } - void GetVectorList( SArray & vectors ) const { vectors = vectorList; } ///< \ru Вторые призводные в хар. точках \en Second derivatives at control points. + ptrdiff_t GetVectorListCount() const { return (ptrdiff_t)vectorList.Count(); } + void GetVectorList( SArray & vectors ) const { vectors = vectorList; } ///< \ru Вторые призводные в хар. точках \en Second derivatives at control points. const MbVector3D & GetVectorList( size_t i ) const { return vectorList[i]; } // \ru Вторые призводные в характеристических точках \en Second derivatives at control points. MbVector3D & SetVectorList( size_t i ) { return vectorList[i]; } // \ru Вторые призводные в характеристических точках \en Second derivatives at control points. - ptrdiff_t GetTListCount() const { return tList.Count(); } ///< \ru Количество параметров в узлах \en The number of parameters in knots. - void GetTList( SArray & params ) const { params = tList; } ///< \ru Параметры в узлах \en Parameters in knots + ptrdiff_t GetTListCount() const { return tList.Count(); } ///< \ru Количество параметров в узлах \en The number of parameters in knots. + void GetTList( SArray & params ) const { params = tList; } ///< \ru Параметры в узлах \en Parameters in knots const double & GetTList( size_t i ) const { return tList[i]; } - ptrdiff_t GetUppParam() const { return splinesCount; } ///< \ru число сегментов \en The number of segments - + ptrdiff_t GetUppParam() const { return splinesCount; } ///< \ru число сегментов \en The number of segments private: - // \ru Усечь кривую с разрывом \en Trim a curve with a break - MbCurve3D * TrimmedBreak( double t1, double t2, int sense ) 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 - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbCubicSpline3D & ); + // \ru Усечь кривую с разрывом \en Trim a curve with a break + MbCurve3D * TrimmedBreak( double t1, double t2, int sense ) 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 + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbCubicSpline3D & ); DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCubicSpline3D ) }; IMPL_PERSISTENT_OPS( MbCubicSpline3D ) + #endif // __CUR_CUBIC_SPLINE3D_H diff --git a/C3d/Include/cur_curve_spiral.h b/C3d/Include/cur_curve_spiral.h index dcf5cc0..fcc5382 100644 --- a/C3d/Include/cur_curve_spiral.h +++ b/C3d/Include/cur_curve_spiral.h @@ -81,9 +81,9 @@ public: VISITING_CLASS( MbCurveSpiral ); /// \ru Инициализация спирали по спирали. \en Spiral initialization by spiral. - void Init( const MbCurveSpiral & ); + void Init( const MbCurveSpiral & ); /// \ru Инициализация спирали по основанию (локальной системе координат). \en Spiral initialization by base (local coordinate system). - void Init( const MbPlacement3D & ); + void Init( const MbPlacement3D & ); // \ru Общие функции математического объекта \en Common functions of the mathematical object @@ -110,7 +110,7 @@ public: void _ThirdDer ( double t, MbVector3D & td ) const override; // \ru Третья производная по t \en Third derivative with respect to t // \ru Вычислить значения точки и производных для заданного параметра. \en Calculate point and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const override; + MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const override; void Inverse( MbRegTransform * iReg = nullptr ) override; // \ru Изменить направление \en Change direction @@ -122,17 +122,18 @@ public: double GetSpiralRadius ( double t ) const override; // \ru Выдать физический радиус спирали \en Get physical radius of spiral protected: - void Init( bool setLimits ); - double GetRadiusValue( double t, double & r0, MbVector & derive ) const; // \ru Выдать радиус спирали \en Get the spiral radius - void GetRadiusDerivative( MbVector & derive, double & r1 ) const; // \ru Выдать первую производную радиуса \en Get the first derivative of the radius - void GetRadiusDerivatives( double wPar, MbVector & derive, double & r1, double & r2, double & r3 ) const; // \ru Выдать первую, вторую и третью производные радиуса \en Get the first, second and third derivatives of the radius + void Init( bool setLimits ); + double GetRadiusValue( double t, double & r0, MbVector & derive ) const; // \ru Выдать радиус спирали \en Get the spiral radius + void GetRadiusDerivative( MbVector & derive, double & r1 ) const; // \ru Выдать первую производную радиуса \en Get the first derivative of the radius + void GetRadiusDerivatives( double wPar, MbVector & derive, double & r1, double & r2, double & r3 ) const; // \ru Выдать первую, вторую и третью производные радиуса \en Get the first, second and third derivatives of the radius private: - void operator = ( const MbCurveSpiral & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbCurveSpiral & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCurveSpiral ) }; // MbCurveSpiral IMPL_PERSISTENT_OPS( MbCurveSpiral ) + #endif // __CUC_CURVE_SPIRAL_H diff --git a/C3d/Include/cur_hermit.h b/C3d/Include/cur_hermit.h index 4d968c4..2c0cf84 100644 --- a/C3d/Include/cur_hermit.h +++ b/C3d/Include/cur_hermit.h @@ -190,26 +190,26 @@ public : public : VISITING_CLASS( MbHermit ); - // \ru Установить параметры сплайна \en Set parameters of spline - bool Init( const SArray & initPoints, bool cls ); - bool Init( const SArray & initParams, - const SArray & initPoints, bool cls ); - bool Init( const SArray & initParams, - const SArray & initPoints, - const SArray & initVectors, bool cls ); - bool Init( const SArray & initParams, - const SArray & initPoints, - const SArray & vLabels, bool cls ); - void Init( const MbHermit & init ); - void Init( double t1, const MbCartPoint & p1, const MbVector & v1, - double t2, const MbCartPoint & p2, const MbVector & v2 ); - bool Init( double t1, double t2 ); + // \ru Установить параметры сплайна \en Set parameters of spline + bool Init( const SArray & initPoints, bool cls ); + bool Init( const SArray & initParams, + const SArray & initPoints, bool cls ); + bool Init( const SArray & initParams, + const SArray & initPoints, + const SArray & initVectors, bool cls ); + bool Init( const SArray & initParams, + const SArray & initPoints, + const SArray & vLabels, bool cls ); + void Init( const MbHermit & init ); + void Init( double t1, const MbCartPoint & p1, const MbVector & v1, + double t2, const MbCartPoint & p2, const MbVector & v2 ); + bool Init( double t1, double t2 ); /** \ru \name Общие функции геометрического объекта. \en \name Common functions of geometric object. \{ */ - MbePlaneType IsA() const override; // \ru Тип элемента \en Type of element + MbePlaneType IsA() const override; // \ru Тип элемента \en Type of element bool SetEqual( const MbPlaneItem & ) override; // \ru Сделать элементы равными \en Make the elements equal void Transform( const MbMatrix & matr, MbRegTransform * ireg = nullptr, const MbSurface * newSurface = nullptr ) override; // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix void Move( const MbVector & to, MbRegTransform * = nullptr, const MbSurface * newSurface = nullptr ) override; // \ru Сдвиг \en Translation @@ -244,7 +244,7 @@ public : void _PointOn ( double t, MbCartPoint & p ) const override; // \ru Вычислить значения точки и производных для заданного параметра. \en Calculate point and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - MbCartPoint & pnt, MbVector & fir, MbVector * sec, MbVector * thir ) const override; + MbCartPoint & pnt, MbVector & fir, MbVector * sec, MbVector * thir ) const override; void Inverse( MbRegTransform * iReg = nullptr ) override; // \ru Изменить направление \en Change direction double Step( double t, double sag ) const override; // \ru Вычисление шага аппроксимации с учетом радиуса кривизны \en Calculation of approximation step with consideration of curvature radius @@ -254,17 +254,16 @@ public : double PointProjection( const MbCartPoint & pnt ) const override; // \ru Проекция точки на кривую \en Point projection on the curve bool NearPointProjection( const MbCartPoint & pnt, double xEpsilon, double yEpsilon, - double & t, bool ext, MbRect1D * tRange = nullptr ) const override; // \ru Проекция точки на кривую или её продолжение в области поиска проекции \en Point projection on the curve or its extension in the projection search area + double & t, bool ext, MbRect1D * tRange = nullptr ) const override; // \ru Проекция точки на кривую или её продолжение в области поиска проекции \en Point projection on the curve or its extension in the projection search area double CalculateMetricLength() const override; // \ru Посчитать метрическую длину разомкнутой \en Calculate the open metric length bool GetWeightCentre( MbCartPoint & wc ) const override; // \ru Посчитать центр тяжести кривой \en Calculate the gravity center of the curve void CalculateGabarit( MbRect & r ) const override; // \ru Определить габариты \en Calculate bounding box bool DistanceAlong( double & t, double len, int curveDir, double eps = Math::LengthEps, - VERSION version = Math::DefaultMathVersion() ) const override; + VERSION version = Math::DefaultMathVersion() ) const override; /// \ru Получить границы участков кривой, которые описываются одной аналитической функцией. /// \en Get the boundaries of the curve sections that are described by one analytical function. \~ void GetAnalyticalFunctionsBounds( std::vector & params ) const override; - bool IsStraight( bool ignoreParams = false ) const override; // \ru Признак прямолинейности кривой \en An attribute of curve straightness size_t GetCount() const override; @@ -281,10 +280,10 @@ public : virtual void SetCurveValue( double t, const MbCartPoint & pnt, double tDelta, const MbVector & v, double xEps, double yEps ); // \ru Установить точку и производную на участке. \en Set a point and derivetive at region. void ChangePoint( ptrdiff_t index, const MbCartPoint & pnt ) override; // \ru Заменить точку \en Replace a point void RemovePoint( ptrdiff_t index ) override; // \ru Удалить точку \en Remove a point - void GetVector( ptrdiff_t index, MbVector & vec ) const; - MbCartPoint & SetPoint( ptrdiff_t index ); - MbVector & SetVector ( ptrdiff_t index ); - bool SetTangentVectors( const SArray & tauVectors ); // \ru vectorList[i] сделать параллельными tauVectors[i] \en Make vectorList[i] parallel to tauVectors[i] + void GetVector( ptrdiff_t index, MbVector & vec ) const; + MbCartPoint & SetPoint( ptrdiff_t index ); + MbVector & SetVector ( ptrdiff_t index ); + bool SetTangentVectors( const SArray & tauVectors ); // \ru vectorList[i] сделать параллельными tauVectors[i] \en Make vectorList[i] parallel to tauVectors[i] size_t GetPointsCount() const override; // \ru Выдать количество точек \en Get the number of points size_t GetParamsCount() const override; // \ru Выдать количество параметров \en Get the number of parameters. bool CheckParam ( double & t, ptrdiff_t & i0, ptrdiff_t & i1, double & t0, double & t1 ) const override; // \ru Установить параметр \en Set parameter @@ -297,56 +296,55 @@ public : void SetBegEndDerivesEqual() override; // \ru Установить равные производные на краях \en Set equal derivatives at the edges void ClosedBreak() override; // \ru Сделать незамкнутой, оставив совпадающими начало и конец \en Make unclosed, leave coinciding start and end - bool SetLimitParam( double newTMin, double newTMax ); // \ru Установить область изменения параметра \en Set range of parameter - void CalculateDerivatives(); - void SetLimitVector( int n, const MbVector & v ); - /// \ru Создать кривую путём сращивания части данной кривой с частью кривой init. \en Create a curve by joining a part of this curve with a part of "init" curve. - MbHermit * CurvesCombine( double t0, double w0, bool add, - const MbHermit & init, double t1, double w1, double koef, bool checkClosed ) const; + bool SetLimitParam( double newTMin, double newTMax ); // \ru Установить область изменения параметра \en Set range of parameter + void CalculateDerivatives(); + void SetLimitVector( int n, const MbVector & v ); + /// \ru Создать кривую путём сращивания части данной кривой с частью кривой init. \en Create a curve by joining a part of this curve with a part of "init" curve. + MbHermit * CurvesCombine( double t0, double w0, bool add, + const MbHermit & init, double t1, double w1, double koef, bool checkClosed ) const; - size_t GetVectorListCount() const { return vectorList.Count(); } + size_t GetVectorListCount() const { return vectorList.Count(); } - template - void GetVectorList( VectorsVector & vectors ) const { vectors.assign( vectorList.begin(), vectorList.end() ); } + template + void GetVectorList( VectorsVector & vectors ) const { vectors.assign( vectorList.begin(), vectorList.end() ); } - const MbVector & _GetVectorList( size_t i ) const { return vectorList[i]; } - MbVector & _SetVectorList( size_t i ) { MbPolyCurve::Refresh(); return vectorList[i]; } + const MbVector & _GetVectorList( size_t i ) const { return vectorList[i]; } + MbVector & _SetVectorList( size_t i ) { MbPolyCurve::Refresh(); return vectorList[i]; } - size_t GetTListCount() const { return tList.Count(); } + size_t GetTListCount() const { return tList.Count(); } void GetTList( SArray & params ) const override { params = tList; } - double _GetTList( size_t i ) const { return tList[i]; } + double _GetTList( size_t i ) const { return tList[i]; } - // \ru Добавить точки и параметры в конец кривой в заданной последовательности. \en Parameters and points add to end successively. - bool AddPoints( SArray & params, SArray & points ); - // \ru Вставить точки и параметры в перед кривой в заданной последовательности. \en Parameters and points insetr to beg successively. - bool InsertPoints( SArray & params, SArray & points ); + // \ru Добавить точки и параметры в конец кривой в заданной последовательности. \en Parameters and points add to end successively. + bool AddPoints( SArray & params, SArray & points ); + // \ru Вставить точки и параметры в перед кривой в заданной последовательности. \en Parameters and points insetr to beg successively. + bool InsertPoints( SArray & params, SArray & points ); - // \ru При линейном расположении нескольких точек согласовать производные на краях участка. \en Aligning the derivatives on the group if several points are located linearly. - bool DerivativesCorrection( double accuracy ); + // \ru При линейном расположении нескольких точек согласовать производные на краях участка. \en Aligning the derivatives on the group if several points are located linearly. + bool DerivativesCorrection( double accuracy ); - /// \ru Определение максимального индекса массива параметров слева. \en Determination of the maximum index of parameter array on the left. - ptrdiff_t GetIndex( double t ) const; + /// \ru Определение максимального индекса массива параметров слева. \en Determination of the maximum index of parameter array on the left. + ptrdiff_t GetIndex( double t ) const; void GetProperties( MbProperties & properties ) override; // \ru Выдать свойства объекта \en Get properties of the object void SetProperties( const MbProperties & properties ) override; // \ru Записать свойства объекта \en Set properties of the object /** \} */ - void LocalCoordinate( double & t, - ptrdiff_t & index1, ptrdiff_t & index2, - double & param1, double & param2, - double & paramD, double & paramW, - double & quota1, double & quota2 ) const; + void LocalCoordinate( double & t, + ptrdiff_t & index1, ptrdiff_t & index2, + double & param1, double & param2, + double & paramD, double & paramW, + double & quota1, double & quota2 ) const; private: - bool Break( MbHermit & trimPart, double t1, double t2 ) 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. - /// \ru Найти параметры пересечение сплайна с прямой x = val или y=val. - /// \ ru Find the parameters of the intersection of the spline with the line x = val or y = val. - void HorVertRoots( bool isVert, double val, SArray & params ) const; + bool Break( MbHermit & trimPart, double t1, double t2 ) 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. + // \ru Найти параметры пересечение сплайна с прямой x = val или y=val. \ ru Find the parameters of the intersection of the spline with the line x = val or y = val. + void HorVertRoots( bool isVert, double val, SArray & params ) const; - void operator = ( const MbHermit & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbHermit & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbHermit ) }; @@ -358,10 +356,10 @@ IMPL_PERSISTENT_OPS( MbHermit ) /// \ru Определение местных координат области поверхности \en Definition of local coordinates in a surface region // --- inline void MbHermit::LocalCoordinate( double & t, - ptrdiff_t & index1, ptrdiff_t & index2, - double & param1, double & param2, - double & paramD, double & paramW, - double & quota1, double & quota2 ) const + ptrdiff_t & index1, ptrdiff_t & index2, + double & param1, double & param2, + double & paramD, double & paramW, + double & quota1, double & quota2 ) const { #define EPS_NULL(a,epsilon) ((a) < epsilon && (a) > -epsilon) // проверка значения в epsilon-окрестности нуля без вызова функции ::fabs diff --git a/C3d/Include/cur_hermit3d.h b/C3d/Include/cur_hermit3d.h index 5586098..6aff27e 100644 --- a/C3d/Include/cur_hermit3d.h +++ b/C3d/Include/cur_hermit3d.h @@ -187,26 +187,26 @@ public: public : VISITING_CLASS( MbHermit3D ); - /// \ru Установить параметры сплайна по точкам и флагу замкнутости. \en Set parameters of spline by points and closeness flag. - bool Init( const SArray & initPoints, bool cls ); - /// \ru Установить параметры сплайна по параметрам, точкам и флагу замкнутости. \en Set parameters of spline by parameters, points and closeness flag. - bool Init( const SArray & initParams, - const SArray & initPoints, bool cls ); - /// \ru Установить параметры сплайна. \en Set parameters of spline. - bool Init( const SArray & initParams, - const SArray & initPoints, - const SArray & initVectors, bool cls ); - /// \ru Установить параметры сплайна. \en Set parameters of spline. - bool Init( const SArray & initParams, - const SArray & initPoints, - const SArray & vLabels, bool cls ); - /// \ru Установить параметры сплайна по другому сплайну Эрмита. \en Set parameters of spline by another spline of Hermit. - void Init( const MbHermit3D & ); - /// \ru Установить параметры сплайна по двумерному сплайну Эрмита. \en Set parameters of spline by two-dimensional spline of Hermit. - void Init( const MbHermit &, const MbPlacement3D & ); - /// \ru Установить параметры сплайна. \en Set parameters of spline. - void Init( double t1, const MbCartPoint3D & p1, const MbVector3D & v1, - double t2, const MbCartPoint3D & p2, const MbVector3D & v2 ); + /// \ru Установить параметры сплайна по точкам и флагу замкнутости. \en Set parameters of spline by points and closeness flag. + bool Init( const SArray & initPoints, bool cls ); + /// \ru Установить параметры сплайна по параметрам, точкам и флагу замкнутости. \en Set parameters of spline by parameters, points and closeness flag. + bool Init( const SArray & initParams, + const SArray & initPoints, bool cls ); + /// \ru Установить параметры сплайна. \en Set parameters of spline. + bool Init( const SArray & initParams, + const SArray & initPoints, + const SArray & initVectors, bool cls ); + /// \ru Установить параметры сплайна. \en Set parameters of spline. + bool Init( const SArray & initParams, + const SArray & initPoints, + const SArray & vLabels, bool cls ); + /// \ru Установить параметры сплайна по другому сплайну Эрмита. \en Set parameters of spline by another spline of Hermit. + void Init( const MbHermit3D & ); + /// \ru Установить параметры сплайна по двумерному сплайну Эрмита. \en Set parameters of spline by two-dimensional spline of Hermit. + void Init( const MbHermit &, const MbPlacement3D & ); + /// \ru Установить параметры сплайна. \en Set parameters of spline. + void Init( double t1, const MbCartPoint3D & p1, const MbVector3D & v1, + double t2, const MbCartPoint3D & p2, const MbVector3D & v2 ); // \ru Общие функции математического объекта \en Common functions of the mathematical object @@ -234,7 +234,7 @@ public : void _PointOn ( double t, MbCartPoint3D &p ) const override; // \ru Вычислить значения точки и производных для заданного параметра. \en Calculate point and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const override; + MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const override; void Inverse( MbRegTransform * iReg = nullptr ) override; // \ru Изменить направление \en Change direction double Step ( double t, double sag ) const override; // \ru Вычисление шага аппроксимации \en Calculation of approximation step @@ -267,8 +267,8 @@ public : virtual void SetCurveValue( double t, const MbCartPoint3D & pnt, double tDelta, const MbVector3D & der, double metrEps ); // \ru Установить точку и производную на участке. \en Set a point and derivetive at region. void RemovePoint( ptrdiff_t index ) override; // \ru Удалить точку \en Remove a point bool ChangePoint( ptrdiff_t index, const MbCartPoint3D & pnt ) override; // \ru Заменить точку \en Replace a point - void GetVector ( ptrdiff_t index, MbVector3D & vec ) const; - bool SetTangentVectors( const SArray & tauVectors ); // \ru vectorList[i] сделать параллельными tauVectors[i] \en Make vectorList[i] parallel to tauVectors[i] + void GetVector ( ptrdiff_t index, MbVector3D & vec ) const; + bool SetTangentVectors( const SArray & tauVectors ); // \ru vectorList[i] сделать параллельными tauVectors[i] \en Make vectorList[i] parallel to tauVectors[i] size_t GetPointsCount() const override; // \ru Выдать количество точек \en Get the number of points void GetRuleInterval( ptrdiff_t index, double & t1, double & t2 ) const override; // \ru Выдать интервал влияния точки \en Get the interval of point influence ptrdiff_t GetNearPointIndex( const MbCartPoint3D & pnt ) const override; // \ru Выдать индекс точки, ближайшей к заданной \en Get the point index which is nearest to the given @@ -280,46 +280,46 @@ public : void GetWeightCentre( MbCartPoint3D &wc ) const override; // \ru Посчитать центр тяжести кривой \en Calculate the gravity center of the curve void CalculateGabarit( MbCube & gab ) const override; // \ru Вычислить габарит кривой \en Calculate the bounding box of curve bool DistanceAlong( double & t, double len, int curveDir, double eps = Math::metricPrecision, - VERSION version = Math::DefaultMathVersion() ) const override; // \ru Сдвинуть параметр t на расстояние len по направлению \en Shift the parameter t by the distance 'len' in the direction + VERSION version = Math::DefaultMathVersion() ) const override; // \ru Сдвинуть параметр t на расстояние len по направлению \en Shift the parameter t by the distance 'len' in the direction // \ru Функции только 3D кривой \en Function for 3D-curve MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = nullptr, - VERSION version = Math::DefaultMathVersion(), bool * coincParams = nullptr ) const override; // \ru Дать плоскую проекцию кривой \en Get a planar projection of curve + VERSION version = Math::DefaultMathVersion(), bool * coincParams = nullptr ) const override; // \ru Дать плоскую проекцию кривой \en Get a planar projection of curve size_t GetCount() const override; // \ru Установить область изменения параметра. \en Set range of parameter. - bool SetLimitParam( double newTMin, double newTMax ); - void CalculateDerivatives(); - void SetLimitVector( ptrdiff_t n, const MbVector3D & v ); + bool SetLimitParam( double newTMin, double newTMax ); + void CalculateDerivatives(); + void SetLimitVector( ptrdiff_t n, const MbVector3D & v ); - size_t GetVectorListCount() const { return vectorList.size(); } + size_t GetVectorListCount() const { return vectorList.size(); } template - void GetVectorList( VectorsVector & vectors ) const { vectors.assign( vectorList.begin(), vectorList.end() ); } + void GetVectorList( VectorsVector & vectors ) const { vectors.assign( vectorList.begin(), vectorList.end() ); } const MbVector3D & _GetVectorList( size_t i ) const { return vectorList[i]; } MbVector3D & _SetVectorList( size_t i ) { MbPolyCurve3D::Refresh(); return vectorList[i]; } - size_t GetTListCount() const { return tList.size(); } - void GetTList( SArray & params ) const { params = tList; } + size_t GetTListCount() const { return tList.size(); } + void GetTList( SArray & params ) const { params = tList; } double _GetTList( size_t i ) const { return tList[i]; } - void LocalCoordinate( double & t, - ptrdiff_t & index1, ptrdiff_t & index2, - double & param1, double & param2, - double & paramD, double & paramW, - double & quota1, double & quota2 ) const; - ptrdiff_t GetIndex( double t ) const; + void LocalCoordinate( double & t, + ptrdiff_t & index1, ptrdiff_t & index2, + double & param1, double & param2, + double & paramD, double & paramW, + double & quota1, double & quota2 ) const; + ptrdiff_t GetIndex( double t ) const; // \ru При линейном расположении нескольких точек согласовать производные на краях участка. \en Aligning the derivatives on the group if several points are located linearly. - bool DerivativesCorrection( double accuracy ); + bool DerivativesCorrection( double accuracy ); private: - bool Break( MbHermit3D & trimPart, double t1, double t2 ) 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. + bool Break( MbHermit3D & trimPart, double t1, double t2 ) 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. - void operator = ( const MbHermit3D & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbHermit3D & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbHermit3D ) }; @@ -331,10 +331,10 @@ IMPL_PERSISTENT_OPS( MbHermit3D ) // \ru Определение местных координат области поверхности \en Definition of local coordinates in a surface region // --- inline void MbHermit3D::LocalCoordinate( double & t, - ptrdiff_t & index1, ptrdiff_t & index2, - double & param1, double & param2, - double & paramD, double & paramW, - double & quota1, double & quota2 ) const + ptrdiff_t & index1, ptrdiff_t & index2, + double & param1, double & param2, + double & paramD, double & paramW, + double & quota1, double & quota2 ) const { double tmin = tList[0]; double tmax = tList[splinesCount]; diff --git a/C3d/Include/cur_line.h b/C3d/Include/cur_line.h index 3ece3e1..d02ca9d 100644 --- a/C3d/Include/cur_line.h +++ b/C3d/Include/cur_line.h @@ -56,12 +56,12 @@ public : \en \name Line initialization functions. \{ */ // \ru Различные варианты инициализации прямой \en Different variants for the initialization of line - void Init( const MbLine & other ) { origin = other.origin; direction = other.direction; } - void Init( const MbCartPoint & pnt, double angle ) { origin = pnt; direction = angle; } - void Init( const MbCartPoint & pnt, const MbDirection & dir ) { origin = pnt; direction = dir; } - void Init( const MbCartPoint & pnt, const MbVector & dir ) { origin = pnt; direction = dir; } - void Init( const MbCartPoint & p1, const MbCartPoint & p2 ) { origin = p1; direction.Calculate( p1, p2 ); } - void Init( double a, double b, double c ); // \ru Инициализация прямой по коэффициентам \en Initialization of a line by coefficients + void Init( const MbLine & other ) { origin = other.origin; direction = other.direction; } + void Init( const MbCartPoint & pnt, double angle ) { origin = pnt; direction = angle; } + void Init( const MbCartPoint & pnt, const MbDirection & dir ) { origin = pnt; direction = dir; } + void Init( const MbCartPoint & pnt, const MbVector & dir ) { origin = pnt; direction = dir; } + void Init( const MbCartPoint & p1, const MbCartPoint & p2 ) { origin = p1; direction.Calculate( p1, p2 ); } + void Init( double a, double b, double c ); // \ru Инициализация прямой по коэффициентам \en Initialization of a line by coefficients /** \} */ /** \ru \name Общие функции геометрического объекта. @@ -129,7 +129,7 @@ public : \{ */ // \ru Вычислить значения точки и производных для заданного параметра. \en Calculate point and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - MbCartPoint & pnt, MbVector & fir, MbVector * sec, MbVector * thir ) const override; + MbCartPoint & pnt, MbVector & fir, MbVector * sec, MbVector * thir ) const override; /** \} */ /** \ru \name Общие функции кривой @@ -152,36 +152,36 @@ public : MbCartPoint * pc = nullptr ) const override; bool DistanceAlong( double & t, double len, int curveDir, double eps = Math::LengthEps, - VERSION version = Math::DefaultMathVersion() ) const override; // \ru Сдвинуть параметр t на расстояние len по направлению \en Shift the parameter t by the distance 'len' in the direction + VERSION version = Math::DefaultMathVersion() ) const override; // \ru Сдвинуть параметр t на расстояние len по направлению \en Shift the parameter t by the distance 'len' in the direction double Step( double t, double sag ) const override; // \ru Вычисление шага аппроксимации \en Calculation of approximation step double DeviationStep( double t, double angle ) const override; // \ru Вычисление шага аппроксимации с учетом угла отклонения \en Calculation of approximation step with consideration of deviation angle - double DistanceToPointSign( const MbCartPoint & to ) const; // \ru Расстояние от прямой до точки со знаком \en Signed distance from the line to the point + double DistanceToPointSign( const MbCartPoint & to ) const; // \ru Расстояние от прямой до точки со знаком \en Signed distance from the line to the point - // \ru Положение точки относительно кривой. \en The point position relative to the curve. - // \ru iloc_InItem = 1 - точка находится слева от прямой, \en Iloc_InItem = 1 - point is located to the left of the line, - // \ru iloc_OnItem = 0 - точка находится на прямой, \en Iloc_OnItem = 0 - point is located on the line, - // \ru iloc_OutOfItem = -1 - точка находится справа от прямой. \en Iloc_OutOfItem = -1 - point is located to the right of the line. + // \ru Положение точки относительно кривой. \en The point position relative to the curve. + // \ru iloc_InItem = 1 - точка находится слева от прямой, \en Iloc_InItem = 1 - point is located to the left of the line, + // \ru iloc_OnItem = 0 - точка находится на прямой, \en Iloc_OnItem = 0 - point is located on the line, + // \ru iloc_OutOfItem = -1 - точка находится справа от прямой. \en Iloc_OutOfItem = -1 - point is located to the right of the line. MbeItemLocation PointRelative ( const MbCartPoint & p, double eps = Math::LengthEps ) const override; double PointProjection ( const MbCartPoint & ) const override; // \ru Проекция точки на кривую \en Point projection on the curve bool NearPointProjection( const MbCartPoint & pnt, double xEpsilon, double yEpsilon, - double & t, bool ext, MbRect1D * tRange = nullptr ) const override; // \ru Проекция точки на кривую или её продолжение в области поиска проекции \en Point projection on the curve or its extension in the projection search area - // \ru Вычисление всех перпендикуляров к кривой из данной точки \en Calculation of all perpendiculars to the curve from a given point + double & t, bool ext, MbRect1D * tRange = nullptr ) const override; // \ru Проекция точки на кривую или её продолжение в области поиска проекции \en Point projection on the curve or its extension in the projection search area + // \ru Вычисление всех перпендикуляров к кривой из данной точки \en Calculation of all perpendiculars to the curve from a given point void PerpendicularPoint( const MbCartPoint & pnt, SArray & tFind ) const override; bool GetMiddlePoint ( MbCartPoint & ) const override; // \ru Выдать среднюю точку кривой \en Calculate a middle point on a curve bool GetWeightCentre( MbCartPoint & ) const override; // \ru Выдать центр прямой \en Get the center of line - bool operator == ( const MbLine & ) const; // \ru Проверка на равенство \en Check for equality - bool operator != ( const MbLine & ) const; // \ru Проверка на неравенство \en Check for inequality + bool operator == ( const MbLine & ) const; // \ru Проверка на равенство \en Check for equality + bool operator != ( const MbLine & ) const; // \ru Проверка на неравенство \en Check for inequality - bool IsHorizontal( double eps = Math::AngleEps ) const { return ::fabs( direction.ay ) < eps; } // \ru Проверка горизонтальности \en Check for horizontality - bool IsVertical ( double eps = Math::AngleEps ) const { return ::fabs( direction.ax ) < eps; } // \ru Проверка вертикальности \en Check for verticality + bool IsHorizontal( double eps = Math::AngleEps ) const { return ::fabs( direction.ay ) < eps; } // \ru Проверка горизонтальности \en Check for horizontality + bool IsVertical ( double eps = Math::AngleEps ) const { return ::fabs( direction.ax ) < eps; } // \ru Проверка вертикальности \en Check for verticality - bool IsSimilar ( const MbLine & ) const; // \ru Проверка одинаковости двух прямых \en Check for sameness of two lines - bool IsParallel( const MbLine & other, double epsilon = Math::AngleEps ) const; // \ru Проверка параллельности двух прямых \en Check for parallelism of two lines - double DistanceToParallel( const MbLine & ) const; // \ru Расстояние до параллельной прямой \en The distance to the parallel line + bool IsSimilar ( const MbLine & ) const; // \ru Проверка одинаковости двух прямых \en Check for sameness of two lines + bool IsParallel( const MbLine & other, double epsilon = Math::AngleEps ) const; // \ru Проверка параллельности двух прямых \en Check for parallelism of two lines + double DistanceToParallel( const MbLine & ) const; // \ru Расстояние до параллельной прямой \en The distance to the parallel line void IntersectHorizontal( double y, SArray & cross ) const override; // \ru Пересечение с горизонтальной прямой \en Intersection with the horizontal line void IntersectVertical ( double x, SArray & cross ) const override; // \ru Пересечение с вертикальной прямой \en Intersection with the vertical line @@ -195,31 +195,31 @@ public : double GetParamToUnit() const override; double GetParamToUnit( double t ) const override; - void SetPoint( const MbCartPoint & pnt ) { origin = pnt; } // \ru Установить новую базовую точку \en Set the new base point - void GetPoint( MbCartPoint & pnt ) const { pnt = origin; } // \ru Выдать базовую точку \en Get the base point - void GetDirection( MbDirection & dir ) const { dir = direction; } // \ru Выдать вектор наклона прямой \en Get the vector of a line inclination - void SetDirection( const MbDirection & dir ) { direction = dir; } // \ru Установить вектор наклона прямой \en Set the vector of a line inclination - void SetDirection( const MbVector & v ) { direction = v; } + void SetPoint( const MbCartPoint & pnt ) { origin = pnt; } // \ru Установить новую базовую точку \en Set the new base point + void GetPoint( MbCartPoint & pnt ) const { pnt = origin; } // \ru Выдать базовую точку \en Get the base point + void GetDirection( MbDirection & dir ) const { dir = direction; } // \ru Выдать вектор наклона прямой \en Get the vector of a line inclination + void SetDirection( const MbDirection & dir ) { direction = dir; } // \ru Установить вектор наклона прямой \en Set the vector of a line inclination + void SetDirection( const MbVector & v ) { direction = v; } - void SetAngle( double angle ) { direction = angle; } // \ru Установить новый угол \en Set the new angle - double GetAngle() const { return direction.DirectionAngle(); } // \ru Выдать значение угла наклона \en Get the value of an angle inclination + void SetAngle( double angle ) { direction = angle; } // \ru Установить новый угол \en Set the new angle + double GetAngle() const { return direction.DirectionAngle(); } // \ru Выдать значение угла наклона \en Get the value of an angle inclination - // \ru Создать NURBS представление кривой \en Create a NURBS representation of the curve + // \ru Создать NURBS представление кривой \en Create a NURBS representation of the curve MbNurbs * NurbsCurve( const MbCurveIntoNurbsInfo & ) const override; MbCurve * NurbsCurve( const MbNurbsParameters & ) const override; // \ru Построить Nurbs-копию кривой \en Construct NURBS copy of the curve MbContour * NurbsContour() const override; size_t GetCount() const override; // \ru Количество разбиений для прохода в операциях \en The number of partitions for passage in the operations - ptrdiff_t IntersectRect( MbRect & rect, MbCartPoint * cross ) const; // \ru Пересечение прямой с прямоугольником \en Intersection of a line with rectangle - void Implicit( double & A, double & B, double & C ) const; // \ru Выдать коэффициенты неявного представления \en Get coefficients of implicit representation + ptrdiff_t IntersectRect( MbRect & rect, MbCartPoint * cross ) const; // \ru Пересечение прямой с прямоугольником \en Intersection of a line with rectangle + void Implicit( double & A, double & B, double & C ) const; // \ru Выдать коэффициенты неявного представления \en Get coefficients of implicit representation const MbCartPoint & GetOrigin() const { return origin; } const MbDirection & GetDirection() const { return direction; } - MbCartPoint & SetOrigin() { return origin; } - MbDirection & SetDirection() { return direction; } + MbCartPoint & SetOrigin() { return origin; } + MbDirection & SetDirection() { return direction; } - MbCartPoint Origin() const { MbCartPoint p( origin ); return p; } - MbVector Derive() const { MbVector v( direction.ax, direction.ay ); return v; } + MbCartPoint Origin() const { MbCartPoint p( origin ); return p; } + MbVector Derive() const { MbVector v( direction.ax, direction.ay ); return v; } void GetProperties( MbProperties & ) override; // \ru Выдать свойства объекта \en Get properties of the object void SetProperties( const MbProperties & ) override; // \ru Записать свойства объекта \en Set properties of the object @@ -229,13 +229,15 @@ public : /** \} */ private: - void operator = ( const MbLine & ); // \ru Не реализовано. \en Not implemented. + + void operator = ( const MbLine & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbLine ) }; // MbLine IMPL_PERSISTENT_OPS( MbLine ) + //------------------------------------------------------------------------------ // \ru Расстояние от прямой до точки со знаком \en Signed distance from the line to the point // --- @@ -243,6 +245,7 @@ inline double MbLine::DistanceToPointSign( const MbCartPoint & to ) const { return direction.ax * ( to.y - origin.y ) - direction.ay * ( to.x - origin.x ); } + //------------------------------------------------------------------------------ // \ru Проверка на равенство \en Check for equality // --- @@ -250,6 +253,7 @@ inline bool MbLine::operator == ( const MbLine & with ) const { return (origin == with.origin) && ( direction.Colinear( with.direction ) ); } + //------------------------------------------------------------------------------ // \ru Проверка на неравенство \en Check for inequality // --- @@ -257,6 +261,7 @@ inline bool MbLine::operator != ( const MbLine & with ) const { return !(*this == with); } + //------------------------------------------------------------------------------ // \ru Проверка параллельности двух прямых \en Check for parallelism of two lines // --- @@ -265,6 +270,7 @@ inline bool MbLine::IsParallel( const MbLine & other, double epsilon ) const { direction.ax * other.direction.ay ) < epsilon; } + //------------------------------------------------------------------------------ // \ru Проверка одинаковости двух прямых \en Check for sameness of two lines // --- @@ -272,6 +278,7 @@ inline bool MbLine::IsSimilar( const MbLine & other ) const { return IsParallel( other ) && fabs( DistanceToPointSign( other.origin ) ) < Math::LengthEps; } + //------------------------------------------------------------------------------ // \ru Расстояние до параллельной прямой \en The distance to the parallel line // --- @@ -279,6 +286,7 @@ inline double MbLine::DistanceToParallel( const MbLine & to ) const { return DistanceToPoint( to.origin ); } + //------------------------------------------------------------------------------ // \ru Выдать коеффициенты неявного представления \en Get coefficients of implicit representation // --- diff --git a/C3d/Include/cur_line3d.h b/C3d/Include/cur_line3d.h index f703d72..ca1bb74 100644 --- a/C3d/Include/cur_line3d.h +++ b/C3d/Include/cur_line3d.h @@ -48,10 +48,10 @@ public : public : VISITING_CLASS( MbLine3D ); - void Init( const MbLine3D & init ); - void Init( const MbCartPoint3D & p0, const MbVector3D & dir ); - void Init( const MbCartPoint3D & p1, const MbCartPoint3D & p2 ); - void Init( const MbPlacement3D & pos, const MbLine & line ); + void Init( const MbLine3D & init ); + void Init( const MbCartPoint3D & p0, const MbVector3D & dir ); + void Init( const MbCartPoint3D & p1, const MbCartPoint3D & p2 ); + void Init( const MbPlacement3D & pos, const MbLine & line ); // \ru Общие функции математического объекта \en Common functions of the mathematical object @@ -87,7 +87,7 @@ public : void _ThirdDer ( double t, MbVector3D & ) const override; // \ru Третья производная по t \en Third derivative with respect to t // \ru Вычислить значения точки и производных для заданного параметра. \en Calculate point and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const override; + MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const override; // \ru Построить NURBS копию кривой \en Create a NURBS copy of the curve MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & ) const override; @@ -112,8 +112,8 @@ public : // \ru Ближайшая проекция точки на кривую \en The nearest point projection to the curve bool NearPointProjection( const MbCartPoint3D &, double & t, bool ext, MbRect1D * tRange = nullptr ) const override; - bool operator == ( const MbLine3D & with ) const; // \ru Проверка на равенство \en Check for equality - bool operator != ( const MbLine3D & with ) const; // \ru Проверка на неравенство \en Check for inequality + bool operator == ( const MbLine3D & with ) const; // \ru Проверка на равенство \en Check for equality + bool operator != ( const MbLine3D & with ) const; // \ru Проверка на неравенство \en Check for inequality void GetCentre ( MbCartPoint3D & c ) const override; // \ru Выдать центр кривой \en Get the center of curve void GetWeightCentre( MbCartPoint3D & wc ) const override; // \ru Выдать центр тяжести кривой \en Get the center of gravity of the curve @@ -125,9 +125,9 @@ public : // \ru Дать плоскую проекцию кривой \en Get a planar projection of curve MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = nullptr, - VERSION version = Math::DefaultMathVersion(), bool * coincParams = nullptr ) const override; + VERSION version = Math::DefaultMathVersion(), bool * coincParams = nullptr ) const override; MbCurve * GetMapPsp( const MbMatrix3D &, double zNear, - MbRect1D * pRgn = nullptr ) const override; + MbRect1D * pRgn = nullptr ) const override; void CalculatePolygon( const MbStepData & stepData, MbPolygon3D & ) const override; // \ru pассчитать полигон \en Calculate a polygon bool IsSimilarToCurve( const MbCurve3D & curve, double precision = METRIC_PRECISION ) const override; // \ru Подобные ли кривые для объединения (слива) \en Whether the curves for union (joining) are similar @@ -135,20 +135,21 @@ public : const MbVector3D & GetDirection() const { return direction;} MbCartPoint3D & SetOrigin() { return origin; } MbVector3D & SetDirection() { return direction;} - void SetOrigin( const MbCartPoint3D & p ) { origin = p; } - void SetDirection( const MbVector3D & v ) { direction = v; } - bool RoundColinear ( const MbLine3D & with, double eps = Math::angleRegion ) const; // \ru Грубая коллинеарность \en Rough collinearity - bool Colinear ( const MbLine3D & with, double eps = Math::angleRegion ) const; // \ru Коллинеарность \en Collinearity - bool Orthogonal( const MbLine3D & with, double eps = Math::angleRegion ) const; // \ru Ортогональность \en Orthogonality + void SetOrigin( const MbCartPoint3D & p ) { origin = p; } + void SetDirection( const MbVector3D & v ) { direction = v; } + bool RoundColinear ( const MbLine3D & with, double eps = Math::angleRegion ) const; // \ru Грубая коллинеарность \en Rough collinearity + bool Colinear ( const MbLine3D & with, double eps = Math::angleRegion ) const; // \ru Коллинеарность \en Collinearity + bool Orthogonal( const MbLine3D & with, double eps = Math::angleRegion ) const; // \ru Ортогональность \en Orthogonality private: - void operator = ( const MbLine3D & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbLine3D & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbLine3D ) }; IMPL_PERSISTENT_OPS( MbLine3D ) + //------------------------------------------------------------------------------ // \ru Проверка на равенство \en Check for equality // --- diff --git a/C3d/Include/cur_line_segment.h b/C3d/Include/cur_line_segment.h index 86a55f0..b753889 100644 --- a/C3d/Include/cur_line_segment.h +++ b/C3d/Include/cur_line_segment.h @@ -57,27 +57,27 @@ public : public : VISITING_CLASS( MbLineSegment ); - /** \ru \name Функции инициализации отрезка. - \en \name Line segment initialization functions. + /** \ru \name Функции инициализации отрезка. + \en \name Line segment initialization functions. \{ */ - // \ru Установить параметры отрезка \en Set the parameters of line segment - void Init( const MbLineSegment & ); - void Init( const MbCartPoint &p1, const MbCartPoint &p2 ); - void Init( const MbCartPoint &pnt, double x1, double x2 ); - void Init( double t1, double t2 ); - void Init1( const MbCartPoint &p1, const MbCartPoint &p2, double &len, double &angle ); - void Init2( const MbCartPoint &p1, MbCartPoint &p2, const double &len, double &angle ); - void Init3( const MbCartPoint &p1, MbCartPoint &p2, double &len, const double &angle, - const DiskreteLengthData * diskrData = nullptr ); - void Init4( MbCartPoint &p1, const MbCartPoint &p2, const double &len, double &angle ); - void Init5( MbCartPoint &p1, const MbCartPoint &p2, double &len, const double &angle, - const DiskreteLengthData * diskrData = nullptr ); - void Init6( const MbCartPoint &p1, MbCartPoint &p2, const double &len, const double &angle ); - void Init7( MbCartPoint &p1, const MbCartPoint &p2, const double &len, const double &angle ); - void Init8( MbCartPoint &p1, MbCartPoint &p2, double &len, double &angle, - const DiskreteLengthData & diskrData, bool correctP1 ); - void Init9( const MbCartPoint & p1, MbCartPoint & p2, double & len, double & angle, - const DiskreteLengthData & diskrData, bool keepX ); + // \ru Установить параметры отрезка \en Set the parameters of line segment + void Init( const MbLineSegment & ); + void Init( const MbCartPoint &p1, const MbCartPoint &p2 ); + void Init( const MbCartPoint &pnt, double x1, double x2 ); + void Init( double t1, double t2 ); + void Init1( const MbCartPoint &p1, const MbCartPoint &p2, double &len, double &angle ); + void Init2( const MbCartPoint &p1, MbCartPoint &p2, const double &len, double &angle ); + void Init3( const MbCartPoint &p1, MbCartPoint &p2, double &len, const double &angle, + const DiskreteLengthData * diskrData = nullptr ); + void Init4( MbCartPoint &p1, const MbCartPoint &p2, const double &len, double &angle ); + void Init5( MbCartPoint &p1, const MbCartPoint &p2, double &len, const double &angle, + const DiskreteLengthData * diskrData = nullptr ); + void Init6( const MbCartPoint &p1, MbCartPoint &p2, const double &len, const double &angle ); + void Init7( MbCartPoint &p1, const MbCartPoint &p2, const double &len, const double &angle ); + void Init8( MbCartPoint &p1, MbCartPoint &p2, double &len, double &angle, + const DiskreteLengthData & diskrData, bool correctP1 ); + void Init9( const MbCartPoint & p1, MbCartPoint & p2, double & len, double & angle, + const DiskreteLengthData & diskrData, bool keepX ); /** \} */ /** \ru \name Общие функции геометрического объекта. @@ -141,7 +141,7 @@ public : \{ */ // \ru Вычислить значения точки и производных для заданного параметра. \en Calculate point and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - MbCartPoint & pnt, MbVector & fir, MbVector * sec, MbVector * thir ) const override; + MbCartPoint & pnt, MbVector & fir, MbVector * sec, MbVector * thir ) const override; /** \} */ /** \ru \name Функции движения по кривой @@ -179,7 +179,7 @@ public : MbeItemLocation PointRelative( const MbCartPoint & pnt, double eps = Math::LengthEps ) const override; double PointProjection( const MbCartPoint & pnt ) const override; // \ru Проекция точки на отрезок \en Point projection on the line segment bool NearPointProjection( const MbCartPoint & pnt, double xEpsilon, double yEpsilon, - double & t, bool ext, MbRect1D * tRange = nullptr ) const override; // \ru Проекция точки на кривую или её продолжение в области поиска проекции \en Point projection on the curve or its extension in the projection search area + double & t, bool ext, MbRect1D * tRange = nullptr ) const override; // \ru Проекция точки на кривую или её продолжение в области поиска проекции \en Point projection on the curve or its extension in the projection search area void PerpendicularPoint( const MbCartPoint & pnt, SArray & tFind ) const override; // \ru Вычисление всех перпендикуляров к кривой из данной точки \en Calculation of all perpendiculars to the curve from a given point void IntersectHorizontal( double y, SArray & cross ) const override; // \ru Пересечение с горизонтальной прямой \en Intersection with the horizontal line void IntersectVertical ( double x, SArray & cross ) const override; // \ru Пересечение с вертикальной прямой \en Intersection with the vertical line @@ -191,7 +191,7 @@ public : double LengthBetween2Points( MbCartPoint & p1, MbCartPoint & p2, MbCartPoint * pc = nullptr ) const override; bool DistanceAlong( double & t, double len, int curveDir, double eps = Math::LengthEps, - VERSION version = Math::DefaultMathVersion() ) const override; + VERSION version = Math::DefaultMathVersion() ) const override; double CalculateLength( double t1, double t2 ) const override; // \ru Посчитать метрическую длину отрезка от параметра t1 до t2 с заданной точностью \en Coclculate the metric length of the line segment from parameter 't1' to 't2' with the given tolerance bool GetMiddlePoint ( MbCartPoint & ) const override; // \ru Выдать среднюю точку отрезка \en Get the middle point on a line segment bool GetCentre ( MbCartPoint & ) const override; // \ru Выдать центр отрезка \en Get the center of a line segment @@ -205,34 +205,35 @@ public : void GetBasisPoints( MbControlData & ) const override; // \ru Выдать контрольные точки объекта. \en Get control points of object. void SetBasisPoints( const MbControlData & ) override; // \ru Изменить объект по контрольным точкам. \en Change the object by control points. - void ThroughPoint( double t, const MbCartPoint & pnt ); // \ru Пройти через точку при данном параметре \en Pass through the point in the given parameter - void InsertPoint( double t, const MbCartPoint & pnt ); // \ru Вставить точку \en Insert a point - double GetAngle() const; // \ru Выдать значение угла наклона отрезка \en Get the value of an angle inclination of a line segment - MbDirection GetDirection() const; // \ru Выдать вектор наклона отрезка \en Get the vector of a line segment inclination - bool IsParallel( const MbLineSegment & seg, double eps = Math::AngleEps ) const; // \ru Проверка параллельности двух прямых \en Check for parallelism of two lines - const MbCartPoint & GetPoint1() const { return point1; } - const MbCartPoint & GetPoint2() const { return point2; } - MbCartPoint & SetPoint1() { return point1; } - MbCartPoint & SetPoint2() { return point2; } - void GetPoint1( MbCartPoint & p ) const { p = point1; } - void GetPoint2( MbCartPoint & p ) const { p = point2; } - void SetPoint1( const MbCartPoint & p ) { point1 = p; } - void SetPoint2( const MbCartPoint & p ) { point2 = p; } - void SetLimitPoint( ptrdiff_t number, const MbCartPoint & pnt ); // \ru Заменить точку отрезка \en Replace the point of a line segment - void CheckParameter( double & t ) const; // \ru Проверка и коррекция параметра \en Check and correction of parameter + void ThroughPoint( double t, const MbCartPoint & pnt ); // \ru Пройти через точку при данном параметре \en Pass through the point in the given parameter + void InsertPoint( double t, const MbCartPoint & pnt ); // \ru Вставить точку \en Insert a point + double GetAngle() const; // \ru Выдать значение угла наклона отрезка \en Get the value of an angle inclination of a line segment + + MbDirection GetDirection() const; // \ru Выдать вектор наклона отрезка \en Get the vector of a line segment inclination + bool IsParallel( const MbLineSegment & seg, double eps = Math::AngleEps ) const; // \ru Проверка параллельности двух прямых \en Check for parallelism of two lines + const MbCartPoint & GetPoint1() const { return point1; } + const MbCartPoint & GetPoint2() const { return point2; } + MbCartPoint & SetPoint1() { return point1; } + MbCartPoint & SetPoint2() { return point2; } + void GetPoint1( MbCartPoint & p ) const { p = point1; } + void GetPoint2( MbCartPoint & p ) const { p = point2; } + void SetPoint1( const MbCartPoint & p ) { point1 = p; } + void SetPoint2( const MbCartPoint & p ) { point2 = p; } + void SetLimitPoint( ptrdiff_t number, const MbCartPoint & pnt ); // \ru Заменить точку отрезка \en Replace the point of a line segment + void CheckParameter( double & t ) const; // \ru Проверка и коррекция параметра \en Check and correction of parameter - // \ru Работа с базовой прямой \en Work with the base line - MbCartPoint Origin() const { MbCartPoint p( point1 ); return p; } - MbVector Derive() const { MbVector v( point1, point2 ); return v; } - MbDirection Direction() const { MbDirection v( point1, point2 ); return v; } - bool Extend( const MbCartPoint & point ); // \ru Удлинить отрезок до проекции точки point \en Extend line segment to projection of point "point" - double PointProjectionOnBaseLine( const MbCartPoint & pnt ) const; // \ru Проекция на прямую \en Projection on the line - double PointProjectionOnBaseLine( const MbCartPoint & pnt, MbCartPoint & proj ) const; // \ru Проекция на прямую \en Projection on the line - double DistanceToPointOnBaseLine( const MbCartPoint & pnt ) const; // \ru Расстояние от точки до проекции на прямую \en Distance from a point to a projection on the line - bool IsHorizontal( double eps = Math::paramEpsilon ) const { return ::fabs(point1.y - point2.y) < eps; } // \ru Проверка горизонтальности \en Check for horizontality - bool IsVertical ( double eps = Math::paramEpsilon ) const { return ::fabs(point1.x - point2.x) < eps; } // \ru Проверка вертикальности \en Check for verticality + // \ru Работа с базовой прямой \en Work with the base line + MbCartPoint Origin() const { MbCartPoint p( point1 ); return p; } + MbVector Derive() const { MbVector v( point1, point2 ); return v; } + MbDirection Direction() const { MbDirection v( point1, point2 ); return v; } + bool Extend( const MbCartPoint & point ); // \ru Удлинить отрезок до проекции точки point \en Extend line segment to projection of point "point" + double PointProjectionOnBaseLine( const MbCartPoint & pnt ) const; // \ru Проекция на прямую \en Projection on the line + double PointProjectionOnBaseLine( const MbCartPoint & pnt, MbCartPoint & proj ) const; // \ru Проекция на прямую \en Projection on the line + double DistanceToPointOnBaseLine( const MbCartPoint & pnt ) const; // \ru Расстояние от точки до проекции на прямую \en Distance from a point to a projection on the line + bool IsHorizontal( double eps = Math::paramEpsilon ) const { return ::fabs(point1.y - point2.y) < eps; } // \ru Проверка горизонтальности \en Check for horizontality + bool IsVertical ( double eps = Math::paramEpsilon ) const { return ::fabs(point1.x - point2.x) < eps; } // \ru Проверка вертикальности \en Check for verticality - // \ru Продлить кривую. \en Extend the curve. \~ + // \ru Продлить кривую. \en Extend the curve. \~ MbResultType Extend( const MbCurveExtensionParameters & parameters, c3d::PlaneCurveSPtr & resCurve ) const override; //private: @@ -240,14 +241,15 @@ public : /** \} */ - void ReadAsLineSeg( reader & in ); // \ru Чтение. - void WriteAsLineSeg( writer & out ) const; // \ru Запись. + void ReadAsLineSeg( reader & in ); // \ru Чтение. + void WriteAsLineSeg( writer & out ) const; // \ru Запись. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbLineSegment ) }; // MbLineSegment IMPL_PERSISTENT_OPS( MbLineSegment ) + //------------------------------------------------------------------------------ // \ru Инициализировать по отрезку \en Initialize by a line segment // --- @@ -256,6 +258,7 @@ inline void MbLineSegment::Init( const MbLineSegment & ls ) { point2 = ls.point2; } + //------------------------------------------------------------------------------ // \ru Пересчитать параметры отрезка \en Recalculate the parameters of the line segment // --- @@ -264,6 +267,7 @@ inline void MbLineSegment::Init( const MbCartPoint & p1, const MbCartPoint & p2 point2 = p2; } + //------------------------------------------------------------------------------ // \ru Инициализация горизонтального отрезка для штриховки \en Initialization of a horizontal segment for hatching // --- @@ -274,6 +278,7 @@ inline void MbLineSegment::Init( const MbCartPoint & pnt, double x1, double x2 ) point2.x += x2; } + //------------------------------------------------------------------------------ // \ru Заменить точку отрезка \en Replace the point of a line segment // --- @@ -285,6 +290,7 @@ inline void MbLineSegment::SetLimitPoint( ptrdiff_t number, const MbCartPoint & point2 = pnt; } + //------------------------------------------------------------------------------ // \ru Выдать значение угла наклона отрезка \en Get the value of an angle inclination of a line segment // --- @@ -293,6 +299,7 @@ inline double MbLineSegment::GetAngle() const { return d0.DirectionAngle(); } + //------------------------------------------------------------------------------ // \ru Выдать вектор наклона отрезка \en Get the vector of a line segment inclination // --- @@ -301,6 +308,7 @@ inline MbDirection MbLineSegment::GetDirection() const { return d0; } + //------------------------------------------------------------------------------ // \ru Проверка параллельности двух прямых \en Check for parallelism of two lines // --- @@ -312,6 +320,7 @@ inline bool MbLineSegment::IsParallel( const MbLineSegment & seg, double eps ) c return ( ::fabs( d0.ay * d1.ax - d0.ax * d1.ay ) < eps ); } + //------------------------------------------------------------------------------ // \ru Проверка и коррекция параметра \en Check and correction of parameter // --- @@ -320,6 +329,7 @@ inline void MbLineSegment::CheckParameter( double & t ) const { if ( t > 1 ) t = 1; } + //------------------------------------------------------------------------------ // \ru Инициализация по другому отрезку \en Initialization by another segment // --- diff --git a/C3d/Include/cur_line_segment3d.h b/C3d/Include/cur_line_segment3d.h index a1084f2..b378b77 100644 --- a/C3d/Include/cur_line_segment3d.h +++ b/C3d/Include/cur_line_segment3d.h @@ -56,11 +56,11 @@ public : VISITING_CLASS( MbLineSegment3D ); // \ru Установить параметры отрезка. \en Set the parameters of line segment. - void Init( const MbLineSegment3D & ); - void Init( const MbCartPoint3D & p1, const MbCartPoint3D & p2 ); - void Init( const MbCartPoint3D & p0, const MbVector3D & v0 ); - void Init( const MbPlacement3D &, const MbLineSegment & ); - void Init( double t1, double t2 ); + void Init( const MbLineSegment3D & ); + void Init( const MbCartPoint3D & p1, const MbCartPoint3D & p2 ); + void Init( const MbCartPoint3D & p0, const MbVector3D & v0 ); + void Init( const MbPlacement3D &, const MbLineSegment & ); + void Init( double t1, double t2 ); // \ru Общие функции математического объекта \en Common functions of the mathematical object @@ -95,7 +95,7 @@ public : void _ThirdDer ( double t, MbVector3D & ) const override; // \ru Третья производная по t \en Third derivative with respect to t // \ru Вычислить значения точки и производных для заданного параметра. \en Calculate point and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const override; + MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const override; MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & ) const override; MbCurve3D * NurbsCurve( const MbNurbsParameters & ) const override; // \ru Построить Nurbs-копию кривой \en Construct NURBS copy of the curve @@ -134,15 +134,15 @@ public : // \ru Построить двумерный отрезок, если пространственный отрезок параллелен плоской поверхности. \en Construct a two-dimensional segment if the spatial segment is parallel to a planar surface bool GetSurfaceCurve( MbCurve *& curve, MbSurface *& surface, VERSION version ) const override; - const MbCartPoint3D & GetPoint1() const { return point1; } - const MbCartPoint3D & GetPoint2() const { return point2; } - MbCartPoint3D & SetPoint1() { return point1; } - MbCartPoint3D & SetPoint2() { return point2; } - void GetPoint1( MbCartPoint3D & p ) const { p = point1; } - void GetPoint2( MbCartPoint3D & p ) const { p = point2; } - void SetPoint1( const MbCartPoint3D & p ) { point1 = p; } - void SetPoint2( const MbCartPoint3D & p ) { point2 = p; } - void SetLimitPoint( ptrdiff_t number, const MbCartPoint3D &pnt ); // \ru Заменить точку отрезка \en Replace the point of a line segment + const MbCartPoint3D & GetPoint1() const { return point1; } + const MbCartPoint3D & GetPoint2() const { return point2; } + MbCartPoint3D & SetPoint1() { return point1; } + MbCartPoint3D & SetPoint2() { return point2; } + void GetPoint1( MbCartPoint3D & p ) const { p = point1; } + void GetPoint2( MbCartPoint3D & p ) const { p = point2; } + void SetPoint1( const MbCartPoint3D & p ) { point1 = p; } + void SetPoint2( const MbCartPoint3D & p ) { point2 = p; } + void SetLimitPoint( ptrdiff_t number, const MbCartPoint3D &pnt ); // \ru Заменить точку отрезка \en Replace the point of a line segment // \ru Продлить кривую. \en Extend the curve. \~ MbResultType Extend( const MbCurveExtensionParameters & parameters, c3d::SpaceCurveSPtr & resCurve ) const override; @@ -151,11 +151,12 @@ public : bool IsShift ( const MbSpaceItem &, MbVector3D &, bool & isSame, double accuracy = LENGTH_EPSILON ) const override; private: - void operator = ( const MbLineSegment3D & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbLineSegment3D & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbLineSegment3D ) }; IMPL_PERSISTENT_OPS( MbLineSegment3D ) + #endif // __CUR_LINE_SEGMENT3D_H diff --git a/C3d/Include/cur_nurbs.h b/C3d/Include/cur_nurbs.h index 3dac254..be8840e 100644 --- a/C3d/Include/cur_nurbs.h +++ b/C3d/Include/cur_nurbs.h @@ -104,25 +104,18 @@ public://protected: protected: /** \brief \ru Конструктор. \en Constructor. \~ - \details \ru Конструктор по порядку, точкам, параметрам и признаку замкнутости. - При недопустимых параметрах initDegree и points поведение кривой не определено.\n - \en Constructor by order, points, parameters and an attribute of closedness. - If parameters initDegree and points is invalid then the curve behavior is undefined. \n \~ - \param[in] degree - \ru Порядок сплайна. - Должен быть больше единицы. Не должен превышать количество контрольных точек. - \en A spline order. - It must be greater than unity. It shouldn't exceed count of control points. \~ + \details \ru Конструктор по порядку, точкам, параметрам и признаку замкнутости. При недопустимых параметрах initDegree и points поведение кривой не определено.\n + \en Constructor by order, points, parameters and an attribute of closedness. If parameters initDegree and points is invalid then the curve behavior is undefined. \n \~ + \param[in] degree - \ru Порядок сплайна. Должен быть больше единицы. Не должен превышать количество контрольных точек. + \en A spline order. It must be greater than unity. It shouldn't exceed count of control points. \~ \param[in] cls - \ru Признак замкнутости. \en A closedness attribute. \~ \param[in] points - \ru Набор контрольных точек. Количество точек должно быть больше или равно двум. \en Set of control points. Count of points must be greater than or equal to two. \~ - \param[in] weights - \ru Набор весов для контрольных точек. - Количество весов должно соответствовать количеству точек. - \en Set of weights for control points. - Count of weights must be equal to count of points. \~ + \param[in] weights - \ru Набор весов для контрольных точек. Количество весов должно соответствовать количеству точек. + \en Set of weights for control points. Count of weights must be equal to count of points. \~ \param[in] knots - \ru Последовательность узловых параметров. \en Sequence of knot parameters. \~ - */ template MbNurbs( size_t degree, bool cls, const PointsVector & points, @@ -339,347 +332,354 @@ public : /** \ru \name Функции инициализации NURBS-кривой. \en \name Functions of NURBS curve initialization. \{ */ - // \ru Приведенные ниже функции меняют степень degree, поэтому в них необходим вызов CatchMemory(); \en The following functions change the degree "degree" therefore they call CatchMemory(); + // \ru Приведенные ниже функции меняют степень degree, поэтому в них необходим вызов CatchMemory(); \en The following functions change the degree "degree" therefore they call CatchMemory(); - /// \ru Установить параметры сплайна по заданной NURBS-кривой. \en Set the spline parameters by a given NURBS curve. - void Init( const MbNurbs & ); - /** \brief \ru Инициализация. - \en Initialization. \~ - \details \ru Установить параметры сплайна.\n - \en Set parameters of spline.\n \~ - \param[in] initDegree - \ru Порядок сплайна. - \en A spline order. \~ - \param[in] initPoints - \ru Набор контрольных точек. - \en Set of control points. \~ - \param[in] initClosed - \ru Признак замкнутости. - \en A closedness attribute. \~ - */ - template - bool Init( size_t initDegree, const PointsVector & initPoints, bool initClosed ) - { - if ( ::IsValidNurbsParams( initDegree, initClosed, initPoints.size() ) ) - { - Refresh(); // Must come first, since frees allocated memory + /// \ru Установить параметры сплайна по заданной NURBS-кривой. \en Set the spline parameters by a given NURBS curve. + void Init( const MbNurbs & ); + /** \brief \ru Инициализация. + \en Initialization. \~ + \details \ru Установить параметры сплайна.\n + \en Set parameters of spline.\n \~ + \param[in] initDegree - \ru Порядок сплайна. + \en A spline order. \~ + \param[in] initPoints - \ru Набор контрольных точек. + \en Set of control points. \~ + \param[in] initClosed - \ru Признак замкнутости. + \en A closedness attribute. \~ + */ - degree = initDegree; - form = ncf_Unspecified; - closed = initClosed; - uppIndex = (ptrdiff_t)initPoints.size() - 1; - pointList.assign( initPoints.begin(), initPoints.end() ); - weights.assign( initPoints.size(), 1.0 ); + template + bool Init( size_t initDegree, const PointsVector & initPoints, bool initClosed ) + { + if ( ::IsValidNurbsParams( initDegree, initClosed, initPoints.size() ) ) + { + Refresh(); // Must come first, since frees allocated memory - DefineKnotsVector(); - return true; - } + degree = initDegree; + form = ncf_Unspecified; + closed = initClosed; + uppIndex = (ptrdiff_t)initPoints.size() - 1; + pointList.assign( initPoints.begin(), initPoints.end() ); + weights.assign( initPoints.size(), 1.0 ); - return false; - } - /** \brief \ru Инициализация. - \en Initialization. \~ - \details \ru Установить параметры сплайна.\n - \en Set parameters of spline.\n \~ - \param[in] initDegree - \ru Порядок сплайна. - \en A spline order. \~ - \param[in] initPoints - \ru Набор контрольных точек. - \en Set of control points. \~ - \param[in] initClosed - \ru Признак замкнутости. - \en A closedness attribute. \~ - \param[in] initWeights - \ru Набор весов для контрольных точек. - \en Set of weights for control points. \~ - */ - template - bool Init( size_t initDegree, const PointsVector & initPoints, bool initClosed, - const DoubleVector * initWeights ) - { - if ( ::IsValidNurbsParamsExt( initDegree, initClosed, initPoints, initWeights ) ) - { - Refresh(); // Must come first, since frees allocated memory + DefineKnotsVector(); + return true; + } - degree = initDegree; - form = ncf_Unspecified; - closed = initClosed; - uppIndex = (ptrdiff_t)initPoints.size() - 1; - pointList.assign( initPoints.begin(), initPoints.end() ); + return false; + } - if ( initWeights != nullptr ) { - if ( (ptrdiff_t)initWeights->size() == uppIndex + 1 ) - weights.assign( initWeights->begin(), initWeights->end() ); - else { - C3D_ASSERT_UNCONDITIONAL( false ); // Wrong size of weights vector - weights.assign( initPoints.size(), 1.0 ); - } - } - else { - weights.assign( initPoints.size(), 1.0 ); - } + /** \brief \ru Инициализация. + \en Initialization. \~ + \details \ru Установить параметры сплайна.\n + \en Set parameters of spline.\n \~ + \param[in] initDegree - \ru Порядок сплайна. + \en A spline order. \~ + \param[in] initPoints - \ru Набор контрольных точек. + \en Set of control points. \~ + \param[in] initClosed - \ru Признак замкнутости. + \en A closedness attribute. \~ + \param[in] initWeights - \ru Набор весов для контрольных точек. + \en Set of weights for control points. \~ + */ + template + bool Init( size_t initDegree, const PointsVector & initPoints, bool initClosed, + const DoubleVector * initWeights ) + { + if ( ::IsValidNurbsParamsExt( initDegree, initClosed, initPoints, initWeights ) ) + { + Refresh(); // Must come first, since frees allocated memory - DefineKnotsVector(); - return true; - } + degree = initDegree; + form = ncf_Unspecified; + closed = initClosed; + uppIndex = (ptrdiff_t)initPoints.size() - 1; + pointList.assign( initPoints.begin(), initPoints.end() ); - return false; - } - /** \brief \ru Инициализация. - \en Initialization. \~ - \details \ru Установить параметры сплайна.\n - \en Set parameters of spline.\n \~ - \param[in] initDegree - \ru Порядок сплайна. - \en A spline order. \~ - \param[in] initClosed - \ru Признак замкнутости. - \en A closedness attribute. \~ - \param[in] initPoints - \ru Набор контрольных точек. - \en Set of control points. \~ - \param[in] initWeights - \ru Набор весов для контрольных точек. - \en Set of weights for control points. \~ - \param[in] initKnots - \ru Неубывающая последовательность весов. - \en Non-decreasing sequence of weights. \~ - \param[in] initForm - \ru Тип построения. - \en Type of construction. \~ - */ - template - bool Init( size_t initDegree, bool initClosed, const PointsVector & initPoints, - const DoubleVector & initWeights, const DoubleVector & initKnots, - MbeNurbsCurveForm initForm = ncf_Unspecified ) - { - if ( ::IsValidNurbsParamsExt( initDegree, initClosed, initPoints, &initWeights, &initKnots ) ) { - Refresh(); // Must come first, since frees allocated memory + if ( initWeights != nullptr ) { + if ( (ptrdiff_t)initWeights->size() == uppIndex + 1 ) + weights.assign( initWeights->begin(), initWeights->end() ); + else { + C3D_ASSERT_UNCONDITIONAL( false ); // Wrong size of weights vector + weights.assign( initPoints.size(), 1.0 ); + } + } + else { + weights.assign( initPoints.size(), 1.0 ); + } - degree = initDegree; - closed = initClosed; - pointList = initPoints; - form = initForm; - weights = initWeights; - knots = initKnots; + DefineKnotsVector(); + return true; + } - uppIndex = (ptrdiff_t)pointList.size() - 1; - uppKnotsIndex = (ptrdiff_t)knots.size() - 1; + return false; + } - SetClamped(); - return true; - } - return false; - } + /** \brief \ru Инициализация. + \en Initialization. \~ + \details \ru Установить параметры сплайна.\n + \en Set parameters of spline.\n \~ + \param[in] initDegree - \ru Порядок сплайна. + \en A spline order. \~ + \param[in] initClosed - \ru Признак замкнутости. + \en A closedness attribute. \~ + \param[in] initPoints - \ru Набор контрольных точек. + \en Set of control points. \~ + \param[in] initWeights - \ru Набор весов для контрольных точек. + \en Set of weights for control points. \~ + \param[in] initKnots - \ru Неубывающая последовательность весов. + \en Non-decreasing sequence of weights. \~ + \param[in] initForm - \ru Тип построения. + \en Type of construction. \~ + */ + template + bool Init( size_t initDegree, bool initClosed, const PointsVector & initPoints, + const DoubleVector & initWeights, const DoubleVector & initKnots, + MbeNurbsCurveForm initForm = ncf_Unspecified ) + { + if ( ::IsValidNurbsParamsExt( initDegree, initClosed, initPoints, &initWeights, &initKnots ) ) { + Refresh(); // Must come first, since frees allocated memory - /** \brief \ru Инициализация. - \en Initialization. \~ - \details \ru Установить параметры сплайна.\n - \en Set parameters of spline.\n \~ - \param[in] degree - \ru Порядок сплайна. - \en A spline order. \~ - \param[in] cls - \ru Признак замкнутости. - \en A closedness attribute. \~ - \param[in] points - \ru Набор контрольных точек. - \en Set of control points. \~ - \param[in] knots - \ru Неубывающая последовательность узлов. - \en Non-decreasing sequence of knots. \~ - \param[in] nPoints - \ru Количество контрольных точек. - \en Count of control points. \~ - \param[in] nKnots - \ru Количество узлов. - \en Count of knots. \~ - */ - bool Init( size_t degree, bool cls, const CcArray & points, - const CcArray & knots, ptrdiff_t nPoints, ptrdiff_t nKnots ); + degree = initDegree; + closed = initClosed; + pointList = initPoints; + form = initForm; + weights = initWeights; + knots = initKnots; - /** \brief \ru Инициализация. - \en Initialization. \~ - \details \ru Сплайн, проходящий через заданные точки при заданных параметрах.\n - В случае замкнутости нужно передавать массив с совпадением первой и последней точек.\n - \en Spline passing through given points at given parameters.\n - In case of closedness it is necessary to pass the array with coincidence of the first and the last points.\n \~ - \param[in] degree - \ru Порядок сплайна. - \en A spline order. \~ - \param[in] cls - \ru Признак замкнутости. - \en A closedness attribute. \~ - \param[in] points - \ru Набор точек, через которые проходит сплайн. - \en Set of points which the spline passes through. \~ - \param[in] params - \ru Последовательность узловых параметров. - \en Sequence of knot parameters. \~ - \param[in] aKnots - \ru Неубывающая последовательность узлов. - \en Nondecreasing sequence of knots. \~ - */ - bool InitThrough( size_t degree, - bool cls, - const SArray & points, - const SArray & params, - SArray * aKnots = nullptr ); + uppIndex = (ptrdiff_t)pointList.size() - 1; + uppKnotsIndex = (ptrdiff_t)knots.size() - 1; - /** \brief \ru Инициализация. - \en Initialization. \~ - \details \ru Сплайн, проходящий через заданные точки при заданных параметрах.\n - В случае замкнутости нужно передавать массив с совпадением первой и последней точек.\n - \en Spline passing through given points at given parameters.\n - In case of closedness it is necessary to pass the array with coincidence of the first and the last points.\n \~ - \param[in] degree - \ru Порядок сплайна. - \en A spline order. \~ - \param[in] cls - \ru Признак замкнутости. - \en A closedness attribute. \~ - \param[in] points - \ru Набор точек, через которые проходит сплайн. - \en Set of points which the spline passes through. \~ - \param[in] params - \ru Последовательность узловых параметров. - \en Sequence of knot parameters. \~ - \param[in] aKnots - \ru Неубывающая последовательность узлов. - \en Nondecreasing sequence of knots. \~ - */ - bool InitThrough( size_t degree, - bool cls, - const c3d::ParamPointsVector & points, - const c3d::DoubleVector & params, - c3d::DoubleVector * aKnots = nullptr ); + SetClamped(); + return true; + } + return false; + } + + /** \brief \ru Инициализация. + \en Initialization. \~ + \details \ru Установить параметры сплайна.\n + \en Set parameters of spline.\n \~ + \param[in] degree - \ru Порядок сплайна. + \en A spline order. \~ + \param[in] cls - \ru Признак замкнутости. + \en A closedness attribute. \~ + \param[in] points - \ru Набор контрольных точек. + \en Set of control points. \~ + \param[in] knots - \ru Неубывающая последовательность узлов. + \en Non-decreasing sequence of knots. \~ + \param[in] nPoints - \ru Количество контрольных точек. + \en Count of control points. \~ + \param[in] nKnots - \ru Количество узлов. + \en Count of knots. \~ + */ + bool Init( size_t degree, bool cls, const CcArray & points, + const CcArray & knots, ptrdiff_t nPoints, ptrdiff_t nKnots ); + + /** \brief \ru Инициализация. + \en Initialization. \~ + \details \ru Сплайн, проходящий через заданные точки при заданных параметрах.\n + В случае замкнутости нужно передавать массив с совпадением первой и последней точек.\n + \en Spline passing through given points at given parameters.\n + In case of closedness it is necessary to pass the array with coincidence of the first and the last points.\n \~ + \param[in] degree - \ru Порядок сплайна. + \en A spline order. \~ + \param[in] cls - \ru Признак замкнутости. + \en A closedness attribute. \~ + \param[in] points - \ru Набор точек, через которые проходит сплайн. + \en Set of points which the spline passes through. \~ + \param[in] params - \ru Последовательность узловых параметров. + \en Sequence of knot parameters. \~ + \param[in] aKnots - \ru Неубывающая последовательность узлов. + \en Nondecreasing sequence of knots. \~ + */ + bool InitThrough( size_t degree, + bool cls, + const SArray & points, + const SArray & params, + SArray * aKnots = nullptr ); + + /** \brief \ru Инициализация. + \en Initialization. \~ + \details \ru Сплайн, проходящий через заданные точки при заданных параметрах.\n + В случае замкнутости нужно передавать массив с совпадением первой и последней точек.\n + \en Spline passing through given points at given parameters.\n + In case of closedness it is necessary to pass the array with coincidence of the first and the last points.\n \~ + \param[in] degree - \ru Порядок сплайна. + \en A spline order. \~ + \param[in] cls - \ru Признак замкнутости. + \en A closedness attribute. \~ + \param[in] points - \ru Набор точек, через которые проходит сплайн. + \en Set of points which the spline passes through. \~ + \param[in] params - \ru Последовательность узловых параметров. + \en Sequence of knot parameters. \~ + \param[in] aKnots - \ru Неубывающая последовательность узлов. + \en Nondecreasing sequence of knots. \~ + */ + bool InitThrough( size_t degree, + bool cls, + const c3d::ParamPointsVector & points, + const c3d::DoubleVector & params, + c3d::DoubleVector * aKnots = nullptr ); - /** \brief \ru Инициализация. - \en Initialization. \~ - \details \ru Инициализировать прямолинейный сплайн.\n - \en Initialize a straight spline. \n \~ - \param[in] t1 - \ru Начальный узел. - \en The initial knot. \~ - \param[in] p1 - \ru Начальная точка, через которую проходит сплайн. - \en The initial point the spline passes through. \~ - \param[in] t2 - \ru Конечный узел. - \en The final knot. \~ - \param[in] p2 - \ru Конечная точка, через которую проходит сплайн. - \en The final point the spline passes through. \~ - */ - bool InitLine( double t1, const MbCartPoint & p1, double t2, const MbCartPoint & p2 ); - /** \brief \ru Инициализация. - \en Initialization. \~ - \details \ru Инициализировать кубическую кривую как сплайн.\n - \en Initialize a cubic curve as a spline. \n \~ - \param[in] p1 - \ru Начальная точка, через которую проходит сплайн. - \en The initial point the spline passes through. \~ - \param[in] v1 - \ru Касательный вектор к кривой в начальной точке. - \en A tangent vector to the curve at the start point. \~ - \param[in] p2 - \ru Конечная точка, через которую проходит сплайн. - \en The final point the spline passes through. \~ - \param[in] v2 - \ru Касательный вектор к кривой в конечной точке. - \en A tangent vector to the curve at the end point. \~ - */ - bool InitCube( const MbCartPoint & p1, const MbVector & v1, const MbCartPoint & p2, const MbVector & v2 ); + /** \brief \ru Инициализация. + \en Initialization. \~ + \details \ru Инициализировать прямолинейный сплайн.\n + \en Initialize a straight spline. \n \~ + \param[in] t1 - \ru Начальный узел. + \en The initial knot. \~ + \param[in] p1 - \ru Начальная точка, через которую проходит сплайн. + \en The initial point the spline passes through. \~ + \param[in] t2 - \ru Конечный узел. + \en The final knot. \~ + \param[in] p2 - \ru Конечная точка, через которую проходит сплайн. + \en The final point the spline passes through. \~ + */ + bool InitLine( double t1, const MbCartPoint & p1, double t2, const MbCartPoint & p2 ); + /** \brief \ru Инициализация. + \en Initialization. \~ + \details \ru Инициализировать кубическую кривую как сплайн.\n + \en Initialize a cubic curve as a spline. \n \~ + \param[in] p1 - \ru Начальная точка, через которую проходит сплайн. + \en The initial point the spline passes through. \~ + \param[in] v1 - \ru Касательный вектор к кривой в начальной точке. + \en A tangent vector to the curve at the start point. \~ + \param[in] p2 - \ru Конечная точка, через которую проходит сплайн. + \en The final point the spline passes through. \~ + \param[in] v2 - \ru Касательный вектор к кривой в конечной точке. + \en A tangent vector to the curve at the end point. \~ + */ + bool InitCube( const MbCartPoint & p1, const MbVector & v1, const MbCartPoint & p2, const MbVector & v2 ); - // \ru Интерполяция. \en Interpolation. + // \ru Интерполяция. \en Interpolation. - /** \brief \ru Интерполяция. - \en Interpolation. \~ - \details \ru Создать плоский сплайн второго порядка по точкам, параметрам и признаку замкнутости. - \en Create a planar spline of second-order by points, parameters and attribute of closedness. \~ - */ + /** \brief \ru Интерполяция. + \en Interpolation. \~ + \details \ru Создать плоский сплайн второго порядка по точкам, параметрам и признаку замкнутости. + \en Create a planar spline of second-order by points, parameters and attribute of closedness. \~ + */ static MbNurbs * CreateNURBS2( const SArray & points, const SArray & params, bool cls ); - /// \ru Создать кубический NURBS по точкам, через которые он проходит, и параметрам сопряжения. \en Create cubic NURBS by parameters of conjugation and points which it passes through. + /// \ru Создать кубический NURBS по точкам, через которые он проходит, и параметрам сопряжения. \en Create cubic NURBS by parameters of conjugation and points which it passes through. static MbNurbs * CreateNURBS4( const SArray &, MbeSplineParamType spType, const c3d::PntMatingData2D & begData, const c3d::PntMatingData2D & endData ); - /// \ru Создать кубический NURBS по интерполяционным точкам и данным сопряжения в каждой точке. \en Create cubic NURBS by interpolation points and data of conjugation at each point. + /// \ru Создать кубический NURBS по интерполяционным точкам и данным сопряжения в каждой точке. \en Create cubic NURBS by interpolation points and data of conjugation at each point. static MbNurbs * CreateNURBS4( const SArray &, MbeSplineParamType spType, - bool closed, - RPArray & ); - /// \ru Создать кубический NURBS по интерполяционным точкам, их параметрам и данным сопряжения в каждой точке. \en Create cubic NURBS by interpolation points, parameters and data of conjugation at each point. + bool closed, RPArray & ); + /// \ru Создать кубический NURBS по интерполяционным точкам, их параметрам и данным сопряжения в каждой точке. \en Create cubic NURBS by interpolation points, parameters and data of conjugation at each point. static MbNurbs * CreateNURBS4( const SArray &, const SArray &, - bool closed, - RPArray & ); - /** \brief \ru Интерполяция. - \en Interpolation. \~ - \details \ru Создать плоский сплайн четвертого порядка по точкам, признаку замкнутости и типу параметризации.\n - Сплайн проходит через точки. Используется граничное условие отсутствия узла. - \en Create a planar spline of fourth order by points, attribute of closedness and parametrization type.\n - NURBS passes through points. Used boundary condition of knot absence. \~ - */ + bool closed, RPArray & ); + /** \brief \ru Интерполяция. + \en Interpolation. \~ + \details \ru Создать плоский сплайн четвертого порядка по точкам, признаку замкнутости и типу параметризации.\n + Сплайн проходит через точки. Используется граничное условие отсутствия узла. + \en Create a planar spline of fourth order by points, attribute of closedness and parametrization type.\n + NURBS passes through points. Used boundary condition of knot absence. \~ + */ static MbNurbs * CreateNURBS4( const SArray &, bool cls, MbeSplineParamType spType, MbeSplineCreateType useInitThrough = sct_Version2 ); - /** \brief \ru Интерполяция. - \en Interpolation. \~ - \details \ru Создать плоский сплайн четвертого порядка по точкам, параметрам и признаку замкнутости.\n - Используется граничное условие отсутствия узла. - \en Create a planar spline of fourth order by points, parameters and attribute of closedness.\n - Used boundary condition of knot absence. \~ - */ + /** \brief \ru Интерполяция. + \en Interpolation. \~ + \details \ru Создать плоский сплайн четвертого порядка по точкам, параметрам и признаку замкнутости.\n + Используется граничное условие отсутствия узла. + \en Create a planar spline of fourth order by points, parameters and attribute of closedness.\n + Used boundary condition of knot absence. \~ + */ static MbNurbs * CreateNURBS4( const SArray & points, const SArray & params, bool cls, MbeSplineCreateType useInitThrough = sct_Version2 ); - /** \brief \ru Интерполяция. - \en Interpolation. \~ - \details \ru Создать плоский сплайн четвертого порядка по весам, точкам, параметрам и признаку замкнутости.\n - Используется граничное условие отсутствия узла. - \en Create a planar spline of fourth order by weights, points, parameters and attribute of closedness.\n - Used boundary condition of knot absence. \~ - */ + /** \brief \ru Интерполяция. + \en Interpolation. \~ + \details \ru Создать плоский сплайн четвертого порядка по весам, точкам, параметрам и признаку замкнутости.\n + Используется граничное условие отсутствия узла. + \en Create a planar spline of fourth order by weights, points, parameters and attribute of closedness.\n + Used boundary condition of knot absence. \~ + */ static MbNurbs * CreateNURBS4( const SArray & weights, const SArray & points, SArray & params, bool cls ); - /** \brief \ru Интерполяция. - \en Interpolation. \~ - \details \ru Создать плоский сплайн четвертого порядка по точкам, параметрам и признаку замкнутости - с граничными условиями - заданными векторами первых или вторых производных.\n - Имеет 2 кратных внутренних узла, принадлежит классу дифференцируемых ( но не дважды дифференцируемых ) функций. - \en Create a planar spline of fourth order by points, parameters and attribute of closedness - with boundary conditions - given vectors of first or second derivatives.\n - Has 2 multiple internal knots, belongs to class of differentiable (but not twice differentiable) functions. \~ - \param[in] bfstS - \ru Если true, то начальное граничное условие - вектор первой производной, иначе - вектор второй производной. - \en If true, then start boundary condition is the vector of the first derivative, otherwise - the vector of the second derivative. \~ - \param[in] bfstN - \ru Если true, то конечное граничное условие - вектор первой производной, иначе - вектор второй производной. - \en If true, then end boundary condition is the vector of first derivative, otherwise - vector of second derivative. \~ - */ + + /** \brief \ru Интерполяция. + \en Interpolation. \~ + \details \ru Создать плоский сплайн четвертого порядка по точкам, параметрам и признаку замкнутости + с граничными условиями - заданными векторами первых или вторых производных.\n + Имеет 2 кратных внутренних узла, принадлежит классу дифференцируемых ( но не дважды дифференцируемых ) функций. + \en Create a planar spline of fourth order by points, parameters and attribute of closedness + with boundary conditions - given vectors of first or second derivatives.\n + Has 2 multiple internal knots, belongs to class of differentiable (but not twice differentiable) functions. \~ + \param[in] bfstS - \ru Если true, то начальное граничное условие - вектор первой производной, иначе - вектор второй производной. + \en If true, then start boundary condition is the vector of the first derivative, otherwise - the vector of the second derivative. \~ + \param[in] bfstN - \ru Если true, то конечное граничное условие - вектор первой производной, иначе - вектор второй производной. + \en If true, then end boundary condition is the vector of first derivative, otherwise - vector of second derivative. \~ + */ static MbNurbs * CreateNURBS4( const SArray & points, const SArray & params, const MbVector &, const MbVector &, bool cls, bool bfstS = true, bool bfstN = true ); - /** \brief \ru Интерполяция. - \en Interpolation. \~ - \details \ru Создать плоский сплайн четвертого порядка по точкам, производным, параметрам и признаку замкнутости.\n - Имеет 2 кратных внутренних узла, принадлежит классу дифференцируемых ( но не дважды дифференцируемых ) функций. - \en Create a planar spline of fourth order by points, derivatives, parameters and attribute of closedness.\n - It has 2 multiple internal knots, belongs to the class of differentiable (but not twice differentiable) functions. \~ - */ - static MbNurbs * CreateNURBS4( const SArray & points, const SArray & vectors, - const SArray & params, bool cls ); - /** \brief \ru Интерполяция. - \en Interpolation. \~ - \details \ru Создать плоский сплайн четвертого порядка по составному сплайну Безье четвертого порядка.\n - Внимание! Параметризация отлична от параметризации исходной кривой Безье. - \en Create a planar spline of fourth order by composite Bezier spline of fourth order.\n - If closedness is necessary - call UnClamped( bezier.IsClosed() ). \~ - */ + + /** \brief \ru Интерполяция. + \en Interpolation. \~ + \details \ru Создать плоский сплайн четвертого порядка по точкам, производным, параметрам и признаку замкнутости.\n + Имеет 2 кратных внутренних узла, принадлежит классу дифференцируемых ( но не дважды дифференцируемых ) функций. + \en Create a planar spline of fourth order by points, derivatives, parameters and attribute of closedness.\n + It has 2 multiple internal knots, belongs to the class of differentiable (but not twice differentiable) functions. \~ + */ + static MbNurbs * CreateNURBS4( const SArray & points, const SArray & vectors, + const SArray & params, bool cls ); + + /** \brief \ru Интерполяция. + \en Interpolation. \~ + \details \ru Создать плоский сплайн четвертого порядка по составному сплайну Безье четвертого порядка.\n + Внимание! Параметризация отлична от параметризации исходной кривой Безье. + \en Create a planar spline of fourth order by composite Bezier spline of fourth order.\n + If closedness is necessary - call UnClamped( bezier.IsClosed() ). \~ + */ static MbNurbs * CreateNURBS4( const MbBezier & ); - /// \ru Установить сопряжение на конце. \en Set conjugation at the end. - bool AttachG( c3d::PntMatingData2D & connectData, bool beg ); + /// \ru Установить сопряжение на конце. \en Set conjugation at the end. + bool AttachG( c3d::PntMatingData2D & connectData, bool beg ); - /** \brief \ru Увеличить порядок кривой, не изменяя ее геометрическую форму и параметризацию. - \en Increase order of curve without changing its geometric shape and parametrization. \~ - \details \ru Увеличить порядок кривой, не изменяя ее геометрическую форму и параметризацию. \n - \en Increase order of curve without changing its geometric shape and parametrization. \n \~ - \param[in] newDegree - \ru Новый порядок сплайна. - \en New order of spline. \~ - \param[in] relEps - \ru Допустимая погрешность изменения формы. - \en Permissible shape error. \~ - \return \ru Возвращает true, если порядок сплайна был изменен. - \en Returns true if the order of the spline was changed. \~ - */ - bool RaiseDegree( size_t newDegree, double relEps = Math::paramEpsilon ); - /** \brief \ru Уменьшить порядок кривой на 1, не изменяя ее геометрическую форму и параметризацию. - \en Decrease order of nurbs curve by 1 without changing its geometric shape and parametrization. \~ - \details \ru Уменьшить порядок кривой на 1, не изменяя ее геометрическую форму и параметризацию. \n - \en Decrease order of nurbs curve by 1 without changing its geometric shape and parametrization. \n \~ - \param[in] relEps - \ru Допустимая погрешность изменения формы. - \en Permissible shape error. \~ - \return \ru Возвращает true, если порядок сплайна был изменен. - \en Returns true if the order of the spline was changed. \~ - */ - bool ReductionDegree( double relEps = Math::paramEpsilon ); - /** \brief \ru Задать порядок сплайна. - \en Set the spline order. \~ - \details \ru Задать порядок сплайна. \n - При изменении порядка параметризация сплайна сбрасывается на равномерную, форма сплайна меняется. \n - \en Set the spline order. \n - When you change the order, the parameterization of the spline is reset to uniform, the shape of the spline changes. \n \~ - \param[in] newDegree - \ru Новый порядок сплайна. - \en A new spline order. \~ - \return \ru Возвращает true, если порядок сплайна был изменен. - \en Returns true if the order of the spline was changed. \~ - */ - bool SetDegree( size_t newDegree ); - /// \ru Увеличить порядок на 1. \en Increase the order by 1. - void DegreeIncrease(); - /// \ru Установить тип формы. \en Set the type of shape. - void SetFormType( MbeNurbsCurveForm f ) { form = f; } - /// \ru Точка на кратном узле. \en The point on a multiple knot. - bool PointOnMultipleKnot( const MbCartPoint & point ) const; + /** \brief \ru Увеличить порядок кривой, не изменяя ее геометрическую форму и параметризацию. + \en Increase order of curve without changing its geometric shape and parametrization. \~ + \details \ru Увеличить порядок кривой, не изменяя ее геометрическую форму и параметризацию. \n + \en Increase order of curve without changing its geometric shape and parametrization. \n \~ + \param[in] newDegree - \ru Новый порядок сплайна. + \en New order of spline. \~ + \param[in] relEps - \ru Допустимая погрешность изменения формы. + \en Permissible shape error. \~ + \return \ru Возвращает true, если порядок сплайна был изменен. + \en Returns true if the order of the spline was changed. \~ + */ + bool RaiseDegree( size_t newDegree, double relEps = Math::paramEpsilon ); + + /** \brief \ru Уменьшить порядок кривой на 1, не изменяя ее геометрическую форму и параметризацию. + \en Decrease order of nurbs curve by 1 without changing its geometric shape and parametrization. \~ + \details \ru Уменьшить порядок кривой на 1, не изменяя ее геометрическую форму и параметризацию. \n + \en Decrease order of nurbs curve by 1 without changing its geometric shape and parametrization. \n \~ + \param[in] relEps - \ru Допустимая погрешность изменения формы. + \en Permissible shape error. \~ + \return \ru Возвращает true, если порядок сплайна был изменен. + \en Returns true if the order of the spline was changed. \~ + */ + bool ReductionDegree( double relEps = Math::paramEpsilon ); + + /** \brief \ru Задать порядок сплайна. + \en Set the spline order. \~ + \details \ru Задать порядок сплайна. \n + При изменении порядка параметризация сплайна сбрасывается на равномерную, форма сплайна меняется. \n + \en Set the spline order. \n + When you change the order, the parameterization of the spline is reset to uniform, the shape of the spline changes. \n \~ + \param[in] newDegree - \ru Новый порядок сплайна. + \en A new spline order. \~ + \return \ru Возвращает true, если порядок сплайна был изменен. + \en Returns true if the order of the spline was changed. \~ + */ + bool SetDegree( size_t newDegree ); + + /// \ru Увеличить порядок на 1. \en Increase the order by 1. + void DegreeIncrease(); + /// \ru Установить тип формы. \en Set the type of shape. + void SetFormType( MbeNurbsCurveForm f ) { form = f; } + /// \ru Точка на кратном узле. \en The point on a multiple knot. + bool PointOnMultipleKnot( const MbCartPoint & point ) const; /** \} */ /** \ru \name Общие функции геометрического объекта. @@ -726,19 +726,19 @@ public : \{ */ // \ru Вычислить значения точки и производных для заданного параметра. \en Calculate point and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - MbCartPoint & pnt, MbVector & fir, MbVector * sec, MbVector * thir ) const override; + MbCartPoint & pnt, MbVector & fir, MbVector * sec, MbVector * thir ) const override; // \ru Вычислить значения производных для заданного параметра. \en Calculate derivatives of object for given parameter. \~ - void Derivatives( double & t, bool ext, MbVector & fir, MbVector * sec, MbVector * thi ) const; + void Derivatives( double & t, bool ext, MbVector & fir, MbVector * sec, MbVector * thi ) const; - // \ru Функции, продолжающие кривую не по касательной как _PointOn() и др., а по кривой. \en Functions which do not continue curve along the tangent as _PointOn (), etc., and along a curve. - /// \ru Точка на продолжении кривой. \en Point on the curve extension. - void ExtPointOn ( double t, MbCartPoint & pnt ) const; - /// \ru Первая производная на продолжении кривой. \en The first derivative on the curve extension. - void ExtFirstDer ( double t, MbVector & fd ) const; - /// \ru Вторая производная на продолжении кривой. \en The second derivative on the curve extension. - void ExtSecondDer( double t, MbVector & sd ) const; - /// \ru Третья производная на продолжении кривой. \en The third derivative on the curve extension. - void ExtThirdDer ( double t, MbVector & td ) const; + // \ru Функции, продолжающие кривую не по касательной как _PointOn() и др., а по кривой. \en Functions which do not continue curve along the tangent as _PointOn (), etc., and along a curve. + /// \ru Точка на продолжении кривой. \en Point on the curve extension. + void ExtPointOn ( double t, MbCartPoint & pnt ) const; + /// \ru Первая производная на продолжении кривой. \en The first derivative on the curve extension. + void ExtFirstDer ( double t, MbVector & fd ) const; + /// \ru Вторая производная на продолжении кривой. \en The second derivative on the curve extension. + void ExtSecondDer( double t, MbVector & sd ) const; + /// \ru Третья производная на продолжении кривой. \en The third derivative on the curve extension. + void ExtThirdDer ( double t, MbVector & td ) const; /** \} */ /** \ru \name Общие функции кривой @@ -751,7 +751,7 @@ public : double CalculateMetricLength() const override; // \ru Сдвинуть параметр t на расстояние len. \en Move parameter t on the metric distance len. bool DistanceAlong( double & t, double len, int curveDir, double eps = Math::LengthEps, - VERSION version = Math::DefaultMathVersion() ) const override; + VERSION version = Math::DefaultMathVersion() ) const override; // \ru Вычислить метрическую длину кривой.\en Calculate the metric length of a curve. double CalculateLength( double t1, double t2 ) const override; @@ -787,10 +787,10 @@ public : bool GetAxisPoint( MbCartPoint & p ) const override; // \ru Выдать центр оси кривой. \en Give the curve axis center. bool IsSimilarToCurve( const MbCurve & curve, double precision = PARAM_PRECISION ) const override; // \ru Подобные ли кривые для объединения (слива). \en Whether the curves to union (joining) are similar. - /// \ru Касание сплайна прямой. \en Touching the spline by line. - void MakeTangentLine( MbLine * line ); - /// \ru Определить выпуклую оболочку сегмента кривой. \en Determine the convex hull of the curve segment. - void ConvexHull( ptrdiff_t seg, MbCartPoint * p ) const; + /// \ru Касание сплайна прямой. \en Touching the spline by line. + void MakeTangentLine( MbLine * line ); + /// \ru Определить выпуклую оболочку сегмента кривой. \en Determine the convex hull of the curve segment. + void ConvexHull( ptrdiff_t seg, MbCartPoint * p ) const; /// \ru Получить границы участков кривой, которые описываются одной аналитической функцией. \en Get the boundaries of the curve sections that are described by one analytical function. \~ void GetAnalyticalFunctionsBounds( std::vector & params ) const override; @@ -825,7 +825,7 @@ public : double PointProjection( const MbCartPoint & pnt ) const override; // \ru Найти проекцию точки на кривую. \en Find the point projection to the curve. bool NearPointProjection( const MbCartPoint & pnt, double xEpsilon, double yEpsilon, - double & t, bool ext, MbRect1D * tRange = nullptr ) const override; + double & t, bool ext, MbRect1D * tRange = nullptr ) const override; bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = nullptr, double epsilon = EPSILON ) const override; // \ru Непрерывна ли первая производная? \en Have the first derivative the continuous? // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. @@ -839,143 +839,143 @@ public : \en \name Functions of B-spline. \{ */ - /// \ru Добавить точку с весом. \en Add a point with weight. - void AddPoint( ptrdiff_t index, const MbCartPoint & pnt, double weight ); - /// \ru Добавить точку в конец массива. \en Add point to the end of the array. - void AddPoint( const MbCartPoint & pnt, double weight ); - /// \ru Сделать контур из NURBS-кривой. \en Create a contour from the NURBS curve. - MbContour * CreateContour() const; - /// \ru Выделить часть. \en Break a part. - MbNurbs * Break( double t1, double t2 ) const; + /// \ru Добавить точку с весом. \en Add a point with weight. + void AddPoint( ptrdiff_t index, const MbCartPoint & pnt, double weight ); + /// \ru Добавить точку в конец массива. \en Add point to the end of the array. + void AddPoint( const MbCartPoint & pnt, double weight ); + /// \ru Сделать контур из NURBS-кривой. \en Create a contour from the NURBS curve. + MbContour * CreateContour() const; + /// \ru Выделить часть. \en Break a part. + MbNurbs * Break( double t1, double t2 ) const; - /// \ru Получить форму В-сплайна. \en Get form of B-spline. - MbeNurbsCurveForm GetFormType() const { return form; } + /// \ru Получить форму В-сплайна. \en Get form of B-spline. + MbeNurbsCurveForm GetFormType() const { return form; } - /// \ru Выдать порядок сплайна. \en Get the spline order. - size_t GetDegree() const { return degree; } - /// \ru Вернуть признак рациональности, но не регулярности кривой. \en Get attribute of rationality, but no regularity of curve. - bool IsRational() const; + /// \ru Выдать порядок сплайна. \en Get the spline order. + size_t GetDegree() const { return degree; } + /// \ru Вернуть признак рациональности, но не регулярности кривой. \en Get attribute of rationality, but no regularity of curve. + bool IsRational() const; - /// \ru Получить размер весового вектора. \en Get a size of weights vector. - size_t GetWeightsCount() const { return weights.size(); } - /// \ru Получить весовой вектор. \en Get a weights vector. - template - void GetWeights( WeightsVector & wts, bool justSet = true ) const { if ( justSet ) { wts.clear(); }; std::copy( weights.begin(), weights.end(), std::back_inserter( wts ) ); } - /// \ru Получить значение элемента весового вектора по индексу. \en Get a weights vector element value by index. - double GetWeight( size_t ind ) const { return weights[ind]; } - /// \ru Получить значение элемента весового вектора по индексу. \en Get a weights vector element value by index. - double & SetWeight( size_t ind ) { return weights[ind]; } + /// \ru Получить размер весового вектора. \en Get a size of weights vector. + size_t GetWeightsCount() const { return weights.size(); } + /// \ru Получить весовой вектор. \en Get a weights vector. + template + void GetWeights( WeightsVector & wts, bool justSet = true ) const { if ( justSet ) { wts.clear(); }; std::copy( weights.begin(), weights.end(), std::back_inserter( wts ) ); } + /// \ru Получить значение элемента весового вектора по индексу. \en Get a weights vector element value by index. + double GetWeight( size_t ind ) const { return weights[ind]; } + /// \ru Получить значение элемента весового вектора по индексу. \en Get a weights vector element value by index. + double & SetWeight( size_t ind ) { return weights[ind]; } - /// \ru Получить размер узлового вектора. \en Get a size of knots vector. - size_t GetKnotsCount() const { return knots.size(); } - /// \ru Получить узловой вектор. \en Get a knots vector. - template - void GetKnots( KnotsVector & kts, bool justSet = true ) const { if ( justSet ) { kts.clear(); }; std::copy( knots.begin(), knots.end(), std::back_inserter( kts ) ); } - /// \ru Получить значение элемента узлового вектора по индексу. \en Get a knots vector element value by index. - double GetKnot( size_t ind ) const { return knots[ind]; } - /// \ru Получить значение элемента узлового вектора по индексу. \en Get a knots vector element value by index. - double & SetKnot( size_t ind ) { return knots[ind]; } - /// \ru Вернуть максимальный индекс узлового вектора. \en Get the maximal index of knots vector. - ptrdiff_t GetUppKnotsIndex() const { return uppKnotsIndex; } + /// \ru Получить размер узлового вектора. \en Get a size of knots vector. + size_t GetKnotsCount() const { return knots.size(); } + /// \ru Получить узловой вектор. \en Get a knots vector. + template + void GetKnots( KnotsVector & kts, bool justSet = true ) const { if ( justSet ) { kts.clear(); }; std::copy( knots.begin(), knots.end(), std::back_inserter( kts ) ); } + /// \ru Получить значение элемента узлового вектора по индексу. \en Get a knots vector element value by index. + double GetKnot( size_t ind ) const { return knots[ind]; } + /// \ru Получить значение элемента узлового вектора по индексу. \en Get a knots vector element value by index. + double & SetKnot( size_t ind ) { return knots[ind]; } + /// \ru Вернуть максимальный индекс узлового вектора. \en Get the maximal index of knots vector. + ptrdiff_t GetUppKnotsIndex() const { return uppKnotsIndex; } - // \ru BEG: для библиотеки (хорошо бы избавиться) \en BEG: for the library (it would be good to get rid of this) - /// \ru Добавить точку в конец массива. \en Add point to the end of the array. - void LtAddPoint ( MbCartPoint & pnt, double weight ) { C3D_ASSERT_UNCONDITIONAL( false ); pointList.push_back( pnt ); weights.push_back( weight ); } - /// \ru Добавить характерную точку в степенном представлении в конец массива. \en Add a control point with degree representation to the end of the array. - void LtAddPowerPoint( MbCartPoint & pnt ) { C3D_ASSERT_UNCONDITIONAL( false ); pointList.push_back( pnt ); } - /// \ru Добавить узел в конец узлового вектора. \en Add a knot to the end of knot vector. - void LtAddKnot ( double knot ) { C3D_ASSERT_UNCONDITIONAL( false ); knots.push_back( knot ); } - /// \ru Задать порядок сплайна. \en Set the spline order. - void LtSetDegree( size_t newDegree ) { C3D_ASSERT_UNCONDITIONAL( false ); if ( newDegree >= 2 && form == ncf_Unspecified ) { degree = newDegree; } } - /// \ru Установить признак замкнутости. \en Set the closedness attribute. - void LtSetClosed( bool cls ) { C3D_ASSERT_UNCONDITIONAL( false ); if ( form == ncf_Unspecified ) { closed = cls; } } - /// \ru Изменить степень, замкнутость и тип формы. \en Change degree, closedness and type of shape. - void LtSetData( size_t d, bool c, MbeNurbsCurveForm f ); - /// \ru Перестроить сплайн после накачки из библиотеки. \en Rebuild the spline. - bool LtRebuild(); - /// \ru Инициализация. \en Initialization. - void LtInit(); - // \ru Преобразование кусочно степенной формы в NURBS-кривую. \en Convert a piecewise exponential form to a NURBS-curve. - bool LtInitPowerArc(); - bool LtTrimmed( double t1, double t2, int sense = 1 ); - // \ru END: для библиотеки (хорошо бы избавиться) \en END: for the library (it would be good escape) + // \ru BEG: для библиотеки (хорошо бы избавиться) \en BEG: for the library (it would be good to get rid of this) + /// \ru Добавить точку в конец массива. \en Add point to the end of the array. + void LtAddPoint ( MbCartPoint & pnt, double weight ) { C3D_ASSERT_UNCONDITIONAL( false ); pointList.push_back( pnt ); weights.push_back( weight ); } + /// \ru Добавить характерную точку в степенном представлении в конец массива. \en Add a control point with degree representation to the end of the array. + void LtAddPowerPoint( MbCartPoint & pnt ) { C3D_ASSERT_UNCONDITIONAL( false ); pointList.push_back( pnt ); } + /// \ru Добавить узел в конец узлового вектора. \en Add a knot to the end of knot vector. + void LtAddKnot ( double knot ) { C3D_ASSERT_UNCONDITIONAL( false ); knots.push_back( knot ); } + /// \ru Задать порядок сплайна. \en Set the spline order. + void LtSetDegree( size_t newDegree ) { C3D_ASSERT_UNCONDITIONAL( false ); if ( newDegree >= 2 && form == ncf_Unspecified ) { degree = newDegree; } } + /// \ru Установить признак замкнутости. \en Set the closedness attribute. + void LtSetClosed( bool cls ) { C3D_ASSERT_UNCONDITIONAL( false ); if ( form == ncf_Unspecified ) { closed = cls; } } + /// \ru Изменить степень, замкнутость и тип формы. \en Change degree, closedness and type of shape. + void LtSetData( size_t d, bool c, MbeNurbsCurveForm f ); + /// \ru Перестроить сплайн после накачки из библиотеки. \en Rebuild the spline. + bool LtRebuild(); + /// \ru Инициализация. \en Initialization. + void LtInit(); + // \ru Преобразование кусочно степенной формы в NURBS-кривую. \en Convert a piecewise exponential form to a NURBS-curve. + bool LtInitPowerArc(); + bool LtTrimmed( double t1, double t2, int sense = 1 ); + // \ru END: для библиотеки (хорошо бы избавиться) \en END: for the library (it would be good escape) - /// \ru Создать Bezier форму Nurbs. \en Create a Bezier shape of Nurbs. - void Bezier( MbNurbs & bezierForm ) const; - /// \ru Присоединить nurbs. \en Attach nurbs. - bool Concatenate( MbNurbs & ); + /// \ru Создать Bezier форму Nurbs. \en Create a Bezier shape of Nurbs. + void Bezier( MbNurbs & bezierForm ) const; + /// \ru Присоединить nurbs. \en Attach nurbs. + bool Concatenate( MbNurbs & ); - /// \ru Задать вес для вершины. \en Set weight for control point. - void SetWeight( ptrdiff_t pointNumber, double newWeight ); + /// \ru Задать вес для вершины. \en Set weight for control point. + void SetWeight( ptrdiff_t pointNumber, double newWeight ); - /// \ru Получить кратность узла. \en Get the knot multiplicity. - size_t KnotMultiplicity( ptrdiff_t knotIndex ) const; - /// \ru Определение базисного узлового вектора. \en Determination of basis knot vector. - void DefineKnotsVector(); - /// \ru Переопределение базисного узлового вектора из Close в Open. \en Redetermination of the basis knot vector from Close to Open. - bool OpenKnotsVector(); - /// \ru Переопределение базисного узлового вектора из Open в Close. \en Redetermination of the basis knot vector from Open to Close. - bool CloseKnotsVector(); - /// \ru Сдвинуть параметр замкнутого сплайна. \en Shift parameter of closed spline. - void CyclicShift( ptrdiff_t interval ); - void CyclicShift( double t ); - bool BasicFunctions( double & t, ptrdiff_t k, CcArray & values, ptrdiff_t & left, double & sum ); + /// \ru Получить кратность узла. \en Get the knot multiplicity. + size_t KnotMultiplicity( ptrdiff_t knotIndex ) const; + /// \ru Определение базисного узлового вектора. \en Determination of basis knot vector. + void DefineKnotsVector(); + /// \ru Переопределение базисного узлового вектора из Close в Open. \en Redetermination of the basis knot vector from Close to Open. + bool OpenKnotsVector(); + /// \ru Переопределение базисного узлового вектора из Open в Close. \en Redetermination of the basis knot vector from Open to Close. + bool CloseKnotsVector(); + /// \ru Сдвинуть параметр замкнутого сплайна. \en Shift parameter of closed spline. + void CyclicShift( ptrdiff_t interval ); + void CyclicShift( double t ); + bool BasicFunctions( double & t, ptrdiff_t k, CcArray & values, ptrdiff_t & left, double & sum ); - void CheckForm(); - /// \ru Преобразовать кривую в коническое сечение, если это возможно. \en Transform a curve into a conic section if it is possible. - MbCurve * ConvertToConic(); - /// \ru Установить область изменения параметра. \en Set the range of parameter. - bool SetLimitParam( double newTMin, double newTMax ); + void CheckForm(); + /// \ru Преобразовать кривую в коническое сечение, если это возможно. \en Transform a curve into a conic section if it is possible. + MbCurve * ConvertToConic(); + /// \ru Установить область изменения параметра. \en Set the range of parameter. + bool SetLimitParam( double newTMin, double newTMax ); // \ru Базовые операции над NURBS-кривой. \en Base operation with NURBS curve. - /// \ru Добавление нового узла; возвращает количество узлов, которые удалось вставить. \en Addition of a new knots; returns the number of knots which have been inserted. - size_t InsertKnots( double & newKnot, size_t multiplicity, double relEps ); - /// \ru Удалить кратный внутренний узел id, num раз; вернуть количество удалений, которое удалось сделать. \en Remove multiple internal 'id' knot 'num' times, return count of removals was successfully made. - ptrdiff_t RemoveKnot( ptrdiff_t id, ptrdiff_t num, double relEps = Math::paramEpsilon, double absEps = Math::lengthEpsilon ); - /// \ru Удалить все внутренние узлы, если это возможно. \en Remove all internal knots if it is possible. - void RemoveAllKnots( double relEps = Math::paramEpsilon, double absEps = Math::lengthEpsilon ); - /// \ru Преобразовать данный nurbs в форму Безье, узловой вектор в зажатый. \en Convert this nurbs to Bezier form; knot vector to clamped. - bool DecomposeCurve(); + /// \ru Добавление нового узла; возвращает количество узлов, которые удалось вставить. \en Addition of a new knots; returns the number of knots which have been inserted. + size_t InsertKnots( double & newKnot, size_t multiplicity, double relEps ); + /// \ru Удалить кратный внутренний узел id, num раз; вернуть количество удалений, которое удалось сделать. \en Remove multiple internal 'id' knot 'num' times, return count of removals was successfully made. + ptrdiff_t RemoveKnot( ptrdiff_t id, ptrdiff_t num, double relEps = Math::paramEpsilon, double absEps = Math::lengthEpsilon ); + /// \ru Удалить все внутренние узлы, если это возможно. \en Remove all internal knots if it is possible. + void RemoveAllKnots( double relEps = Math::paramEpsilon, double absEps = Math::lengthEpsilon ); + /// \ru Преобразовать данный nurbs в форму Безье, узловой вектор в зажатый. \en Convert this nurbs to Bezier form; knot vector to clamped. + bool DecomposeCurve(); - /// \ru Преобразовать узловой вектор в зажатый (если кривая замкнута и clm = false) или разжатый (если кривая не замкнута и clm = true). \en Transform knot vector to clamped (if curve is closed and clm = false) or unclamped (if curve is open and clm = true). - bool UnClamped( bool clm ); - /// \ru Добавить кривую в конец. \en Add curve to the end. - void AddCurve ( MbNurbs &, bool bmerge = true ); - /// \ru Добавить кривые в конец. \en Add curves to the end. - template - void AddCurves( NurbsCurves & curves ) - { - for ( size_t i = 0, icount = curves.size(); i < icount; ++i ) { - if ( curves[i] != nullptr ) - AddCurve( *curves[i] ); - } - } - /** \brief \ru Разбить кривую. - \en Split the curve. \~ - \details \ru Разбить недифференцируемую NURBS-кривую четвертой степени в трижды кратном внутреннем узле.\n - Если внутренних трижды кратных узлов не существует, то в массив заносится копия кривой.\n - Если bline = true, то проверить вырожденность в прямую, если прямая - преобразовать в прямую. - \en Split the non-differentiable NURBS-curve of fourth degree at internal knot with multiplicity of three.\n - If there are no internal knots with multiplicity of three, then the array is filled with copy of curve.\n - If bline = true, then check the curve for degeneration into a line, if it is a line then transform to a line. \~ - */ - bool BreakC0NURBS4( RPArray &, bool bline = true ); - /// \ru Разбить NURBS-кривую в местах, где кривая не дифференцируема. Параметризация не сохраняется. \en Split NURBS-curve at places where the curve is non-differentiable. Parametrization does not remain. - bool BreakC0( c3d::PlaneCurvesSPtrVector &, double metricAcc = METRIC_EPSILON ); - /// \ru Расширить незамкнутую NURBS-кривую по касательным. \en Extend open NURBS-curve by tangents. - bool ExtendNurbs( double, double, bool bmerge = false ); + /// \ru Преобразовать узловой вектор в зажатый (если кривая замкнута и clm = false) или разжатый (если кривая не замкнута и clm = true). \en Transform knot vector to clamped (if curve is closed and clm = false) or unclamped (if curve is open and clm = true). + bool UnClamped( bool clm ); + /// \ru Добавить кривую в конец. \en Add curve to the end. + void AddCurve ( MbNurbs &, bool bmerge = true ); + /// \ru Добавить кривые в конец. \en Add curves to the end. + template + void AddCurves( NurbsCurves & curves ) + { + for ( size_t i = 0, icount = curves.size(); i < icount; ++i ) { + if ( curves[i] != nullptr ) + AddCurve( *curves[i] ); + } + } + /** \brief \ru Разбить кривую. + \en Split the curve. \~ + \details \ru Разбить недифференцируемую NURBS-кривую четвертой степени в трижды кратном внутреннем узле.\n + Если внутренних трижды кратных узлов не существует, то в массив заносится копия кривой.\n + Если bline = true, то проверить вырожденность в прямую, если прямая - преобразовать в прямую. + \en Split the non-differentiable NURBS-curve of fourth degree at internal knot with multiplicity of three.\n + If there are no internal knots with multiplicity of three, then the array is filled with copy of curve.\n + If bline = true, then check the curve for degeneration into a line, if it is a line then transform to a line. \~ + */ + bool BreakC0NURBS4( RPArray &, bool bline = true ); + /// \ru Разбить NURBS-кривую в местах, где кривая не дифференцируема. Параметризация не сохраняется. \en Split NURBS-curve at places where the curve is non-differentiable. Parametrization does not remain. + bool BreakC0( c3d::PlaneCurvesSPtrVector &, double metricAcc = METRIC_EPSILON ); + /// \ru Расширить незамкнутую NURBS-кривую по касательным. \en Extend open NURBS-curve by tangents. + bool ExtendNurbs( double, double, bool bmerge = false ); - /** \brief \ru Замкнуть кривую. - \en Make curve closed. \~ - \details \ru Замкнуть фактически замкнутую кривую.\n - То есть если первая и последняя точки кривой совпадают, но она реализована как незамкнутая, - то одна из совпадающих точек убирается и кривая делается замкнутой. - \en Make actually closed curve closed.\n - That is, if the first and the last points of curve are coincident, but curve implemented as open, - then one of coincident points is taken away and curve becomes closed. \~ - */ - void FixClosedNurbs(); + /** \brief \ru Замкнуть кривую. + \en Make curve closed. \~ + \details \ru Замкнуть фактически замкнутую кривую.\n + То есть если первая и последняя точки кривой совпадают, но она реализована как незамкнутая, + то одна из совпадающих точек убирается и кривая делается замкнутой. + \en Make actually closed curve closed.\n + That is, if the first and the last points of curve are coincident, but curve implemented as open, + then one of coincident points is taken away and curve becomes closed. \~ + */ + void FixClosedNurbs(); /** \} */ @@ -983,13 +983,13 @@ protected: bool CanChangeClosed() const override; // \ru Можно ли поменять признак замкнутости. // ЯТ К6 \en Whether it is possible to change the attribute of closedness. // ЯТ К6 private: // \ru Системные методы. \en System methods. - bool CatchMemory( MbNurbsAuxiliaryData * cache ) const; // \ru Выделить память. \en Allocate memory. - void FreeMemory( MbNurbsAuxiliaryData * cache ) const; // \ru Освободить память. \en Free memory. - void VerifyParam( double & t ) const; // \ru Загнать параметр t в параметрическую область кривой. \en Parameter set in the curve region. - void CalculateSegment( double & t, MbNurbsAuxiliaryData * cache ) const; // \ru Рассчитать базисные функции и разностные формы на участке. \en Calculate the basis functions and differential forms on the region. - void CalculateSpline( ptrdiff_t n, MbNurbsAuxiliaryData * cache ) const; // \ru Рассчитать точку NURBS-кривой или производную n-го порядка. \en Calculate point of NURBS-curve or n-th order derivative. - void CalculateSplineWeight( double & t, ptrdiff_t n, MbNurbsAuxiliaryData * cache ) const; - bool InitSegments( MbNurbsAuxiliaryData * cache ) const; + bool CatchMemory( MbNurbsAuxiliaryData * cache ) const; // \ru Выделить память. \en Allocate memory. + void FreeMemory( MbNurbsAuxiliaryData * cache ) const; // \ru Освободить память. \en Free memory. + void VerifyParam( double & t ) const; // \ru Загнать параметр t в параметрическую область кривой. \en Parameter set in the curve region. + void CalculateSegment( double & t, MbNurbsAuxiliaryData * cache ) const; // \ru Рассчитать базисные функции и разностные формы на участке. \en Calculate the basis functions and differential forms on the region. + void CalculateSpline( ptrdiff_t n, MbNurbsAuxiliaryData * cache ) const; // \ru Рассчитать точку NURBS-кривой или производную n-го порядка. \en Calculate point of NURBS-curve or n-th order derivative. + void CalculateSplineWeight( double & t, ptrdiff_t n, MbNurbsAuxiliaryData * cache ) const; + bool InitSegments( MbNurbsAuxiliaryData * cache ) const; /** \brief \ru Инициализация. \en Initialization. \~ @@ -1007,33 +1007,33 @@ private: // \ru Системные методы. \en System methods. \en Sequence of knot parameters. \~ */ template - bool InitThroughTempl( size_t degree, - bool cls, + bool InitThroughTempl( size_t degree, + bool cls, const PointsVector & points, const ParamsVector & params, ParamsVector * aKnots = nullptr ); // \ru Служебные аналоги публичных функций, которые используют заданный кэш. \en Service analogs of public functions that use a given cache. - void PointOn( double & t, MbCartPoint & pnt, MbNurbsAuxiliaryData * ucache ) const; // \ru Точка на кривой. \en Point on the curve. - void FirstDer( double & t, MbVector & fd, MbNurbsAuxiliaryData * ucache ) const; // \ru Первая производная. \en First derivative. - void SecondDer( double & t, MbVector & sd, MbNurbsAuxiliaryData * ucache ) const; // \ru Вторая производная. \en Second derivative. - void Derivatives( double & t, bool ext, MbVector & fir, MbVector * sec, MbVector * thi, MbNurbsAuxiliaryData * ucache ) const; + void PointOn( double & t, MbCartPoint & pnt, MbNurbsAuxiliaryData * ucache ) const; // \ru Точка на кривой. \en Point on the curve. + void FirstDer( double & t, MbVector & fd, MbNurbsAuxiliaryData * ucache ) const; // \ru Первая производная. \en First derivative. + void SecondDer( double & t, MbVector & sd, MbNurbsAuxiliaryData * ucache ) const; // \ru Вторая производная. \en Second derivative. + void Derivatives( double & t, bool ext, MbVector & fir, MbVector * sec, MbVector * thi, MbNurbsAuxiliaryData * ucache ) const; - void SetClamped(); // \ru Делаем зажатый узловой вектор. \en Set clamped knots vector. + 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; + void ResetCache(); // \ru Очистить кэш главного потока, сбросить остальные кэши. \en Clear main thread cache, reset other caches. + bool NurbsPlus( MbNurbs & nurbs, double tin, double tax ) const; // \ru Расчет весовых функций и их первых производных. \en Calculation of weight functions and its first derivatives. - ptrdiff_t WeightFunctions( double & x, CcArray & ) const; + ptrdiff_t WeightFunctions( double & x, CcArray & ) const; // \ru Вычисление шага аппроксимации в обе стороны. \en Calculation of approximation step in both directions. - double StepD( double & t, double sag, bool checkAngle = false, double angle = 0.0, MbNurbsAuxiliaryData * cache = nullptr ) const; + double StepD( double & t, double sag, bool checkAngle = false, double angle = 0.0, MbNurbsAuxiliaryData * cache = nullptr ) const; // \ru Вычисление шага аппроксимации сплайна второго порядка. \en Calculation of approximation step of second order spline. - double PolylineStep( double t, bool half, MbNurbsAuxiliaryData * cache ) const; + double PolylineStep( double t, bool half, MbNurbsAuxiliaryData * cache ) const; // \ru Уточнить проекцию \en Specify projection. - double SpecifyProjection( const MbCartPoint & pnt, double xEpsilon, double yEpsilon, double t, bool ext ) const; + double SpecifyProjection( const MbCartPoint & pnt, double xEpsilon, double yEpsilon, double t, bool ext ) const; - void operator = ( const MbNurbs & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbNurbs & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbNurbs ) }; @@ -1079,6 +1079,7 @@ MbNurbs::MbNurbs( size_t initDegree, bool initClosed, const PointsVector & initP } } + //------------------------------------------------------------------------------ // \ru Добавить точку в конец массива. \en Add point to the end of the array. // --- diff --git a/C3d/Include/cur_nurbs3d.h b/C3d/Include/cur_nurbs3d.h index 26e750a..0b7ba28 100644 --- a/C3d/Include/cur_nurbs3d.h +++ b/C3d/Include/cur_nurbs3d.h @@ -108,23 +108,22 @@ protected: \en Constructor. \~ \details \ru Конструктор по порядку, точкам, параметрам и признаку замкнутости.\n \en Constructor by order, points, parameters and an attribute of closedness.\n \~ - \param[in] deg - \ru Порядок сплайна. - Должен быть больше единицы. Не должен превышать количество контрольных точек. - \en A spline order. - Must be greater than unity. Shouldn't exceed the count of control points. \~ - \param[in] cls - \ru Признак замкнутости. - \en Closedness attribute. \~ - \param[in] points - \ru Набор контрольных точек. - Количество точек должно быть больше или равно двум. - \en Set of control points. - Count of points must be greater than or equal to two. \~ - \param[in] weights - \ru Набор весов для контрольных точек. - Количество весов должно соответствовать количеству точек. - \en Set of weights for control points. - Count of weights must be equal to count of points. \~ - \param[in] knots - \ru Последовательность узловых параметров. - \en Sequence of knot parameters. \~ - + \param[in] deg - \ru Порядок сплайна. + Должен быть больше единицы. Не должен превышать количество контрольных точек. + \en A spline order. + Must be greater than unity. Shouldn't exceed the count of control points. \~ + \param[in] cls - \ru Признак замкнутости. + \en Closedness attribute. \~ + \param[in] points - \ru Набор контрольных точек. + Количество точек должно быть больше или равно двум. + \en Set of control points. + Count of points must be greater than or equal to two. \~ + \param[in] weights - \ru Набор весов для контрольных точек. + Количество весов должно соответствовать количеству точек. + \en Set of weights for control points. + Count of weights must be equal to count of points. \~ + \param[in] knots - \ru Последовательность узловых параметров. + \en Sequence of knot parameters. \~ */ MbNurbs3D( size_t deg, bool cls, const SArray & points, const SArray * weights = nullptr, const SArray * knots = nullptr ); @@ -298,187 +297,188 @@ public : double scl ); public: - /// \ru Установить параметры сплайна. \en Set parameters of the spline. - void Init( const MbNurbs3D & ); - void Init( const MbNurbs &, const MbPlacement3D & ); - /** \brief \ru Инициализация. - \en Initialization. \~ - \details \ru Установить параметры сплайна.\n - \en Set parameters of the spline.\n \~ - \param[in] degree - \ru Порядок сплайна. - \en A spline order. \~ - \param[in] points - \ru Набор контрольных точек. - \en Set of control points. \~ - \param[in] weights - \ru Набор весов для контрольных точек. - \en Set of weights for control points. \~ - \param[in] closed - \ru Признак замкнутости. - \en Closedness attribute. \~ - */ - bool Init( size_t degree, const SArray & points, bool closed, - const SArray * weights = nullptr ); - /** \brief \ru Инициализация. - \en Initialization. \~ - \details \ru Установить параметры сплайна.\n - \en Set parameters of the spline.\n \~ - \param[in] degree - \ru Порядок сплайна. - \en A spline order. \~ - \param[in] closed - \ru Признак замкнутости. - \en Closedness attribute. \~ - \param[in] points - \ru Набор контрольных точек. - \en Set of control points. \~ - \param[in] knots - \ru Неубывающая последовательность узлов. - \en Nondecreasing sequence of knots. \~ + + /// \ru Установить параметры сплайна. \en Set parameters of the spline. + void Init( const MbNurbs3D & ); + void Init( const MbNurbs &, const MbPlacement3D & ); + /** \brief \ru Инициализация. + \en Initialization. \~ + \details \ru Установить параметры сплайна.\n + \en Set parameters of the spline.\n \~ + \param[in] degree - \ru Порядок сплайна. + \en A spline order. \~ + \param[in] points - \ru Набор контрольных точек. + \en Set of control points. \~ + \param[in] weights - \ru Набор весов для контрольных точек. + \en Set of weights for control points. \~ + \param[in] closed - \ru Признак замкнутости. + \en Closedness attribute. \~ + */ + bool Init( size_t degree, const SArray & points, bool closed, + const SArray * weights = nullptr ); + /** \brief \ru Инициализация. + \en Initialization. \~ + \details \ru Установить параметры сплайна.\n + \en Set parameters of the spline.\n \~ + \param[in] degree - \ru Порядок сплайна. + \en A spline order. \~ + \param[in] closed - \ru Признак замкнутости. + \en Closedness attribute. \~ + \param[in] points - \ru Набор контрольных точек. + \en Set of control points. \~ + \param[in] knots - \ru Неубывающая последовательность узлов. + \en Nondecreasing sequence of knots. \~ - */ - bool Init( size_t degree, bool closed, const SArray & points, - const SArray & knots ); - /** \brief \ru Инициализация. - \en Initialization. \~ - \details \ru Установить параметры сплайна.\n - \en Set parameters of the spline.\n \~ - \param[in] degree - \ru Порядок сплайна. - \en A spline order. \~ - \param[in] closed - \ru Признак замкнутости. - \en Closedness attribute. \~ - \param[in] points - \ru Набор контрольных точек. - \en Set of control points. \~ - \param[in] weights - \ru Набор весов для контрольных точек. - \en Set of weights for control points. \~ - \param[in] knots - \ru Неубывающая последовательность узлов. - \en Nondecreasing sequence of knots. \~ - \param[in] initForm - \ru Тип построения. - \en Type of construction. \~ + */ + bool Init( size_t degree, bool closed, const SArray & points, + const SArray & knots ); + /** \brief \ru Инициализация. + \en Initialization. \~ + \details \ru Установить параметры сплайна.\n + \en Set parameters of the spline.\n \~ + \param[in] degree - \ru Порядок сплайна. + \en A spline order. \~ + \param[in] closed - \ru Признак замкнутости. + \en Closedness attribute. \~ + \param[in] points - \ru Набор контрольных точек. + \en Set of control points. \~ + \param[in] weights - \ru Набор весов для контрольных точек. + \en Set of weights for control points. \~ + \param[in] knots - \ru Неубывающая последовательность узлов. + \en Nondecreasing sequence of knots. \~ + \param[in] initForm - \ru Тип построения. + \en Type of construction. \~ - */ - template - bool Init( size_t initDegree, bool initClosed, const PointsVector & initPoints, - const DoubleVector & initWeights, const DoubleVector & initKnots, - MbeNurbsCurveForm initForm = ncf_Unspecified ) - { - bool bRes = ::IsValidNurbsParamsExt( initDegree, initClosed, initPoints, &initWeights, &initKnots ); + */ + template + bool Init( size_t initDegree, bool initClosed, const PointsVector & initPoints, + const DoubleVector & initWeights, const DoubleVector & initKnots, + MbeNurbsCurveForm initForm = ncf_Unspecified ) + { + bool bRes = ::IsValidNurbsParamsExt( initDegree, initClosed, initPoints, &initWeights, &initKnots ); - if ( bRes ) { - Refresh(); // Must come first, since frees allocated memory + if ( bRes ) { + Refresh(); // Must come first, since frees allocated memory - pointList = initPoints; - uppIndex = (ptrdiff_t)pointList.size() - 1; - closed = initClosed; - form = initForm; - degree = initDegree; - uppKnotsIndex = (ptrdiff_t)initKnots.size() - 1; - weights = initWeights; - knots = initKnots; + pointList = initPoints; + uppIndex = (ptrdiff_t)pointList.size() - 1; + closed = initClosed; + form = initForm; + degree = initDegree; + uppKnotsIndex = (ptrdiff_t)initKnots.size() - 1; + weights = initWeights; + knots = initKnots; - SetClamped(); - } - else if ( ::IsValidNurbsParams( initDegree, initClosed, initPoints.size(), initWeights.size() ) ) { - // Lets try to redefine knots vector (BUG_42356) - Refresh(); // Must come first, since frees allocated memory - pointList = initPoints; - uppIndex = (ptrdiff_t)pointList.size() - 1; - closed = initClosed; - form = ncf_Unspecified; - degree = initDegree; - weights = initWeights; + SetClamped(); + } + else if ( ::IsValidNurbsParams( initDegree, initClosed, initPoints.size(), initWeights.size() ) ) { + // Lets try to redefine knots vector (BUG_42356) + Refresh(); // Must come first, since frees allocated memory + pointList = initPoints; + uppIndex = (ptrdiff_t)pointList.size() - 1; + closed = initClosed; + form = ncf_Unspecified; + degree = initDegree; + weights = initWeights; - DefineKnotsVector(); - C3D_ASSERT_UNCONDITIONAL( false ); // Wrong constructor use - // Valid variants: - // 1. Really, result is false - // 2. The result should have 3 positions, - // 3. Initial knots should be analyzed and corrected - bRes = true; // Not been deleted recurring point for a closed curve - } + DefineKnotsVector(); + C3D_ASSERT_UNCONDITIONAL( false ); // Wrong constructor use + // Valid variants: + // 1. Really, result is false + // 2. The result should have 3 positions, + // 3. Initial knots should be analyzed and corrected + bRes = true; // Not been deleted recurring point for a closed curve + } - return bRes; - } - /** \brief \ru Инициализация. - \en Initialization. \~ - \details \ru Установить параметры сплайна.\n - \en Set parameters of the spline.\n \~ - \param[in] degree - \ru Порядок сплайна. - \en A spline order. \~ - \param[in] points - \ru Набор контрольных точек. - \en Set of control points. \~ - \param[in] weights - \ru Набор весов для контрольных точек. - \en Set of weights for control points. \~ - \param[in] begData - \ru Параметр сопряжения в начальной точке сплайна. - \en Parameter of conjugation at the start point of the spline. \~ - \param[in] endData - \ru Параметр сопряжения в конечной точке сплайна. - \en Parameter of conjugation at the end point of the spline. \~ - */ - bool Init( size_t degree, - const SArray & points, - const SArray & weights, - c3d::PntMatingData3D & begData, - c3d::PntMatingData3D & endData ); - /** \brief \ru Инициализация. - \en Initialization. \~ - \details \ru Установить параметры сплайна.\n - \en Set parameters of the spline.\n \~ - \param[in] degree - \ru Порядок сплайна. - \en A spline order. \~ - \param[in] closed - \ru Признак замкнутости. - \en Closedness attribute. \~ - \param[in] points - \ru Набор контрольных точек. - \en Set of control points. \~ - \param[in] knots - \ru Неубывающая последовательность узлов. - \en Nondecreasing sequence of knots. \~ - \param[in] nPoints - \ru Число контрольных точек. - \en The number of control points. \~ - \param[in] endData - \ru Количество узлов. - \en Count of knots. \~ - */ - bool Init( size_t degree, bool closed, const CcArray & points, - const CcArray & knots, size_t nPoints, size_t nKnots ); - /** \brief \ru Инициализация. - \en Initialization. \~ - \details \ru Сплайн, проходящий через заданные точки при заданных параметрах.\n - В случае замкнутости нужно передавать массив с совпадением первой и последней точек.\n - \en Spline passing through the given points at the given parameters.\n - In case of closedness it is necessary to pass the array with coincidence of the first and the last points.\n \~ - \param[in] degree - \ru Порядок сплайна. - \en A spline order. \~ - \param[in] cls - \ru Признак замкнутости. - \en Closedness attribute. \~ - \param[in] points - \ru Набор точек, через которые проходит сплайн. - \en Set of points which the spline passes through. \~ - \param[in] params - \ru Последовательность узловых параметров. - \en Sequence of knot parameters. \~ - \param[in] aKnots - \ru Неубывающая последовательность узлов. - \en Nondecreasing sequence of knots. \~ - */ - bool InitThrough( size_t degree, - bool cls, - const SArray & points, - const SArray & params, - SArray * aKnots = nullptr ); + return bRes; + } + /** \brief \ru Инициализация. + \en Initialization. \~ + \details \ru Установить параметры сплайна.\n + \en Set parameters of the spline.\n \~ + \param[in] degree - \ru Порядок сплайна. + \en A spline order. \~ + \param[in] points - \ru Набор контрольных точек. + \en Set of control points. \~ + \param[in] weights - \ru Набор весов для контрольных точек. + \en Set of weights for control points. \~ + \param[in] begData - \ru Параметр сопряжения в начальной точке сплайна. + \en Parameter of conjugation at the start point of the spline. \~ + \param[in] endData - \ru Параметр сопряжения в конечной точке сплайна. + \en Parameter of conjugation at the end point of the spline. \~ + */ + bool Init( size_t degree, + const SArray & points, + const SArray & weights, + c3d::PntMatingData3D & begData, + c3d::PntMatingData3D & endData ); + /** \brief \ru Инициализация. + \en Initialization. \~ + \details \ru Установить параметры сплайна.\n + \en Set parameters of the spline.\n \~ + \param[in] degree - \ru Порядок сплайна. + \en A spline order. \~ + \param[in] closed - \ru Признак замкнутости. + \en Closedness attribute. \~ + \param[in] points - \ru Набор контрольных точек. + \en Set of control points. \~ + \param[in] knots - \ru Неубывающая последовательность узлов. + \en Nondecreasing sequence of knots. \~ + \param[in] nPoints - \ru Число контрольных точек. + \en The number of control points. \~ + \param[in] endData - \ru Количество узлов. + \en Count of knots. \~ + */ + bool Init( size_t degree, bool closed, const CcArray & points, + const CcArray & knots, size_t nPoints, size_t nKnots ); + /** \brief \ru Инициализация. + \en Initialization. \~ + \details \ru Сплайн, проходящий через заданные точки при заданных параметрах.\n + В случае замкнутости нужно передавать массив с совпадением первой и последней точек.\n + \en Spline passing through the given points at the given parameters.\n + In case of closedness it is necessary to pass the array with coincidence of the first and the last points.\n \~ + \param[in] degree - \ru Порядок сплайна. + \en A spline order. \~ + \param[in] cls - \ru Признак замкнутости. + \en Closedness attribute. \~ + \param[in] points - \ru Набор точек, через которые проходит сплайн. + \en Set of points which the spline passes through. \~ + \param[in] params - \ru Последовательность узловых параметров. + \en Sequence of knot parameters. \~ + \param[in] aKnots - \ru Неубывающая последовательность узлов. + \en Nondecreasing sequence of knots. \~ + */ + bool InitThrough( size_t degree, + bool cls, + const SArray & points, + const SArray & params, + SArray * aKnots = nullptr ); - /** \brief \ru Инициализация. - \en Initialization. \~ - \details \ru Сплайн, проходящий через заданные точки при заданных параметрах.\n - В случае замкнутости нужно передавать массив с совпадением первой и последней точек.\n - \en Spline passing through the given points at the given parameters.\n - In case of closedness it is necessary to pass the array with coincidence of the first and the last points.\n \~ - \param[in] degree - \ru Порядок сплайна. - \en A spline order. \~ - \param[in] cls - \ru Признак замкнутости. - \en Closedness attribute. \~ - \param[in] points - \ru Набор точек, через которые проходит сплайн. - \en Set of points which the spline passes through. \~ - \param[in] params - \ru Последовательность узловых параметров. - \en Sequence of knot parameters. \~ - \param[in] aKnots - \ru Неубывающая последовательность узлов. - \en Nondecreasing sequence of knots. \~ - */ - bool InitThrough( size_t degree, - bool cls, - const c3d::SpacePointsVector & points, - const c3d::DoubleVector & params, - c3d::DoubleVector * aKnots = nullptr ); + /** \brief \ru Инициализация. + \en Initialization. \~ + \details \ru Сплайн, проходящий через заданные точки при заданных параметрах.\n + В случае замкнутости нужно передавать массив с совпадением первой и последней точек.\n + \en Spline passing through the given points at the given parameters.\n + In case of closedness it is necessary to pass the array with coincidence of the first and the last points.\n \~ + \param[in] degree - \ru Порядок сплайна. + \en A spline order. \~ + \param[in] cls - \ru Признак замкнутости. + \en Closedness attribute. \~ + \param[in] points - \ru Набор точек, через которые проходит сплайн. + \en Set of points which the spline passes through. \~ + \param[in] params - \ru Последовательность узловых параметров. + \en Sequence of knot parameters. \~ + \param[in] aKnots - \ru Неубывающая последовательность узлов. + \en Nondecreasing sequence of knots. \~ + */ + bool InitThrough( size_t degree, + bool cls, + const c3d::SpacePointsVector & points, + const c3d::DoubleVector & params, + c3d::DoubleVector * aKnots = nullptr ); - /// \ru Установить тип формы. \en Set the type of shape. - void SetFormType( MbeNurbsCurveForm f ) { form = f; } + /// \ru Установить тип формы. \en Set the type of shape. + void SetFormType( MbeNurbsCurveForm f ) { form = f; } // \ru Общие функции математического объекта. \en The common functions of the mathematical object. @@ -494,7 +494,7 @@ public: void SetProperties( const MbProperties & ) override; // \ru Записать свойства объекта. \en Set properties of the object. void GetBasisPoints( MbControlData3D & ) const override; // \ru Выдать контрольные точки объекта. \en Get control points of object. void SetBasisPoints( const MbControlData3D & ) override; // \ru Изменить объект по контрольным точкам. \en Change the object by control points. - void GetControlPoints( SArray & ) const; // \ru Выдать контрольные точки объекта. \en Get control points of object. + void GetControlPoints( SArray & ) const; // \ru Выдать контрольные точки объекта. \en Get control points of object. // \ru Общие функции кривой. \en Common functions of curve. @@ -510,9 +510,9 @@ public: void ThirdDer ( double & t, MbVector3D & ) const override; // \ru Третья производная по t. \en The third derivative with respect to t. // \ru Вычислить значения точки и производных для заданного параметра. \en Calculate point and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const override; + MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const override; // \ru Вычислить значения производных для заданного параметра. \en Calculate derivatives of object for given parameter. \~ - void Derivatives( double & t, bool ext, MbVector3D & fir, MbVector3D * sec, MbVector3D * thi ) const; + void Derivatives( double & t, bool ext, MbVector3D & fir, MbVector3D * sec, MbVector3D * thi ) const; 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. @@ -536,10 +536,10 @@ public: bool IsReparamSame( const MbCurve3D & curve, double & factor ) const override; bool IsDegenerate ( double eps = METRIC_PRECISION ) const override; // \ru Проверка вырожденности кривой. \en Check the curve degeneracy. - void SetDegenerate(); // \ru Стать вырожденным. \en Became degenerate. + void SetDegenerate(); // \ru Стать вырожденным. \en Became degenerate. - /// \ru Усечение кривой. \en Trim the curve. - MbNurbs3D * Trimm( double t1, double t2, int sense ) const; + /// \ru Усечение кривой. \en Trim the curve. + MbNurbs3D * Trimm( double t1, double t2, int sense ) const; // \ru Вычислить габарит кривой. \en Calculate bounding box of a curve. void CalculateGabarit( MbCube & cube ) const override; @@ -547,7 +547,7 @@ public: double CalculateMetricLength() const override; // \ru Сдвинуть параметр t на расстояние len. \en Move parameter t on the metric distance len. bool DistanceAlong( double & t, double len, int curveDir, double eps = Math::metricPrecision, - VERSION version = Math::DefaultMathVersion() ) const override; + VERSION version = Math::DefaultMathVersion() ) const override; // \ru Вычислить метрическую длину кривой. \en Calculate the metric length of a curve. double CalculateLength( double t1, double t2 ) const override; @@ -575,100 +575,102 @@ public: bool SetContinuousDerivativeLength( VERSION version, double epsilon = EPSILON ) override; // \ru Функции B-сплайн кривой. \en Functions of B-spline curve. - /// \ru Выделить часть кривой. \en Extract a piece of a curve. - MbNurbs3D * Break( double t1, double t2 ) const; - /// \ru Задать вес для вершины. \en Set weight for a control point. - void SetWeight( ptrdiff_t pointNumber, double newWeight ); - /// \ru Добавить точку с весом. \en Add a point with weight. - void AddPoint ( ptrdiff_t index, const MbCartPoint3D & pnt, double weight ); + + /// \ru Выделить часть кривой. \en Extract a piece of a curve. + MbNurbs3D * Break( double t1, double t2 ) const; + /// \ru Задать вес для вершины. \en Set weight for a control point. + void SetWeight( ptrdiff_t pointNumber, double newWeight ); + /// \ru Добавить точку с весом. \en Add a point with weight. + void AddPoint ( ptrdiff_t index, const MbCartPoint3D & pnt, double weight ); // \ru Функции B-сплайна. \en Functions of B-spline. - /// \ru Добавление нового узла с заданной кратностью. \en Add a new knot with the given multiplicity. - void InsertKnots ( double & newKnot, size_t multiplicity, double relEps = Math::paramEpsilon ); - /// \ru Добавление новых узлов равномерно в промежуток от idBegin до idBegin+1. \en Add new equally spaced knots into the range from idBegin to idBegin+1. - void InsertKnotsInRegion( ptrdiff_t idBegin ); + + /// \ru Добавление нового узла с заданной кратностью. \en Add a new knot with the given multiplicity. + void InsertKnots ( double & newKnot, size_t multiplicity, double relEps = Math::paramEpsilon ); + /// \ru Добавление новых узлов равномерно в промежуток от idBegin до idBegin+1. \en Add new equally spaced knots into the range from idBegin to idBegin+1. + void InsertKnotsInRegion( ptrdiff_t idBegin ); - /// \ru Удалить кратный внутренний узел id num раз, вернуть количество удалений, которое удалось сделать. \en Remove multiple internal 'id' knot 'num' times, return count of removals which were successfully made. - ptrdiff_t RemoveKnot( ptrdiff_t id, ptrdiff_t num, double relEps = Math::paramEpsilon, double absEps = Math::lengthEpsilon ); + /// \ru Удалить кратный внутренний узел id num раз, вернуть количество удалений, которое удалось сделать. \en Remove multiple internal 'id' knot 'num' times, return count of removals which were successfully made. + ptrdiff_t RemoveKnot( ptrdiff_t id, ptrdiff_t num, double relEps = Math::paramEpsilon, double absEps = Math::lengthEpsilon ); - /// \ru Удалить узел id 1 раз, не проверяя точность изменения кривой. \en Remove knot 'id' once without checking the accuracy of the curve modification. - bool RemoveKnotAlways( ptrdiff_t id ); + /// \ru Удалить узел id 1 раз, не проверяя точность изменения кривой. \en Remove knot 'id' once without checking the accuracy of the curve modification. + bool RemoveKnotAlways( ptrdiff_t id ); - /// \ru Удалить все внутренние узлы, если это возможно. \en Remove all the internal knots if it is possible. - void RemoveAllKnots( double relEps = Math::paramEpsilon, double absEps = Math::lengthEpsilon ); - /// \ru Преобразовать данный NURBS в форму кривой Безье. \en Transform current NURBS into Bezier curve. - bool DecomposeCurve(); + /// \ru Удалить все внутренние узлы, если это возможно. \en Remove all the internal knots if it is possible. + void RemoveAllKnots( double relEps = Math::paramEpsilon, double absEps = Math::lengthEpsilon ); + /// \ru Преобразовать данный NURBS в форму кривой Безье. \en Transform current NURBS into Bezier curve. + bool DecomposeCurve(); - /** \brief \ru Увеличить порядок кривой, не изменяя ее геометрическую форму и параметризацию. - \en Increase order of curve without changing its geometric shape and parametrization. \~ - \details \ru Увеличить порядок кривой, не изменяя ее геометрическую форму и параметризацию. \n - \en Increase order of curve without changing its geometric shape and parametrization. \n \~ - \param[in] newDegree - \ru Новый порядок сплайна. - \en New order of spline. \~ - \param[in] relEps - \ru Допустимая погрешность изменения формы. - \en Permissible shape error. \~ - \return \ru Возвращает true, если порядок сплайна был изменен. - \en Returns true if the order of the spline was changed. \~ - */ - bool RaiseDegree( size_t newDegree, double relEps = Math::paramEpsilon ); - /** \brief \ru Уменьшить порядок кривой на 1, не изменяя ее геометрическую форму и параметризацию. - \en Decrease order of nurbs curve by 1 without changing its geometric shape and parametrization. \~ - \details \ru Уменьшить порядок кривой на 1, не изменяя ее геометрическую форму и параметризацию. \n - \en Decrease order of nurbs curve by 1 without changing its geometric shape and parametrization. \n \~ - \param[in] relEps - \ru Допустимая погрешность изменения формы. - \en Permissible shape error. \~ - \return \ru Возвращает true, если порядок сплайна был изменен. - \en Returns true if the order of the spline was changed. \~ - */ - bool ReductionDegree( double relEps = Math::paramEpsilon ); + /** \brief \ru Увеличить порядок кривой, не изменяя ее геометрическую форму и параметризацию. + \en Increase order of curve without changing its geometric shape and parametrization. \~ + \details \ru Увеличить порядок кривой, не изменяя ее геометрическую форму и параметризацию. \n + \en Increase order of curve without changing its geometric shape and parametrization. \n \~ + \param[in] newDegree - \ru Новый порядок сплайна. + \en New order of spline. \~ + \param[in] relEps - \ru Допустимая погрешность изменения формы. + \en Permissible shape error. \~ + \return \ru Возвращает true, если порядок сплайна был изменен. + \en Returns true if the order of the spline was changed. \~ + */ + bool RaiseDegree( size_t newDegree, double relEps = Math::paramEpsilon ); + /** \brief \ru Уменьшить порядок кривой на 1, не изменяя ее геометрическую форму и параметризацию. + \en Decrease order of nurbs curve by 1 without changing its geometric shape and parametrization. \~ + \details \ru Уменьшить порядок кривой на 1, не изменяя ее геометрическую форму и параметризацию. \n + \en Decrease order of nurbs curve by 1 without changing its geometric shape and parametrization. \n \~ + \param[in] relEps - \ru Допустимая погрешность изменения формы. + \en Permissible shape error. \~ + \return \ru Возвращает true, если порядок сплайна был изменен. + \en Returns true if the order of the spline was changed. \~ + */ + bool ReductionDegree( double relEps = Math::paramEpsilon ); - /// \ru Получить кратность узла с заданным номером. \en Get multiplicity of a knot with a given index. - size_t KnotMultiplicity( size_t knotIndex ) const; - /// \ru Определение базисного узлового вектора. \en Definition of the basis knot vector. - void DefineKnotsVector(); - /// \ru Переопределение базисного узлового вектора из Close в Open. \en Redefine the basis knot vector from Close to Open. - bool OpenKnotsVector (); - /// \ru Переопределение базисного узлового вектора из Open в Close. \en Redefine the basis knot vector from Open to Close. - bool CloseKnotsVector (); + /// \ru Получить кратность узла с заданным номером. \en Get multiplicity of a knot with a given index. + size_t KnotMultiplicity( size_t knotIndex ) const; + /// \ru Определение базисного узлового вектора. \en Definition of the basis knot vector. + void DefineKnotsVector(); + /// \ru Переопределение базисного узлового вектора из Close в Open. \en Redefine the basis knot vector from Close to Open. + bool OpenKnotsVector (); + /// \ru Переопределение базисного узлового вектора из Open в Close. \en Redefine the basis knot vector from Open to Close. + bool CloseKnotsVector (); - /// \ru Установить область изменения параметра. \en Set the range of parameter. - bool SetLimitParam( double pmin, double pmax ); - /// \ru Добавить кривую в конец. \en Add a curve to the end. - void AddCurve ( MbNurbs3D &, bool bmerge = true ); - /// \ru Добавить кривые в конец. \en Add curves to the end. - void AddCurves ( const RPArray & ); + /// \ru Установить область изменения параметра. \en Set the range of parameter. + bool SetLimitParam( double pmin, double pmax ); + /// \ru Добавить кривую в конец. \en Add a curve to the end. + void AddCurve ( MbNurbs3D &, bool bmerge = true ); + /// \ru Добавить кривые в конец. \en Add curves to the end. + void AddCurves ( const RPArray & ); - /// \ru Репераметризовать кривую в соответствии с длиной в случае, если кривая получена из набора кривых Безье. \en Reparameterize a curve according to the length if the curve is obtained from a set of Bezier curves. - bool ReparamCurveInBezierForm(); + /// \ru Репераметризовать кривую в соответствии с длиной в случае, если кривая получена из набора кривых Безье. \en Reparameterize a curve according to the length if the curve is obtained from a set of Bezier curves. + bool ReparamCurveInBezierForm(); - /// \ru Получить форму В-сплайна. \en Get the form of B-spline. - MbeNurbsCurveForm GetFormType() const { return form; } - /// \ru Получить порядок В-сплайна. \en Get the order of B-spline. - size_t GetDegree() const { return degree; } - /// \ru Вернуть признак рациональности, но не регулярности кривой. \en Get the attribute of rationality, but not regularity of a curve. - bool IsRational() const; + /// \ru Получить форму В-сплайна. \en Get the form of B-spline. + MbeNurbsCurveForm GetFormType() const { return form; } + /// \ru Получить порядок В-сплайна. \en Get the order of B-spline. + size_t GetDegree() const { return degree; } + /// \ru Вернуть признак рациональности, но не регулярности кривой. \en Get the attribute of rationality, but not regularity of a curve. + bool IsRational() const; - /// \ru Получить размер весового вектора. \en Get a size of weights vector. - size_t GetWeightsCount() const { return weights.size(); } - /// \ru Получить весовой вектор. \en Get a weights vector. - template - void GetWeights( WeightsVector & wts, bool justSet = true ) const { if ( justSet ) { wts.clear(); }; std::copy( weights.begin(), weights.end(), std::back_inserter( wts ) ); } - /// \ru Получить значение элемента весового вектора по индексу. \en Get a weights vector element value by index. - double GetWeight( size_t ind ) const { return weights[ind]; } - /// \ru Получить значение элемента весового вектора по индексу. \en Get a weights vector element value by index. - double & SetWeight( size_t ind ) { return weights[ind]; } + /// \ru Получить размер весового вектора. \en Get a size of weights vector. + size_t GetWeightsCount() const { return weights.size(); } + /// \ru Получить весовой вектор. \en Get a weights vector. + template + void GetWeights( WeightsVector & wts, bool justSet = true ) const { if ( justSet ) { wts.clear(); }; std::copy( weights.begin(), weights.end(), std::back_inserter( wts ) ); } + /// \ru Получить значение элемента весового вектора по индексу. \en Get a weights vector element value by index. + double GetWeight( size_t ind ) const { return weights[ind]; } + /// \ru Получить значение элемента весового вектора по индексу. \en Get a weights vector element value by index. + double & SetWeight( size_t ind ) { return weights[ind]; } - /// \ru Получить размер узлового вектора. \en Get a size of knots vector. - size_t GetKnotsCount() const { return knots.size(); } - /// \ru Получить узловой вектор. \en Get a knots vector. - template - void GetKnots( KnotsVector & kts, bool justSet = true ) const { if ( justSet ) { kts.clear(); }; std::copy( knots.begin(), knots.end(), std::back_inserter( kts ) ); } - /// \ru Получить значение элемента узлового вектора по индексу. \en Get a knots vector element value by index. - double GetKnot ( size_t ind ) const { return knots[ind]; } - /// \ru Получить значение элемента узлового вектора по индексу. \en Get a knots vector element value by index. - double & SetKnot ( size_t ind ) { return knots[ind]; } - /// \ru Вернуть максимальный индекс узлового вектора. \en Get the maximal index of knots vector. - ptrdiff_t GetUppKnotsIndex() const { return uppKnotsIndex; } + /// \ru Получить размер узлового вектора. \en Get a size of knots vector. + size_t GetKnotsCount() const { return knots.size(); } + /// \ru Получить узловой вектор. \en Get a knots vector. + template + void GetKnots( KnotsVector & kts, bool justSet = true ) const { if ( justSet ) { kts.clear(); }; std::copy( knots.begin(), knots.end(), std::back_inserter( kts ) ); } + /// \ru Получить значение элемента узлового вектора по индексу. \en Get a knots vector element value by index. + double GetKnot ( size_t ind ) const { return knots[ind]; } + /// \ru Получить значение элемента узлового вектора по индексу. \en Get a knots vector element value by index. + double & SetKnot ( size_t ind ) { return knots[ind]; } + /// \ru Вернуть максимальный индекс узлового вектора. \en Get the maximal index of knots vector. + ptrdiff_t GetUppKnotsIndex() const { return uppKnotsIndex; } // \ru Функции только 3D кривой. \en Functions of 3D curve only. @@ -677,193 +679,196 @@ public: size_t GetCount() const override; // \ru Количество разбиений для прохода в операциях с поверхностями. \en Count of subdivisions for pass in operations with surfaces. - /// \ru Установить сопряжение на конце. \en Set conjugation at the end. - bool AttachG( c3d::PntMatingData3D & connectData, bool beg, bool isWrongAttachG1_K12 = false ); + /// \ru Установить сопряжение на конце. \en Set conjugation at the end. + bool AttachG( c3d::PntMatingData3D & connectData, bool beg, bool isWrongAttachG1_K12 = false ); - /// \ru Создать кубический NURBS по точкам, через которые он проходит, и параметрам сопряжения. \en Create cubic NURBS by parameters of conjugation and points which it passes through. + /// \ru Создать кубический NURBS по точкам, через которые он проходит, и параметрам сопряжения. \en Create cubic NURBS by parameters of conjugation and points which it passes through. static MbNurbs3D * CreateNURBS4( const SArray & points, MbeSplineParamType spType, const c3d::PntMatingData3D & begData, const c3d::PntMatingData3D & endData, MbeSplineCreateType useInitThrough ); - /// \ru Создать кубический NURBS по интерполяционным точкам и данным сопряжения в каждой точке. \en Create cubic NURBS by interpolation points and data of conjugation at each point. + + /// \ru Создать кубический NURBS по интерполяционным точкам и данным сопряжения в каждой точке. \en Create cubic NURBS by interpolation points and data of conjugation at each point. static MbNurbs3D * CreateNURBS4( const SArray & points, MbeSplineParamType spType, - bool closed, + bool closed, RPArray & matingData, MbeSplineCreateType useInitThrough ); - /// \ru Создать кубический NURBS по интерполяционным точкам, их параметрам и данным сопряжения в каждой точке. \en Create cubic NURBS by interpolation points, parameters and data of conjugation at each point. + + /// \ru Создать кубический NURBS по интерполяционным точкам, их параметрам и данным сопряжения в каждой точке. \en Create cubic NURBS by interpolation points, parameters and data of conjugation at each point. static MbNurbs3D * CreateNURBS4( const SArray &, const SArray &, bool closed, RPArray &, MbeSplineCreateType useInitThrough ); - /// \ru Создать кубический NURBS по точкам, через которые он проходит, и признаку замкнутости. \en Create a cubic NURBS by the attribute of closedness and points which it passes through. + + /// \ru Создать кубический NURBS по точкам, через которые он проходит, и признаку замкнутости. \en Create a cubic NURBS by the attribute of closedness and points which it passes through. static MbNurbs3D * CreateNURBS4( const SArray &, bool cls, MbeSplineParamType spType, MbeSplineCreateType useInitThrough = sct_Version2 ); - /** \brief \ru Интерполяция. - \en Interpolation. \~ - \details \ru Создать незамкнутый сплайн четвертого порядка по точкам, параметрам и признаку замкнутости.\n - Используется граничное условие отсутствия узла.\n - \en Create an open spline of fourth order by points, parameters and the attribute of closedness.\n - Used boundary condition of knot absence.\n \~ - */ + /** \brief \ru Интерполяция. + \en Interpolation. \~ + \details \ru Создать незамкнутый сплайн четвертого порядка по точкам, параметрам и признаку замкнутости.\n + Используется граничное условие отсутствия узла.\n + \en Create an open spline of fourth order by points, parameters and the attribute of closedness.\n + Used boundary condition of knot absence.\n \~ + */ static MbNurbs3D * CreateNURBS4( const SArray & points, const SArray & params, bool cls, MbeSplineCreateType useInitThrough = sct_Version2 ); - /** \brief \ru Интерполяция. - \en Interpolation. \~ - \details \ru Создать незамкнутый сплайн четвертого порядка по точкам, параметрам и признаку замкнутости.\n - Используется граничное условие отсутствия узла. - \en Create an open spline of fourth order by points, parameters and the attribute of closedness.\n - Used boundary condition of knot absence. \~ - */ + /** \brief \ru Интерполяция. + \en Interpolation. \~ + \details \ru Создать незамкнутый сплайн четвертого порядка по точкам, параметрам и признаку замкнутости.\n + Используется граничное условие отсутствия узла. + \en Create an open spline of fourth order by points, parameters and the attribute of closedness.\n + Used boundary condition of knot absence. \~ + */ static MbNurbs3D * CreateNURBS4( const SArray & weights, const SArray & points, SArray & params, bool cls ); - /** \brief \ru Интерполяция. - \en Interpolation. \~ - \details \ru Создать сплайн четвертого порядка по точкам, параметрам и признаку замкнутости - с граничными условиями - заданными векторами первых или вторых производных.\n - Имеет 2 кратных внутренних узла, принадлежит классу дифференцируемых ( но не дважды дифференцируемых ) функций.. - \en Create a spline of the fourth order by points, parameters and the attribute of closedness - with boundary conditions - given vectors of the first or the second derivatives.\n - Has 2 multiple internal knots, belongs to the class of differentiable (but not twice differentiable) functions. \~ - \param[in] bfstS - \ru Если true, то начальное граничное условие - вектор первой производной, иначе - вектор второй производной. - \en If true, then start boundary condition is the vector of the first derivative, otherwise - the vector of the second derivative. \~ - \param[in] bfstN - \ru Если true, то конечное граничное условие - вектор первой производной, иначе - вектор второй производной. - \en If true, then end boundary condition - vector of first derivative, otherwise - vector of second derivative. \~ - */ + /** \brief \ru Интерполяция. + \en Interpolation. \~ + \details \ru Создать сплайн четвертого порядка по точкам, параметрам и признаку замкнутости + с граничными условиями - заданными векторами первых или вторых производных.\n + Имеет 2 кратных внутренних узла, принадлежит классу дифференцируемых ( но не дважды дифференцируемых ) функций.. + \en Create a spline of the fourth order by points, parameters and the attribute of closedness + with boundary conditions - given vectors of the first or the second derivatives.\n + Has 2 multiple internal knots, belongs to the class of differentiable (but not twice differentiable) functions. \~ + \param[in] bfstS - \ru Если true, то начальное граничное условие - вектор первой производной, иначе - вектор второй производной. + \en If true, then start boundary condition is the vector of the first derivative, otherwise - the vector of the second derivative. \~ + \param[in] bfstN - \ru Если true, то конечное граничное условие - вектор первой производной, иначе - вектор второй производной. + \en If true, then end boundary condition - vector of first derivative, otherwise - vector of second derivative. \~ + */ static MbNurbs3D * CreateNURBS4( const SArray &, const SArray &, const MbVector3D &, const MbVector3D &, bool cls, bool bfstS = true, bool bfstN = true ); - /** \brief \ru Интерполяция. - \en Interpolation. \~ - \details \ru Создать сплайн четвертого порядка по точкам, производным, параметрам и признаку замкнутости.\n - Имеет 2 кратных внутренних узла, принадлежит классу дифференцируемых ( но не дважды дифференцируемых ) функций. - \en Create a spline of the fourth order by points, derivatives, parameters and the attribute of closedness.\n - Has 2 multiple internal knots, belongs to the class of differentiable (but not twice differentiable) functions. \~ - */ + /** \brief \ru Интерполяция. + \en Interpolation. \~ + \details \ru Создать сплайн четвертого порядка по точкам, производным, параметрам и признаку замкнутости.\n + Имеет 2 кратных внутренних узла, принадлежит классу дифференцируемых ( но не дважды дифференцируемых ) функций. + \en Create a spline of the fourth order by points, derivatives, parameters and the attribute of closedness.\n + Has 2 multiple internal knots, belongs to the class of differentiable (but not twice differentiable) functions. \~ + */ static MbNurbs3D * CreateNURBS4( const SArray & points, const SArray & vectors, const SArray & params, bool cls ); - /// \ru Создать сплайн четвертого порядка c учетом изломов кривой \en Create a spline of the fourth order taking breaks of curve into account + /// \ru Создать сплайн четвертого порядка c учетом изломов кривой \en Create a spline of the fourth order taking breaks of curve into account static MbNurbs3D * CreateNURBS4WithBreak( const SArray &, const SArray &, const SArray &, bool cls ); - /** \brief \ru Интерполяция. - \en Interpolation. \~ - \details \ru Создать сплайн четвертого порядка по составному сплайну Безье четвертого порядка.\n - Внимание! Параметризация отлична от параметризации исходной кривой Безье. - \en Create a spline of the fourth order by a composite Bezier spline of the fourth order.\n - Attention! Parameterization is different from the parameterization of the source Bezier curve. \~ - */ + /** \brief \ru Интерполяция. + \en Interpolation. \~ + \details \ru Создать сплайн четвертого порядка по составному сплайну Безье четвертого порядка.\n + Внимание! Параметризация отлична от параметризации исходной кривой Безье. + \en Create a spline of the fourth order by a composite Bezier spline of the fourth order.\n + Attention! Parameterization is different from the parameterization of the source Bezier curve. \~ + */ static MbNurbs3D * CreateNURBS4( const MbBezier3D & ); - /** \brief \ru Создать сплайн. - \en Create NURBS. \~ - \details \ru Создать сплайн произвольного порядка через точки, с управлением касательными и кривизной в этих точках. - \en Create a spline of any order containing the given points with managing of tangent and curvature at these points.\~ - */ + /** \brief \ru Создать сплайн. + \en Create NURBS. \~ + \details \ru Создать сплайн произвольного порядка через точки, с управлением касательными и кривизной в этих точках. + \en Create a spline of any order containing the given points with managing of tangent and curvature at these points.\~ + */ static MbNurbs3D * CreateNURBS( size_t initDegree, const SArray & initPoints, const SArray & initParams, bool initClosed, RPArray & matingData ); - /** \brief \ru Разбить кривую. - \en Split the curve. \~ - \details \ru Разбить недифференцируемую NURBS-кривую четвертой степени в трижды кратном внутреннем узле.\n - Если внутренних трижды кратных узлов не существует, то в массив заносится копия кривой.\n - Если bline = true, то проверить вырожденность в прямую, если прямая - преобразовать в прямую. - \en Split the non-differentiable NURBS-curve of the fourth degree at an internal knot with multiplicity of three.\n - If there is no internal knots with multiplicity of three, then a copy of the curve is added to the array.\n - If bline = true, then check the curve for degeneration into a line, if it is a line - transform to a line. \~ - */ - bool BreakC0NURBS4( RPArray &, bool bline = true ) const; + /** \brief \ru Разбить кривую. + \en Split the curve. \~ + \details \ru Разбить недифференцируемую NURBS-кривую четвертой степени в трижды кратном внутреннем узле.\n + Если внутренних трижды кратных узлов не существует, то в массив заносится копия кривой.\n + Если bline = true, то проверить вырожденность в прямую, если прямая - преобразовать в прямую. + \en Split the non-differentiable NURBS-curve of the fourth degree at an internal knot with multiplicity of three.\n + If there is no internal knots with multiplicity of three, then a copy of the curve is added to the array.\n + If bline = true, then check the curve for degeneration into a line, if it is a line - transform to a line. \~ + */ + bool BreakC0NURBS4( RPArray &, bool bline = true ) const; - /// \ru Расширить незамкнутую NURBS-кривую по касательным. \en Extend an open NURBS-curve by tangents. - bool ExtendNurbs( double, double, bool bmerge = false ); + /// \ru Расширить незамкнутую NURBS-кривую по касательным. \en Extend an open NURBS-curve by tangents. + bool ExtendNurbs( double, double, bool bmerge = false ); - /// \ru Преобразовать узловой вектор в зажатый (если кривая замкнута и clm = false) или разжатый (если кривая не замкнута и clm = true). \en Transform knot vector to a clamped one (if the curve is closed and clm = false) or unclamped one (if the curve is open and clm = true). - bool UnClamped( bool clm, bool savePointsCount = false ); - /// \ru Преобразовать кривую в коническое сечение, если это возможно. \en Transform a curve into a conic section if it is possible. - MbCurve3D * ConvertToConic(); - /// \ru Разбить NURBS-кривую в местах, где кривая не дифференцируема. Если кривая дифференцируема, то добавляется копия кривой. \en Split a NURBS-curve at places where the curve is non-differentiable. If the curve is differentiable, then the curve copy is added. - bool BreakC0( c3d::SpaceCurvesSPtrVector &, double metricAcc = METRIC_EPSILON ); + /// \ru Преобразовать узловой вектор в зажатый (если кривая замкнута и clm = false) или разжатый (если кривая не замкнута и clm = true). \en Transform knot vector to a clamped one (if the curve is closed and clm = false) or unclamped one (if the curve is open and clm = true). + bool UnClamped( bool clm, bool savePointsCount = false ); + /// \ru Преобразовать кривую в коническое сечение, если это возможно. \en Transform a curve into a conic section if it is possible. + MbCurve3D * ConvertToConic(); + /// \ru Разбить NURBS-кривую в местах, где кривая не дифференцируема. Если кривая дифференцируема, то добавляется копия кривой. \en Split a NURBS-curve at places where the curve is non-differentiable. If the curve is differentiable, then the curve copy is added. + bool BreakC0( c3d::SpaceCurvesSPtrVector &, double metricAcc = METRIC_EPSILON ); - /** \brief \ru Замкнуть кривую. - \en Make the curve closed. \~ - \details \ru Замкнуть фактически замкнутую кривую.\n - То есть если первая и последняя точки кривой совпадают, но она реализована как незамкнутая, - то одна из совпадающих точек убирается и кривая делается замкнутой. - \en Make the actually closed curve closed.\n - That is, if the first and the last points of curve are coincident, but curve was implemented as open, - then one of the coincident points is took away and the curve becomes closed. \~ - */ - void FixClosedNurbs(); + /** \brief \ru Замкнуть кривую. + \en Make the curve closed. \~ + \details \ru Замкнуть фактически замкнутую кривую.\n + То есть если первая и последняя точки кривой совпадают, но она реализована как незамкнутая, + то одна из совпадающих точек убирается и кривая делается замкнутой. + \en Make the actually closed curve closed.\n + That is, if the first and the last points of curve are coincident, but curve was implemented as open, + then one of the coincident points is took away and the curve becomes closed. \~ + */ + void FixClosedNurbs(); /// \ru Получить значение параметра, соответствующего узловой точке с номером num. \en Get value of the parameter corresponding to a knot point with 'num' index. - double GetBSplineParameter ( size_t num ) const; + double GetBSplineParameter ( size_t num ) const; private: - bool CatchMemory( MbNurbs3DAuxiliaryData * cache ) const; // \ru Выделить память. \en Allocate memory. - void FreeMemory ( MbNurbs3DAuxiliaryData * cache ) const; // \ru Освободить память. \en Free memory. - void VerifyParam( double & t ) const; // \ru Загнать параметр t в параметрическую область кривой. \en Parameter set in the curve region. - void CalculateSegment( double & t, MbNurbs3DAuxiliaryData * cache ) const; - void CalculateSpline( ptrdiff_t n, MbNurbs3DAuxiliaryData * cache ) const; - void CalculateSplineWeight( double & t, ptrdiff_t n, MbNurbs3DAuxiliaryData * cache ) const; - bool InitSegments( MbNurbs3DAuxiliaryData * cache ) const; + bool CatchMemory( MbNurbs3DAuxiliaryData * cache ) const; // \ru Выделить память. \en Allocate memory. + void FreeMemory ( MbNurbs3DAuxiliaryData * cache ) const; // \ru Освободить память. \en Free memory. + void VerifyParam( double & t ) const; // \ru Загнать параметр t в параметрическую область кривой. \en Parameter set in the curve region. + void CalculateSegment( double & t, MbNurbs3DAuxiliaryData * cache ) const; + void CalculateSpline( ptrdiff_t n, MbNurbs3DAuxiliaryData * cache ) const; + void CalculateSplineWeight( double & t, ptrdiff_t n, MbNurbs3DAuxiliaryData * cache ) const; + bool InitSegments( MbNurbs3DAuxiliaryData * cache ) const; - // \ru Вычислить значения производных для заданного параметра, используя заданный кэш. \en Calculate derivatives of object for given parameter using defined cache. \~ - void DerivativesEx( double & t, bool ext, MbVector3D & fir, MbVector3D * sec, MbVector3D * thi, MbNurbs3DAuxiliaryData * ucache ) const; + // \ru Вычислить значения производных для заданного параметра, используя заданный кэш. \en Calculate derivatives of object for given parameter using defined cache. \~ + void DerivativesEx( double & t, bool ext, MbVector3D & fir, MbVector3D * sec, MbVector3D * thi, MbNurbs3DAuxiliaryData * ucache ) const; - void SetClamped(); // \ru Делаем зажатый узловой вектор. \en Set clamped knots vector. + void SetClamped(); // \ru Делаем зажатый узловой вектор. \en Set clamped knots vector. - void ResetMainCache() const; // \ru Очистить кэш главного потока. Использует блокировку кэша. \en Reset main thread cache. Use cache lock. + void ResetMainCache() const; // \ru Очистить кэш главного потока. Использует блокировку кэша. \en Reset main thread cache. Use cache lock. - MbNurbs3D * NurbsPlus( double tin, double tax ) const; + MbNurbs3D * NurbsPlus( double tin, double tax ) const; - /** \brief \ru Инициализация. - \en Initialization. \~ - \details \ru Сплайн, проходящий через заданные точки при заданных параметрах.\n - В случае замкнутости нужно передавать массив с совпадением первой и последней точек.\n - \en Spline passing through the given points at the given parameters.\n - In case of closedness it is necessary to pass the array with coincidence of the first and the last points.\n \~ - \param[in] degree - \ru Порядок сплайна. - \en A spline order. \~ - \param[in] cls - \ru Признак замкнутости. - \en Closedness attribute. \~ - \param[in] points - \ru Набор точек, через которые проходит сплайн. - \en Set of points which the spline passes through. \~ - \param[in] params - \ru Последовательность узловых параметров. - \en Sequence of knot parameters. \~ - \param[in] knots - \ru Неубывающая последовательность узлов. - \en Nondecreasing sequence of knots. \~ - */ - template - bool InitThroughTempl( size_t degree, - bool cls, - const PointsVector & points, - const ParamsVector & params, - ParamsVector * knots ); + /** \brief \ru Инициализация. + \en Initialization. \~ + \details \ru Сплайн, проходящий через заданные точки при заданных параметрах.\n + В случае замкнутости нужно передавать массив с совпадением первой и последней точек.\n + \en Spline passing through the given points at the given parameters.\n + In case of closedness it is necessary to pass the array with coincidence of the first and the last points.\n \~ + \param[in] degree - \ru Порядок сплайна. + \en A spline order. \~ + \param[in] cls - \ru Признак замкнутости. + \en Closedness attribute. \~ + \param[in] points - \ru Набор точек, через которые проходит сплайн. + \en Set of points which the spline passes through. \~ + \param[in] params - \ru Последовательность узловых параметров. + \en Sequence of knot parameters. \~ + \param[in] knots - \ru Неубывающая последовательность узлов. + \en Nondecreasing sequence of knots. \~ + */ + template + bool InitThroughTempl( size_t degree, + bool cls, + const PointsVector & points, + const ParamsVector & params, + ParamsVector * knots ); - // \ru BEG: Внутренние функции CreateNURBS4 по двум сопряжениям. \en BEG: Internal CreateNURBS4 functions by two conjugations. - // \ru Создать интерполяционный кубический NURBS, удовлетворяющий условиям сопряжения по касательным. \en Create an interpolation cubic NURBS meeting conditions of conjugation by tangents. - bool AttachG1_NURBS4( const SArray & points, - const SArray & params, - const c3d::PntMatingData3D & begData, - const c3d::PntMatingData3D & endData ); - // \ru Создать интерполяционный кубический NURBS, удовлетворяющий условиям сопряжения со вторым порядком гладкости. \en Create an interpolation cubic NURBS meeting conditions of conjugation with the second order of smoothness. - bool AttachG2_NURBS4( const SArray & points, - const SArray & params, - const c3d::PntMatingData3D & begData, - const c3d::PntMatingData3D & endData ); - // \ru END: Внутренние функции CreateNURBS4 по двум сопряжениям. \en END: Internal CreateNURBS4 functions by two conjugations. + // \ru BEG: Внутренние функции CreateNURBS4 по двум сопряжениям. \en BEG: Internal CreateNURBS4 functions by two conjugations. + // \ru Создать интерполяционный кубический NURBS, удовлетворяющий условиям сопряжения по касательным. \en Create an interpolation cubic NURBS meeting conditions of conjugation by tangents. + bool AttachG1_NURBS4( const SArray & points, + const SArray & params, + const c3d::PntMatingData3D & begData, + const c3d::PntMatingData3D & endData ); + // \ru Создать интерполяционный кубический NURBS, удовлетворяющий условиям сопряжения со вторым порядком гладкости. \en Create an interpolation cubic NURBS meeting conditions of conjugation with the second order of smoothness. + bool AttachG2_NURBS4( const SArray & points, + const SArray & params, + const c3d::PntMatingData3D & begData, + const c3d::PntMatingData3D & endData ); + // \ru END: Внутренние функции CreateNURBS4 по двум сопряжениям. \en END: Internal CreateNURBS4 functions by two conjugations. - // \ru BEG: Внутренние функции CreateNURBS4 по массиву сопряжений. \en BEG: Internal CreateNURBS4 functions by an array of conjugations. - // \ru Построение интерполяционного NURBS4 с возможными заданными управляющими параметрами. \en Create an interpolation NURBS4 with possibly given driving parameters. - bool CreateC2_NURBS4( const SArray & points, - MbeSplineParamType spType, - RPArray & inferredData, - const SArray & params, - MbeSplineCreateType useInitThrough, - bool cls = false ); - // \ru Построение интерполяционного незамкнутого NURBS4 в общем случае \en Create an interpolation open NURBS4 in general case - // \ru С возможными заданными управляющими параметрами в средних точках. \en With possibly given driving parameters at middle points. - // \ru Считаем, что данные для сопряжений заданы корректно. Этот факт проверяется до запуска функции. \en Consider that the given data for conjugations is correct. This fact is checked before calling the function. + // \ru BEG: Внутренние функции CreateNURBS4 по массиву сопряжений. \en BEG: Internal CreateNURBS4 functions by an array of conjugations. + // \ru Построение интерполяционного NURBS4 с возможными заданными управляющими параметрами. \en Create an interpolation NURBS4 with possibly given driving parameters. + bool CreateC2_NURBS4( const SArray & points, + MbeSplineParamType spType, + RPArray & inferredData, + const SArray & params, + MbeSplineCreateType useInitThrough, + bool cls = false ); + // \ru Построение интерполяционного незамкнутого NURBS4 в общем случае \en Create an interpolation open NURBS4 in general case + // \ru С возможными заданными управляющими параметрами в средних точках. \en With possibly given driving parameters at middle points. + // \ru Считаем, что данные для сопряжений заданы корректно. Этот факт проверяется до запуска функции. \en Consider that the given data for conjugations is correct. This fact is checked before calling the function. static MbNurbs3D * CreateC2Nurbs4Common( const SArray & points, RPArray & inferredData, const SArray & params, @@ -872,18 +877,18 @@ private: bool cls, MbeSplineCreateType useInitThrough, size_t deg = 4 ); - // \ru END: Внутренние функции CreateNURBS4 по массиву сопряжений. \en END: Internal CreateNURBS4 functions by an array of conjugations. + // \ru END: Внутренние функции CreateNURBS4 по массиву сопряжений. \en END: Internal CreateNURBS4 functions by an array of conjugations. - // \ru Расчет весовых функций и их первых производных. \en Calculation of weight functions and their first derivatives. - ptrdiff_t WeightFunctions ( double & x, CcArray & m ) const; - /// \ru Вычисление шага аппроксимации. \en Calculation of a step of approximation. - double StepD( double t, double sag, bool checkAngle, double angle = Math::lowRenderAng, MbNurbs3DAuxiliaryData * cache = nullptr ) const; - // \ru Вычисление шага аппроксимации сплайна второго порядка. \en Calculation of approximation step of second order spline. - double PolylineStep( double t, bool half, MbNurbs3DAuxiliaryData * cache ) const; - // \ru Уточнить проекцию \en Specify projection. - double SpecifyProjection( const MbCartPoint3D & pnt, double t, bool ext ) const; + // \ru Расчет весовых функций и их первых производных. \en Calculation of weight functions and their first derivatives. + ptrdiff_t WeightFunctions ( double & x, CcArray & m ) const; + /// \ru Вычисление шага аппроксимации. \en Calculation of a step of approximation. + double StepD( double t, double sag, bool checkAngle, double angle = Math::lowRenderAng, MbNurbs3DAuxiliaryData * cache = nullptr ) const; + // \ru Вычисление шага аппроксимации сплайна второго порядка. \en Calculation of approximation step of second order spline. + double PolylineStep( double t, bool half, MbNurbs3DAuxiliaryData * cache ) const; + // \ru Уточнить проекцию \en Specify projection. + double SpecifyProjection( const MbCartPoint3D & pnt, double t, bool ext ) const; - void operator = ( const MbNurbs3D & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbNurbs3D & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbNurbs3D ) }; diff --git a/C3d/Include/cur_nurbs_vector.h b/C3d/Include/cur_nurbs_vector.h index 84f10e0..ab4a425 100644 --- a/C3d/Include/cur_nurbs_vector.h +++ b/C3d/Include/cur_nurbs_vector.h @@ -113,4 +113,3 @@ inline void MbNURBSVector2D::Set( ptrdiff_t i, const MbNURBSVector2D & p, ptrdif #endif // __CUR_NURBS_VECTOR_H - diff --git a/C3d/Include/cur_offset_curve.h b/C3d/Include/cur_offset_curve.h index 82546f0..1727306 100644 --- a/C3d/Include/cur_offset_curve.h +++ b/C3d/Include/cur_offset_curve.h @@ -113,26 +113,26 @@ public : /** \ru \name Функции инициализации. \en \name Initialization functions. \{ */ - /** \brief \ru Инициализация по смещению и приращениям параметров. - \en Initialization by offset and increments of parameters. \~ - \details \ru Смещение задано на краях параметрической области базовой кривой и может изменяться по константному, линейному и кубическому законам.\n - Приращение параметров нужно использовать для изменения области определения кривой относительно базовой кривой. - \en The offset displacement is defined in the begin and the end of the parametric region of the base curve and can be changed by constant, linear and cubic laws.\n - Increment of parameters needs to be used for change of curve domain relative to base curve. \~ - \param[in] d1 - \ru Смещение в точке Tmin базовой кривой. - \en Offset distance on point Tmin of base curve. \~ - \param[in] d2 - \ru Смещение в точке Tmax базовой кривой. - \en Offset distance on point Tmax of base curve. \~ - \param[in] t - \ru Тип смещения точек: константный, линейный или кубический. - \en The offset type: constant, or linear, or cubic. \~ - \param[in] t1 - \ru Увеличение tmin параметра - \en Increment of tmin parameter \~ - \param[in] t2 - \ru Увеличение tmax параметра - \en Increment of tmax parameter \~ - */ - void Init( double d1, double d2, MbeOffsetType t, double t1, double t2 ); - void Init( double d, double t1, double t2 ); - void Init( double t1, double t2 ); + /** \brief \ru Инициализация по смещению и приращениям параметров. + \en Initialization by offset and increments of parameters. \~ + \details \ru Смещение задано на краях параметрической области базовой кривой и может изменяться по константному, линейному и кубическому законам.\n + Приращение параметров нужно использовать для изменения области определения кривой относительно базовой кривой. + \en The offset displacement is defined in the begin and the end of the parametric region of the base curve and can be changed by constant, linear and cubic laws.\n + Increment of parameters needs to be used for change of curve domain relative to base curve. \~ + \param[in] d1 - \ru Смещение в точке Tmin базовой кривой. + \en Offset distance on point Tmin of base curve. \~ + \param[in] d2 - \ru Смещение в точке Tmax базовой кривой. + \en Offset distance on point Tmax of base curve. \~ + \param[in] t - \ru Тип смещения точек: константный, линейный или кубический. + \en The offset type: constant, or linear, or cubic. \~ + \param[in] t1 - \ru Увеличение tmin параметра + \en Increment of tmin parameter \~ + \param[in] t2 - \ru Увеличение tmax параметра + \en Increment of tmax parameter \~ + */ + void Init( double d1, double d2, MbeOffsetType t, double t1, double t2 ); + void Init( double d, double t1, double t2 ); + void Init( double t1, double t2 ); /** \} */ /** \ru \name Функции описания области определения кривой. @@ -177,7 +177,7 @@ public : \{ */ // \ru Вычислить значения точки и производных для заданного параметра. \en Calculate point and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - MbCartPoint & pnt, MbVector & fir, MbVector * sec, MbVector * thir ) const override; + MbCartPoint & pnt, MbVector & fir, MbVector * sec, MbVector * thir ) const override; /** \} */ /** \ru \name Функции движения по кривой @@ -196,9 +196,8 @@ public : void Refresh() override; // \ru Сбросить все временные данные \en Reset all temporary data void PrepareIntegralData( const bool forced ) const override; // \ru Рассчитать временные (mutable) данные объекта. \en Calculate temporary (mutable) data of an object. - // BUG_54628 - // \ru Функция не работает для самопересекающейся кривой \en This function does not work for self-intersecting curve // \ru Проекция точки на кривую \en Point projection on the curve + // \ru Функция не работает для самопересекающейся кривой \en This function does not work for self-intersecting curve // BUG_54628 // virtual double PointProjection( const MbCartPoint & pnt ) const override; MbeState Deformation( const MbRect &, const MbMatrix & ) override; // \ru Деформация \en Deformation @@ -210,7 +209,7 @@ public : MbNurbs * NurbsCurve( const MbCurveIntoNurbsInfo & ) const override; - bool Break( MbNurbs &nurbs, double t1, double t2, ptrdiff_t degree ); + bool Break( MbNurbs &nurbs, double t1, double t2, ptrdiff_t degree ); bool IsBounded() const override; // \ru Признак ограниченной кривой \en Attribute of a bounded curve bool IsDegenerate( double eps = Math::LengthEps ) const override; // \ru Проверка вырожденности кривой \en Check for curve degeneracy @@ -229,7 +228,7 @@ public : double Curvature( double t ) const override; // \ru Кривизна кривой \en Curvature of the curve // \ru Сдвинуть параметр t на расстояние len \en Move parameter t on the distance len bool DistanceAlong( double & t1, double ln, int curveDir, double eps = Math::LengthEps, - VERSION version = Math::DefaultMathVersion() ) const override; + VERSION version = Math::DefaultMathVersion() ) const override; bool IsSimilarToCurve( const MbCurve & curve, double precision = PARAM_PRECISION ) const override; // \ru Подобные ли кривые для объединения (слива) \en Whether the curves are similar for merge (joining) void GetProperties( MbProperties & properties ) override; // \ru Выдать свойства объекта \en Get properties of the object @@ -241,66 +240,67 @@ public : // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. bool SetContinuousDerivativeLength( VERSION version, double epsilon = EPSILON ) override; - void SetBasisCurve( MbCurve & ); // \ru Установить базовую кривую \en Set the base curve - // \ru Тип смещения точек. \en The type of points offset. - MbeOffsetType GetOffsetType() const { return type; } - // \ru Постоянное ли смещение точек? \en Is const the offset type? - bool IsConstOffset() const { return ( (type == off_Empty) || (type == off_Const) ); } - // \ru Величина смещения. \en The offset distance. - double GetDistance( size_t i ) const { - i = i % 2; - if ( i == 0 ) - return offsetTmin; - return offsetTmax; - } - // \ru Средняя величина смещения. \en The average offset distance. - double GetDistance() const { return ( offsetTmin + offsetTmax ) / 2; } + void SetBasisCurve( MbCurve & ); // \ru Установить базовую кривую \en Set the base curve + // \ru Тип смещения точек. \en The type of points offset. + MbeOffsetType GetOffsetType() const { return type; } + // \ru Постоянное ли смещение точек? \en Is const the offset type? + bool IsConstOffset() const { return ( (type == off_Empty) || (type == off_Const) ); } + // \ru Величина смещения. \en The offset distance. + double GetDistance( size_t i ) const { + i = i % 2; + if ( i == 0 ) + return offsetTmin; + return offsetTmax; + } + // \ru Средняя величина смещения. \en The average offset distance. + double GetDistance() const { return ( offsetTmin + offsetTmax ) / 2; } - /** \brief \ru Установить величины смещения. - \en Set offset distances. \~ - \param[in] d - \ru Новая величина смещения - \en New offset distance. \~ - */ - void SetDistance( double d, size_t i ); - // \ru Установить постоянную величину смещения. Set new constant offset distance. - void SetDistance( double d ); + /** \brief \ru Установить величины смещения. + \en Set offset distances. \~ + \param[in] d - \ru Новая величина смещения + \en New offset distance. \~ + */ + void SetDistance( double d, size_t i ); + // \ru Установить постоянную величину смещения. Set new constant offset distance. + void SetDistance( double d ); void CalculateGabarit( MbRect & ) const override; // \ru Определить габаритный прямоугольник кривой. \en Detect the bounding box of a curve. double CalculateMetricLength() const override; // \ru Вычислить метрическую длину кривой. \en Calculate the metric length of a curve. - const MbRect & GetGabarit() const; - void SetDirtyGabarit() const; + const MbRect & GetGabarit() const; + void SetDirtyGabarit() const; const double & GetDmin() const { return deltaTmin; } // \ru Дать расширение начала \en Get extension of start const double & GetDmax() const { return deltaTmax; } // \ru Дать расширение конца \en Get extension of end - void SetDmin( double d ) { deltaTmin = d; } // \ru Установить расширение начала \en Set extension of start - void SetDmax( double d ) { deltaTmax = d; } // \ru Установить расширение конца \en Set extension of end + void SetDmin( double d ) { deltaTmin = d; } // \ru Установить расширение начала \en Set extension of start + void SetDmax( double d ) { deltaTmax = d; } // \ru Установить расширение конца \en Set extension of end - double GetBegExtend() const { return deltaTmin; } // \ru Дать расширение начала \en Get extension of start - double GetEndExtend() const { return deltaTmax; } // \ru Дать расширение конца \en Get extension of end - int ExtendedParam( double &t ) const; // \ru Проверка, лежит ли параметр в пределах \en Check if parameter is in range - void GetCurves( RPArray & curves ); // \ru Дать составляющие кривые \en Get curves + double GetBegExtend() const { return deltaTmin; } // \ru Дать расширение начала \en Get extension of start + double GetEndExtend() const { return deltaTmax; } // \ru Дать расширение конца \en Get extension of end + int ExtendedParam( double &t ) const; // \ru Проверка, лежит ли параметр в пределах \en Check if parameter is in range + void GetCurves( RPArray & curves ); // \ru Дать составляющие кривые \en Get curves - bool operator == ( const MbOffsetCurve & ) const; // \ru Проверка на равенство \en Check for equality - bool operator != ( const MbOffsetCurve & ) const; // \ru Проверка на неравенство \en Check for inequality + bool operator == ( const MbOffsetCurve & ) const; // \ru Проверка на равенство \en Check for equality + bool operator != ( const MbOffsetCurve & ) const; // \ru Проверка на неравенство \en Check for inequality - bool SubstrateParamOn( double &t, double &delta ) const; // \ru Находится ли параметр в пределах подложки \en Check if parameter is in the range of substrate - bool IsMatrixSingle() const { return transform.IsSingle(); } ///< \ru Является ли матрица преобразования единичной. \en Whether the transformation matrix is unit. - const MbMatrix & GetMatrix() const { return transform; } ///< \ru Матрица преобразования. \en A transformation matrix. + bool SubstrateParamOn( double &t, double &delta ) const; // \ru Находится ли параметр в пределах подложки \en Check if parameter is in the range of substrate + bool IsMatrixSingle() const { return transform.IsSingle(); } ///< \ru Является ли матрица преобразования единичной. \en Whether the transformation matrix is unit. + const MbMatrix & GetMatrix() const { return transform; } ///< \ru Матрица преобразования. \en A transformation matrix. /** \} */ private: - // \ru Вычисление эквидистанты и её производных. \en The offset calculation and it derivatives calculation. - double Offset0 ( double t ) const; - double OffsetT ( double t ) const; - double OffsetTT ( double t ) const; - double OffsetTTT( double t ) const; + // \ru Вычисление эквидистанты и её производных. \en The offset calculation and it derivatives calculation. + double Offset0 ( double t ) const; + double OffsetT ( double t ) const; + double OffsetTT ( double t ) const; + double OffsetTTT( double t ) const; - void operator = ( const MbOffsetCurve & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbOffsetCurve & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbOffsetCurve ) }; // MbOffsetCurve IMPL_PERSISTENT_OPS( MbOffsetCurve ) + #endif // __CUR_OFFSET_CURVE_H diff --git a/C3d/Include/cur_offset_curve3d.h b/C3d/Include/cur_offset_curve3d.h index fa9fc2e..a6232cd 100644 --- a/C3d/Include/cur_offset_curve3d.h +++ b/C3d/Include/cur_offset_curve3d.h @@ -125,7 +125,7 @@ public: \param[in] dt2 - \ru Изменение tmax параметра \en The change of tmax parameter \~ */ - void Init( double d1, double d2, MbeOffsetType t, double dt1, double dt2 ); + void Init( double d1, double d2, MbeOffsetType t, double dt1, double dt2 ); // \ru Общие функции математического объекта \en Common functions of the mathematical object @@ -166,7 +166,7 @@ public: //virtual void _ThirdDer ( double t, MbVector3D &td ) const; // \ru Третья производная по t \en The third derivative with respect to t // \ru Вычислить значения точки и производных для заданного параметра. \en Calculate point and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const override; + MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const override; double Step( double t, double sag ) const override; // \ru Вычисление шага аппроксимации \en Calculation of approximation step double DeviationStep( double t, double angle ) const override; @@ -189,55 +189,55 @@ public: /// \ru Смещение в начальной точке. \en Offset in the start point. const MbVector3D & GetOffsetVector() const { return offset; } - // \ru Тип смещения точек. \en The type of points offset. - MbeOffsetType GetOffsetType() const { return type; } - // \ru Постоянное ли смещение точек? \en Is const the offset type? - bool IsConstOffset() const { return ( (type == off_Empty) || (type == off_Const) ); } - // \ru Множитель смещения. \en The offset multiplier. - double GetFactor( size_t i ) const { - i = i % 2; - if ( i == 0 ) - return factorTmin; - return factorTmax; - } - // \ru Средний множитель смещения. \en The average offset multiplier. - double GetFactor() const { return ( factorTmin + factorTmax ) / 2; } + // \ru Тип смещения точек. \en The type of points offset. + MbeOffsetType GetOffsetType() const { return type; } + // \ru Постоянное ли смещение точек? \en Is const the offset type? + bool IsConstOffset() const { return ( (type == off_Empty) || (type == off_Const) ); } + // \ru Множитель смещения. \en The offset multiplier. + double GetFactor( size_t i ) const { + i = i % 2; + if ( i == 0 ) + return factorTmin; + return factorTmax; + } + // \ru Средний множитель смещения. \en The average offset multiplier. + double GetFactor() const { return ( factorTmin + factorTmax ) / 2; } - /** \brief \ru Установить множитель смещения. \en Set offset multiplier. \~ - \param[in] d - \ru Новый множитель смещения. \en New offset multiplier. \~ - */ - void SetFactor( double d, size_t i ); - // \ru Установить постоянный множитель смещения. Set new constant offset multiplier. - void SetFactor( double d ); - // \ru Проверить факторы и тип. \en Check factors and typr. - void CheckFactor(); + /** \brief \ru Установить множитель смещения. \en Set offset multiplier. \~ + \param[in] d - \ru Новый множитель смещения. \en New offset multiplier. \~ + */ + void SetFactor( double d, size_t i ); + // \ru Установить постоянный множитель смещения. Set new constant offset multiplier. + void SetFactor( double d ); + // \ru Проверить факторы и тип. \en Check factors and typr. + void CheckFactor(); const MbCube & GetGabarit() const; // \ru Выдать габарит кривой \en Get the bounding box of curve - bool IsSelfIntersect() const; - /** \brief \ru Поиск точек излома оффсетной кривой. - \en Search of break points of the offset curve. \~ - \details \ru Для нахождения точек точек излома используется характеристическая функция Ratio(), - представляющая собой разность аналитически и численно посчитанной производной деленную - на модуль аналитической производной и величину шага, использованного для численного рассчета производной. - Увеличение этой функции на порядок по сравнению с ее значением в гладкой области означает точку излома. \n - \en To find the break points using the characteristic function Ratio(), - which represents a difference between the analytical and numerical calculated derivative divided - by module of analytical derivative and step used for numerical calculation of the derivative. - Increase of this function on the order in comparison with its value in smooth region is a break point. \n \~ - \param[out] breakParams - \ru Массив параметров точек излома - \en Parameter array of break points \~ - */ - void FindBreakParams( SArray & breakParams ) const; - int ExtendedParam( double &t ) const; // \ru Проверка, лежит ли параметр в пределах \en Check if parameter is in range + bool IsSelfIntersect() const; + /** \brief \ru Поиск точек излома оффсетной кривой. + \en Search of break points of the offset curve. \~ + \details \ru Для нахождения точек точек излома используется характеристическая функция Ratio(), + представляющая собой разность аналитически и численно посчитанной производной деленную + на модуль аналитической производной и величину шага, использованного для численного рассчета производной. + Увеличение этой функции на порядок по сравнению с ее значением в гладкой области означает точку излома. \n + \en To find the break points using the characteristic function Ratio(), + which represents a difference between the analytical and numerical calculated derivative divided + by module of analytical derivative and step used for numerical calculation of the derivative. + Increase of this function on the order in comparison with its value in smooth region is a break point. \n \~ + \param[out] breakParams - \ru Массив параметров точек излома + \en Parameter array of break points \~ + */ + void FindBreakParams( SArray & breakParams ) const; + int ExtendedParam( double &t ) const; // \ru Проверка, лежит ли параметр в пределах \en Check if parameter is in range private: // \ru Вычисление множителя смещения и его производных. \en The offset multiplier and it derivatives. - double Factor0 ( double t ) const; - double FactorT ( double t ) const; - double FactorTT ( double t ) const; - double FactorTTT( double t ) const; + double Factor0 ( double t ) const; + double FactorT ( double t ) const; + double FactorTT ( double t ) const; + double FactorTTT( double t ) const; - void operator = ( const MbOffsetCurve3D & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbOffsetCurve3D & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbOffsetCurve3D ) }; diff --git a/C3d/Include/cur_plane_curve.h b/C3d/Include/cur_plane_curve.h index 193776e..085c200 100644 --- a/C3d/Include/cur_plane_curve.h +++ b/C3d/Include/cur_plane_curve.h @@ -52,8 +52,8 @@ public : public : VISITING_CLASS( MbPlaneCurve ); - void Init( const MbPlaneCurve &init ); - void Init( const MbPlacement3D &pl, MbCurve &initCurve ); + void Init( const MbPlaneCurve &init ); + void Init( const MbPlacement3D &pl, MbCurve &initCurve ); // \ru Общие функции математического объекта \en Common functions of the mathematical object @@ -96,12 +96,11 @@ public : void _Normal ( double t, MbVector3D & ) const override; // \ru Вектор главной нормали \en Vector of the principal normal // \ru Вычислить значения точки и производных для заданного параметра. \en Calculate point and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const override; + MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const override; MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & ) const override; MbCurve3D * NurbsCurve( const MbNurbsParameters & ) const override; - MbCurve3D * Trimmed( double t1, double t2, int sense ) const override; // \ru Создание усеченной кривой \en Creation of a trimmed curve void Inverse( MbRegTransform * iReg = nullptr ) override; // \ru Изменить направление \en Change direction @@ -128,9 +127,9 @@ public : double DistanceToPlace( const MbPlacement3D & place, double & t0, double & angle ) const override; MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = nullptr, - VERSION version = Math::DefaultMathVersion(), bool * coincParams = nullptr ) const override; // \ru Дать плоскую проекцию кривой \en Get a planar projection of curve + VERSION version = Math::DefaultMathVersion(), bool * coincParams = nullptr ) const override; // \ru Дать плоскую проекцию кривой \en Get a planar projection of curve MbCurve * GetMapPsp( const MbMatrix3D &, double zNear, - MbRect1D * pRgn = nullptr ) const override; + MbRect1D * pRgn = nullptr ) const override; double GetRadius() 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 curve axis @@ -151,17 +150,17 @@ public : // \ru Заполнить плейсемент, если кривая плоская \en Fill the placement if curve is planar bool GetPlacement( MbPlacement3D & place, PlanarCheckParams params = PlanarCheckParams() ) const override; - MbCurve * GetCurve ( const MbPlacement3D & , MbMatrix & ) const; // \ru Дать плоскую кривую \en Get the plane curve - MbCurve * MakeCurve( const MbPlacement3D & ) const; - MbCurve3D * MakeCurve() const; // \ru Дать пространственную кривую \en Get the spatial curve + MbCurve * GetCurve ( const MbPlacement3D & , MbMatrix & ) const; // \ru Дать плоскую кривую \en Get the plane curve + MbCurve * MakeCurve( const MbPlacement3D & ) const; + MbCurve3D * MakeCurve() const; // \ru Дать пространственную кривую \en Get the spatial curve - void SetCurve( const MbCurve & ); // \ru Заменить плоскую кривую \en Replace the plane curve - bool SetLimitParam( double newTMin, double newTMax ); // \ru Установить область изменения параметра. \en Set range of parameter. - void SetOrigin( const MbCartPoint3D & org ) { position.SetOrigin(org); } + void SetCurve( const MbCurve & ); // \ru Заменить плоскую кривую \en Replace the plane curve + bool SetLimitParam( double newTMin, double newTMax ); // \ru Установить область изменения параметра. \en Set range of parameter. + void SetOrigin( const MbCartPoint3D & org ) { position.SetOrigin(org); } - const MbPlacement3D & GetPlacement() const { return position; } - const MbCurve & GetCurve() const { return *curve; } // \ru Дать плоскую кривую \en Get the plane curve - MbCurve & SetCurve() { return *curve; } // \ru Дать плоскую кривую \en Get the plane curve + const MbPlacement3D & GetPlacement() const { return position; } + const MbCurve & GetCurve() const { return *curve; } // \ru Дать плоскую кривую \en Get the plane curve + MbCurve & SetCurve() { return *curve; } // \ru Дать плоскую кривую \en Get the plane curve // \ru Является ли объект смещением? \en Is the object a shift? bool IsShift( const MbSpaceItem &, MbVector3D &, bool & isSame, double accuracy = LENGTH_EPSILON ) const override; @@ -173,14 +172,18 @@ public : /// \ ru Определение точек излома кривой. \en The determination of curve smoothness break points. void BreakPoints( std::vector & vBreaks, double precision = ANGLE_REGION ) const override; + // \ru Продлить кривую. \en Extend the curve. \~ + MbResultType Extend( const MbCurveExtensionParameters & parameters, c3d::SpaceCurveSPtr & resCurve ) const override; + private: - void operator = ( const MbPlaneCurve & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbPlaneCurve & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbPlaneCurve ) }; IMPL_PERSISTENT_OPS( MbPlaneCurve ) + //------------------------------------------------------------------------------ /** \brief \ru Cоздать пространственную кривую. \en Create a spatial curve. \~ diff --git a/C3d/Include/cur_point_curve.h b/C3d/Include/cur_point_curve.h index c32969a..1f8380c 100644 --- a/C3d/Include/cur_point_curve.h +++ b/C3d/Include/cur_point_curve.h @@ -51,12 +51,12 @@ public : /** \ru \name Функции кривой, вырожденной в точку. \en \name Functions of curve degenerated to a point. \{ */ - void Init( const MbCartPoint &p, double t1, double t2, bool cl ); - void Init( double t1, double t2, bool cl ); - void Init( const MbCartPoint &p ); - void SetTMin ( double t ) { tmin = t; } - void SetTMax ( double t ) { tmax = t; } - void SetClosed( bool cl ) { closed = cl; } + void Init( const MbCartPoint &p, double t1, double t2, bool cl ); + void Init( double t1, double t2, bool cl ); + void Init( const MbCartPoint &p ); + void SetTMin ( double t ) { tmin = t; } + void SetTMax ( double t ) { tmax = t; } + void SetClosed( bool cl ) { closed = cl; } /** \} */ /** \ru \name Общие функции геометрического объекта. @@ -117,7 +117,7 @@ public : \{ */ // \ru Вычислить значения точки и производных для заданного параметра. \en Calculate point and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - MbCartPoint & pnt, MbVector & fir, MbVector * sec, MbVector * thir ) const override; + MbCartPoint & pnt, MbVector & fir, MbVector * sec, MbVector * thir ) const override; /** \} */ /** \ru \name Функции движения по кривой @@ -175,12 +175,13 @@ public : /** \} */ private: - void CheckParameter( double & t ) const; - void operator = ( const MbPointCurve & ); // \ru Не реализовано. \en Not implemented. + void CheckParameter( double & t ) const; + void operator = ( const MbPointCurve & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbPointCurve ) }; // MbPointCurve IMPL_PERSISTENT_OPS( MbPointCurve ) + #endif // __CUR_POINT_CURVE_H diff --git a/C3d/Include/cur_polycurve.h b/C3d/Include/cur_polycurve.h index ae94850..3723dbd 100644 --- a/C3d/Include/cur_polycurve.h +++ b/C3d/Include/cur_polycurve.h @@ -297,25 +297,25 @@ public : virtual size_t GetParamsCount() const = 0; ///< \ru Выдать количество параметров. \en Get count of parameters. virtual void GetTList( SArray & params ) const; - size_t GetPointListCount() const { return pointList.Count(); } ///< \ru Выдать количество характерный точек. \en Get count of control points. - ptrdiff_t GetPointListMaxIndex() const { return pointList.MaxIndex(); } ///< \ru Выдать максимальный индекс массива контрольных точек. \en Get maximal index of array of control points. + size_t GetPointListCount() const { return pointList.Count(); } ///< \ru Выдать количество характерный точек. \en Get count of control points. + ptrdiff_t GetPointListMaxIndex() const { return pointList.MaxIndex(); } ///< \ru Выдать максимальный индекс массива контрольных точек. \en Get maximal index of array of control points. - template - void GetPoints( PointsVector & pnts ) const { std::copy( pointList.begin(), pointList.end(), std::back_inserter( pnts ) ); } ///< \ru Вернуть массив контрольных точек. \en Get array of control points. - void GetPointList( SArray & pnts ) const { pnts.assign( pointList.begin(), pointList.end() ); } ///< \ru Вернуть массив контрольных точек. \en Get array of control points. - void GetPointList( c3d::ParamPointsVector & pnts ) const { pnts.assign( pointList.begin(), pointList.end() ); } ///< \ru Вернуть массив контрольных точек. \en Get array of control points. + template + void GetPoints( PointsVector & pnts ) const { std::copy( pointList.begin(), pointList.end(), std::back_inserter( pnts ) ); } ///< \ru Вернуть массив контрольных точек. \en Get array of control points. + void GetPointList( SArray & pnts ) const { pnts.assign( pointList.begin(), pointList.end() ); } ///< \ru Вернуть массив контрольных точек. \en Get array of control points. + void GetPointList( c3d::ParamPointsVector & pnts ) const { pnts.assign( pointList.begin(), pointList.end() ); } ///< \ru Вернуть массив контрольных точек. \en Get array of control points. - bool ReplacePoints( const SArray & pnts ); ///< \ru Заменить набор контрольных точек. \en Replace the set of control points. - bool ReplacePoints( const std::vector & pnts ); ///< \ru Заменить набор контрольных точек. \en Replace the set of control points. + bool ReplacePoints( const SArray & pnts ); ///< \ru Заменить набор контрольных точек. \en Replace the set of control points. + bool ReplacePoints( const std::vector & pnts ); ///< \ru Заменить набор контрольных точек. \en Replace the set of control points. const MbCartPoint & GetPointList( size_t i ) const { return pointList[i]; } ///< \ru Вернуть характерную точку с заданным индексом. \en Get control point with the given index. MbCartPoint & SetPointList( size_t i ) { Refresh(); return pointList[i]; } ///< \ru Вернуть характерную точку с заданным индексом. \en Get control point with the given index. - ptrdiff_t GetUppIndex() const { return uppIndex; } ///< \ru Вернуть максимальный индекс массива контрольных точек. \en Get the maximal index of array of control points. - size_t GetSegmentsCount() const { return (uppIndex > 0) ? (uppIndex + (!!closed)) : 0; } ///< \ru Вернуть количество интервалов. \en Get count of ranges. + ptrdiff_t GetUppIndex() const { return uppIndex; } ///< \ru Вернуть максимальный индекс массива контрольных точек. \en Get the maximal index of array of control points. + size_t GetSegmentsCount() const { return (uppIndex > 0) ? (uppIndex + (!!closed)) : 0; } ///< \ru Вернуть количество интервалов. \en Get count of ranges. - template - void GetLineSegments( SegmentsVector & segments, double eps = PARAM_PRECISION ) const; ///< \ru Выдать массив отрезков. \en Get the array of segments. + template + void GetLineSegments( SegmentsVector & segments, double eps = PARAM_PRECISION ) const; ///< \ru Выдать массив отрезков. \en Get the array of segments. /** \brief \ru Дать информацию для функции NurbsCurve. \en Get information for NurbsCurve function. \~ @@ -340,21 +340,22 @@ public : \param[in] t2 - \ru Параметр предшествующей pmax характерной точки. \en Parameter of the control point preceding 'pmax' . \~ */ - bool NurbsParam( double epsilon, double & pmin, double & pmax, - ptrdiff_t & i1, double & t1, ptrdiff_t & i2, double & t2 ) const; + bool NurbsParam( double epsilon, double & pmin, double & pmax, + ptrdiff_t & i1, double & t1, ptrdiff_t & i2, double & t2 ) const; /** \} */ protected: + virtual bool CanChangeClosed() const; ///< \ru Определить, можно ли поменять признак замкнутости. \en Determine whether it is possible to change an attribute of closedness. - // \ru Сдвинуть параметр t на расстояние len. \en Move parameter t on the metric distance len. - bool CompositeDistanceAlong( double & t, double len, int curveDir, double eps, const SArray & tList ) const; - // \ru Рассчитать метрическую длину сегмента кривой. \en Calculate metric length of curve segment. - double SegmentCalculateLength( double w1, double w2, size_t n, double * x, double * w ) const; - // \ru Сдвинуть параметр t на расстояние len. \en Move parameter t on the metric distance len. - bool SegmentDistanceAlong( double & t1, double ln, int curveDir, double eps, double stepMax, size_t n, double * x, double * w ) const; + // \ru Сдвинуть параметр t на расстояние len. \en Move parameter t on the metric distance len. + bool CompositeDistanceAlong( double & t, double len, int curveDir, double eps, const SArray & tList ) const; + // \ru Рассчитать метрическую длину сегмента кривой. \en Calculate metric length of curve segment. + double SegmentCalculateLength( double w1, double w2, size_t n, double * x, double * w ) const; + // \ru Сдвинуть параметр t на расстояние len. \en Move parameter t on the metric distance len. + bool SegmentDistanceAlong( double & t1, double ln, int curveDir, double eps, double stepMax, size_t n, double * x, double * w ) const; private: - void operator = ( const MbPolyCurve & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbPolyCurve & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS( MbPolyCurve ) }; // MbPolyCurve diff --git a/C3d/Include/cur_polycurve3d.h b/C3d/Include/cur_polycurve3d.h index 34b8ca1..9d4570a 100644 --- a/C3d/Include/cur_polycurve3d.h +++ b/C3d/Include/cur_polycurve3d.h @@ -81,7 +81,7 @@ public : //virtual double GetTMax() const = 0; // \ru Вернуть максимальное значение параметра \en Get the maximum value of parameter //virtual double GetTMin() const = 0; // \ru Вернуть минимальное значение параметра \en Get the minimum value of parameter bool IsClosed() const override; // \ru Замкнутость кривой \en A curve closedness - //virtual void Inverse( MbRegTransform * iReg = nullptr ) = 0; // \ru Изменить направление \en Change direction + //virtual void Inverse( MbRegTransform * iReg = nullptr ) = 0; // \ru Изменить направление \en Change direction double GetMetricLength() const override; // \ru Выдать метрическую длину ограниченной кривой \en Get metric length of bounded curve double GetLengthEvaluation() const override; // \ru Оценка метрической длины кривой \en Estimation of metric length of the curve @@ -116,38 +116,38 @@ public : const MbCube & GetGabarit() const; // \ru Выдать габарит кривой \en Get bounding box of curve - size_t GetPointListCount() const { return pointList.Count(); } - ptrdiff_t GetPointListMaxIndex() const { return pointList.MaxIndex(); } + size_t GetPointListCount() const { return pointList.Count(); } + ptrdiff_t GetPointListMaxIndex() const { return pointList.MaxIndex(); } - template - void GetPoints( PointsVector & pnts ) const { std::copy( pointList.begin(), pointList.end(), std::back_inserter( pnts ) ); } ///< \ru Вернуть массив контрольных точек. \en Get array of control points. - void GetPointList( SArray & pnts ) const { pnts.assign( pointList.begin(), pointList.end() ); } // \ru Получить характерные точки \en Get control points - void GetPointList( c3d::SpacePointsVector & pnts ) const { pnts.assign( pointList.begin(), pointList.end() ); } // \ru Получить характерные точки \en Get control points + template + void GetPoints( PointsVector & pnts ) const { std::copy( pointList.begin(), pointList.end(), std::back_inserter( pnts ) ); } ///< \ru Вернуть массив контрольных точек. \en Get array of control points. + void GetPointList( SArray & pnts ) const { pnts.assign( pointList.begin(), pointList.end() ); } // \ru Получить характерные точки \en Get control points + void GetPointList( c3d::SpacePointsVector & pnts ) const { pnts.assign( pointList.begin(), pointList.end() ); } // \ru Получить характерные точки \en Get control points const MbCartPoint3D & GetPointList( size_t i ) const { return pointList[i]; } // \ru Характерные точки \en Control points MbCartPoint3D & SetPointList( size_t i ) { return pointList[i]; } // \ru Характерные точки \en Control points - ptrdiff_t GetUppIndex() const { return uppIndex; } - size_t GetSegmentsCount() const { return (uppIndex > 0) ? (uppIndex + (!!closed)) : 0; } + ptrdiff_t GetUppIndex() const { return uppIndex; } + size_t GetSegmentsCount() const { return (uppIndex > 0) ? (uppIndex + (!!closed)) : 0; } - template - void GetLineSegments( SegmentsVector & segments, double eps = PARAM_REGION ) const; ///< \ru Выдать массив отрезков. \en Get the array of segments. + template + void GetLineSegments( SegmentsVector & segments, double eps = PARAM_REGION ) const; ///< \ru Выдать массив отрезков. \en Get the array of segments. - // \ru Дать информацию для функции NurbsCurve \en Get information for NurbsCurve function - bool NurbsParam( double epsilon, double & pmin, double & pmax, - ptrdiff_t & i1, double & t1, ptrdiff_t & i2, double & t2 ) const; + // \ru Дать информацию для функции NurbsCurve \en Get information for NurbsCurve function + bool NurbsParam( double epsilon, double & pmin, double & pmax, + ptrdiff_t & i1, double & t1, ptrdiff_t & i2, double & t2 ) const; protected: - // \ru Сдвинуть параметр t на расстояние len. \en Move parameter t on the metric distance len. - bool CompositeDistanceAlong( double & t, double len, int curveDir, double eps, const SArray & tList ) const; - // \ru Рассчитать метрическую длину сегмента кривой. \en Calculate metric length of curve segment. - double SegmentCalculateLength( double w1, double w2, size_t n, double * x, double * w ) const; - // \ru Сдвинуть параметр t на расстояние len. \en Move parameter t on the metric distance len. - bool SegmentDistanceAlong( double & t1, double ln, int curveDir, double eps, double stepMax, size_t n, double * x, double * w ) const; + // \ru Сдвинуть параметр t на расстояние len. \en Move parameter t on the metric distance len. + bool CompositeDistanceAlong( double & t, double len, int curveDir, double eps, const SArray & tList ) const; + // \ru Рассчитать метрическую длину сегмента кривой. \en Calculate metric length of curve segment. + double SegmentCalculateLength( double w1, double w2, size_t n, double * x, double * w ) const; + // \ru Сдвинуть параметр t на расстояние len. \en Move parameter t on the metric distance len. + bool SegmentDistanceAlong( double & t1, double ln, int curveDir, double eps, double stepMax, size_t n, double * x, double * w ) const; private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbPolyCurve3D & ); + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbPolyCurve3D & ); DECLARE_PERSISTENT_CLASS( MbPolyCurve3D ) }; diff --git a/C3d/Include/cur_polyline.h b/C3d/Include/cur_polyline.h index c463b65..8646b8a 100644 --- a/C3d/Include/cur_polyline.h +++ b/C3d/Include/cur_polyline.h @@ -136,41 +136,41 @@ public : \{ */ // \ru Вычислить значения точки и производных для заданного параметра. \en Calculate point and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - MbCartPoint & pnt, MbVector & fir, MbVector * sec, MbVector * thir ) const override; + MbCartPoint & pnt, MbVector & fir, MbVector * sec, MbVector * thir ) const override; /** \} */ /** \ru \name Функции инициализации кривой. \en \name Initialization functions of a curve. \{ */ - /// \ru Инициализация по другой ломаной. \en Initialization by another polyline. - void Init( const MbPolyline & ); - /// \ru Инициализация по точкам и признаку замкнутости. \en Initialization by points and an attribute of closedness. - template - bool Init( const PointsVector & initList, bool cls ) - { - if ( initList.size() > 1 ) { - pointList.clear(); - pointList = initList; - uppIndex = (ptrdiff_t)pointList.size() - 1; - closed = cls; - // if curve is closed then the start and the end points have to be different - if ( (uppIndex > 1) && closed && c3d::EqualPoints( pointList.front(), pointList.back(), Math::LengthEps ) ) { - closed = true; - pointList.erase( pointList.begin() + uppIndex ); - uppIndex--; - } - segmentsCount = (uppIndex > 0) ? ( uppIndex + !!closed ) : 0; - Refresh(); // сбросить кривую - return true; - } - return false; - } - /// \ru Построение прямоугольника. \en Construction of a rectangle. - void Init( const MbCartPoint & p1, const MbCartPoint & p2 ); - /// \ru Построение правильного многоугольника. \en Construction of a regular polygon. - void Init( ptrdiff_t nVertex, const MbCartPoint & pc, double rad, const MbCartPoint & on, bool describe ); - /// \ru Построение наклонного прямоугольника. \en Constructor of an inclined rectangle. - void Init( const MbCartPoint & p1, double height, double weight, const MbDirection & angle ); + /// \ru Инициализация по другой ломаной. \en Initialization by another polyline. + void Init( const MbPolyline & ); + /// \ru Инициализация по точкам и признаку замкнутости. \en Initialization by points and an attribute of closedness. + template + bool Init( const PointsVector & initList, bool cls ) + { + if ( initList.size() > 1 ) { + pointList.clear(); + pointList = initList; + uppIndex = (ptrdiff_t)pointList.size() - 1; + closed = cls; + // if curve is closed then the start and the end points have to be different + if ( (uppIndex > 1) && closed && c3d::EqualPoints( pointList.front(), pointList.back(), Math::LengthEps ) ) { + closed = true; + pointList.erase( pointList.begin() + uppIndex ); + uppIndex--; + } + segmentsCount = (uppIndex > 0) ? ( uppIndex + !!closed ) : 0; + Refresh(); // сбросить кривую + return true; + } + return false; + } + /// \ru Построение прямоугольника. \en Construction of a rectangle. + void Init( const MbCartPoint & p1, const MbCartPoint & p2 ); + /// \ru Построение правильного многоугольника. \en Construction of a regular polygon. + void Init( ptrdiff_t nVertex, const MbCartPoint & pc, double rad, const MbCartPoint & on, bool describe ); + /// \ru Построение наклонного прямоугольника. \en Constructor of an inclined rectangle. + void Init( const MbCartPoint & p1, double height, double weight, const MbDirection & angle ); /** \} */ /** \ru \name Общие функции кривой @@ -206,15 +206,15 @@ public : void CalculateLocalGabarit( const MbMatrix & into, MbRect & local ) const override; // \ru Добавь в прям-к свой габарит с учетом матрицы \en Add your own gabarit taking the matrix into account void CalculateGabarit ( MbRect & ) const override; // \ru Определить габариты кривой \en Determine the bounding box of a curve - // \ru Сдвинуть параметр t на расстояние len по направлению \en Translate parameter 't' by distance 'len' along the direction + // \ru Сдвинуть параметр t на расстояние len по направлению \en Translate parameter 't' by distance 'len' along the direction bool DistanceAlong( double & t, double len, int curveDir, double eps = Math::LengthEps, - VERSION version = Math::DefaultMathVersion() ) const override; + VERSION version = Math::DefaultMathVersion() ) const override; double DistanceToPoint( const MbCartPoint & to ) const override; // \ru Расстояние до точки \en Distance to a point bool DistanceToPointIfLess( const MbCartPoint & toP, double & d ) const override; // \ru Расстояние до точки, если оно меньше d \en Distance to a point if it is less than 'd' bool GetMiddlePoint( MbCartPoint & midPoint ) const override; // \ru Выдать среднюю точку кривой \en Get mid-point of a curve bool GoThroughPoint( MbCartPoint & ) override; // \ru Пройти через точку \en Pass through point - ptrdiff_t GoThroughPoint( double t, MbCartPoint & p, double eps ); + ptrdiff_t GoThroughPoint( double t, MbCartPoint & p, double eps ); /** \} */ /** \ru \name Общие функции полигональной кривой @@ -231,15 +231,15 @@ public : void IntersectVertical ( double x, SArray & ) const override; // \ru Пересечение с вертикальной прямой \en Intersection with a vertical line void SelfIntersect( SArray &, double metricEps = Math::LengthEps ) const override; // \ru Самопересечение полилинии \en Self-intersection of a polyline - // \ru Прямые, проходящие под углом к оси 0X и касательные к кривой \en Lines passing angularly to the 0X axis and tangent to the curve + // \ru Прямые, проходящие под углом к оси 0X и касательные к кривой \en Lines passing angularly to the 0X axis and tangent to the curve void Isoclinal( const MbVector & angle, SArray & tFind ) const override; bool GetCentre( MbCartPoint & ) const override; // \ru Выдать центр полилинии \en Get center of a polyline bool GetWeightCentre( MbCartPoint & ) const override; // \ru Выдать центр тяжести кривой \en Get the center of gravity of the curve size_t GetCount() const override; // \ru Количество разбиений для прохода в операциях \en Count of subdivisions for pass in operations - void CheckParameter( double & ) const; ///< \ru Проверка параметра. \en Check parameter. - ptrdiff_t ChangeThroughPoint( const MbCartPoint & ); + void CheckParameter( double & ) const; ///< \ru Проверка параметра. \en Check parameter. + ptrdiff_t ChangeThroughPoint( const MbCartPoint & ); void InsertPoint( ptrdiff_t index, const MbCartPoint & pnt ) override; // \ru Вставить точку по индексу \en Insert point by index void InsertPoint( double t, const MbCartPoint & pnt, double, double ) override; // \ru Вставить точку \en Insert a point @@ -247,8 +247,8 @@ public : double GetParam( ptrdiff_t i ) const override; size_t GetParamsCount() const override; - double Area() const; // \ru Площадь замкнутого многоугольника \en Area of closed a polygon - int Orientation() const; // \ru Ориентация замкнутого многоугольника \en Orientation of a closed polygon + double Area() const; // \ru Площадь замкнутого многоугольника \en Area of closed a polygon + int Orientation() const; // \ru Ориентация замкнутого многоугольника \en Orientation of a closed polygon bool IsDegenerate( double eps = Math::LengthEps ) const override; // \ru Проверка вырожденности кривой \en Check for curve degeneracy bool IsSmoothConnected( double angleEps ) const override; // \ru Являются ли стыки контура\кривой гладкими? \en Whether the joints of a contour\curve are smooth. @@ -265,76 +265,77 @@ public : \en \name Functions of polyline \{ */ - void Trimm( SArray & point, double t1, double t2, double eps = Math::LengthEps ) const; + void Trimm( SArray & point, double t1, double t2, double eps = Math::LengthEps ) const; - // \ru Выдать среднюю точку сегмента полилинии \en Get mid-point of a segment of a polyline - bool GetSegmentMiddlePoint( const MbCartPoint & from, MbCartPoint & midPoint ) const; - // \ru Выдать линейный сегмент полилинии \en Get linear segment of a polyline - bool GetLinearSegment( const MbCartPoint & from, MbCartPoint & p1, MbCartPoint & p2 ) const; - bool GetSegmentLength( const MbCartPoint & from, double & length ) const; // \ru Выдать длину сегмента полилинии \en Get length of segment of a polyline - ptrdiff_t FindNearestSegment( const MbCartPoint & from ) const; // \ru Найти ближайший к точке сегмент полилинии \en Find the segment of polyline nearest to a point - MbContour * CreateContour() const; // \ru Сделать контур из полилинии \en Create a contour from a polyline - // \ru Вставка фаски между двумя соседними элементами \en Insert a chamfer between two neighboring elements - bool ChamferTwoSegments( ptrdiff_t & index, double len, double angle, - bool type, bool firstSeg = true ); - bool Chamfer( double len, double angle, bool type ); // \ru Вставка фаски. \en Insertion of the chamfer. - MbeState RemoveChamfer( const MbCartPoint & pnt ); // \ru Удалить фаску полилинии. \en Remove a chamfer of a polyline. - // \ru Построить точки и параметры для гладкого сплайна. \en Create points and parameters for a smooth spline. - bool GetSplinePoints( SArray & points, SArray & arParams ) const; - MbCubicSpline * CubicSpline() const; // \ru Построить гладкий сплайн из ломаной. \en Create a smooth spline from a polyline. + // \ru Выдать среднюю точку сегмента полилинии \en Get mid-point of a segment of a polyline + bool GetSegmentMiddlePoint( const MbCartPoint & from, MbCartPoint & midPoint ) const; + // \ru Выдать линейный сегмент полилинии \en Get linear segment of a polyline + bool GetLinearSegment( const MbCartPoint & from, MbCartPoint & p1, MbCartPoint & p2 ) const; + bool GetSegmentLength( const MbCartPoint & from, double & length ) const; // \ru Выдать длину сегмента полилинии \en Get length of segment of a polyline + ptrdiff_t FindNearestSegment( const MbCartPoint & from ) const; // \ru Найти ближайший к точке сегмент полилинии \en Find the segment of polyline nearest to a point + MbContour * CreateContour() const; // \ru Сделать контур из полилинии \en Create a contour from a polyline + // \ru Вставка фаски между двумя соседними элементами \en Insert a chamfer between two neighboring elements + bool ChamferTwoSegments( ptrdiff_t & index, double len, double angle, + bool type, bool firstSeg = true ); + bool Chamfer( double len, double angle, bool type ); // \ru Вставка фаски. \en Insertion of the chamfer. + MbeState RemoveChamfer( const MbCartPoint & pnt ); // \ru Удалить фаску полилинии. \en Remove a chamfer of a polyline. + // \ru Построить точки и параметры для гладкого сплайна. \en Create points and parameters for a smooth spline. + bool GetSplinePoints( SArray & points, SArray & arParams ) const; + MbCubicSpline * CubicSpline() const; // \ru Построить гладкий сплайн из ломаной. \en Create a smooth spline from a polyline. - ptrdiff_t GetSegmentsCount() const { return segmentsCount; } + ptrdiff_t GetSegmentsCount() const { return segmentsCount; } - double Step ( double t, double sag, ThreeStates dir ) const; ///< \ru Шаг параметра с учетом радиуса кривизны. \en Step of parameter with consideration of curvature. - double DeviationStep( double t, double angle, ThreeStates dir ) const; ///< \ru Шаг параметра по заданному углу отклонения касательной. \en Step of parameter by a given angle of deviation of tangent. + double Step ( double t, double sag, ThreeStates dir ) const; ///< \ru Шаг параметра с учетом радиуса кривизны. \en Step of parameter with consideration of curvature. + double DeviationStep( double t, double angle, ThreeStates dir ) const; ///< \ru Шаг параметра по заданному углу отклонения касательной. \en Step of parameter by a given angle of deviation of tangent. - /** \brief \ru Определить точки пересечения с отрезком. - \en Determine points of intersection with a line segment. \~ - \details \ru Определить точки пересечения ломаной и отрезка. \n - \en Determine intersection points of the polyline and a line segment. \n \~ - \param[in] lineSegment - \ru Отрезок. - \en A line segment. \~ - \param[in] xEps - \ru Погрешность по U. - \en U-accuracy. \~ - \param[out] ttPolyline - \ru Массив параметров на ломаной. - \en An array of parameters on the polyline. \~ - \param[out] ttSegment - \ru Массив параметров на отрезке. - \en An array of parameters on the line segment. \~ - \return \ru Количество точек пересечения. - \en The number of cross points. \~ - */ - template - size_t SegmentIntersection( const MbLineSegment & lineSegment, double xEps, double yEps, ParamsVector & ttPolyline, ParamsVector & ttSegment ) const; - /// \ru Определить положение точки относительно кривой при известном индексе ближайшего сегмента. \en Define the point position relative to the curve when the nearest segment index is known. - bool PointRelative( const MbCartPoint & pnt, ptrdiff_t nearestSegmentIndex, double eps, MbeItemLocation & iLoc ) const; - /// \ru Определить номер сегмента (или пару номеров сегментов) по параметру на ломаной. \en Define segment index (or pair of segment indices) by parameter on polyline. - bool FindSegmentPair( double t, c3d::IndicesPair & ) const; - /// \ru Определить расстояние от точки до сегмента ломаной как отрезка. \en Calculate distance from a point to segment of polyline. - double DistanceToPolylineSegment( size_t, const MbCartPoint & ) const; - /// \ru Самопересечение ломаной. \en Self-intersection of a polyline. - bool IsSelfIntersecting( double metricEps = Math::LengthEps ) const; + /** \brief \ru Определить точки пересечения с отрезком. + \en Determine points of intersection with a line segment. \~ + \details \ru Определить точки пересечения ломаной и отрезка. \n + \en Determine intersection points of the polyline and a line segment. \n \~ + \param[in] lineSegment - \ru Отрезок. + \en A line segment. \~ + \param[in] xEps - \ru Погрешность по U. + \en U-accuracy. \~ + \param[out] ttPolyline - \ru Массив параметров на ломаной. + \en An array of parameters on the polyline. \~ + \param[out] ttSegment - \ru Массив параметров на отрезке. + \en An array of parameters on the line segment. \~ + \return \ru Количество точек пересечения. + \en The number of cross points. \~ + */ + template + size_t SegmentIntersection( const MbLineSegment & lineSegment, double xEps, double yEps, ParamsVector & ttPolyline, ParamsVector & ttSegment ) const; + /// \ru Определить положение точки относительно кривой при известном индексе ближайшего сегмента. \en Define the point position relative to the curve when the nearest segment index is known. + bool PointRelative( const MbCartPoint & pnt, ptrdiff_t nearestSegmentIndex, double eps, MbeItemLocation & iLoc ) const; + /// \ru Определить номер сегмента (или пару номеров сегментов) по параметру на ломаной. \en Define segment index (or pair of segment indices) by parameter on polyline. + bool FindSegmentPair( double t, c3d::IndicesPair & ) const; + /// \ru Определить расстояние от точки до сегмента ломаной как отрезка. \en Calculate distance from a point to segment of polyline. + double DistanceToPolylineSegment( size_t, const MbCartPoint & ) const; + /// \ru Самопересечение ломаной. \en Self-intersection of a polyline. + bool IsSelfIntersecting( double metricEps = Math::LengthEps ) const; /** \} */ protected: - /// \ru Удалить дерево поиска сегментов. \en Delete segments search tree. - void DeleteSearchTree() const; - /// \ru Создать и заполнить дерево поиска сегментов. \en Create and fill segments search tree. - bool CreateSearchTree() const; - /// \ru Поиск ближайших к точке сегментов по дереву поиска. \en Nearest to point segments by search tree. - bool FindNearestSegmentsByTree( const MbCartPoint &, c3d::IndicesVector & ) const; - /// \ru Поиск пересекающихся с отрезком сегментов по дереву поиска. \en Intersecting of line segment and segments of polyline by search tree. - bool FindIntersectingSegmentsByTree( const MbCartPoint & p1, const MbCartPoint & p2, double xEps, double yEps, c3d::IndicesVector & ) const; - /// \ru Самопересечение ломаной. \en Self-intersection of a polyline. - template - bool SelfIntersect( CrossPointsVector &, bool tillFirst, double metricEps ) const; + /// \ru Удалить дерево поиска сегментов. \en Delete segments search tree. + void DeleteSearchTree() const; + /// \ru Создать и заполнить дерево поиска сегментов. \en Create and fill segments search tree. + bool CreateSearchTree() const; + /// \ru Поиск ближайших к точке сегментов по дереву поиска. \en Nearest to point segments by search tree. + bool FindNearestSegmentsByTree( const MbCartPoint &, c3d::IndicesVector & ) const; + /// \ru Поиск пересекающихся с отрезком сегментов по дереву поиска. \en Intersecting of line segment and segments of polyline by search tree. + bool FindIntersectingSegmentsByTree( const MbCartPoint & p1, const MbCartPoint & p2, double xEps, double yEps, c3d::IndicesVector & ) const; + /// \ru Самопересечение ломаной. \en Self-intersection of a polyline. + template + bool SelfIntersect( CrossPointsVector &, bool tillFirst, double metricEps ) const; private: - void operator = ( const MbPolyline & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbPolyline & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbPolyline ) -}; +}; // MbPolyline IMPL_PERSISTENT_OPS( MbPolyline ) + #endif // __CUR_POLYLINE_H diff --git a/C3d/Include/cur_polyline3d.h b/C3d/Include/cur_polyline3d.h index 393d774..3dba52a 100644 --- a/C3d/Include/cur_polyline3d.h +++ b/C3d/Include/cur_polyline3d.h @@ -72,124 +72,125 @@ public : public : VISITING_CLASS( MbPolyline3D ); - /// \ru Инициализация по другой ломаной. \en Initialization by another polyline. - void Init( const MbPolyline3D & ); - /// \ru Инициализация по другой плоской ломаной. \en Initialization by another planar polyline. - void Init( const MbPolyline &, const MbPlacement3D & ); - /// \ru Инициализация по точкам и признаку замкнутости. \en Initialization by points and an attribute of closedness. - template - bool Init( const PointsVector & initList, bool cls ) - { - if ( initList.size() > 1 ) { - pointList = initList; - uppIndex = (ptrdiff_t)pointList.size() - 1; - closed = cls; - // if curve is closed then the start and the end points have to be different - if ( uppIndex>1 && closed && c3d::EqualPoints( pointList.front(), pointList.back(), Math::metricRegion ) ) { - pointList.erase( pointList.begin() + uppIndex ); - uppIndex--; - } - segmentsCount = ( uppIndex > 0 ) ? ( uppIndex + !!closed ) : 0; - Refresh(); - return true; - } - return false; - } - /// \ru Построение прямоугольника. \en Construction of a rectangle. - void Init( const MbCartPoint3D & p1, const MbCartPoint3D & p2 ); + /// \ru Инициализация по другой ломаной. \en Initialization by another polyline. + void Init( const MbPolyline3D & ); + /// \ru Инициализация по другой плоской ломаной. \en Initialization by another planar polyline. + void Init( const MbPolyline &, const MbPlacement3D & ); + /// \ru Инициализация по точкам и признаку замкнутости. \en Initialization by points and an attribute of closedness. + template + bool Init( const PointsVector & initList, bool cls ) + { + if ( initList.size() > 1 ) { + pointList = initList; + uppIndex = (ptrdiff_t)pointList.size() - 1; + closed = cls; + // if curve is closed then the start and the end points have to be different + if ( uppIndex>1 && closed && c3d::EqualPoints( pointList.front(), pointList.back(), Math::metricRegion ) ) { + pointList.erase( pointList.begin() + uppIndex ); + uppIndex--; + } + segmentsCount = ( uppIndex > 0 ) ? ( uppIndex + !!closed ) : 0; + Refresh(); + return true; + } + return false; + } + /// \ru Построение прямоугольника. \en Construction of a rectangle. + void Init( const MbCartPoint3D & p1, const MbCartPoint3D & p2 ); // \ru Общие функции математического объекта \en Common functions of the mathematical object MbeSpaceType IsA() const override; // \ru Тип элемента \en Type of element MbSpaceItem & Duplicate( MbRegDuplicate * = nullptr ) const override; // \ru Сделать копию элемента. \en Create a copy of the element. - bool IsSame ( const MbSpaceItem &, double accuracy = LENGTH_EPSILON ) const override; - bool SetEqual ( const MbSpaceItem & ) override; // \ru Сделать равным. \en Make equal. - void Transform( const MbMatrix3D &, MbRegTransform * = nullptr ) override; // \ru Преобразовать. \en Transform. - 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. - double DistanceToPoint( const MbCartPoint3D & ) const override;// \ru Расстояние до точки. \en Distance to a point. + bool IsSame ( const MbSpaceItem &, double accuracy = LENGTH_EPSILON ) const override; + bool SetEqual ( const MbSpaceItem & ) override; // \ru Сделать равным. \en Make equal. + void Transform( const MbMatrix3D &, MbRegTransform * = nullptr ) override; // \ru Преобразовать. \en Transform. + 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. + double DistanceToPoint( const MbCartPoint3D & ) const override;// \ru Расстояние до точки. \en Distance to a point. - void GetProperties( MbProperties & ) override; // \ru Выдать свойства объекта. \en Get properties of the object. - void SetProperties( const MbProperties & ) override; // \ru Записать свойства объекта. \en Set properties of the object. + 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 Common functions of polyline // \ru Функции кривой для работы в области определения параметрической кривой \en Functions of curve for working at parametric curve domain - void PointOn ( double & t, MbCartPoint3D & ) const override;// \ru Точка на кривой. \en Point on the curve. - void FirstDer ( double & t, MbVector3D & ) const override; // \ru Первая производная. \en The first derivative. - void SecondDer( double & t, MbVector3D & ) const override; // \ru Вторая производная. \en The second derivative. - void ThirdDer ( double & t, MbVector3D & ) const override; // \ru Третья производная. \en The third derivative. + void PointOn ( double & t, MbCartPoint3D & ) const override;// \ru Точка на кривой. \en Point on the curve. + void FirstDer ( double & t, MbVector3D & ) const override; // \ru Первая производная. \en The first derivative. + void SecondDer( double & t, MbVector3D & ) const override; // \ru Вторая производная. \en The second derivative. + void ThirdDer ( double & t, MbVector3D & ) const override; // \ru Третья производная. \en The third derivative. // \ru Вычислить значения точки и производных для заданного параметра. \en Calculate point and derivatives of object for given parameter. \~ - void Explore( double & t, bool ext, - MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const override; + void Explore( double & t, bool ext, + MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const override; // \ru Построить NURBS копию кривой \en Create a NURBS copy of the curve MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & ) const override; MbCurve3D * NurbsCurve( const MbNurbsParameters & ) const override; MbCurve3D * Trimmed( double t1, double t2, int sense ) const override; - void Trimm( SArray & points, double t1, double t2, double eps = METRIC_EPSILON ) const; + 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. - double GetTMax() const override; // \ru Вернуть максимальное значение параметра. \en Get the maximum value of parameter. - void Inverse( MbRegTransform * iReg = nullptr ) override; // \ru Изменить направление \en Change direction + double GetTMin() const override; // \ru Вернуть минимальное значение параметра. \en Get the minimum value of the parameter. + double GetTMax() const override; // \ru Вернуть максимальное значение параметра. \en Get the maximum value of parameter. + void Inverse( MbRegTransform * iReg = nullptr ) override; // \ru Изменить направление \en Change direction - double Step ( double t, double sag ) const override; // \ru Шаг параметра с учетом радиуса кривизны \en Step of parameter with consideration of curvature - double DeviationStep( double t, double angle ) const override; // \ru Шаг параметра по заданному углу отклонения касательной \en Step of parameter by a given angle of deviation of tangent + double Step ( double t, double sag ) const override; // \ru Шаг параметра с учетом радиуса кривизны \en Step of parameter with consideration of curvature + double DeviationStep( double t, double angle ) const override; // \ru Шаг параметра по заданному углу отклонения касательной \en Step of parameter by a given angle of deviation of tangent - bool IsStraight( bool ignoreParams = false ) const override; // \ru Признак прямолинейности кривой \en An attribute of curve straightness. + bool IsStraight( bool ignoreParams = false ) const override; // \ru Признак прямолинейности кривой \en An attribute of curve straightness. - void CalculateGabarit( MbCube & ) const override; // \ru Определить габариты кривой. \en Determine the bounding box of a curve. - void CalculateLocalGabarit( const MbMatrix3D &, MbCube & ) const override; // \ru Рассчитать габарит относительно л.с.к. \en Calculate bounding box relative to the local coordinate system. + void CalculateGabarit( MbCube & ) const override; // \ru Определить габариты кривой. \en Determine the bounding box of a curve. + void CalculateLocalGabarit( const MbMatrix3D &, MbCube & ) const override; // \ru Рассчитать габарит относительно л.с.к. \en Calculate bounding box relative to the local coordinate system. - double CalculateMetricLength() const override; // \ru Посчитать метрическую длину. \en Calculate the metric length. - void GetCentre ( MbCartPoint3D & wc ) const override; // \ru Посчитать центр кривой. \en Calculate the center of a curve. - void GetWeightCentre( MbCartPoint3D & wc ) const override; // \ru Посчитать центр тяжести кривой. \en Calculate the gravity center of the curve. + double CalculateMetricLength() const override; // \ru Посчитать метрическую длину. \en Calculate the metric length. + void GetCentre ( MbCartPoint3D & wc ) const override; // \ru Посчитать центр кривой. \en Calculate the center of a curve. + void GetWeightCentre( MbCartPoint3D & wc ) const override; // \ru Посчитать центр тяжести кривой. \en Calculate the gravity center of the curve. // \ru Дать плоскую кривую и плейсмент, если пространственная кривая плоская (после использования вызывать DeleteItem на двумерную кривую). \en Get the planar curve and placement if the spatial curve is planar (call DeleteItem for two-dimensional curve after using). - bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place, bool saveParams, PlanarCheckParams params = PlanarCheckParams() ) const override; + bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place, bool saveParams, PlanarCheckParams params = PlanarCheckParams() ) const override; // \ru Общие функции полигональной кривой \en Common functions of polygonal curve - void Rebuild() override; // \ru Перестроить кривую \en Rebuild curve - void GetRuleInterval( ptrdiff_t index, double & t1, double & t2 ) const override; // \ru Выдать интервал влияния точки кривой. \en Get the interval of point influence. + void Rebuild() override; // \ru Перестроить кривую \en Rebuild curve + void GetRuleInterval( ptrdiff_t index, double & t1, double & t2 ) const override; // \ru Выдать интервал влияния точки кривой. \en Get the interval of point influence. // \ru Функции только 3D кривой \en Functions of 3D curve only - bool NearPointProjection( const MbCartPoint3D &, double & t, bool ext, MbRect1D * tRange = nullptr ) const override; // \ru Ближайшая проекция точки на кривую. \en The nearest point projection to the curve. - void InsertPoint( ptrdiff_t index, const MbCartPoint3D & ) override; // \ru Добавить точку \en Add a point - void InsertPoint( double t, const MbCartPoint3D &, double ) override; // \ru Добавить точку \en Add a point - bool CheckParam ( double & t, ptrdiff_t & i0, ptrdiff_t & i1, double & t0, double & t1 ) const override; // \ru Установить параметр. \en Set parameter. - double GetParam( ptrdiff_t i ) const override; // \ru Выдать параметр для точки с номером. \en Get parameter for a point with index. + bool NearPointProjection( const MbCartPoint3D &, double & t, bool ext, MbRect1D * tRange = nullptr ) const override; // \ru Ближайшая проекция точки на кривую. \en The nearest point projection to the curve. + void InsertPoint( ptrdiff_t index, const MbCartPoint3D & ) override; // \ru Добавить точку \en Add a point + void InsertPoint( double t, const MbCartPoint3D &, double ) override; // \ru Добавить точку \en Add a point + bool CheckParam ( double & t, ptrdiff_t & i0, ptrdiff_t & i1, double & t0, double & t1 ) const override; // \ru Установить параметр. \en Set parameter. + double GetParam( ptrdiff_t i ) const override; // \ru Выдать параметр для точки с номером. \en Get parameter for a point with index. - void CheckParameter( double & ) const; ///< \ru Проверка параметра. \en Check parameter. + void CheckParameter( double & ) const; ///< \ru Проверка параметра. \en Check parameter. //virtual bool GoThroughPoint( double t, MbCartPoint3D & p ); // \ru Пройти через точку. \en Pass through point. - MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = nullptr, - VERSION version = Math::DefaultMathVersion(), bool * coincParams = nullptr ) const override; // \ru Дать плоскую проекцию кривой. \en Get a planar projection of a curve. - MbCurve * GetMapPsp( const MbMatrix3D &, double zNear, MbRect1D * pRgn = nullptr ) const override; // \ru Дать перспективную плоскую проекцию кривой. \en Get a planar geometric projection of a curve. + MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = nullptr, + VERSION version = Math::DefaultMathVersion(), bool * coincParams = nullptr ) const override; // \ru Дать плоскую проекцию кривой. \en Get a planar projection of a curve. + MbCurve * GetMapPsp( const MbMatrix3D &, double zNear, MbRect1D * pRgn = nullptr ) const override; // \ru Дать перспективную плоскую проекцию кривой. \en Get a planar geometric projection of a curve. - size_t GetCount() const override; - bool IsSmoothConnected( double angleEps ) const override; // \ru Являются ли стыки контура\кривой гладкими? \en Whether the joints of a contour\curve are smooth. + size_t GetCount() const override; + bool IsSmoothConnected( double angleEps ) const override; // \ru Являются ли стыки контура\кривой гладкими? \en Whether the joints of a contour\curve are smooth. - bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = nullptr, double epsilon = EPSILON ) const override; // \ru Непрерывна ли первая производная? \en Have the first derivative the continuous? + bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = nullptr, double epsilon = EPSILON ) const override; // \ru Непрерывна ли первая производная? \en Have the first derivative the continuous? // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. - bool SetContinuousDerivativeLength( VERSION version, double epsilon = EPSILON ) override; + bool SetContinuousDerivativeLength( VERSION version, double epsilon = EPSILON ) override; public: - ptrdiff_t GetSegmentsCount() const { return segmentsCount; } + ptrdiff_t GetSegmentsCount() const { return segmentsCount; } - double Step ( double t, double sag, ThreeStates dir ) const; ///< \ru Шаг параметра с учетом радиуса кривизны. \en Step of parameter with consideration of curvature. - double DeviationStep( double t, double angle, ThreeStates dir ) const; ///< \ru Шаг параметра по заданному углу отклонения касательной. \en Step of parameter by a given angle of deviation of tangent. + double Step ( double t, double sag, ThreeStates dir ) const; ///< \ru Шаг параметра с учетом радиуса кривизны. \en Step of parameter with consideration of curvature. + double DeviationStep( double t, double angle, ThreeStates dir ) const; ///< \ru Шаг параметра по заданному углу отклонения касательной. \en Step of parameter by a given angle of deviation of tangent. - bool UnClamped( bool ); - void DeleteEqPoints( double absEps ); // \ru Удалить одинаковые точки \en Remove equal points - void AddAt( const MbCartPoint3D & spsP, ptrdiff_t i ); + bool UnClamped( bool ); + void DeleteEqPoints( double absEps ); // \ru Удалить одинаковые точки \en Remove equal points + void AddAt( const MbCartPoint3D & spsP, ptrdiff_t i ); private: - void operator = ( const MbPolyline3D & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbPolyline3D & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbPolyline3D ) }; IMPL_PERSISTENT_OPS( MbPolyline3D ) + #endif // __CUR_POLYLINE3D_H diff --git a/C3d/Include/cur_projection_curve.h b/C3d/Include/cur_projection_curve.h index 1c71113..88a4bab 100644 --- a/C3d/Include/cur_projection_curve.h +++ b/C3d/Include/cur_projection_curve.h @@ -240,7 +240,7 @@ public : \{ */ // \ru Вычислить значения точки и производных для заданного параметра. \en Calculate point and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - MbCartPoint & pnt, MbVector & fir, MbVector * sec, MbVector * thir ) const override; + MbCartPoint & pnt, MbVector & fir, MbVector * sec, MbVector * thir ) const override; /** \} */ /** \ru \name Общие функции кривой @@ -248,7 +248,7 @@ public : \{ */ double PointProjection( const MbCartPoint & pnt ) const override; // \ru Проекция точки на кривую. \en Point projection on the curve. bool NearPointProjection( const MbCartPoint & pnt, double xEpsilon, double yEpsilon, - double & t, bool ext, MbRect1D * tRange = nullptr ) const override; // \ru Проекция точки на кривую или её продолжение в области поиска проекции. \en Projection of a point onto the curve or its extension in the projection region. + double & t, bool ext, MbRect1D * tRange = nullptr ) const override; // \ru Проекция точки на кривую или её продолжение в области поиска проекции. \en Projection of a point onto the curve or its extension in the projection region. bool HasLength( double & ) const override; // \ru Метрическая длина кривой. \en Metric length of a curve. double GetMetricLength() const override; // \ru Метрическая длина кривой. \en Metric length of a curve. @@ -274,27 +274,27 @@ public : MbCurve * Trimmed( double t1, double t2, int sense ) const override; - const MbCurve3D & GetSpaceCurve() const { return *spaceCurve; } - const MbSurface & GetSurface () const { return *surface; } - const MbCurve & GetParamCurve() const { return *curve; } + const MbCurve3D & GetSpaceCurve() const { return *spaceCurve; } + const MbSurface & GetSurface () const { return *surface; } + const MbCurve & GetParamCurve() const { return *curve; } bool GetCentre( MbCartPoint & c ) const override; // \ru Выдать центр кривой \en Get center of curve double GetRadius() const override; // \ru Дать физический радиус объекта или ноль, если это невозможно. \en Get the physical radius of the object or null if it impossible. bool GetAxisPoint( MbCartPoint & ) const override; // \ru Точка для построения оси \en Point for the axis construction - bool SetSameSurface( const MbSurface & s ); ///< \ru Заменить поверхность на такую же. \en Whether the projecting curve lies on the surface. + bool SetSameSurface( const MbSurface & s ); ///< \ru Заменить поверхность на такую же. \en Whether the projecting curve lies on the surface. - bool IsBelong() const { return (projProp & pcp_SpaceCurveBelongSurf) > 0; } ///< \ru Лежит ли проецируемая кривая на поверхности. \en Whether the projecting curve lies on the surface. + bool IsBelong() const { return (projProp & pcp_SpaceCurveBelongSurf) > 0; } ///< \ru Лежит ли проецируемая кривая на поверхности. \en Whether the projecting curve lies on the surface. - bool InvertNormal( MbRegTransform * = nullptr ); ///< \ru Инвертировать нормаль, если поверхность - плоскость. \en Invert normal if the surface is a plane. + bool InvertNormal( MbRegTransform * = nullptr ); ///< \ru Инвертировать нормаль, если поверхность - плоскость. \en Invert normal if the surface is a plane. - bool ChangeCarrierBorne( const MbSurface & item, MbSurface & init, const MbMatrix & matr ); ///< \ru Изменение носителя. \en Change a carrier. + bool ChangeCarrierBorne( const MbSurface & item, MbSurface & init, const MbMatrix & matr ); ///< \ru Изменение носителя. \en Change a carrier. - /// \ru Получить 2d сплайн с данной относительной точностью аппроксимирующий данную кривую. \en Get 2d spline which approximates given curve with a given relative tolerance. - MbCurve * CreateSpline( double relEps, MbRect1D * pRgn = nullptr ) const; + /// \ru Получить 2d сплайн с данной относительной точностью аппроксимирующий данную кривую. \en Get 2d spline which approximates given curve with a given relative tolerance. + MbCurve * CreateSpline( double relEps, MbRect1D * pRgn = nullptr ) const; - /// \ru Создать кривую путём сращивания части данной кривой с частью другой кривой. \en Create a curve by joining a part of this curve with a part of other curve. - MbProjCurve * AddCurve( const MbProjCurve &, double accuracy, VERSION version = Math::DefaultMathVersion() ) const; + /// \ru Создать кривую путём сращивания части данной кривой с частью другой кривой. \en Create a curve by joining a part of this curve with a part of other curve. + MbProjCurve * AddCurve( const MbProjCurve &, double accuracy, VERSION version = Math::DefaultMathVersion() ) const; void GetProperties( MbProperties & ) override; // \ru Выдать свойства объекта \en Get properties of the object void SetProperties( const MbProperties & ) override; // \ru Записать свойства объекта \en Set properties of the object @@ -304,62 +304,62 @@ public : /** \} */ private: - // \ru Функция инициализации. \en Function of initialization. - void Init( const MbCurve3D & sCurve, bool sameSpaceCurve, const MbSurface & surface, - const MbCurve & pCurve, bool samePlaneCurve, size_t vers, - MbRegDuplicate * iReg = nullptr ); - void CheckPoint ( double & t, bool ext, MbCartPoint & cPoint ) const; // \ru Обнулить данные, вычислить точку \en Set data to zero, calculate point. - void CheckFirst ( double & t, bool ext, MbVector & cFirst ) const; // \ru Вычислить производную \en Calculate derivative - void CheckSecond( double & t, bool ext, MbVector & cSecond ) const; // \ru Вычислить производную \en Calculate derivative - void CheckThird ( double & t, bool ext, MbVector & cThird ) const; // \ru Вычислить производную \en Calculate derivative - bool CalculatePoint( const MbCartPoint3D & sPoint, MbCartPoint & cPoint, - MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, - MbVector3D & uuDer, MbVector3D & vvDer, MbVector3D & uvDer, MbVector3D * nor ) const; // \ru Вычислить данные для точки. \en Calculate point. - void CalculateFirst( bool result, MbCartPoint3D & surfacePoint, MbVector3D & sDeriveU, MbVector3D & sDeriveV, - MbVector3D & sDeriveUU, MbVector3D & sDeriveVV, MbVector3D & sDeriveUV, MbVector3D & sNormal, - const MbCartPoint3D & sPoint, const MbCartPoint & cPoint, const MbVector3D & sFirst, MbVector & cFirst ) const; // \ru Вычислить производную \en Calculate derivative - void CalculateSecond( const MbCartPoint3D & surfacePoint, const MbVector3D & sDeriveU, const MbVector3D & sDeriveV, - const MbVector3D & sDeriveUU, const MbVector3D & sDeriveVV, const MbVector3D & sDeriveUV, const MbVector3D & sNormal, - const MbCartPoint3D & sPoint, const MbCartPoint & cPoint, const MbVector3D & sFirst, const MbVector & cFirst, - const MbVector3D & sSecond, MbVector & cSecond ) const; // \ru Вычислить производную \en Calculate derivative - void SetBelong(); // \ru Вычисление параметра belong: лежит ли проецируемая кривая на поверхности \en Calculate 'belong' parameter: whether the projecting curve lies on the surface - // \ru Расчет в точке для общего случая. - // \en Calculation of mathematics at a point for the general case. - void GeneralCaseExplore( double t, size_t ord ) const; - // \ru Расчет в точке для случая, когда кривая лежит на поверхности. - // \en Calculation of mathematics at a point for the case when the curve lies on the surface. - void BelongCaseExplore( double t, size_t ord ) const; - // \ru Расчет в точке для случая проецирования на плоскость. - // \en Calculation at a point for the case of projection onto a plane. - void PlaneCaseExplore( double t, size_t ord, bool single ) const; - // \ru Расчет в точке. - // \en Calculation at a point. - void Explore( double & t, bool ext, size_t ord, bool single ) const; - // \ru Определение типа проецирования. \en Determining the type of projection - void SetProjType(); - // \ru Обновить связь кривой и поверхности. \en Refresh curve-to-surface relationship. - void UpdateProjSurface(); - void SetInto(); // \ru Инициализировать матрицу пересчета в систему координат плоскости. \en Initialize matrix of transformation to the plane coordinate system. - void PrepareCurveToTrimmed( MbCurve * curvett, double t1, double t2 ) const; // \ru Подготовить двумерную кривую к усечению \en Prepare a two-dimensional curve for trimming + // \ru Функция инициализации. \en Function of initialization. + void Init( const MbCurve3D & sCurve, bool sameSpaceCurve, const MbSurface & surface, + const MbCurve & pCurve, bool samePlaneCurve, size_t vers, + MbRegDuplicate * iReg = nullptr ); + void CheckPoint ( double & t, bool ext, MbCartPoint & cPoint ) const; // \ru Обнулить данные, вычислить точку \en Set data to zero, calculate point. + void CheckFirst ( double & t, bool ext, MbVector & cFirst ) const; // \ru Вычислить производную \en Calculate derivative + void CheckSecond( double & t, bool ext, MbVector & cSecond ) const; // \ru Вычислить производную \en Calculate derivative + void CheckThird ( double & t, bool ext, MbVector & cThird ) const; // \ru Вычислить производную \en Calculate derivative + bool CalculatePoint( const MbCartPoint3D & sPoint, MbCartPoint & cPoint, + MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, + MbVector3D & uuDer, MbVector3D & vvDer, MbVector3D & uvDer, MbVector3D * nor ) const; // \ru Вычислить данные для точки. \en Calculate point. + void CalculateFirst( bool result, MbCartPoint3D & surfacePoint, MbVector3D & sDeriveU, MbVector3D & sDeriveV, + MbVector3D & sDeriveUU, MbVector3D & sDeriveVV, MbVector3D & sDeriveUV, MbVector3D & sNormal, + const MbCartPoint3D & sPoint, const MbCartPoint & cPoint, const MbVector3D & sFirst, MbVector & cFirst ) const; // \ru Вычислить производную \en Calculate derivative + void CalculateSecond( const MbCartPoint3D & surfacePoint, const MbVector3D & sDeriveU, const MbVector3D & sDeriveV, + const MbVector3D & sDeriveUU, const MbVector3D & sDeriveVV, const MbVector3D & sDeriveUV, const MbVector3D & sNormal, + const MbCartPoint3D & sPoint, const MbCartPoint & cPoint, const MbVector3D & sFirst, const MbVector & cFirst, + const MbVector3D & sSecond, MbVector & cSecond ) const; // \ru Вычислить производную \en Calculate derivative + void SetBelong(); // \ru Вычисление параметра belong: лежит ли проецируемая кривая на поверхности \en Calculate 'belong' parameter: whether the projecting curve lies on the surface + // \ru Расчет в точке для общего случая. + // \en Calculation of mathematics at a point for the general case. + void GeneralCaseExplore( double t, size_t ord ) const; + // \ru Расчет в точке для случая, когда кривая лежит на поверхности. + // \en Calculation of mathematics at a point for the case when the curve lies on the surface. + void BelongCaseExplore( double t, size_t ord ) const; + // \ru Расчет в точке для случая проецирования на плоскость. + // \en Calculation at a point for the case of projection onto a plane. + void PlaneCaseExplore( double t, size_t ord, bool single ) const; + // \ru Расчет в точке. + // \en Calculation at a point. + void Explore( double & t, bool ext, size_t ord, bool single ) const; + // \ru Определение типа проецирования. \en Determining the type of projection + void SetProjType(); + // \ru Обновить связь кривой и поверхности. \en Refresh curve-to-surface relationship. + void UpdateProjSurface(); + void SetInto(); // \ru Инициализировать матрицу пересчета в систему координат плоскости. \en Initialize matrix of transformation to the plane coordinate system. + void PrepareCurveToTrimmed( MbCurve * curvett, double t1, double t2 ) const; // \ru Подготовить двумерную кривую к усечению \en Prepare a two-dimensional curve for trimming - /** \brief \ru Поменять базовую поверхность на подобную. - \en Change base surface to the similar one. \~ - \details \ru Поменять базовую поверхность. Новая поверхность должна быть подобна старой. - \en Change the base surface. The new surface has to be similar to the old one. \~ - \param[in] newSurface - \ru Новая поверхность. Захватывается кривой. - \en New surface. Is captured by the curve. \~ - \param[in] matrix - \ru Матрица преобразования из старой поверхности в новую. - \en Transformation matrix from the old surface to a new one. \~ - */ - void ChangeSurfaceToSimilar( const MbSurface & newSurface, const MbMatrix & matrix, MbRegTransform * iReg ); - + /** \brief \ru Поменять базовую поверхность на подобную. + \en Change base surface to the similar one. \~ + \details \ru Поменять базовую поверхность. Новая поверхность должна быть подобна старой. + \en Change the base surface. The new surface has to be similar to the old one. \~ + \param[in] newSurface - \ru Новая поверхность. Захватывается кривой. + \en New surface. Is captured by the curve. \~ + \param[in] matrix - \ru Матрица преобразования из старой поверхности в новую. + \en Transformation matrix from the old surface to a new one. \~ + */ + void ChangeSurfaceToSimilar( const MbSurface & newSurface, const MbMatrix & matrix, MbRegTransform * iReg ); DECLARE_PERSISTENT_CLASS_NEW_DEL( MbProjCurve ) OBVIOUS_PRIVATE_COPY( MbProjCurve ) -}; +}; // MbProjCurve IMPL_PERSISTENT_OPS( MbProjCurve ) + //------------------------------------------------------------------------------ // \ru Изменение носимых элементов \en Change a carrier elements // --- diff --git a/C3d/Include/cur_reparam_curve.h b/C3d/Include/cur_reparam_curve.h index 46ebec3..09fa4a9 100644 --- a/C3d/Include/cur_reparam_curve.h +++ b/C3d/Include/cur_reparam_curve.h @@ -70,19 +70,19 @@ public : public : VISITING_CLASS( MbReparamCurve ); - /// \ru Установить параметрическую область кривой. \en Set curve parametric range. - void Init( double t1, double t2 ); - /// \ru Установить параметрическую область кривой и длину производной в начале кривой. \en Set curve parametric range and first derive length. - void Init( double t1, double t2, double begFirstDerValue ); - /// \ru Установить параметрическую область кривой. \en Set curve parametric range. - void InitScaledEnds( double scaleDer1, double scaleDer2 ); - /// \ru Установить параметрическую область кривой пропорциональную метрической длине кривой. \en Set the parametric area of the curve proportional to the metric length of the curve. - bool InitProportional( double t1, double t2 ); - /// \ru Установить пользовательскую функцию репараметризации. \en Set users reparameterization function. - bool InitByUsersFunction( MbFunction & repFunc ); - /// \ru Установить параметрическую область кривой пропорциональную метрической длине кривой. \en Set the parametric area of the curve proportional to the metric length of the curve. + /// \ru Установить параметрическую область кривой. \en Set curve parametric range. + void Init( double t1, double t2 ); + /// \ru Установить параметрическую область кривой и длину производной в начале кривой. \en Set curve parametric range and first derive length. + void Init( double t1, double t2, double begFirstDerValue ); + /// \ru Установить параметрическую область кривой. \en Set curve parametric range. + void InitScaledEnds( double scaleDer1, double scaleDer2 ); + /// \ru Установить параметрическую область кривой пропорциональную метрической длине кривой. \en Set the parametric area of the curve proportional to the metric length of the curve. + bool InitProportional( double t1, double t2 ); + /// \ru Установить пользовательскую функцию репараметризации. \en Set users reparameterization function. + bool InitByUsersFunction( MbFunction & repFunc ); + /// \ru Установить параметрическую область кривой пропорциональную метрической длине кривой. \en Set the parametric area of the curve proportional to the metric length of the curve. static MbReparamCurve * CreateProportional( const MbCurve & curve, double t1, double t2 ); - /// \ru Установить пользовательскую функцию репараметризации. \en Set users reparameterization function. + /// \ru Установить пользовательскую функцию репараметризации. \en Set users reparameterization function. static MbReparamCurve * CreateByFunction( const MbCurve & curve, MbFunction & repFunc ); /** \ru \name Общие функции геометрического объекта. @@ -153,7 +153,7 @@ public : \{ */ // \ru Вычислить значения точки и производных для заданного параметра. \en Calculate point and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - MbCartPoint & pnt, MbVector & fir, MbVector * sec, MbVector * thir ) const override; + MbCartPoint & pnt, MbVector & fir, MbVector * sec, MbVector * thir ) const override; /** \} */ /** \ru \name Функции движения по кривой @@ -225,30 +225,27 @@ public : bool GetAxisPoint( MbCartPoint & ) const override; // \ru Точка для построения оси \en Point for the axis construction bool IsSimilarToCurve( const MbCurve & curve, double precision = PARAM_PRECISION ) const override; // \ru Подобные ли кривые для объединения (слива) \en Whether the curves for union (joining) are similar size_t GetCount() const override; // \ru Количество разбиений для прохода в операциях \en Count of subdivisions for pass in operations - /// \ru Получить границы участков кривой, которые описываются одной аналитической функцией. - /// \en Get the boundaries of the curve sections that are described by one analytical function. \~ + /// \ru Получить границы участков кривой, которые описываются одной аналитической функцией. \en Get the boundaries of the curve sections that are described by one analytical function. \~ void GetAnalyticalFunctionsBounds( std::vector & params ) const override; - - void GetPointsByEvenLengthDelta( size_t n, std::vector & pnts ) const override; // \ru Выдать n точек кривой с равными интервалами по длине дуги \en Get n points of curve equally spaced by the arc length - void ParameterInto( double & ) const; // \ru Перевод параметра базовой кривой в локальный параметр \en Transformation of the base curve parameter to a local parameter - void ParameterFrom( double & ) const; // \ru Перевод локального параметра в параметр базовой кривой \en Transformation of a local parameter to the base curve parameter - double EpsilonInto( double eps ) const; // \ru Перевод точности параметра базовой кривой в точность локального параметра \en Transformation of the base curve parameter tolerance to a local parameter tolerance - double EpsilonFrom( double eps ) const; // \ru Перевод точности локального параметра в точность параметра базовой кривой \en Transformation of a local parameter tolerance to the base curve parameter tolerance + void ParameterInto( double & ) const; // \ru Перевод параметра базовой кривой в локальный параметр \en Transformation of the base curve parameter to a local parameter + void ParameterFrom( double & ) const; // \ru Перевод локального параметра в параметр базовой кривой \en Transformation of a local parameter to the base curve parameter + double EpsilonInto( double eps ) const; // \ru Перевод точности параметра базовой кривой в точность локального параметра \en Transformation of the base curve parameter tolerance to a local parameter tolerance + double EpsilonFrom( double eps ) const; // \ru Перевод точности локального параметра в точность параметра базовой кривой \en Transformation of a local parameter tolerance to the base curve parameter tolerance const MbCurve & GetBasisCurve() const override; MbCurve & SetBasisCurve() override; - bool SetBasisCurve( const MbCurve &, const MbRect1D * tRange = nullptr ); ///< \ru Заменить плоскую кривую \en Replace the planar curve - double Tmin() const; ///< \ru Начальный параметр. \en Start parameter. - double Tmax() const; ///< \ru Конечный параметр. \en End parameter. - double Dt() const; ///< \ru Производная параметра кривой basisCurve по параметру. \en Derivative of parameter of 'basisCurve' curve by parameter. - bool SetTmin( double t ); - bool SetTmax( double t ); - bool SetDt ( double d ); + bool SetBasisCurve( const MbCurve &, const MbRect1D * tRange = nullptr ); ///< \ru Заменить плоскую кривую \en Replace the planar curve + double Tmin() const; ///< \ru Начальный параметр. \en Start parameter. + double Tmax() const; ///< \ru Конечный параметр. \en End parameter. + double Dt() const; ///< \ru Производная параметра кривой basisCurve по параметру. \en Derivative of parameter of 'basisCurve' curve by parameter. + bool SetTmin( double t ); + bool SetTmax( double t ); + bool SetDt ( double d ); - MbeReparamType GetReparamType() const { return reparamType; } // \ru Тип параметризации. \en Parameterization type. + MbeReparamType GetReparamType() const { return reparamType; } // \ru Тип параметризации. \en Parameterization type. // \ru !!! геометрия подложки тождественна геометрии кривой, отлична параметризация !!! \en !!! geometry of substrate is identical to geometry of curve, parameterization is different !!! const MbCurve & GetSubstrate() const override; // \ru Выдать подложку или себя \en Get substrate or itself @@ -266,16 +263,16 @@ public : // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. bool SetContinuousDerivativeLength( VERSION version, double epsilon = EPSILON ) override; - bool IsProportional() const { return (reparamType == rt_Proportional); } ///< \ru Является ли репараметризация пропорциональной? \en Is the re-parametrization proportional? - bool IsLinear() const { return (reparamType == rt_Linear); } // \ru Является ли репараметризация линейной? \en Is the re-parametrization linear? - bool SetLimitParam( double newTMin, double newTMax ); // \ru Установить область изменения параметра \en Set range of parameter + bool IsProportional() const { return (reparamType == rt_Proportional); } ///< \ru Является ли репараметризация пропорциональной? \en Is the re-parametrization proportional? + bool IsLinear() const { return (reparamType == rt_Linear); } // \ru Является ли репараметризация линейной? \en Is the re-parametrization linear? + bool SetLimitParam( double newTMin, double newTMax ); // \ru Установить область изменения параметра \en Set range of parameter /** \} */ private: - void operator = ( const MbReparamCurve & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbReparamCurve & ); // \ru Не реализовано. \en Not implemented. // \ru Параметр базовой кривой и его производные. \en The base curve parameter and its derivatives. - void Explore( double & t, bool ext, double & par, double & dpar, double * ddpar, double * dddpar ) const; + void Explore( double & t, bool ext, double & par, double & dpar, double * ddpar, double * dddpar ) const; DECLARE_PERSISTENT_CLASS_NEW_DEL( MbReparamCurve ) }; // MbReparamCurve diff --git a/C3d/Include/cur_reparam_curve3d.h b/C3d/Include/cur_reparam_curve3d.h index 369416b..321826e 100644 --- a/C3d/Include/cur_reparam_curve3d.h +++ b/C3d/Include/cur_reparam_curve3d.h @@ -69,19 +69,19 @@ public : public : VISITING_CLASS( MbReparamCurve3D ); - /// \ru Установить параметрическую область кривой. \en Set curve parametric range. - void Init( double t1, double t2 ); - /// \ru Установить параметрическую область кривой и длину производной в начале кривой. \en Set curve parametric range and first derive length. - void Init( double t1, double t2, double begFirstDerValue ); - /// \ru Установить параметрическую область кривой. \en Set curve parametric range. - void InitScaledEnds( double scaleDer1, double scaleDer2 ); - /// \ru Установить параметрическую область кривой пропорциональную метрической длине кривой. \en Set the parametric area of the curve proportional to the metric length of the curve. - bool InitProportional( double t1, double t2 ); - /// \ru Установить пользовательскую функцию репараметризации. \en Set users reparameterization function. - bool InitByUsersFunction( MbFunction & repFunc ); - /// \ru Установить параметрическую область кривой пропорциональную метрической длине кривой. \en Set the parametric area of the curve proportional to the metric length of the curve. + /// \ru Установить параметрическую область кривой. \en Set curve parametric range. + void Init( double t1, double t2 ); + /// \ru Установить параметрическую область кривой и длину производной в начале кривой. \en Set curve parametric range and first derive length. + void Init( double t1, double t2, double begFirstDerValue ); + /// \ru Установить параметрическую область кривой. \en Set curve parametric range. + void InitScaledEnds( double scaleDer1, double scaleDer2 ); + /// \ru Установить параметрическую область кривой пропорциональную метрической длине кривой. \en Set the parametric area of the curve proportional to the metric length of the curve. + bool InitProportional( double t1, double t2 ); + /// \ru Установить пользовательскую функцию репараметризации. \en Set users reparameterization function. + bool InitByUsersFunction( MbFunction & repFunc ); + /// \ru Установить параметрическую область кривой пропорциональную метрической длине кривой. \en Set the parametric area of the curve proportional to the metric length of the curve. static MbReparamCurve3D * CreateProportional( const MbCurve3D & curve, double t1, double t2 ); - /// \ru Установить пользовательскую функцию репараметризации. \en Set users reparameterization function. + /// \ru Установить пользовательскую функцию репараметризации. \en Set users reparameterization function. static MbReparamCurve3D * CreateByFunction( const MbCurve3D & curve, MbFunction & repFunc ); // \ru Общие функции математического объекта \en Common functions of the mathematical object @@ -125,7 +125,7 @@ public : void _Normal ( double t, MbVector3D & ) const override;// \ru Вектор главной нормали \en Vector of the principal normal // \ru Вычислить значения точки и производных для заданного параметра. \en Calculate point and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const override; + MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const override; MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & ) const override; MbCurve3D * NurbsCurve( const MbNurbsParameters & ) const override; // \ru Построить NURBS-копию кривой \en Create a NURBS-copy of the curve @@ -174,7 +174,7 @@ public : //virtual bool GoThroughPointWithDerive( double t, MbCartPoint3D & p0, MbVector3D & v0 ); MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = nullptr, - VERSION version = Math::DefaultMathVersion(), bool * coincParams = nullptr ) const override; // \ru Дать плоскую проекцию кривой \en Get a planar projection of a curve + VERSION version = Math::DefaultMathVersion(), bool * coincParams = nullptr ) const override; // \ru Дать плоскую проекцию кривой \en Get a planar projection of a curve size_t GetCount() const override; void ChangeCarrier( const MbSpaceItem & item, MbSpaceItem & init ) override; // \ru Изменение носителя \en Change a carrier @@ -183,16 +183,16 @@ public : double GetRadius() const override; // \ru Дать физический радиус объекта или ноль, если это невозможно. \en Get the physical radius of the object or null if it impossible. bool GetCircleAxis ( MbAxis3D & ) const override; // \ru Дать ось кривой \en Get axis of curve - void ParameterInto( double & ) const; // \ru Перевод параметра базовой кривой в локальный параметр \en Transformation of the base curve parameter to a local parameter - void ParameterFrom( double & ) const; // \ru Перевод локального параметра в параметр базовой кривой \en Transformation of a local parameter to the base curve parameter + void ParameterInto( double & ) const; // \ru Перевод параметра базовой кривой в локальный параметр \en Transformation of the base curve parameter to a local parameter + void ParameterFrom( double & ) const; // \ru Перевод локального параметра в параметр базовой кривой \en Transformation of a local parameter to the base curve parameter - void SetBasisCurve( MbCurve3D & ); // \ru Заменить плоскую кривую \en Replace the planar curve - double Tmin() const; ///< \ru Начальный параметр. \en Start parameter. - double Tmax() const; ///< \ru Конечный параметр. \en End parameter. - double Dt() const; ///< \ru Производная параметра кривой basisCurve по параметру. \en Derivative of parameter of 'basisCurve' curve by parameter. - void SetTmin( double t ); - void SetTmax( double t ); - void SetDt ( double d ); + void SetBasisCurve( MbCurve3D & ); // \ru Заменить плоскую кривую \en Replace the planar curve + double Tmin() const; ///< \ru Начальный параметр. \en Start parameter. + double Tmax() const; ///< \ru Конечный параметр. \en End parameter. + double Dt() const; ///< \ru Производная параметра кривой basisCurve по параметру. \en Derivative of parameter of 'basisCurve' curve by parameter. + void SetTmin( double t ); + void SetTmax( double t ); + void SetDt ( double d ); // \ru !!! геометрия подложки тождественна геометрии кривой, отлична параметризация !!! \en !!! geometry of substrate is identical to geometry of curve, parameterization is different !!! const MbCurve3D & GetSubstrate() const override; // \ru Выдать подложку или себя \en Get substrate or itself @@ -215,17 +215,17 @@ public : // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. bool SetContinuousDerivativeLength( VERSION version, double epsilon = EPSILON ) override; - bool IsProportional() const { return (reparamType == rt_Proportional); } ///< \ru Является ли репараметризация пропорциональной? \en Is the re-parametrization proportional? - bool IsLinear() const { return (reparamType == rt_Linear); } // \ru Является ли репараметризация линейной? \en Is the re-parametrization linear? - bool SetLimitParam( double newTMin, double newTMax ); // \ru Установить область изменения параметра \en Set range of parameter + bool IsProportional() const { return (reparamType == rt_Proportional); } ///< \ru Является ли репараметризация пропорциональной? \en Is the re-parametrization proportional? + bool IsLinear() const { return (reparamType == rt_Linear); } // \ru Является ли репараметризация линейной? \en Is the re-parametrization linear? + bool SetLimitParam( double newTMin, double newTMax ); // \ru Установить область изменения параметра \en Set range of parameter /// \ru Получить границы участков кривой, которые описываются одной аналитической функцией. /// \en Get the boundaries of the curve sections that are described by one analytical function. \~ void GetAnalyticalFunctionsBounds( std::vector & params ) const override; private: - void operator = ( const MbReparamCurve3D & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbReparamCurve3D & ); // \ru Не реализовано. \en Not implemented. // \ru Параметр базовой кривой и его производные. \en The base curve parameter and its derivatives. - void Explore( double & t, bool ext, double & par, double & dpar, double * ddpar, double * dddpar ) const; + void Explore( double & t, bool ext, double & par, double & dpar, double * ddpar, double * dddpar ) const; DECLARE_PERSISTENT_CLASS_NEW_DEL( MbReparamCurve3D ) }; // MbReparamCurve3D diff --git a/C3d/Include/cur_spiral.h b/C3d/Include/cur_spiral.h index a2511e1..c70fc16 100644 --- a/C3d/Include/cur_spiral.h +++ b/C3d/Include/cur_spiral.h @@ -82,14 +82,14 @@ public : public : VISITING_CLASS( MbSpiral ); - /// \ru Установить параметры спирали по другой спирали. \en Set spiral parameters by another spiral. - void Init( const MbSpiral & ); - /// \ru Установить другую локальную систему координат. \en Replace local coordinate system. - void Init( const MbPlacement3D & ); - /// \ru Установить высоту и шаг. \en Set height and step between coils of spiral. - bool Init( double height, double st ); - /// \ru Установить локальную систему координат, высоту и шаг спирали. \en Set local coordinates system, height and step of spiral. - bool Init( const MbPlacement3D & place, double height, double st ); + /// \ru Установить параметры спирали по другой спирали. \en Set spiral parameters by another spiral. + void Init( const MbSpiral & ); + /// \ru Установить другую локальную систему координат. \en Replace local coordinate system. + void Init( const MbPlacement3D & ); + /// \ru Установить высоту и шаг. \en Set height and step between coils of spiral. + bool Init( double height, double st ); + /// \ru Установить локальную систему координат, высоту и шаг спирали. \en Set local coordinates system, height and step of spiral. + bool Init( const MbPlacement3D & place, double height, double st ); // \ru Общие функции математического объекта \en Common functions of the mathematical object @@ -137,7 +137,7 @@ public : double DeviationStep( double t, double angle ) const override; size_t GetCount() const override; - double GetSpiralPeriod() const; // \ru Вернуть период \en Get period + double GetSpiralPeriod() const; // \ru Вернуть период \en Get period // \ru Заполнить плейсемент, если кривая плоская \en Fill the placement if the curve is planar bool GetPlacement( MbPlacement3D & place, PlanarCheckParams params = PlanarCheckParams() ) const override; @@ -151,61 +151,61 @@ public : virtual bool SetStep( double s ) = 0; // \ru Изменить шаг \en Change step virtual double GetSpiralRadius ( double t ) const = 0; // \ru Выдать физический радиус спирали \en Get physical radius of spiral - void CheckParam( double & t ) const; - /// \ru Дать направление спирали. \en Get direction of spiral. - void GetDirection ( MbVector3D & v ) const { v = position.GetAxisZ(); } - /// \ru Дать ось спирали. \en Get axis of spiral. - bool GetAxis( MbAxis3D & axis ) const; - /// \ru Выдать шаг. \en Get step. - double GetStep() const { return step; } - /// \ru Выдать физический шаг спирали. \en Get physical pitch of spiral. - double GetSpiralStep() const; - /// \ru Выдать полный угол спирали \en Get full angle of spiral - double GetAngle() const { return tmax-tmin; } - /// \ru Изменить граничный угол. \en Change boundary angle. - bool SetTMin( double t ) - { - C3D_ASSERT( t < tmax ); - if ( t < tmax ) { - tmin = t; - Refresh(); - return true; - } - return false; - } - /// \ru Изменить граничный угол. \en Change boundary angle. - bool SetTMax( double t ) - { - C3D_ASSERT( t > tmin ); - if ( t > tmin ) { - tmax = t; - Refresh(); - return true; - } - return false; - } - /// \ru Изменить граничные углы. \en Change boundary angles. - bool SetLimit( double t1, double t2 ) - { - if ( t1 > t2 ) - std::swap( t1, t2 ); - C3D_ASSERT( t1 < t2 ); - if ( t1 < t2 ) { - tmin = t1; - tmax = t2; - Refresh(); - return true; - } - return false; - } + void CheckParam( double & t ) const; + /// \ru Дать направление спирали. \en Get direction of spiral. + void GetDirection ( MbVector3D & v ) const { v = position.GetAxisZ(); } + /// \ru Дать ось спирали. \en Get axis of spiral. + bool GetAxis( MbAxis3D & axis ) const; + /// \ru Выдать шаг. \en Get step. + double GetStep() const { return step; } + /// \ru Выдать физический шаг спирали. \en Get physical pitch of spiral. + double GetSpiralStep() const; + /// \ru Выдать полный угол спирали \en Get full angle of spiral + double GetAngle() const { return tmax-tmin; } + /// \ru Изменить граничный угол. \en Change boundary angle. + bool SetTMin( double t ) + { + C3D_ASSERT( t < tmax ); + if ( t < tmax ) { + tmin = t; + Refresh(); + return true; + } + return false; + } + /// \ru Изменить граничный угол. \en Change boundary angle. + bool SetTMax( double t ) + { + C3D_ASSERT( t > tmin ); + if ( t > tmin ) { + tmax = t; + Refresh(); + return true; + } + return false; + } + /// \ru Изменить граничные углы. \en Change boundary angles. + bool SetLimit( double t1, double t2 ) + { + if ( t1 > t2 ) + std::swap( t1, t2 ); + C3D_ASSERT( t1 < t2 ); + if ( t1 < t2 ) { + tmin = t1; + tmax = t2; + Refresh(); + return true; + } + return false; + } const MbPlacement3D & GetPlacement() const { return position; } - bool IsPositionNormal() const { return ( !position.IsAffine() ); } + bool IsPositionNormal() const { return ( !position.IsAffine() ); } protected: static bool IsNonZeroStep( double s ) { return (::fabs( s ) >= METRIC_EPSILON); } private: - void operator = ( const MbSpiral & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbSpiral & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS( MbSpiral ) }; diff --git a/C3d/Include/cur_surface_curve.h b/C3d/Include/cur_surface_curve.h index 59ed2cc..8676893 100644 --- a/C3d/Include/cur_surface_curve.h +++ b/C3d/Include/cur_surface_curve.h @@ -252,6 +252,9 @@ public: /// \ ru Определение точек излома кривой. \en The determination of curve smoothness break points. void BreakPoints( std::vector & vBreaks, double precision = ANGLE_REGION ) const override; + /// \ru Продлить кривую. \en Extend the curve. \~ + MbResultType Extend( const MbCurveExtensionParameters & parameters, c3d::SpaceCurveSPtr & resCurve ) const override; + /** \} */ /// \ru Определить, является ли кривая curve копией этой кривой. \en Determine whether the 'curve' curve is a duplicate of the current curve. diff --git a/C3d/Include/cur_surface_intersection.h b/C3d/Include/cur_surface_intersection.h index bdb8d6a..69c60d7 100644 --- a/C3d/Include/cur_surface_intersection.h +++ b/C3d/Include/cur_surface_intersection.h @@ -542,12 +542,14 @@ public: \param[in] version - \ru Версия математики. \n \en The version of mathematics. \n \~ \param[in] insertInterimPoints - \ru Флаг, разрешающий вставлять дополнительные точки в кривые типа cbt_Specific. \n - \en Flag, which allows to insert interim points into curve of type cbt_Specific. \n \~ + \en Flag, which allows to insert interim points into curve of type cbt_Specific. \n \~ + \param[in] eps - \ru Точность сравнения точек и классификации расположения точек относительно кривой. \n + - \en The precision of points comparison and classification of point location relative to the curve. \n \~ \return \ru Возвращает true, если произошло присоединение кривой. \en Returns true if there was a curve joining. \~ */ bool MergeCurves( const MbSurfaceIntersectionCurve & addCurve, bool toBegin, bool fromBegin, bool allowCntr, - const VERSION version, bool insertInterimPoints = true, double eps = PARAM_NEAR ); + const VERSION version, bool insertInterimPoints = true, double eps = Math::paramNear ); /** \brief \ru Продлить кривую. \en Extend curve. \~ @@ -558,11 +560,13 @@ public: \param[in] beg - \ru Продлить начало кривой (true) или продлить конец кривой (false), \en Extend the beginning of the curve (true) or extend the end of the curve (false) \~ \param[in] version - \ru Версия математики. \n - \en The version of mathematics. \n \~ + \en The version of mathematics. \n \~ + \param[in] eps - \ru Точность построений.\n + - \en Build precision.\n \~ \return \ru Возвращает true, если произошло продление. \en Returns true if there was an extension. \~ */ - bool ProlongCurve( double & t, bool beg, double sag, const VERSION version ); + bool ProlongCurve( double & t, bool beg, double sag, const VERSION version, double eps = Math::paramNear ); /// \ru Согласовать параметрическую длину двумерных кривых. \en Match parametric length of two-dimensional curves. void Normalize(); @@ -728,7 +732,7 @@ private: // \ru Добавить точки одной полилинии в другую. \en Add points of one polyline to the another one. bool AddCurveToCurve( const MbCurve & from1, const MbCurve & from2, bool fromBegin, bool toBegin, MbeCurveBuildType & spec, - bool insertInterimPoints, const VERSION version ); + bool insertInterimPoints, double tolerance, const VERSION version ); // \ru Добавить базовые кривые усеченных кривых. \en Add the base curves of trimmed curves. bool AddTrimmedToTrimmed( const MbCurve * addCurveOne, const MbCurve * addCurveTwo, diff --git a/C3d/Include/cur_trimmed_curve.h b/C3d/Include/cur_trimmed_curve.h index 434b01b..c5e0168 100644 --- a/C3d/Include/cur_trimmed_curve.h +++ b/C3d/Include/cur_trimmed_curve.h @@ -129,7 +129,7 @@ public : \{ */ // \ru Вычислить значения точки и производных для заданного параметра. \en Calculate point and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - MbCartPoint & pnt, MbVector & fir, MbVector * sec, MbVector * thir ) const override; + MbCartPoint & pnt, MbVector & fir, MbVector * sec, MbVector * thir ) const override; /** \} */ /** \ru \name Функции движения по кривой @@ -149,7 +149,6 @@ public : double GetMetricLength() const override; // \ru Метрическая длина \en The metric length bool GetMiddlePoint( MbCartPoint & ) const override; // \ru Вычислить среднюю точку кривой. \en Calculate mid-point of curve. - double PointProjection( const MbCartPoint & pnt ) const override; // \ru Проекция точки на кривую \en Point projection on the curve bool IsStraight( bool ignoreParams = false ) const override; // \ru Признак прямолинейности кривой \en An attribute of curve straightness. @@ -163,7 +162,6 @@ public : /// \en Get the boundaries of the curve sections that are described by one analytical function. \~ void GetAnalyticalFunctionsBounds( std::vector & params ) const override; - const MbCurve & GetBasisCurve() const override; // \ru Вернуть базовую кривую \en Get the base curve MbCurve & SetBasisCurve() override; // \ru Вернуть базовую кривую \en Get the base curve @@ -178,16 +176,16 @@ public : MbNurbs * NurbsCurve( const MbCurveIntoNurbsInfo & ) const override; MbCurve * NurbsCurve( const MbNurbsParameters & ) const override; // \ru Построить NURBS-копию кривой \en Create a NURBS-copy of the curve - void ParameterInto( double & t ) const; // \ru Перевод параметра базовой кривой в локальный параметр \en Transformation of the base curve parameter to a local parameter - void ParameterFrom( double & t ) const; // \ru Перевод локального параметра в параметр базовой кривой \en Transformation of a local parameter to the base curve parameter - double GetBasisParameter( double & t ) const; // \ru Установить параметр в область допустимых значений \en Set the parameter into the region of the legal values - bool IsBaseParamOn( double t, double eps = Math::paramEpsilon ) const; // \ru Находится ли параметр базовой кривой в диапазоне усеченной кривой \en Whether the parameter of base curve is in range of a trimmed curve + void ParameterInto( double & t ) const; // \ru Перевод параметра базовой кривой в локальный параметр \en Transformation of the base curve parameter to a local parameter + void ParameterFrom( double & t ) const; // \ru Перевод локального параметра в параметр базовой кривой \en Transformation of a local parameter to the base curve parameter + double GetBasisParameter( double & t ) const; // \ru Установить параметр в область допустимых значений \en Set the parameter into the region of the legal values + bool IsBaseParamOn( double t, double eps = Math::paramEpsilon ) const; // \ru Находится ли параметр базовой кривой в диапазоне усеченной кривой \en Whether the parameter of base curve is in range of a trimmed curve - double GetTrim1() const { return trim1; } - double GetTrim2() const { return trim2; } - int GetSense() const { return trim2 > trim1 ? 1 : -1; } // \ru Флаг совпадения направления с направлением базовой кривой \en Flag of coincidence of the direction with the direction of base curve - void SetTrim1( double t ) { trim1 = t; InitParam( trim1, trim2, sense ); } - void SetTrim2( double t ) { trim2 = t; InitParam( trim1, trim2, sense ); } + double GetTrim1() const { return trim1; } + double GetTrim2() const { return trim2; } + int GetSense() const { return trim2 > trim1 ? 1 : -1; } // \ru Флаг совпадения направления с направлением базовой кривой \en Flag of coincidence of the direction with the direction of base curve + void SetTrim1( double t ) { trim1 = t; InitParam( trim1, trim2, sense ); } + void SetTrim2( double t ) { trim2 = t; InitParam( trim1, trim2, sense ); } void Inverse( MbRegTransform * iReg = nullptr ) override; // \ru Изменить направление кривой \en Change direction of a curve bool GetAxisPoint( MbCartPoint & p ) const override; // \ru Точка для построения оси \en Point for the axis construction @@ -208,20 +206,23 @@ public : void GetBasisPoints( MbControlData & ) const override; // \ru Выдать контрольные точки объекта. \en Get control points of object. void SetBasisPoints( const MbControlData & ) override; // \ru Изменить объект по контрольным точкам. \en Change the object by control points. - void SetBasisCurve( MbCurve & newCurve ); - void InitParam( double t1, double t2, int s, double eps = Math::paramEpsilon ); - void Init( double t1, double t2, int initSense ) { - InitParam( t1, t2, initSense ); - Refresh(); - } + /** \} */ + + void SetBasisCurve( MbCurve & newCurve ); + void InitParam( double t1, double t2, int s, double eps = Math::paramEpsilon ); + void Init( double t1, double t2, int initSense ) { + InitParam( t1, t2, initSense ); + Refresh(); + } + const MbTrimmedCurve & operator = ( const MbTrimmedCurve & source ); // \ru Присвоение параметров усеченной кривой \en Assignment of parameters of trimmed curve DECLARE_PERSISTENT_CLASS_NEW_DEL( MbTrimmedCurve ) - /** \} */ -}; +}; // MbTrimmedCurve IMPL_PERSISTENT_OPS( MbTrimmedCurve ) + //------------------------------------------------------------------------------ // \ru Находится ли параметр базовой кривой в диапазоне \en Whether the parameter of the base curve is in the range // \ru Усеченной кривой \en Of the trimmed curve diff --git a/C3d/Include/cur_trimmed_curve3d.h b/C3d/Include/cur_trimmed_curve3d.h index b3d1294..51cefab 100644 --- a/C3d/Include/cur_trimmed_curve3d.h +++ b/C3d/Include/cur_trimmed_curve3d.h @@ -95,7 +95,7 @@ public : void _Normal ( double t, MbVector3D & ) const override; // \ru Вектор главной нормали \en Vector of the principal normal // \ru Вычислить значения точки и производных для заданного параметра. \en Calculate point and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const override; + MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const override; MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & ) const override; MbCurve3D * NurbsCurve( const MbNurbsParameters & ) const override; // \ru Построить NURBS-копию кривой \en Create a NURBS-copy of the curve @@ -124,17 +124,17 @@ public : double GetLengthEvaluation() const override; // \ru Оценка метрической длины кривой \en Estimation of metric length of the curve 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 ); - 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 + void SetBasisCurve( MbCurve3D & ); // \ru Заменить плоскую кривую \en Replace the planar curve + void InitParam( double t1, double t2, int initSense ); + 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 - void ParameterInto( double &t ) const; // \ru Перевод параметра базовой кривой в параметр усеченной кривой \en Transformation of parameter of base curve to a parameter of trimmed curve - void ParameterFrom( double &t ) const; // \ru Перевод локального параметра в параметр базовой кривой \en Transformation of a local parameter to the base curve parameter - double GetBasisParameter( double &t ) const; // \ru Установить параметр в область допустимых значений \en Set the parameter into the region of the legal values + void ParameterInto( double &t ) const; // \ru Перевод параметра базовой кривой в параметр усеченной кривой \en Transformation of parameter of base curve to a parameter of trimmed curve + void ParameterFrom( double &t ) const; // \ru Перевод локального параметра в параметр базовой кривой \en Transformation of a local parameter to the base curve parameter + double GetBasisParameter( double &t ) const; // \ru Установить параметр в область допустимых значений \en Set the parameter into the region of the legal values - bool IsBaseParamOn( double t ) const; // \ru Находится ли параметр базовой кривой в диапазоне усеченной кривой \en Whether the parameter of base curve is in range of a trimmed curve + bool IsBaseParamOn( double t ) const; // \ru Находится ли параметр базовой кривой в диапазоне усеченной кривой \en Whether the parameter of base curve is in range of a trimmed curve // \ru Ближайшая проекция точки на кривую. \en The nearest projection of a point onto the curve. bool NearPointProjection( const MbCartPoint3D &, double & t, bool ext, MbRect1D * tRange = nullptr ) const override; // \ru Ближайшая проекция точки на кривую \en The nearest projection of a point onto the curve @@ -164,13 +164,14 @@ public : bool IsSimilarToCurve( const MbCurve3D & curve, double precision = METRIC_PRECISION ) const override; // \ru Подобные ли кривые для объединения (слива) \en Whether the curves for union (joining) are similar private: - void operator = ( const MbTrimmedCurve3D & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbTrimmedCurve3D & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbTrimmedCurve3D ) }; IMPL_PERSISTENT_OPS( MbTrimmedCurve3D ) + //------------------------------------------------------------------------------ // \ru Находится ли параметр базовой кривой в диапазоне усеченной кривой \en Whether the parameter of base curve is in range of a trimmed curve // --- diff --git a/C3d/Include/curve.h b/C3d/Include/curve.h index 488696c..42e55e3 100644 --- a/C3d/Include/curve.h +++ b/C3d/Include/curve.h @@ -41,14 +41,14 @@ struct MbNurbsParameters; class MATH_CLASS MbCurve; namespace c3d // namespace C3D { -typedef SPtr PlaneCurveSPtr; -typedef SPtr ConstPlaneCurveSPtr; +typedef SPtr PlaneCurveSPtr; +typedef SPtr ConstPlaneCurveSPtr; -typedef std::vector PlaneCurvesVector; -typedef std::vector ConstPlaneCurvesVector; +typedef std::vector PlaneCurvesVector; +typedef std::vector ConstPlaneCurvesVector; -typedef std::vector PlaneCurvesSPtrVector; -typedef std::vector ConstPlaneCurvesSPtrVector; +typedef std::vector PlaneCurvesSPtrVector; +typedef std::vector ConstPlaneCurvesSPtrVector; } @@ -252,7 +252,7 @@ public : \details \ru Определить, замкнута ли кривая фактически независимо от гладкости замыкания. \en Determine whether a curve is actually closed regardless of the smoothness of the closure. \~ */ - bool IsTouch( double eps = Math::LengthEps ) const; + bool IsTouch( double eps = Math::LengthEps ) const; /** \} */ /** \ru \name Функции для работы в области определения кривой. @@ -283,13 +283,13 @@ public : /// \ru Вычислить третью производную. \en Calculate third derivative. virtual void ThirdDer ( double & t, MbVector & v ) const = 0; /// \ru Вычислить касательный вектор (нормализованный). \en Calculate tangent vector (normalized). - void Tangent ( double & t, MbVector & v ) const; + void Tangent ( double & t, MbVector & v ) const; /// \ru Вычислить касательный вектор (нормализованный). \en Calculate tangent vector (normalized). - void Tangent ( double & t, MbDirection & d ) const; + void Tangent ( double & t, MbDirection & d ) const; /// \ru Вычислить вектор главной нормали (нормализованный). \en Calculate main normal vector (normalized). - void Normal ( double & t, MbVector & v ) const; + void Normal ( double & t, MbVector & v ) const; /// \ru Вычислить вектор главной нормали (нормализованный). \en Calculate main normal vector (normalized). - void Normal ( double & t, MbDirection & d ) const; + void Normal ( double & t, MbDirection & d ) const; /** \} */ /** \ru \name Функции для работы внутри и вне области определения кривой. @@ -322,13 +322,13 @@ public : /// \ru Вычислить третью производную на кривой и её продолжении. \en Calculate third derivative at curve and its extension. virtual void _ThirdDer ( double t, MbVector & v ) const; /// \ru Вычислить касательный вектор (нормализованный). \en Calculate tangent vector (normalized). - void _Tangent ( double t, MbVector & v ) const; + void _Tangent ( double t, MbVector & v ) const; /// \ru Вычислить касательный вектор (нормализованный). \en Calculate tangent vector (normalized). - void _Tangent ( double t, MbDirection & d ) const; + void _Tangent ( double t, MbDirection & d ) const; /// \ru Вычислить вектор главной нормали (нормализованный) на кривой и её продолжении. \en Calculate main normal vector (normalized) at curve and its extension. - void _Normal ( double t, MbVector & v ) const; + void _Normal ( double t, MbVector & v ) const; /// \ru Вычислить вектор главной нормали (нормализованный) на кривой и её продолжении. \en Calculate main normal vector (normalized) at curve and its extension. - void _Normal ( double t, MbDirection & d ) const; + void _Normal ( double t, MbDirection & d ) const; /** \brief \ru Вычислить значения точки и производных для заданного параметра. \en Calculate point and derivatives of object for given parameter. \~ @@ -400,9 +400,9 @@ public : /// \ru Вычислить кривизну кривой. \en Calculate curvature of curve. virtual double Curvature ( double t ) const; /// \ru Вычислить производную кривизны по параметру. \en Calculate derivative of curvature by parameter. - double CurvatureDerive( double t ) const; + double CurvatureDerive( double t ) const; /// \ru Вычислить радиус кривизны кривой со знаком. \en Calculate radius of curve with a sign. - double CurvatureRadius( double t ) const; + double CurvatureRadius( double t ) const; /** \brief \ru Вычислить метрическую длину кривой. \en Calculate the metric length of a curve. \~ @@ -424,7 +424,7 @@ public : virtual bool IsSmoothConnected( double angleEps ) const; /// \ru Вычислить параметрическую длину кривой. \en Calculate the parametric length of a curve. - double GetParamLength() const { return GetTMax() - GetTMin(); } + double GetParamLength() const { return GetTMax() - GetTMin(); } // \ru Функции с расчетом метрической длины перегружать все сразу, чтобы не было рассогласования. \en Functions with calculation of metric length, they should be overloaded simultaneously to avoid mismatches. /// \ru Вычислить метрическую длину кривой. \en Calculate the metric length of a curve. virtual double CalculateMetricLength() const; @@ -821,7 +821,7 @@ public : \param[in, out] on - \ru Искомая точка - проекция. \en The required point - projection. \~ */ - void PointProjection( const MbCartPoint & pnt, MbCartPoint & on ) const; + void PointProjection( const MbCartPoint & pnt, MbCartPoint & on ) const; /** \brief \ru Вычислить проекцию точки на кривую. \en Calculate the point projection to the curve. \~ @@ -834,7 +834,7 @@ public : \param[in, out] on - \ru Искомая точка - проекция. \en The required point - projection. \~ */ - void BasePointProjection( const MbCartPoint & pnt, MbCartPoint & on ) const; + void BasePointProjection( const MbCartPoint & pnt, MbCartPoint & on ) const; /** \brief \ru Вычислить проекцию точки на кривую. \en Calculate the point projection to the curve. \~ @@ -847,7 +847,7 @@ public : \param[in, out] angle - \ru Вычисленный угол наклона касательной к оси 0X. \en A calculated inclination angle of a curve to the axis OX. \~ */ - void PointProjectionAndAngle( MbCartPoint & on, double & angle ) const; + void PointProjectionAndAngle( MbCartPoint & on, double & angle ) const; /** \brief \ru Вычислить проекцию точки на кривую. \en Calculate the point projection to the curve. \~ @@ -862,8 +862,8 @@ public : \param[in, out] pp - \ru Искомая точка на кривой. \en Required point on the curve. \~ */ - bool DirectPointProjection( const MbCartPoint & pnt, - const MbDirection & dir, MbCartPoint & pp ) const; + bool DirectPointProjection( const MbCartPoint & pnt, + const MbDirection & dir, MbCartPoint & pp ) const; /** \brief \ru Найти ближайший перпендикуляр к кривой. \en Find the nearest perpendicular to the curve. \~ @@ -946,7 +946,7 @@ public : \param[in, out] tFind - \ru Массив параметров кривой, соответствующих точкам касания. \en An array of parameters of a curve, corresponding to the tangent points. \~ */ - void HorzIsoclinal( SArray & tFind ) const; + void HorzIsoclinal( SArray & tFind ) const; /** \brief \ru Построить вертикальные изоклины. \en Construct vertical isoclines. \~ @@ -955,10 +955,10 @@ public : \param[in, out] tFind - \ru Массив параметров кривой, соответствующих точкам касания. \en An array of parameters of a curve, corresponding to the tangent points. \~ */ - void VertIsoclinal( SArray & tFind ) const; + void VertIsoclinal( SArray & tFind ) const; /// \ru Найти нижнюю точку кривой и соответствующий ей параметр. \en Find the lowest point of a curve and the corresponding parameter. - void LowestPoint( MbCartPoint & lowestPoint, double & tLowest ) const; + void LowestPoint( MbCartPoint & lowestPoint, double & tLowest ) const; /** \brief \ru Найти самопересечения кривой. \en Find self-intersections of curve. \~ @@ -1032,11 +1032,11 @@ public : virtual size_t GetCount() const; /// \ru Выдать n точек кривой с равными интервалами по параметру. \en Get n points of a curve with equal intervals by parameter. - void GetPointsByEvenParamDelta ( size_t n, std::vector & pnts ) const; - void GetPointsByEvenParamDelta ( size_t n, SArray & pnts ) const; // Deprecated. + void GetPointsByEvenParamDelta ( size_t n, std::vector & pnts ) const; + void GetPointsByEvenParamDelta ( size_t n, SArray & pnts ) const; // Deprecated. /// \ru Выдать n точек кривой с равными интервалами по длине дуги. \en Get n points of a curve with equal intervals by arc length. virtual void GetPointsByEvenLengthDelta( size_t n, std::vector & pnts ) const; - void GetPointsByEvenLengthDelta( size_t n, SArray & pnts ) const; // Deprecated. + void GetPointsByEvenLengthDelta( size_t n, SArray & pnts ) const; // Deprecated. /** \brief \ru Вычислить минимальную длину кривой между двумя точками на ней. \en Calculate minimal length of a curve between two points on it. \~ @@ -1064,9 +1064,9 @@ public : virtual bool GetWeightCentre ( MbCartPoint & ) const; /// \ru Проверить лежит ли точка на кривой с точностью eps. \en Check whether the point is on a curve with the tolerance eps. - bool IsPointOn( const MbCartPoint &, double eps = Math::LengthEps ) const; + bool IsPointOn( const MbCartPoint &, double eps = Math::LengthEps ) const; /// \ru Проверить лежит ли параметр в диапазоне кривой с точностью eps. \en Check whether the parameter is inside a range with the tolerance eps. - bool IsParamOn( double t, double eps = Math::paramEpsilon ) const; + bool IsParamOn( double t, double eps = Math::paramEpsilon ) const; /** \brief \ru Корректировать параметр для замкнутых кривых. \en Correct parameter for closed curves. \~ @@ -1081,7 +1081,7 @@ public : \param[in] eps - \ru Точность попадания на край диапазона. \en A tolerance of getting to the bound of the range. \~ */ - void CorrectCyclicParameter( double & t, double eps = Math::paramRegion ) const; + void CorrectCyclicParameter( double & t, double eps = Math::paramRegion ) const; /** \brief \ru Корректировать параметр. \en Correct parameter. \~ @@ -1090,12 +1090,12 @@ public : \param[in, out] t - \ru На входе - заданное значение параметра, на выходе - скорректированное. \en Input - given value of parameter, output - corrected value of parameter. \~ */ - void CorrectParameter ( double & t ) const; + void CorrectParameter ( double & t ) const; /// \ru Сделать копию с измененным направлением. \en Create a copy with changed direction. MbCurve * InverseDuplicate() const; /// \ru Определить, являются ли кривая инверсно такой же. \en Define whether an inversed curve is the same. - bool IsInverseSame( const MbCurve & curve, double accuracy = LENGTH_EPSILON ) const; + bool IsInverseSame( const MbCurve & curve, double accuracy = LENGTH_EPSILON ) const; /** \brief \ru Определить, является ли кривая репараметризованно такой же. \en Define whether a reparameterized curve is the same. \~ @@ -1103,10 +1103,8 @@ public : \en Define whether a reparameterized curve is the same. \~ \param[in] curve - \ru Кривая для сравнения. \en A curve for comparison. \~ - \param[out] factor - \ru Коэффициент сжатия параметрической области при переходе - к указанной кривой. - \en Coefficient of compression of parametric region at the time of transition - to the pointed curve. \~ + \param[out] factor - \ru Коэффициент сжатия параметрической области при переходе к указанной кривой. + \en Coefficient of compression of parametric region at the time of transition to the pointed curve. \~ */ virtual bool IsReparamSame( const MbCurve & curve, double & factor ) const; @@ -1119,7 +1117,7 @@ public : \return \ru Вычисленная точка. \en A calculated point. \~ */ - MbCartPoint GetLimitPoint( ptrdiff_t number ) const; + MbCartPoint GetLimitPoint( ptrdiff_t number ) const; /** \brief \ru Вычислить граничную точку. \en Calculate the boundary point. \~ @@ -1130,7 +1128,7 @@ public : \param[in, out] pnt - \ru Вычисленная точка. \en A calculated point. \~ */ - void GetLimitPoint( ptrdiff_t number, MbCartPoint & pnt ) const; + void GetLimitPoint( ptrdiff_t number, MbCartPoint & pnt ) const; /** \brief \ru Вычислить касательный вектор в граничной точке. \en Calculate a tangent vector to the boundary point. \~ @@ -1141,7 +1139,7 @@ public : \param[in, out] v - \ru Касательный вектор. \en Tangent vector \~ */ - void GetLimitTangent( ptrdiff_t number, MbVector & v ) const; + void GetLimitTangent( ptrdiff_t number, MbVector & v ) const; /** \brief \ru Вычислить касательный вектор и точку на конце кривой. \en Calculate a tangent vector and point at the end of a curve. \~ @@ -1154,7 +1152,7 @@ public : \param[in, out] v - \ru Касательный вектор. \en Tangent vector \~ */ - void GetLimitPointAndTangent( ptrdiff_t number, MbCartPoint & pnt, MbVector & v ) const; + void GetLimitPointAndTangent( ptrdiff_t number, MbCartPoint & pnt, MbVector & v ) const; /** \brief \ru Равны ли граничные точки? \en Are boundary points equal? \~ @@ -1163,7 +1161,7 @@ public : \return \ru true, если точки равны. \en Returns true if points are equal. \~ */ - bool AreLimitPointsEqual() const { return GetLimitPoint( 1 ) == GetLimitPoint( 2 ); } + bool AreLimitPointsEqual() const { return GetLimitPoint( 1 ) == GetLimitPoint( 2 ); } /** \brief \ru Вернуть характерную точку кривой. \en Return a specific point of a curve. \~ @@ -1173,10 +1171,8 @@ public : Specific points of a bounded curve are its start and end points. \~ \param[in] from - \ru Контрольная точка. \en A control point \~ - \param[in, out] dmax - \ru На входе - максимальное расстояние для поиска характерной точки. - На выходе - расстояние от точки from до найденной характерной точки. - \en Input - maximum distance for search of specific point. - Output - a distance from the point 'from' to the found specific point. \~ + \param[in, out] dmax - \ru На входе - максимальное расстояние для поиска характерной точки. На выходе - расстояние от точки from до найденной характерной точки. + \en Input - maximum distance for search of specific point. Output - a distance from the point 'from' to the found specific point. \~ \param[in, out] pnt - \ru Касательный вектор. \en Tangent vector. \~ \result \ru true - если характерная точка найдена. @@ -1227,9 +1223,9 @@ public : virtual double GetTRegion ( double t, double epsilon ) const; /// \ru Вернуть середину параметрического диапазона кривой. \en Return the middle of parametric range of a curve. - double GetTMid() const { return ((GetTMin() + GetTMax()) * 0.5); } + double GetTMid() const { return ((GetTMin() + GetTMax()) * 0.5); } /// \ru Вернуть параметрическую длину кривой. \en Return the parametric length of a curve. - double GetTRange() const { return (GetTMax() - GetTMin()); } + double GetTRange() const { return (GetTMax() - GetTMin()); } /// \ru Вычислить точку на кривой. \en Calculate point on the curve. MbCartPoint PointOn ( double & t ) const; /// \ru Вычислить первую производную. \en Calculate first derivative. @@ -1239,7 +1235,7 @@ public : /// \ru Вычислить нормальный вектор. \en Calculate the normal vector. MbDirection Normal ( double & t ) const; /// \ru Вычислить длину вектора производной. \en Calculate the length of derivative vector. - double DerLength( double & t ) const; + double DerLength( double & t ) const; /** \brief \ru Получить границы участков кривой, которые описываются одной аналитической функцией. \en Get the boundaries of the curve sections that are described by one analytical function. \~ @@ -1309,15 +1305,13 @@ public : \param[in] devSag - \ru Максимальная величина прогиба. \en Maximal value of sag. \~ */ - bool IsSpaceNear( const MbCurve & curve, double eps, bool ext, double devSag = 5.0*Math::deviateSag ) const; + bool IsSpaceNear( const MbCurve & curve, double eps, bool ext, double devSag = 5.0*Math::deviateSag ) const; /** \brief \ru Определить, близки ли две кривые метрически. \en Check whether the two curves are metrically close. \~ - \details \ru Близость кривых определяется, исходя из равенства их конечных точек - и расстояния произвольной точки одной кривой от другой кривой. + \details \ru Близость кривых определяется, исходя из равенства их конечных точек и расстояния произвольной точки одной кривой от другой кривой. Параметрически кривые могут отличаться. - \en The proximity of curves is defined by equality of their ends - and the distance of an arbitrary point of one curve to another curve. + \en The proximity of curves is defined by equality of their ends and the distance of an arbitrary point of one curve to another curve. Curves may differ parametrically. \~ \param[in] curve - \ru Кривая, с которой производится сравнение. \en A curve to compare with. \~ @@ -1336,16 +1330,16 @@ public : \param[in] devSag - \ru Максимальная величина прогиба. \en Maximal value of sag. \~ */ - bool IsSpaceNear( const MbCurve & curve, double xEps, double yEps, bool ext, - double xNear, double yNear, - double devSag = 5.0*Math::deviateSag ) const; + bool IsSpaceNear( const MbCurve & curve, double xEps, double yEps, bool ext, + double xNear, double yNear, + double devSag = 5.0*Math::deviateSag ) const; - SimpleName GetCurveName() const { return name; } ///< \ru Имя кривой. \en A curve name. - void SetCurveName( SimpleName newName ) { name = newName; } ///< \ru Установить имя кривой. \en Set a curve name. + SimpleName GetCurveName() const { return name; } ///< \ru Имя кривой. \en A curve name. + void SetCurveName( SimpleName newName ) { name = newName; } ///< \ru Установить имя кривой. \en Set a curve name. /** \} */ // \ru Функции унификации объекта и вектора объектов в шаблонных функциях. \en Functions for compatibility of a object and a vector of objects in template functions. - size_t size() const { return 1; } ///< \ru Количество объектов при трактовке объекта как вектора объектов. \en Number of objects if object is interpreted as vector of objects. + size_t size() const { return 1; } ///< \ru Количество объектов при трактовке объекта как вектора объектов. \en Number of objects if object is interpreted as vector of objects. const MbCurve * operator [] ( size_t ) const { return this; } ///< \ru Оператор доступа. \en An access operator. /** \brief \ru Продлить кривую. @@ -1365,8 +1359,8 @@ public : virtual MbResultType Extend( const MbCurveExtensionParameters & parameters, c3d::PlaneCurveSPtr & resCurve ) const; private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию \en Declaration without implementation of the assignment operator to prevent an assignment by default - void operator = ( const MbCurve & ); + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию \en Declaration without implementation of the assignment operator to prevent an assignment by default + void operator = ( const MbCurve & ); DECLARE_PERSISTENT_CLASS( MbCurve ) diff --git a/C3d/Include/curve3d.h b/C3d/Include/curve3d.h index c4f4ada..d658f1e 100644 --- a/C3d/Include/curve3d.h +++ b/C3d/Include/curve3d.h @@ -188,7 +188,7 @@ public : \details \ru Определить, замкнута ли кривая фактически независимо от гладкости замыкания. \en Determine whether a curve is actually closed regardless of the smoothness of the closure. \~ */ - bool IsTouch( double eps = Math::metricPrecision ) const; + bool IsTouch( double eps = Math::metricPrecision ) const; /** \} */ @@ -369,7 +369,7 @@ public : \en A sag value by parameter at given point. \~ \ingroup Curves_3D */ - double CurveStep( const double & t, const MbStepData & stepData ) const; + double CurveStep( const double & t, const MbStepData & stepData ) const; /** \} */ /** \ru \name Общие функции кривой @@ -500,7 +500,7 @@ public : virtual MbCurve3D * Trimmed( double t1, double t2, int sense ) const; // \ru Создание усеченной кривой. \en Creation of trimmed curve. /// \ru Вернуть параметрическую длину кривой. \en Return the parametric length of a curve. - double GetParamLength () const { return GetTMax() - GetTMin(); } + double GetParamLength () const { return GetTMax() - GetTMin(); } // \ru Функции с расчетом метрической длины перегружать все сразу, чтобы не было рассогласования \en Functions with calculation of metric length, they should be overloaded simultaneously to avoid mismatches /// \ru Вычислить метрическую длину кривой. \en Calculate the metric length of a curve. @@ -778,11 +778,11 @@ public : virtual size_t GetCount() const; /// \ru Выдать n точек кривой с равными интервалами по параметру. \en Get n points of a curve with equal intervals by parameter. - void GetPointsByEvenParamDelta ( size_t n, std::vector & pnts ) const; - void GetPointsByEvenParamDelta ( size_t n, SArray & pnts ) const; // Deprecated. + void GetPointsByEvenParamDelta ( size_t n, std::vector & pnts ) const; + void GetPointsByEvenParamDelta ( size_t n, SArray & pnts ) const; // Deprecated. /// \ru Выдать n точек кривой с равными интервалами по длине дуги. \en Get n points of a curve with equal intervals by arc length. virtual void GetPointsByEvenLengthDelta( size_t n, std::vector & pnts ) const; - void GetPointsByEvenLengthDelta( size_t n, SArray & pnts ) const; // Deprecated. + void GetPointsByEvenLengthDelta( size_t n, SArray & pnts ) const; // Deprecated. void GetBasisPoints( MbControlData3D & ) const override; // \ru Выдать контрольные точки объекта. \en Get control points of object. void SetBasisPoints( const MbControlData3D & ) override; // \ru Изменить объект по контрольным точкам. \en Change the object by control points. @@ -833,14 +833,14 @@ public : \en True - if curves are metrically close. \~ \ingroup Curves_3D */ - bool IsSpaceNear( const MbCurve3D & curve, double eps, bool ext, double devSag = 5.0*Math::deviateSag ) const; + bool IsSpaceNear( const MbCurve3D & curve, double eps, bool ext, double devSag = 5.0*Math::deviateSag ) const; /// \ru Проверить, лежит ли точка на кривой. \en Check whether a point is on a curve or not. - bool IsPointOn( const MbCartPoint3D &, double eps = METRIC_PRECISION ) const; + bool IsPointOn( const MbCartPoint3D &, double eps = METRIC_PRECISION ) const; /// \ru Вернуть середину параметрического диапазона кривой. \en Return the middle of parametric range of a curve. - double GetTMid() const { return ((GetTMin() + GetTMax()) * 0.5); } + double GetTMid() const { return ((GetTMin() + GetTMax()) * 0.5); } /// \ru Вернуть параметрическую длину кривой. \en Return the parametric length of a curve. - double GetTRange() const { return (GetTMax() - GetTMin()); } + double GetTRange() const { return (GetTMax() - GetTMin()); } /// \ru Вычислить точку на кривой. \en Calculate point on the curve. MbCartPoint3D PointOn ( double & t ) const; @@ -901,7 +901,7 @@ public : \en A calculated point. \~ \ingroup Curves_3D */ - MbCartPoint3D GetLimitPoint( ptrdiff_t number ) const; // \ru number <= 1 : в начале, иначе - в конце \en Number <= 1 : at start, otherwise - at end + MbCartPoint3D GetLimitPoint( ptrdiff_t number ) const; // \ru number <= 1 : в начале, иначе - в конце \en Number <= 1 : at start, otherwise - at end /** \brief \ru Вычислить граничную точку. \en Calculate the boundary point. \~ @@ -913,7 +913,7 @@ public : \en A calculated point. \~ \ingroup Curves_3D */ - void GetLimitPoint( ptrdiff_t number, MbCartPoint3D & pnt ) const; + void GetLimitPoint( ptrdiff_t number, MbCartPoint3D & pnt ) const; /** \brief \ru Вычислить касательный вектор в граничной точке. \en Calculate a tangent vector to the boundary point. \~ @@ -924,7 +924,7 @@ public : \return \ru Касательный вектор. \en Tangent vector. \~ */ - MbVector3D GetLimitTangent( ptrdiff_t number ) const; + MbVector3D GetLimitTangent( ptrdiff_t number ) const; /** \brief \ru Вычислить касательный вектор в граничной точке. \en Calculate a tangent vector to the boundary point. \~ @@ -935,7 +935,7 @@ public : \param[in, out] v - \ru Касательный вектор. \en Tangent vector. \~ */ - void GetLimitTangent( ptrdiff_t number, MbVector3D & v ) const; + void GetLimitTangent( ptrdiff_t number, MbVector3D & v ) const; /** \brief \ru Равны ли граничные точки. \en Are boundary points equal? \~ @@ -944,14 +944,14 @@ public : \return \ru true, если точки равны. \en Returns true if points are equal. \~ */ - bool AreLimitPointsEqual() const { return GetLimitPoint( 1 ) == GetLimitPoint( 2 ); } + bool AreLimitPointsEqual() const { return GetLimitPoint( 1 ) == GetLimitPoint( 2 ); } /// \ru Загнать в параметрическую область. \en Move to the parametric region. - bool SetInParamRegion( double & t ) const; + bool SetInParamRegion( double & t ) const; /// \ru Проверить, что параметр в диапазоне кривой. \en Check whether a parameter is in the range of the curve. - bool IsParamOn( double t, double eps ) const { return ( GetTMin()-eps<=t && t<=GetTMax()+eps ); } + bool IsParamOn( double t, double eps ) const { return ( GetTMin()-eps<=t && t<=GetTMax()+eps ); } /// \ru Являются ли кривая инверсно такой же? \en Whether an inversed curve is the same. - bool IsInverseSame( const MbCurve3D & curve, double accuracy = LENGTH_EPSILON ) const; + bool IsInverseSame( const MbCurve3D & curve, double accuracy = LENGTH_EPSILON ) const; /** \brief \ru Определить, является ли кривая репараметризованно такой же. \en Define whether a reparameterized curve is the same. \~ @@ -971,13 +971,13 @@ public : /// \ru Дать приращение параметра, соответствующее единичной длине в пространстве. \en Get increment of parameter, corresponding to the unit length in space. virtual double GetParamToUnit( double t ) const; /// \ru Дать минимально различимую величину параметра. \en Get the minimum distinguishable value of parameter. - double GetTEpsilon() const; + double GetTEpsilon() const; /// \ru Дать минимально различимую величину параметра. \en Get the minimum distinguishable value of parameter. - double GetTEpsilon( double t ) const; + double GetTEpsilon( double t ) const; /// \ru Дать минимально различимую величину параметра. \en Get the minimum distinguishable value of parameter. - double GetTRegion() const; + double GetTRegion() const; /// \ru Дать минимально различимую величину параметра. \en Get the minimum distinguishable value of parameter. - double GetTRegion( double t ) const; + double GetTRegion( double t ) 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. @@ -1031,7 +1031,7 @@ public : \return \ru true, если создана плоская кривая. \en true if a flat curve was created. \~ */ - bool GetPlaneCurve( SPtr & curve2d, MbPlacement3D & place, bool saveParams, PlanarCheckParams params = PlanarCheckParams() ) const; + bool GetPlaneCurve( SPtr & curve2d, MbPlacement3D & place, bool saveParams, PlanarCheckParams params = PlanarCheckParams() ) const; /** \brief \ru Дать плоскую кривую и плейсмент, если пространственная кривая плоская. \en Get planar curve and placement if the space curve is planar. \~ @@ -1052,14 +1052,14 @@ public : \return \ru true, если создана плоская кривая. \en true if a flat curve was created. \~ */ - bool GetPlaneCurve( SPtr & curve2d, MbPlacement3D & place, bool saveParams, PlanarCheckParams params = PlanarCheckParams() ) const; + bool GetPlaneCurve( SPtr & curve2d, MbPlacement3D & place, bool saveParams, PlanarCheckParams params = PlanarCheckParams() ) const; /// \ru Дать поверхностную кривую, если пространственная кривая поверхностная (после использования вызывать DeleteItem на аргументы). \en Get surface curve if the space curve is surface (after the using call DeleteItem for arguments) virtual bool GetSurfaceCurve( MbCurve *& curve2d, MbSurface *& surface, VERSION version = Math::DefaultMathVersion() ) const; /// \ru Дать поверхностную кривую, если пространственная кривая поверхностная (после использования вызывать DeleteItem на аргументы). \en Get surface curve if the space curve is surface (after the using call DeleteItem for arguments) - bool GetSurfaceCurve( SPtr & curve2d, SPtr & surface, VERSION version = Math::DefaultMathVersion() ) const; + bool GetSurfaceCurve( SPtr & curve2d, SPtr & surface, VERSION version = Math::DefaultMathVersion() ) const; /// \ru Дать поверхностную кривую, если пространственная кривая поверхностная (после использования вызывать DeleteItem на аргументы). \en Get surface curve if the space curve is surface (after the using call DeleteItem for arguments) - bool GetSurfaceCurve( SPtr & curve2d, SPtr & surface, VERSION version = Math::DefaultMathVersion() ) const; + bool GetSurfaceCurve( SPtr & curve2d, SPtr & surface, VERSION version = Math::DefaultMathVersion() ) const; /// \ru Заполнить плейсемент, если кривая плоская. \en Fill the placement if a curve is planar. virtual bool GetPlacement( MbPlacement3D & place, PlanarCheckParams params = PlanarCheckParams() ) const; /// \ru Является ли объект смещением. \en Is the object is a shift? @@ -1067,10 +1067,10 @@ public : /// \ru Подобные ли кривые для объединения (слива). \en Whether the curves to union (joining) are similar. virtual bool IsSimilarToCurve( const MbCurve3D & other, double precision = METRIC_PRECISION ) const; /// \ru Аппроксимация кривой плоскогранной трубкой радиуса radius. \en Approximation of a curve by the flat tube with the given radius. - void CalculateGrid( double radius, const MbStepData & stepData, MbMesh & mesh ) const; + void CalculateGrid( double radius, const MbStepData & stepData, MbMesh & mesh ) const; - SimpleName GetCurveName() const { return name; } ///< \ru Имя кривой. \en A curve name. - void SetCurveName( SimpleName newName ) { name = newName; } ///< \ru Установить имя кривой. \en Set a curve name. + SimpleName GetCurveName() const { return name; } ///< \ru Имя кривой. \en A curve name. + void SetCurveName( SimpleName newName ) { name = newName; } ///< \ru Установить имя кривой. \en Set a curve name. /** \} */ /** \brief \ru Продлить кривую. @@ -1086,16 +1086,15 @@ public : \warning \ru В разработке. \en Under development. \~ */ -// --- virtual MbResultType Extend( const MbCurveExtensionParameters & parameters, c3d::SpaceCurveSPtr & resCurve ) const; - // \ru Функции унификации кривой и вектора кривых в шаблонных функциях. \en Functions for compatibility of a curve and a vector of curves in template functions. - size_t size() const { return 1; } ///< \ru Размер кривой трактуемой как в виде вектора кривых. \en Size of curve interpreted as vector of curves. + // \ru Функции унификации кривой и вектора кривых в шаблонных функциях. \en Functions for compatibility of a curve and a vector of curves in template functions. + size_t size() const { return 1; } ///< \ru Размер кривой трактуемой как в виде вектора кривых. \en Size of curve interpreted as vector of curves. const MbCurve3D * operator [] ( size_t ) const { return this; } ///< \ru Оператор доступа. \en An access operator. private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию \en Declaration without implementation of the assignment operator to prevent an assignment by default - MbCurve3D & operator = ( const MbCurve3D & ); + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию \en Declaration without implementation of the assignment operator to prevent an assignment by default + MbCurve3D & operator = ( const MbCurve3D & ); DECLARE_PERSISTENT_CLASS( MbCurve3D ) }; diff --git a/C3d/Include/func_analytical_function.h b/C3d/Include/func_analytical_function.h index a357d4d..a8a3625 100644 --- a/C3d/Include/func_analytical_function.h +++ b/C3d/Include/func_analytical_function.h @@ -47,9 +47,9 @@ public : const MbListVars & vars, const c3d::string_t & data, const c3d::string_t & argument, - double tmin, - double tmax, - bool sense ); + double tmin, + double tmax, + bool sense ); virtual ~MdCharacterFunction(); private: @@ -61,8 +61,8 @@ public : MbFunction & Duplicate() const override; // \ru Сделать копию элемента \en Create a copy of the element bool IsSame ( const MbFunction & other, double accuracy = LENGTH_EPSILON ) const override; // \ru Являются ли объекты равными \en Determine whether objects are equal bool SetEqual ( const MbFunction & ) override; // \ru Сделать равным \en Make equal - void GetProperties( MbProperties & ) override; // \ru Выдать свойства объекта \en Get properties of object - void SetProperties( const MbProperties & ) override; // \ru Записать свойства объекта \en Set properties of object + void GetProperties( MbProperties & ) override; // \ru Выдать свойства объекта \en Get properties of object + void SetProperties( const MbProperties & ) override; // \ru Записать свойства объекта \en Set properties of object double GetTMin () const override; // \ru Вернуть минимальное значение параметра \en Get the minimum value of parameter double GetTMax () const override; // \ru Вернуть максимальное значение параметра \en Get the maximum value of parameter @@ -75,7 +75,7 @@ public : double ThirdDer ( double & t ) const override; // \ru Третья производная по t \en The third derivative with respect to t // \ru Вычислить значение и производные. \en Calculate value and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - double & val, double & fir, double * sec, double * thr ) const override; + double & val, double & fir, double * sec, double * thr ) const override; void Inverse ( MbRegTransform * iReg = nullptr ) override; // \ru Изменить направление \en Change direction double Step ( double t, double sag ) const override; @@ -99,16 +99,17 @@ public : MbFunction * BreakFunction( double t, bool beg ) override; private: - void Translate (); - void CheckParam ( double & t ) const; + void Translate (); + void CheckParam ( double & t ) const; private: - void operator = ( const MdCharacterFunction & ); // \ru Не реализовано \en Not implemented + void operator = ( const MdCharacterFunction & ); // \ru Не реализовано \en Not implemented DECLARE_PERSISTENT_CLASS_NEW_DEL( MdCharacterFunction ) }; IMPL_PERSISTENT_OPS( MdCharacterFunction ) + //------------------------------------------------------------------------------ /** \brief \ru Скалярная функция, заданная аналитическим выражением. \en The analytical function. \~ @@ -200,4 +201,5 @@ private: IMPL_PERSISTENT_OPS( MdAnalyticalFunction ) + #endif // __FUNC_ANLYTICAL_FUNCTION_H diff --git a/C3d/Include/func_const_function.h b/C3d/Include/func_const_function.h index 1b3e631..2df608a 100644 --- a/C3d/Include/func_const_function.h +++ b/C3d/Include/func_const_function.h @@ -33,14 +33,14 @@ private: public : virtual ~MbConstFunction(); public: - void Init ( double v ); ///< \ru Инициализация по значению. \en Initialization by the value. + void Init ( double v ); ///< \ru Инициализация по значению. \en Initialization by the value. public: // \ru Общие функции математического объекта \en Common functions of mathematical object - MbeFunctionType IsA() const override; // \ru Тип элемента \en A type of element - MbFunction & Duplicate () const override; // \ru Сделать копию элемента \en Create a copy of the element + MbeFunctionType IsA() const override; // \ru Тип элемента \en A type of element + MbFunction & Duplicate () const override; // \ru Сделать копию элемента \en Create a copy of the element bool IsSame ( const MbFunction & other, double accuracy = LENGTH_EPSILON ) const override; // \ru Являются ли объекты равными \en Determine whether objects are equal bool SetEqual ( const MbFunction & ) override; // \ru Сделать равным \en Make equal - void GetProperties( MbProperties & ) override; // \ru Выдать свойства объекта \en Get properties of the object + void GetProperties( MbProperties & ) override; // \ru Выдать свойства объекта \en Get properties of the object void SetProperties( const MbProperties & ) override; // \ru Записать свойства объекта \en Set properties of the object double GetTMax () const override; // \ru Вернуть максимальное значение параметра \en Get the maximum value of parameter @@ -59,7 +59,7 @@ public: double _ThirdDer ( double t ) const override; // \ru Третья производная по t \en The third derivative with respect to t // \ru Вычислить значение и производные. \en Calculate value and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - double & val, double & fir, double * sec, double * thr ) const override; + double & val, double & fir, double * sec, double * thr ) const override; void Inverse ( MbRegTransform * iReg = nullptr ) override; // \ru Изменить направление \en Change direction double Step( double t, double sag ) const override; @@ -84,11 +84,12 @@ public: MbFunction * BreakFunction( double t, bool beg ) override; private: - void operator = ( const MbConstFunction & ); // \ru Не реализовано \en Not implemented + void operator = ( const MbConstFunction & ); // \ru Не реализовано \en Not implemented DECLARE_PERSISTENT_CLASS_NEW_DEL( MbConstFunction ) }; IMPL_PERSISTENT_OPS( MbConstFunction ) + #endif // __FUNC_CONST_FUNCTION_H diff --git a/C3d/Include/func_cubic_function.h b/C3d/Include/func_cubic_function.h index 6dace13..856ee7f 100644 --- a/C3d/Include/func_cubic_function.h +++ b/C3d/Include/func_cubic_function.h @@ -28,15 +28,15 @@ c3d_constexpr size_t FUNC_NUMB = 4; ///< \ru Количество элемент // --- class MATH_CLASS MbCubicFunction : public MbFunction { protected: - SArray valueList; ///< \ru Контрольные точки. \en The control points. - SArray firstList; ///< \ru Производные в контрольных точках. \en The derivatives in control points. - SArray tList; ///< \ru Значения параметров функции, которую моделирует кубический сплайн. \en The values of parameters on a function which is modeled by a cubic spline. - bool monotonic; ///< \ru Признак монотонности набора значений. \en The sign of monotonicity of a set of values. - bool closed; ///< \ru Для немонотонного набора значений - признак замыкания на начальное значение. - ///< \ru Для монотонного набора значений - признак периодичности набора. - ///< \en For a non-monotonic set of values, the sign of closeness to the initial value. - ///< \en For a monotonic set of values, the sign of periodicity of a monotonic set of values. - ptrdiff_t uppIndex; ///< \ru Количество интервалов (число точек - 1). \en The number of intervals (a number of points - 1). + SArray valueList; ///< \ru Контрольные точки. \en The control points. + SArray firstList; ///< \ru Производные в контрольных точках. \en The derivatives in control points. + SArray tList; ///< \ru Значения параметров функции, которую моделирует кубический сплайн. \en The values of parameters on a function which is modeled by a cubic spline. + bool monotonic; ///< \ru Признак монотонности набора значений. \en The sign of monotonicity of a set of values. + bool closed; ///< \ru Для немонотонного набора значений - признак замыкания на начальное значение. + ///< \ru Для монотонного набора значений - признак периодичности набора. + ///< \en For a non-monotonic set of values, the sign of closeness to the initial value. + ///< \en For a monotonic set of values, the sign of periodicity of a monotonic set of values. + ptrdiff_t uppIndex; ///< \ru Количество интервалов (число точек - 1). \en The number of intervals (a number of points - 1). public : /// \ru Конструктор по точкам и признаку замкнутости. \en Constructor by points and an attribute of closedness. @@ -56,10 +56,10 @@ public : public: /// \ru Инициализация по точкам, параметрам и признаку замкнутости. \en Initialization by points, parameters and an attribute of closedness. - void Init( const SArray & values, + void Init( const SArray & values, const SArray & params, bool cls ); /// \ru Инициализация монотонного сплайна. \en Monotone spline initialization. - bool InitMonotonic( const SArray & values, const SArray & params, bool valClosed ); + bool InitMonotonic( const SArray & values, const SArray & params, bool valClosed ); public: // \ru Общие функции математического объекта \en Common functions of mathematical object MbeFunctionType IsA () const override; // \ru Тип элемента \en A type of element @@ -85,7 +85,7 @@ public: double _ThirdDer ( double t ) const override; // \ru Третья производная по t \en The third derivative with respect to t // \ru Вычислить значение и производные. \en Calculate value and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - double & val, double & fir, double * sec, double * thr ) const override; + double & val, double & fir, double * sec, double * thr ) const override; // \ru Вычислить аргумент t по значению функции. \en Calculate the argument t by the function value. double Argument( double & val ) const override; @@ -113,41 +113,42 @@ public: MbFunction * Trimmed( double t1, double t2, int sense ) const override; // \ru Разбить функцию точкой с параметром t и вернуть отрезанную часть. \en Function break by the parameter t, and cut off part of the function: begs == true - save the initial half, beg == false - save the final half. MbFunction * BreakFunction( double t, bool beg ) override; - MbFunction * Break( double t1, double t2 ) const; ///< \ru Выделить часть функции. \en Select a part of a function. - // \ru В указанной точке t установить заданное поведение, изменив функцию на интервале, не превышающем tDelta. \en Set a given behavior at point t by modifying the function of an interval not exceeding tDelta. - void SetFunctionValue( double t, const double & val, double tDelta, const double & der, double eps ); + MbFunction * Break( double t1, double t2 ) const; ///< \ru Выделить часть функции. \en Select a part of a function. + // \ru В указанной точке t установить заданное поведение, изменив функцию на интервале, не превышающем tDelta. \en Set a given behavior at point t by modifying the function of an interval not exceeding tDelta. + void SetFunctionValue( double t, const double & val, double tDelta, const double & der, double eps ); - size_t GetParamsCount() const; ///< \ru Выдать количество параметров. \en Get count of parameters. - double GetParam( size_t index ) const; // \ru Дать значение параметра точки по номеру \en Get the value of point parameter by its number - void GetTList( SArray & params ) const; ///< \ru Выдать параметры. \en Get parameters tList. - size_t GetValuesCount() const; // \ru Выдать количество опорных точек \en Get the number of control points - double GetValue( size_t index ) const; // \ru Дать значение точки по номеру \en Get the value of point by its number - bool SetValue( size_t index, double v ); // \ru Установить значение точки по номеру \en Set the value of point by its number - void GetValueList( SArray & vals ) const; ///< \ru Вернуть массив контрольных значений. \en Get array of control values. - double GetDerive( size_t index ) const; // \ru Дать значение производной по номеру \en Get the value of derivative by its number - bool SetDerive( size_t index, double v ); // \ru Дать значение производной по номеру \en Get the value of derivative by its number - bool CalculateDerivatives(); // \ru Расчет производных. \en Calculation of derivatives + size_t GetParamsCount() const; ///< \ru Выдать количество параметров. \en Get count of parameters. + double GetParam( size_t index ) const; // \ru Дать значение параметра точки по номеру \en Get the value of point parameter by its number + void GetTList( SArray & params ) const; ///< \ru Выдать параметры. \en Get parameters tList. + size_t GetValuesCount() const; // \ru Выдать количество опорных точек \en Get the number of control points + double GetValue( size_t index ) const; // \ru Дать значение точки по номеру \en Get the value of point by its number + bool SetValue( size_t index, double v ); // \ru Установить значение точки по номеру \en Set the value of point by its number + void GetValueList( SArray & vals ) const; ///< \ru Вернуть массив контрольных значений. \en Get array of control values. + double GetDerive( size_t index ) const; // \ru Дать значение производной по номеру \en Get the value of derivative by its number + bool SetDerive( size_t index, double v ); // \ru Дать значение производной по номеру \en Get the value of derivative by its number + bool CalculateDerivatives(); // \ru Расчет производных. \en Calculation of derivatives private: inline bool LocalCoordinate( double & t, ptrdiff_t & j1, ptrdiff_t & j2, double & y1, double & y2, double & t1, double & t2 ) const; - ptrdiff_t GetIndex ( double t ) const; - void ParamPoint ( double y1, double y2, double t1, double t2, double * tLoft ) const; - void ParamFirst ( double y1, double y2, double t1, double t2, double * tLoft ) const; - void ParamSecond( double y1, double y2, double t1, double t2, double * tLoft ) const; - void ParamThird ( double t1, double t2, double * tLoft ) const; - bool SetCorrection( size_t ind, double tDelta ); // \ru Скорректировать функцию по индексу. \en Function correction by index. - void CalculateValues( size_t i1, size_t i2 ); // \ru Скорректировать функцию на интервале i1-i2. \en Function correction on the interval i1-i2. + ptrdiff_t GetIndex ( double t ) const; + void ParamPoint ( double y1, double y2, double t1, double t2, double * tLoft ) const; + void ParamFirst ( double y1, double y2, double t1, double t2, double * tLoft ) const; + void ParamSecond( double y1, double y2, double t1, double t2, double * tLoft ) const; + void ParamThird ( double t1, double t2, double * tLoft ) const; + bool SetCorrection( size_t ind, double tDelta ); // \ru Скорректировать функцию по индексу. \en Function correction by index. + void CalculateValues( size_t i1, size_t i2 ); // \ru Скорректировать функцию на интервале i1-i2. \en Function correction on the interval i1-i2. private: - void operator = ( const MbCubicFunction & ); // \ru Не реализовано \en Not implemented + void operator = ( const MbCubicFunction & ); // \ru Не реализовано \en Not implemented DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCubicFunction ) }; IMPL_PERSISTENT_OPS( MbCubicFunction ) + //------------------------------------------------------------------------------ // \ru Определение местных координат области поверхности \en Definition of local coordinates in a surface region // --- diff --git a/C3d/Include/func_cubic_spline_function.h b/C3d/Include/func_cubic_spline_function.h index d02aca8..d6b7197 100644 --- a/C3d/Include/func_cubic_spline_function.h +++ b/C3d/Include/func_cubic_spline_function.h @@ -43,7 +43,7 @@ public : public: /// \ru Инициализация по точкам, параметрам и признаку замкнутости. \en Initialization by points, parameters and an attribute of closeness. - void Init( const SArray & values, // \ru Инициализация переменных \en Initialization of variables + void Init( const SArray & values, // \ru Инициализация переменных \en Initialization of variables const SArray & params, bool cls ); public: // \ru Общие функции математического объекта \en Common functions of mathematical object @@ -70,7 +70,7 @@ public: double _ThirdDer ( double t ) const override; // \ru Третья производная по t \en The third derivative with respect to t // \ru Вычислить значение и производные. \en Calculate value and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - double & val, double & fir, double * sec, double * thr ) const override; + double & val, double & fir, double * sec, double * thr ) const override; void Inverse( MbRegTransform * iReg = nullptr ) override; // \ru Изменить направление \en Change direction double Step( double t, double sag ) const override; @@ -94,31 +94,32 @@ public: MbFunction * Trimmed( double t1, double t2, int sense ) const override; // \ru Разбить функцию точкой с параметром t и вернуть отрезанную часть. \en Function break by the parameter t, and cut off part of the function: begs == true - save the initial half, beg == false - save the final half. MbFunction * BreakFunction( double t, bool beg ) override; - MbFunction * Break( double t1, double t2 ) const; ///< \ru Выделить часть функции. \en Select a part of a function. + MbFunction * Break( double t1, double t2 ) const; ///< \ru Выделить часть функции. \en Select a part of a function. - size_t GetParamsCount() const; ///< \ru Выдать количество параметров. \en Get count of parameters. - double GetParam( size_t index ) const; // \ru Дать значение параметра точки по номеру \en Get the value of point parameter by its number - void GetTList( SArray & params ) const; ///< \ru Выдать параметры. \en Get parameters tList. - size_t GetValuesCount() const; // \ru Выдать количество опорных точек \en Get the number of control points - double GetValue( size_t index ) const; // \ru Дать значение точки по номеру \en Get the value of point by its number - bool SetValue( size_t index, double v ); // \ru Установить значение точки по номеру \en Set the value of point by its number - void GetValueList( SArray & vals ) const; ///< \ru Вернуть массив контрольных значений. \en Get array of control values. - double GetDerive( size_t index ) const; // \ru Дать значение производной по номеру \en Get the value of derivative by its number - bool CalcSecondDerives(); // \ru Расчет вторых производных \en Calculation of second derivatives + size_t GetParamsCount() const; ///< \ru Выдать количество параметров. \en Get count of parameters. + double GetParam( size_t index ) const; // \ru Дать значение параметра точки по номеру \en Get the value of point parameter by its number + void GetTList( SArray & params ) const; ///< \ru Выдать параметры. \en Get parameters tList. + size_t GetValuesCount() const; // \ru Выдать количество опорных точек \en Get the number of control points + double GetValue( size_t index ) const; // \ru Дать значение точки по номеру \en Get the value of point by its number + bool SetValue( size_t index, double v ); // \ru Установить значение точки по номеру \en Set the value of point by its number + void GetValueList( SArray & vals ) const; ///< \ru Вернуть массив контрольных значений. \en Get array of control values. + double GetDerive( size_t index ) const; // \ru Дать значение производной по номеру \en Get the value of derivative by its number + bool CalcSecondDerives(); // \ru Расчет вторых производных \en Calculation of second derivatives private: - double Value ( double t, size_t num ) const; // \ru Точка на кривой \en The point on the curve - double FirstDer( double t, size_t num ) const; // \ru Первая производная \en First derivative - ptrdiff_t GetIndex( double t ) const; - bool CalcClosedSpline (); // \ru Расчет вторых производных в узлах для замкнутой кривой \en Calculation of second derivatives in nodes of closed curve - bool CalcUnClosedSpline(); // \ru Расчет вторых производных в узлах для разомкнутой кривой \en Calculation of second derivatives in nodes of unclosed curve - bool DefineIntervalPar( double & t, size_t & num ) const; // \ru Определение принадлежности интервалу параметров \en Check belonging to interval of parameters + double Value ( double t, size_t num ) const; // \ru Точка на кривой \en The point on the curve + double FirstDer( double t, size_t num ) const; // \ru Первая производная \en First derivative + ptrdiff_t GetIndex( double t ) const; + bool CalcClosedSpline (); // \ru Расчет вторых производных в узлах для замкнутой кривой \en Calculation of second derivatives in nodes of closed curve + bool CalcUnClosedSpline(); // \ru Расчет вторых производных в узлах для разомкнутой кривой \en Calculation of second derivatives in nodes of unclosed curve + bool DefineIntervalPar( double & t, size_t & num ) const; // \ru Определение принадлежности интервалу параметров \en Check belonging to interval of parameters private: - void operator = ( const MbCubicSplineFunction & ); // \ru Не реализовано \en Not implemented + void operator = ( const MbCubicSplineFunction & ); // \ru Не реализовано \en Not implemented DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCubicSplineFunction ) }; IMPL_PERSISTENT_OPS( MbCubicSplineFunction ) + #endif // __FUNC_CUBIC_SPLINE_FUNCTION_H diff --git a/C3d/Include/func_curve_coordinate.h b/C3d/Include/func_curve_coordinate.h index 9169d6d..504e81f 100644 --- a/C3d/Include/func_curve_coordinate.h +++ b/C3d/Include/func_curve_coordinate.h @@ -43,7 +43,7 @@ public : virtual ~MbCurveCoordinate(); public: - void Init( const MbCurve3D & cur, size_t process, const MbPlacement3D & place, size_t coord ); ///< \ru Инициализация по значениям и параметрам. \en Initialization by values and parameters. + void Init( const MbCurve3D & cur, size_t process, const MbPlacement3D & place, size_t coord ); ///< \ru Инициализация по значениям и параметрам. \en Initialization by values and parameters. // \ru Общие функции математического объекта \en Common functions of mathematical object MbeFunctionType IsA() const override; // \ru Тип элемента \en A type of element @@ -69,7 +69,7 @@ public: double _ThirdDer ( double t ) const override; // \ru Третья производная по t \en The third derivative with respect to t // \ru Вычислить значение и производные. \en Calculate value and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - double & val, double & fir, double * sec, double * thr ) const override; + double & val, double & fir, double * sec, double * thr ) const override; // \ru Вычислить аргумент t по значению функции. \en Calculate the argument t by the function value. double Argument( double & val ) const override; @@ -96,9 +96,9 @@ public: double GetLimitValue( size_t n ) const override; // \ru Дать значение на конце ( 1 - в начале, 2 - в конце) \en Get the value at the end (1 - at beginning, 2 - at ending) private: - void SetOriginAndDerive(); - double GetCurveParam( double & t, bool ext ) const; - void operator = ( const MbCurveCoordinate & ); // \ru Не реализовано \en Not implemented + void SetOriginAndDerive(); + double GetCurveParam( double & t, bool ext ) const; + void operator = ( const MbCurveCoordinate & ); // \ru Не реализовано \en Not implemented DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCurveCoordinate ) }; diff --git a/C3d/Include/func_line_function.h b/C3d/Include/func_line_function.h index 8185b14..83ccc40 100644 --- a/C3d/Include/func_line_function.h +++ b/C3d/Include/func_line_function.h @@ -37,14 +37,14 @@ private: public : virtual ~MbLineFunction(); public: - void Init( double v1, double v2, double t1, double t2 ); ///< \ru Инициализация по значениям и параметрам. \en Initialization by values and parameters. + void Init( double v1, double v2, double t1, double t2 ); ///< \ru Инициализация по значениям и параметрам. \en Initialization by values and parameters. public: // \ru Общие функции математического объекта \en Common functions of mathematical object MbeFunctionType IsA() const override; // \ru Тип элемента \en A type of element MbFunction & Duplicate() const override; // \ru Сделать копию элемента \en Create a copy of the element bool IsSame ( const MbFunction & other, double accuracy = LENGTH_EPSILON ) const override; // \ru Являются ли объекты равными \en Determine whether objects are equal bool SetEqual ( const MbFunction & ) override; // \ru Сделать равным \en Make equal - void GetProperties( MbProperties & ) override; // \ru Выдать свойства объекта \en Get properties of the object + void GetProperties( MbProperties & ) override; // \ru Выдать свойства объекта \en Get properties of the object void SetProperties( const MbProperties & ) override; // \ru Записать свойства объекта \en Set properties of the object double GetTMax() const override; // \ru Вернуть максимальное значение параметра \en Get the maximum value of parameter @@ -63,7 +63,7 @@ public: double _ThirdDer ( double t ) const override; // \ru Третья производная по t \en The third derivative with respect to t // \ru Вычислить значение и производные. \en Calculate value and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - double & val, double & fir, double * sec, double * thr ) const override; + double & val, double & fir, double * sec, double * thr ) const override; // \ru Вычислить аргумент t по значению функции. \en Calculate the argument t by the function value. double Argument( double & val ) const override; @@ -90,7 +90,7 @@ public: double GetLimitValue( size_t n ) const override; // \ru Дать значение на конце ( 1 - в начале, 2 - в конце) \en Get the value at the end (1 - at beginning, 2 - at ending) private: - void operator = ( const MbLineFunction & ); // \ru Не реализовано \en Not implemented + void operator = ( const MbLineFunction & ); // \ru Не реализовано \en Not implemented DECLARE_PERSISTENT_CLASS_NEW_DEL( MbLineFunction ) }; diff --git a/C3d/Include/func_mono_smooth_function.h b/C3d/Include/func_mono_smooth_function.h index c884e14..a31dded 100644 --- a/C3d/Include/func_mono_smooth_function.h +++ b/C3d/Include/func_mono_smooth_function.h @@ -90,14 +90,14 @@ public: \return \ru Статус операции. \en Operation status. \~ */ - bool Init ( const c3d::DoubleVector & pars, const c3d::DoubleVector & vals, bool periodic ); + bool Init ( const c3d::DoubleVector & pars, const c3d::DoubleVector & vals, bool periodic ); public: // \ru Общие функции математического объекта \en Common functions of mathematical object MbeFunctionType IsA () const override; // \ru Тип элемента \en A type of element MbFunction & Duplicate() const override; // \ru Сделать копию элемента \en Create a copy of the element bool IsSame ( const MbFunction & other, double accuracy = LENGTH_EPSILON ) const override; // \ru Являются ли объекты равными \en Determine whether objects are equal bool SetEqual ( const MbFunction & ) override; // \ru Сделать равным \en Make equal - void GetProperties( MbProperties & ) override; // \ru Выдать свойства объекта \en Get properties of object + void GetProperties( MbProperties & ) override; // \ru Выдать свойства объекта \en Get properties of object void SetProperties( const MbProperties & ) override; // \ru Записать свойства объекта \en Set properties of object double GetTMax () const override; // \ru Вернуть максимальное значение параметра \en Get the maximum value of parameter @@ -119,9 +119,9 @@ public: // \ru Вычислить аргумент t по значению функции. \en Calculate the argument t by the function value. double Argument( double & val ) const override; - size_t GetListCount() const { return x.size(); } // \ru Количество точек в наборе \en Number of points in a set. - double GetValue(size_t ind ) const { return y[ind]; } // \ru Получить значение по индексу. \en Get value by index. - double GetParam(size_t ind ) const { return x[ind]; } // \ru Получить параметр по индексу. \en Get parameter by index. + size_t GetListCount() const { return x.size(); } // \ru Количество точек в наборе \en Number of points in a set. + double GetValue(size_t ind ) const { return y[ind]; } // \ru Получить значение по индексу. \en Get value by index. + double GetParam(size_t ind ) const { return x[ind]; } // \ru Получить параметр по индексу. \en Get parameter by index. void Inverse( MbRegTransform * iReg = nullptr ) override; // \ru Изменить направление \en Change direction double Step( double t, double sag ) const override; @@ -145,19 +145,20 @@ public: MbFunction * Trimmed( double t1, double t2, int sense ) const override; // \ru Разбить функцию точкой с параметром t и вернуть отрезанную часть. \en Function break by the parameter t, and cut off part of the function: begs == true - save the initial half, beg == false - save the final half. MbFunction * BreakFunction( double t, bool beg ) override; - MbFunction * Break( double t1, double t2 ) const; ///< \ru Выделить часть функции. \en Select a part of a function. + MbFunction * Break( double t1, double t2 ) const; ///< \ru Выделить часть функции. \en Select a part of a function. private: - void CheckParam( double & t ) const; // \ru Установить параметр в область определения. \en Set the parameter to the domain. - void DivExplore( size_t ord, double( &P )[4], double( &T )[4], double( &res )[4] ) const; // \ru Найти производные частного P/T. \en Find the derivatives of the quotient P / T. - void ExploreBet( double b, size_t ord, double( &res )[4] ) const; // \ru Расчитать производные beta функции. \en Calculate the derivatives of the beta function. - void ExploreGam( double b, size_t ord, double( &res )[4] ) const;// \ru Расчитать производные gamma функции. \en Calculate the derivatives of the gamma function. - void Explore( double x, size_t ord, double( &res )[4] ) const;// \ru Расчитать производные сплайна. \en Calculate the derivatives of the spline. - void operator = ( const MbMonoSmoothFunction & ); // \ru Не реализовано \en Not implemented + void CheckParam( double & t ) const; // \ru Установить параметр в область определения. \en Set the parameter to the domain. + void DivExplore( size_t ord, double( &P )[4], double( &T )[4], double( &res )[4] ) const; // \ru Найти производные частного P/T. \en Find the derivatives of the quotient P / T. + void ExploreBet( double b, size_t ord, double( &res )[4] ) const; // \ru Расчитать производные beta функции. \en Calculate the derivatives of the beta function. + void ExploreGam( double b, size_t ord, double( &res )[4] ) const;// \ru Расчитать производные gamma функции. \en Calculate the derivatives of the gamma function. + void Explore( double x, size_t ord, double( &res )[4] ) const;// \ru Расчитать производные сплайна. \en Calculate the derivatives of the spline. + void operator = ( const MbMonoSmoothFunction & ); // \ru Не реализовано \en Not implemented DECLARE_PERSISTENT_CLASS_NEW_DEL( MbMonoSmoothFunction ) }; IMPL_PERSISTENT_OPS( MbCubicSplineFunction ) + #endif // __FUNC_MONO_SMOOTH_FUNCTION_H diff --git a/C3d/Include/func_nurbs_function.h b/C3d/Include/func_nurbs_function.h index 745af21..90b43b9 100644 --- a/C3d/Include/func_nurbs_function.h +++ b/C3d/Include/func_nurbs_function.h @@ -73,42 +73,42 @@ public: const SArray & params, const SArray * aKnots = nullptr ); /// \ru Инициализация сплайна, проходящего через заданные точки при заданных параметрах. В случае замкнутости нужно передавать массив с совпадением первой и последней точек.\n \~ /// \en Initialization of spline passing through given points at given parameters. In case of closedness it is necessary to pass the array with coincidence of the first and the last points.\n \~ - bool InitThrough( size_t deg, bool cls, const SArray & points, const SArray & params, const SArray * aKnots = nullptr ); + bool InitThrough( size_t deg, bool cls, const SArray & points, const SArray & params, const SArray * aKnots = nullptr ); private: /// \ru Инициализация по точкам и признаку замкнутости. \en Initialization by values and an attribute of closedness. - template - bool Init( size_t initDegree, const DoubleVector & initPoints, bool initClosed ) - { - if ( ::IsValidNurbsParams( initDegree, initClosed, initPoints.size() ) ) { - degree = initDegree; - closed = initClosed; - uppIndex = (ptrdiff_t)initPoints.size() - 1; - pointList.assign( initPoints.begin(), initPoints.end() ); - weights.assign( initPoints.size(), 1.0 ); - uppKnotsIndex = ::DefineKnotsVector( degree, closed, uppIndex, knots ); - return true; - } - return false; - } + template + bool Init( size_t initDegree, const DoubleVector & initPoints, bool initClosed ) + { + if ( ::IsValidNurbsParams( initDegree, initClosed, initPoints.size() ) ) { + degree = initDegree; + closed = initClosed; + uppIndex = (ptrdiff_t)initPoints.size() - 1; + pointList.assign( initPoints.begin(), initPoints.end() ); + weights.assign( initPoints.size(), 1.0 ); + uppKnotsIndex = ::DefineKnotsVector( degree, closed, uppIndex, knots ); + return true; + } + return false; + } /// \ru Инициализация по точкам, параметрам и признаку замкнутости. \en Initialization by values, knots and an attribute of closedness. - template - bool Init( size_t initDegree, const DoubleVector & initPoints, const DoubleVector & initKnots, bool initClosed ) - { - if ( ::IsValidNurbsParams( initDegree, initClosed, initPoints.size(), initPoints.size(), initKnots.size() ) ) { - degree = initDegree; - closed = initClosed; - pointList = initPoints; - weights.assign( initPoints.size(), 1.0 ); - knots = initKnots; - uppIndex = (ptrdiff_t)pointList.size() - 1; - uppKnotsIndex = (ptrdiff_t)knots.size() - 1; - SetClamped(); - return true; - } - return false; - } + template + bool Init( size_t initDegree, const DoubleVector & initPoints, const DoubleVector & initKnots, bool initClosed ) + { + if ( ::IsValidNurbsParams( initDegree, initClosed, initPoints.size(), initPoints.size(), initKnots.size() ) ) { + degree = initDegree; + closed = initClosed; + pointList = initPoints; + weights.assign( initPoints.size(), 1.0 ); + knots = initKnots; + uppIndex = (ptrdiff_t)pointList.size() - 1; + uppKnotsIndex = (ptrdiff_t)knots.size() - 1; + SetClamped(); + return true; + } + return false; + } public: @@ -136,7 +136,7 @@ public: double _ThirdDer ( double t ) const override; // \ru Третья производная по t \en The third derivative with respect to t // \ru Вычислить значение и производные. \en Calculate value and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - double & val, double & fir, double * sec, double * thr ) const override; + double & val, double & fir, double * sec, double * thr ) const override; // \ru Вычислить аргумент t по значению функции. \en Calculate the argument t by the function value. double Argument( double & val ) const override; @@ -165,60 +165,60 @@ public: MbFunction * Trimmed( double t1, double t2, int sense ) const override; // \ru Разбить функцию точкой с параметром t и вернуть отрезанную часть. \en Function break by the parameter t, and cut off part of the function: begs == true - save the initial half, beg == false - save the final half. MbFunction * BreakFunction( double t, bool beg ) override; - MbFunction * Break( double t1, double t2 ) const; ///< \ru Выделить часть функции. \en Select a part of a function. + MbFunction * Break( double t1, double t2 ) const; ///< \ru Выделить часть функции. \en Select a part of a function. - /// \ru Добавление нового узла; возвращает количество узлов, которые удалось вставить. \en Addition of a new knots; returns the number of knots which have been inserted. - size_t InsertKnots( double & newKnot, size_t multiplicity, double relEps ); - /// \ru Удалить кратный внутренний узел id, num раз; вернуть количество удалений, которое удалось сделать. \en Remove multiple internal 'id' knot 'num' times, return count of removals was successfully made. - ptrdiff_t RemoveKnot( ptrdiff_t id, ptrdiff_t num, double relEps = Math::paramEpsilon, double absEps = Math::lengthEpsilon ); - /// \ru Преобразовать узловой вектор в зажатый (если кривая замкнута и clm = false) или разжатый (если кривая не замкнута и clm = true). \en Transform knot vector to clamped (if curve is closed and clm = false) or unclamped (if curve is open and clm = true). - bool UnClamped( bool clm ); - void SetClamped(); // \ru Делаем зажатый узловой вектор. \en Set clamped knots vector. + /// \ru Добавление нового узла; возвращает количество узлов, которые удалось вставить. \en Addition of a new knots; returns the number of knots which have been inserted. + size_t InsertKnots( double & newKnot, size_t multiplicity, double relEps ); + /// \ru Удалить кратный внутренний узел id, num раз; вернуть количество удалений, которое удалось сделать. \en Remove multiple internal 'id' knot 'num' times, return count of removals was successfully made. + ptrdiff_t RemoveKnot( ptrdiff_t id, ptrdiff_t num, double relEps = Math::paramEpsilon, double absEps = Math::lengthEpsilon ); + /// \ru Преобразовать узловой вектор в зажатый (если кривая замкнута и clm = false) или разжатый (если кривая не замкнута и clm = true). \en Transform knot vector to clamped (if curve is closed and clm = false) or unclamped (if curve is open and clm = true). + bool UnClamped( bool clm ); + void SetClamped(); // \ru Делаем зажатый узловой вектор. \en Set clamped knots vector. - size_t GetValuesCount() const; // \ru Выдать количество опорных точек \en Get the number of control points - double GetValue( size_t index ) const; // \ru Дать значение точки по номеру \en Get the value of point by its number - bool SetValue( size_t index, double v ); // \ru Установить значение точки по номеру \en Set the value of point by its number - void GetValueList( SArray & vals ) const; ///< \ru Вернуть массив контрольных значений. \en Get array of control values. + size_t GetValuesCount() const; // \ru Выдать количество опорных точек \en Get the number of control points + double GetValue( size_t index ) const; // \ru Дать значение точки по номеру \en Get the value of point by its number + bool SetValue( size_t index, double v ); // \ru Установить значение точки по номеру \en Set the value of point by its number + void GetValueList( SArray & vals ) const; ///< \ru Вернуть массив контрольных значений. \en Get array of control values. - /// \ru Получить размер весового вектора. \en Get a size of weights vector. - size_t GetWeightsCount() const { return weights.size(); } - /// \ru Получить весовой вектор. \en Get a weights vector. - template - void GetWeights( WeightsVector & wts, bool justSet = true ) const { if ( justSet ) { wts.clear(); }; std::copy( weights.begin(), weights.end(), std::back_inserter( wts ) ); } - /// \ru Получить значение элемента весового вектора по индексу. \en Get a weights vector element value by index. - double GetWeight( size_t ind ) const { return weights[ind]; } - /// \ru Получить значение элемента весового вектора по индексу. \en Get a weights vector element value by index. - double & SetWeight( size_t ind ) { return weights[ind]; } + /// \ru Получить размер весового вектора. \en Get a size of weights vector. + size_t GetWeightsCount() const { return weights.size(); } + /// \ru Получить весовой вектор. \en Get a weights vector. + template + void GetWeights( WeightsVector & wts, bool justSet = true ) const { if ( justSet ) { wts.clear(); }; std::copy( weights.begin(), weights.end(), std::back_inserter( wts ) ); } + /// \ru Получить значение элемента весового вектора по индексу. \en Get a weights vector element value by index. + double GetWeight( size_t ind ) const { return weights[ind]; } + /// \ru Получить значение элемента весового вектора по индексу. \en Get a weights vector element value by index. + double & SetWeight( size_t ind ) { return weights[ind]; } - /// \ru Получить размер узлового вектора. \en Get a size of knots vector. - size_t GetKnotsCount() const { return knots.size(); } - /// \ru Получить узловой вектор. \en Get a knots vector. - template - void GetKnots( KnotsVector & kts, bool justSet = true ) const { if ( justSet ) { kts.clear(); }; std::copy( knots.begin(), knots.end(), std::back_inserter( kts ) ); } - /// \ru Получить значение элемента узлового вектора по индексу. \en Get a knots vector element value by index. - double GetKnot( size_t ind ) const { return knots[ind]; } - /// \ru Получить значение элемента узлового вектора по индексу. \en Get a knots vector element value by index. - double & SetKnot( size_t ind ) { return knots[ind]; } - /// \ru Вернуть максимальный индекс узлового вектора. \en Get the maximal index of knots vector. - ptrdiff_t GetUppKnotsIndex() const { return uppKnotsIndex; } + /// \ru Получить размер узлового вектора. \en Get a size of knots vector. + size_t GetKnotsCount() const { return knots.size(); } + /// \ru Получить узловой вектор. \en Get a knots vector. + template + void GetKnots( KnotsVector & kts, bool justSet = true ) const { if ( justSet ) { kts.clear(); }; std::copy( knots.begin(), knots.end(), std::back_inserter( kts ) ); } + /// \ru Получить значение элемента узлового вектора по индексу. \en Get a knots vector element value by index. + double GetKnot( size_t ind ) const { return knots[ind]; } + /// \ru Получить значение элемента узлового вектора по индексу. \en Get a knots vector element value by index. + double & SetKnot( size_t ind ) { return knots[ind]; } + /// \ru Вернуть максимальный индекс узлового вектора. \en Get the maximal index of knots vector. + ptrdiff_t GetUppKnotsIndex() const { return uppKnotsIndex; } - bool CheckParam( double & t ) const; // \ru Проверить параметр. \en Parameter check. + bool CheckParam( double & t ) const; // \ru Проверить параметр. \en Parameter check. private: - // \ru Вычисление функции и веса. \en Calculating the function and weight. - bool CalculateValue( double & t, size_t deriveN, Array2 & values, - ptrdiff_t & left, double & valw, double & weig ) const; - // \ru Вычисление производной функции и производной веса. \en Calculating the function and weight derivatives. - void CalculateFirst( const Array2 & values, const ptrdiff_t & left, - SArray & pointsM, SArray & weightM, - double & firw, double & weig_ ) const; - void CalculateDerive( const Array2 & values, const ptrdiff_t & left, size_t deriveN, - SArray & pointsM, SArray & weightM, - double & derw, double & weig_ ) const; + // \ru Вычисление функции и веса. \en Calculating the function and weight. + bool CalculateValue( double & t, size_t deriveN, Array2 & values, + ptrdiff_t & left, double & valw, double & weig ) const; + // \ru Вычисление производной функции и производной веса. \en Calculating the function and weight derivatives. + void CalculateFirst( const Array2 & values, const ptrdiff_t & left, + SArray & pointsM, SArray & weightM, + double & firw, double & weig_ ) const; + void CalculateDerive( const Array2 & values, const ptrdiff_t & left, size_t deriveN, + SArray & pointsM, SArray & weightM, + double & derw, double & weig_ ) const; - void operator = ( const MbNurbsFunction & ); // \ru Не реализовано \en Not implemented + void operator = ( const MbNurbsFunction & ); // \ru Не реализовано \en Not implemented DECLARE_PERSISTENT_CLASS_NEW_DEL( MbNurbsFunction ) }; diff --git a/C3d/Include/func_power_function.h b/C3d/Include/func_power_function.h index 095f8de..e5b439a 100644 --- a/C3d/Include/func_power_function.h +++ b/C3d/Include/func_power_function.h @@ -39,7 +39,7 @@ private: public : virtual ~MbPowerFunction(); public: - void Init( double orig, double scal, double shif, double expo, double t1, double t2 ); ///< \ru Инициализация по значениям и параметрам. \en Initialization by values and parameters. + void Init( double orig, double scal, double shif, double expo, double t1, double t2 ); ///< \ru Инициализация по значениям и параметрам. \en Initialization by values and parameters. public: // \ru Общие функции математического объекта \en Common functions of mathematical object MbeFunctionType IsA() const override; // \ru Тип элемента \en A type of element @@ -65,7 +65,7 @@ public: double _ThirdDer ( double t ) const override; // \ru Третья производная по t \en The third derivative with respect to t // \ru Вычислить значение и производные. \en Calculate value and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - double & val, double & fir, double * sec, double * thr ) const override; + double & val, double & fir, double * sec, double * thr ) const override; void Inverse( MbRegTransform * iReg = nullptr ) override; // \ru Изменить направление \en Change direction double Step( double t, double sag ) const override; @@ -85,23 +85,24 @@ public: MbFunction * BreakFunction( double t, bool beg ) override; void SetOffsetFunc( double off, double scaleFactor ) override; // \ru Сместить функцию \en Shift a function - bool SetLimit( double newTMin, double newTMax ); // \ru Установить область изменения параметра \en Set range of parameter + bool SetLimit( double newTMin, double newTMax ); // \ru Установить область изменения параметра \en Set range of parameter void SetLimitValue( size_t n, double newValue ) override; // \ru Установить значение на конце ( 1 - в начале, 2 - в конце) \en Set the value at the end (1 - at beginning, 2 - at ending) double GetLimitValue( size_t n ) const override; // \ru Дать значение на конце ( 1 - в начале, 2 - в конце) \en Get the value at the end (1 - at beginning, 2 - at ending) - double GetOrigin() const { return origin; } ///< \ru Выдать начальное значение. \en Get start value. - void SetOrigin( double p ) { origin = p; } ///< \ru Изменить начальное значение. \en Set start value. - double GetScale() const { return scale; } ///< \ru Выдать коэффициент усиления. \en Get scale gain. - void SetScale( double a ) { scale = a; } ///< \ru Изменить коэффициент усиления. \en Set scale gain. - double GetShift() const { return shift; } ///< \ru Выдать cдвиг параметра. \en Get parameter shift. - void SetShift( double p ) { shift = p; } ///< \ru Изменить cдвиг параметра. \en Set parameter shift. + double GetOrigin() const { return origin; } ///< \ru Выдать начальное значение. \en Get start value. + void SetOrigin( double p ) { origin = p; } ///< \ru Изменить начальное значение. \en Set start value. + double GetScale() const { return scale; } ///< \ru Выдать коэффициент усиления. \en Get scale gain. + void SetScale( double a ) { scale = a; } ///< \ru Изменить коэффициент усиления. \en Set scale gain. + double GetShift() const { return shift; } ///< \ru Выдать cдвиг параметра. \en Get parameter shift. + void SetShift( double p ) { shift = p; } ///< \ru Изменить cдвиг параметра. \en Set parameter shift. private: - void operator = ( const MbPowerFunction & ); // \ru Не реализовано \en Not implemented + void operator = ( const MbPowerFunction & ); // \ru Не реализовано \en Not implemented DECLARE_PERSISTENT_CLASS_NEW_DEL( MbPowerFunction ) }; IMPL_PERSISTENT_OPS( MbPowerFunction ) + #endif // __FUNC_POWER_FUNCTION_H diff --git a/C3d/Include/func_serve_function.h b/C3d/Include/func_serve_function.h index b92db8d..d1d1d73 100644 --- a/C3d/Include/func_serve_function.h +++ b/C3d/Include/func_serve_function.h @@ -24,11 +24,11 @@ // --- class MATH_CLASS MbServeFunction : public MbFunction { public : - double a; ///< \ru Коэффициент при квадратичном члене репараметризующего многочлена. \en The coefficient of the quadratic term of the reparametrizing polynomial. - double b; ///< \ru Коэффициент при линейном члене репараметризующего многочлена. \en The coefficient of the linear term of the reparametrizing polynomial. - double c; ///< \ru Свободный коэффициент репараметризующего многочлена. \en The free coefficient of the reparametrizing polynomial. - double tmin; ///< \ru Начальный параметр. \en Start parameter. - double tmax; ///< \ru Конечный параметр. \en End parameter. + double a; ///< \ru Коэффициент при квадратичном члене репараметризующего многочлена. \en The coefficient of the quadratic term of the reparametrizing polynomial. + double b; ///< \ru Коэффициент при линейном члене репараметризующего многочлена. \en The coefficient of the linear term of the reparametrizing polynomial. + double c; ///< \ru Свободный коэффициент репараметризующего многочлена. \en The free coefficient of the reparametrizing polynomial. + double tmin; ///< \ru Начальный параметр. \en Start parameter. + double tmax; ///< \ru Конечный параметр. \en End parameter. public : ///< \ru Конструктор по умолчанию. \en Default constructor. @@ -48,7 +48,7 @@ public: \param[in] t1, t2 - \ru Область определения репараметризованной кривой \en Parametric region of the reparameterized curve. \~ */ - void InitLinear( double basisTMin, double basisTMax, double t1, double t2 ); + void InitLinear( double basisTMin, double basisTMax, double t1, double t2 ); /** \brief \ru Инициализация переменных для репараметризации с заданной производной в начале. \en Initialization of variables for reparameterization with a given derivative at the beginning. \~ @@ -63,7 +63,7 @@ public: \en true - if reparameterization is successful, false - if the reparametrization is degenerate and reduced to linear. \~ */ - bool InitQuadratic( double basisTMin, double basisTMax, double t1, double t2, double begDer ); + bool InitQuadratic( double basisTMin, double basisTMax, double t1, double t2, double begDer ); /** \brief \ru Репараметризация, обеспечивающая на концах новой кривой указаные производные параметра. \en Reparametrization providing the indicated derivatives of the parameter at the ends of the new curve. \~ @@ -78,7 +78,7 @@ public: \en true - reparameterization is successful, false - reparametrization is degenerate and reduced to linear. \~ */ - bool InitScaledEnds( double basisTMin, double basisTMax, double dt1, double dt2); + bool InitScaledEnds( double basisTMin, double basisTMax, double dt1, double dt2); public: // \ru Общие функции математического объекта \en Common functions of mathematical object MbeFunctionType IsA() const override; // \ru Тип элемента \en A type of element @@ -104,7 +104,7 @@ public: double _ThirdDer ( double t ) const override; // \ru Третья производная по t \en The third derivative with respect to t // \ru Вычислить значение и производные. \en Calculate value and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - double & val, double & fir, double * sec, double * thr ) const override; + double & val, double & fir, double * sec, double * thr ) const override; // \ru Вычислить аргумент t по значению функции. \en Calculate the argument t by the function value. double Argument( double & val ) const override; @@ -131,7 +131,7 @@ public: double GetLimitValue( size_t n ) const override; // \ru Дать значение на конце ( 1 - в начале, 2 - в конце) \en Get the value at the end (1 - at beginning, 2 - at ending) private: - void operator = ( const MbServeFunction & ); // \ru Не реализовано \en Not implemented + void operator = ( const MbServeFunction & ); // \ru Не реализовано \en Not implemented DECLARE_PERSISTENT_CLASS_NEW_DEL( MbServeFunction ) }; diff --git a/C3d/Include/func_sinus_function.h b/C3d/Include/func_sinus_function.h index 9c9af30..6ab707f 100644 --- a/C3d/Include/func_sinus_function.h +++ b/C3d/Include/func_sinus_function.h @@ -39,14 +39,14 @@ private: public : virtual ~MbSinusFunction(); public: - void Init( double orig, double ampl, double shif, double freq, double t1, double t2 ); ///< \ru Инициализация по значениям и параметрам. \en Initialization by values and parameters. + void Init( double orig, double ampl, double shif, double freq, double t1, double t2 ); ///< \ru Инициализация по значениям и параметрам. \en Initialization by values and parameters. public: // \ru Общие функции математического объекта \en Common functions of mathematical object MbeFunctionType IsA() const override; // \ru Тип элемента \en A type of element MbFunction & Duplicate() const override; // \ru Сделать копию элемента \en Create a copy of the element bool IsSame ( const MbFunction & other, double accuracy = LENGTH_EPSILON ) const override; // \ru Являются ли объекты равными \en Determine whether objects are equal bool SetEqual ( const MbFunction & ) override; // \ru Сделать равным \en Make equal - void GetProperties( MbProperties & ) override; // \ru Выдать свойства объекта \en Get properties of the object + void GetProperties( MbProperties & ) override; // \ru Выдать свойства объекта \en Get properties of the object void SetProperties( const MbProperties & ) override; // \ru Записать свойства объекта \en Set properties of the object double GetTMax() const override; // \ru Вернуть максимальное значение параметра \en Get the maximum value of parameter @@ -65,7 +65,7 @@ public: double _ThirdDer ( double t ) const override; // \ru Третья производная по t \en The third derivative with respect to t // \ru Вычислить значение и производные. \en Calculate value and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, - double & val, double & fir, double * sec, double * thr ) const override; + double & val, double & fir, double * sec, double * thr ) const override; void Inverse( MbRegTransform * iReg = nullptr ) override; // \ru Изменить направление \en Change direction double Step( double t, double sag ) const override; @@ -85,17 +85,17 @@ public: MbFunction * BreakFunction( double t, bool beg ) override; void SetOffsetFunc( double off, double scale ) override; // \ru Сместить функцию \en Shift a function - bool SetLimit( double newTMin, double newTMax ); // \ru Установить область изменения параметра \en Set range of parameter + bool SetLimit( double newTMin, double newTMax ); // \ru Установить область изменения параметра \en Set range of parameter void SetLimitValue( size_t n, double newValue ) override; // \ru Установить значение на конце ( 1 - в начале, 2 - в конце) \en Set the value at the end (1 - at beginning, 2 - at ending) double GetLimitValue( size_t n ) const override; // \ru Дать значение на конце ( 1 - в начале, 2 - в конце) \en Get the value at the end (1 - at beginning, 2 - at ending) - double GetOrigin() const { return origin; } ///< \ru Выдать начальное значение. \en Get start value. - void SetOrigin( double p ) { origin = p; } ///< \ru Изменить начальное значение. \en Set start value. - double GetAmplitude() const { return amplitude; } ///< \ru Выдать амплитуду. \en Get amplitude. - void SetAmplitude( double a ) { amplitude = a; } ///< \ru Изменить амплитуду. \en Set amplitude. + double GetOrigin() const { return origin; } ///< \ru Выдать начальное значение. \en Get start value. + void SetOrigin( double p ) { origin = p; } ///< \ru Изменить начальное значение. \en Set start value. + double GetAmplitude() const { return amplitude; } ///< \ru Выдать амплитуду. \en Get amplitude. + void SetAmplitude( double a ) { amplitude = a; } ///< \ru Изменить амплитуду. \en Set amplitude. private: - void operator = ( const MbSinusFunction & ); // \ru Не реализовано \en Not implemented + void operator = ( const MbSinusFunction & ); // \ru Не реализовано \en Not implemented DECLARE_PERSISTENT_CLASS_NEW_DEL( MbSinusFunction ) }; diff --git a/C3d/Include/function.h b/C3d/Include/function.h index 577271c..4321dc4 100644 --- a/C3d/Include/function.h +++ b/C3d/Include/function.h @@ -188,7 +188,7 @@ public: virtual MbFunction * BreakFunction( double t, bool beg ) = 0; /// \ru Разбить функцию параметрами: beg == true - соранить начальную половину, beg == false - соранить конечную половину. /// \en Function break by the parameters: begs == true - save the initial half, beg == false - save the final half. - bool CuttingFunction( SArray & params, bool beginSafe, double eps, RPArray & cutted ); + bool CuttingFunction( SArray & params, bool beginSafe, double eps, RPArray & cutted ); /// \ru Сместить функцию. \en Shift a function. virtual void SetOffsetFunc( double off, double scale ) = 0; /// \ru Установить область изменения параметра. \en Set the range of parameter. @@ -209,23 +209,24 @@ public: /** \} */ /// \ru Наличие нулевого значения функции. \en The presence of a null function value. - bool IsZero( double t, double accuracy = METRIC_REGION ) const; - bool IsPole( double t ) const { return IsZero( t, METRIC_REGION ); } // \ru Устаревший метод. \en Deprecated method. + bool IsZero( double t, double accuracy = METRIC_REGION ) const; + bool IsPole( double t ) const { return IsZero( t, METRIC_REGION ); } // \ru Устаревший метод. \en Deprecated method. /// \ru Вернуть середину параметрического диапазона. \en Return the middle of parametric range. - double GetTMid() const { return ((GetTMin() + GetTMax()) * 0.5); } + double GetTMid() const { return ((GetTMin() + GetTMax()) * 0.5); } /// \ru Параметрическая длина. \en The parametric length. - double GetParamLength () const { return GetTMax()-GetTMin(); } + double GetParamLength () const { return GetTMax()-GetTMin(); } /// \ru Находится ли параметр в области определения функции. \en Whether the parameter belongs to the function domain. - bool IsParamOn( double t, double eps ) const { return ( GetTMin()-eps <= t && t <= GetTMax()+eps ); } + bool IsParamOn( double t, double eps ) const { return ( GetTMin()-eps <= t && t <= GetTMax()+eps ); } /// \ru Подготовить к записи регистрируемый объект. \en Prepare for writing the registered object. - void PrepareWrite() const { SetRegistrable( (GetUseCount() > 1) ? registrable : noRegistrable ); } + void PrepareWrite() const { SetRegistrable( (GetUseCount() > 1) ? registrable : noRegistrable ); } private: - void operator = ( const MbFunction & ); // \ru Не реализовано \en Not implemented + void operator = ( const MbFunction & ); // \ru Не реализовано \en Not implemented DECLARE_PERSISTENT_CLASS( MbFunction ) }; IMPL_PERSISTENT_OPS( MbFunction ) + #endif // __FUNCTION_H diff --git a/C3d/Include/instance_item.h b/C3d/Include/instance_item.h index 20037df..272a247 100644 --- a/C3d/Include/instance_item.h +++ b/C3d/Include/instance_item.h @@ -99,7 +99,7 @@ public : // \ru Добавить полигонную сетку объекта. \en Add a polygon mesh of the object. bool AddYourMesh( const MbStepData & stepData, const MbFormNote & note, MbMesh & mesh ) const override; // \ru Разрезать полигональный объект одной или двумя параллельными плоскостями. \en Cut the polygonal object by one or two parallel planes. - MbItem * CutMesh( const MbPlacement3D & cutPlace, double distance ) const override; + MbItem * CutMesh( const MbPlacement3D & cutPlace, double distance, const MbSNameMaker * = nullptr ) const override; // \ru Найти ближайший объект или имя ближайшего объекта. \en Find the closest object or its name. bool NearestMesh( MbeSpaceType sType, MbeTopologyType tType, MbePlaneType pType, const MbAxis3D & axis, double maxDistance, bool gridPriority, double & t, double & dMin, diff --git a/C3d/Include/math_define.h b/C3d/Include/math_define.h index 9e8ba39..2d9cd02 100644 --- a/C3d/Include/math_define.h +++ b/C3d/Include/math_define.h @@ -158,13 +158,11 @@ size_t DirectSearch( const ElementsVector & items, const Element & item ) template size_t BinarySearch( const ElementsVector & items, const Element & item ) { - size_t ind = SYS_MAX_T; - - typename ElementsVector::iterator it = std::lower_bound( items.begin(), items.end(), item ); + typename ElementsVector::const_iterator it = std::lower_bound( items.begin(), items.end(), item ); if ( (it != items.end()) && !(item < *it) ) { - ind = std::distance( items.begin(), it ); + return std::distance( items.begin(), it ); } - return ind; + return SYS_MAX_T; } } // namespace C3D diff --git a/C3d/Include/mb_enum.h b/C3d/Include/mb_enum.h index c3f64d8..be12313 100644 --- a/C3d/Include/mb_enum.h +++ b/C3d/Include/mb_enum.h @@ -844,7 +844,7 @@ enum MbeFairCurveType //------------------------------------------------------------------------------ -/// \ru Форма поверхности заметания переменного сечения. \en The swept surface cross-section shape. \~ +/// \ru Форма поверхности заметания переменного сечения. \en The shape of the variable section surface. \~ // --- enum MbeSectionShape { cs_Round = 0, ///< \ru Окружность или её дуга в сечении. \en The section is circle or arc. @@ -855,6 +855,28 @@ enum MbeSectionShape { }; // MbeSectionShape +//------------------------------------------------------------------------------ +/// \ru Форма обрезки боков поверхности переменного сечения. \en The shape of cropping the sides of the variable section surface. \~ +// --- +enum MbeSideShape { + side_Non = 0, ///< \ru Прямоугольная продлённая без обрезки. \en Rectangular extending without cropping. \~ + side_Min = 1, ///< \ru Прямоугольная обрезка по ближнему краю. \en Rectangular cropping on the near edge. \~ + side_Max = 2, ///< \ru Прямоугольная обрезка по дальнему краю. \en Rectangular cropping on the far edge. \~ + side_Cut = 3, ///< \ru Обрезка по кротчайшей линии. \en Cropping along the shortest line. \~ + side_Tau = 4, ///< \ru Обрезка по кубической линии с ортогональными краями. \en Cropping along a cubic curve with orthogonal edges. \~ +}; // MbeSideShape + + +//------------------------------------------------------------------------------ +/// \ru Обработка исходных опорных граней. \en The processing of initial reference faces. \~ +// --- +enum MbeFaceHandling { + face_Non = 0, ///< \ru Без обработки. \en Without processing. \~ + face_Cut = 1, ///< \ru Обрезать по опорным кривым. \en Cropping by reference curves. \~ + face_Sew = 2, ///< \ru Обрезать по опорным кривым и сшить с построенной гранью. \en Cropping by reference curves and sew with the constructed face. \~ +}; // MbeFaceProcessing + + //------------------------------------------------------------------------------ /** \brief \ru Выбор из пары объектов. \en Selection from a pair of objects. \~ @@ -882,8 +904,8 @@ enum class MbeCurveExtensionWays : unsigned int cew_Linear = 0, ///< \ru Кривая продлевается по касательной в крайней точке. \en The curve is extended by tangent to the boundary point. \~ cew_Circular = 1, ///< \ru Кривая продлевается по дуге, радиус которой равен радиусу кривизны кривой в крайней точке. \en The curve is extended by an arc with radius equal to its curvature radius in the boundary point. \~ - cew_BaseNatural = 2, ///< \ru Если существует уравнение кривой, то расширяется диапазон изменения параметра в уравнении. В противном случае, результатом будет гладко стыкующийся контур, распрямляющийся в бесконечности. \en If there exist the curve equation then the range of a parameter change will be extended. Otherwise, the result will be a smoothly connected contour straightening at the end. ~ - cew_CommonNatural = 3, ///< \ru Пока не используется. \en Currently, it is not implemented. \~ + cew_CommonNatural = 2, ///< \ru Если существует уравнение кривой, то расширяется диапазон изменения параметра в уравнении. В противном случае, результатом будет гладко стыкующийся контур, распрямляющийся в бесконечности. \en If there exist the curve equation then the range of a parameter change will be extended. Otherwise, the result will be a smoothly connected contour straightening at the end. ~ + cew_BaseNatural = 3, ///< \ru Пока не используется. \en Currently, it is not implemented. \~ // \ru !!! СТРОКИ ВСТАВЛЯТЬ СТРОГО ПЕРЕД ЭТОЙ СТРОКОЙ !!!! \en !!! INSERT LINES STRICTLY BEFORE THIS LINE !!!! diff --git a/C3d/Include/mb_property_title.h b/C3d/Include/mb_property_title.h index 7a7f6cc..c141b52 100644 --- a/C3d/Include/mb_property_title.h +++ b/C3d/Include/mb_property_title.h @@ -280,7 +280,7 @@ enum MbePrompt IDS_ITEM_0549, ///< \ru Набор тел. \en Set of solids. IDS_ITEM_0550, ///< \ru Часть набора тел. \en Set of solids part. IDS_ITEM_0551, ///< \ru Клон граней тела. \en Solid's faces drafting. - IDS_ITEM_0552, ///< \ru Разбивка граней тела. \en Splitting of Solid's faces. + IDS_ITEM_0552, ///< \ru Разбивка граней тела. \en Splitting of Solid's faces. IDS_ITEM_0553, ///< \ru Сшитое из оболочек тело. \en Stitched Solid. IDS_ITEM_0554, ///< \ru Сшитая из оболочек оболочка. \en Shell stitched from shells. IDS_ITEM_0555, ///< \ru Оболочка из NURBS-поверхностей. \en Shell from NURBS-surfaces. @@ -444,6 +444,7 @@ enum MbePrompt IDS_ITEM_0791, ///< \ru Атрибут бинарный. \en Binary Attribute. IDS_ITEM_0792, ///< \ru Атрибут массив целочисленных значений типа int32. \en Array of integer (int32) values attribute. IDS_ITEM_0793, ///< \ru Атрибут массив целочисленных значений типа int64. \en Array of integer (int64) values attribute. + IDS_ITEM_0794, ///< \ru Атрибут массив действительных чисел типа double. \en Array of real (double) values attribute. // \ru Сообщения. \en Messages. @@ -797,6 +798,10 @@ enum MbePrompt IDS_PROP_0463, ///< \ru Количество двумерных точек. \en Number of two-dimension points. IDS_PROP_0464, ///< \ru Количество точек полигонов. \en Number of points of polygons. + IDS_PROP_0467, ///< \ru Форма обрезки боков поверхности. \en Shape of cropping the surface sides. + IDS_PROP_0468, ///< \ru Обработка опорных граней. \en Initial faces processing. + IDS_PROP_0469, ///< \ru Разделять оболочку на грани. \en Division the shell into faces. + IDS_PROP_0501, ///< \ru Число вершин. \en Number of vertices. IDS_PROP_0502, ///< \ru Число ребер. \en Number of edges. IDS_PROP_0503, ///< \ru Число граней. \en Number of faces. @@ -1180,9 +1185,8 @@ enum MbePrompt IDS_PROP_1043, ///< \ru Элемент описания. \en Description element. - /* - 1100 .. 1199 is a range for C3D Solver - */ +// \ru 1100 .. 1199 зарезервированы для решателя геометрических ограничений. \en 1100 .. 1199 is a range for C3D Solver. + IDS_PROP_1100, ///< \ru Геометрический решатель. \en Geom solver. IDS_PROP_1101, ///< \ru Схема сопряжений. \en Scheme of matings. IDS_PROP_1102, ///< \ru Система ограничений. \en Constraint system. @@ -1199,9 +1203,8 @@ enum MbePrompt IDS_PROP_1113, ///< \ru Вещественный параметр. \en Real parameter. IDS_PROP_1114, ///< \ru Величина взаимоориентации. \en Value of coorientation. - /* - Types of geometric constraint - */ +// \ru Типы геометрических ограничений. \en Types of geometric constraint. + IDS_PROP_1130, ///< \ru Совпадение \en Coincident IDS_PROP_1131, ///< \ru Параллельность \en Parallel IDS_PROP_1132, ///< \ru Перпендикулярность \en Perpendicular @@ -1229,9 +1232,7 @@ enum MbePrompt IDS_PROP_1156, // "Координата СК паттерна." IDS_PROP_1199, // The last id for C3D Solver - /* - \ru Новые описания без группировки \en New unsorted descriptions - */ +// \ru Новые описания без группировки \en New unsorted descriptions IDS_PROP_2001, ///< \ru Внимание: \en Attention: IDS_PROP_2002, ///< \ru Начало общих операций. \en Beginning of the shared operations. diff --git a/C3d/Include/mb_rect2d.h b/C3d/Include/mb_rect2d.h index c5f7fd5..a8bc0d0 100644 --- a/C3d/Include/mb_rect2d.h +++ b/C3d/Include/mb_rect2d.h @@ -192,6 +192,8 @@ public: bool IsBound ( const MbVector3D &, double ) const; /// \ru Cдвинуть куб. \en Move box. void Move ( const MbVector & ); + /// \ru Выдать вершину габаритного прямоугольника по индексу от 0 до 3. \en Get vertex of bounding rectangle by index in range from 0 to 3. + void GetVertex( size_t index, MbCartPoint & p ) const; }; @@ -820,6 +822,31 @@ void MbRect2D::Move( const MbVector & vShift ) } +//------------------------------------------------------------------------------ +// выдать вершину габаритного прямоугольника по индексу от 0 до 3 +// +// Y +// | +// 3 - - - 2 +// | | +// | | +// 0 - - - 1 - X +// +// --- +inline +void MbRect2D::GetVertex( size_t index, MbCartPoint & p ) const +{ + index = std_max( (ptrdiff_t)0, (ptrdiff_t)index ); + index = std_min( (ptrdiff_t)3, (ptrdiff_t)index ); + + switch ( index ) { + case 0: { p.x = rx.zmin; p.y = ry.zmin; break; } + case 1: { p.x = rx.zmax; p.y = ry.zmin; break; } + case 2: { p.x = rx.zmax; p.y = ry.zmax; break; } + case 3: { p.x = rx.zmin; p.y = ry.zmax; break; } + } +} + //////////////////////////////////////////////////////////////////////////////// // // \ru Трехмерный куб \en Three-dimensional box diff --git a/C3d/Include/mesh.h b/C3d/Include/mesh.h index e95e92b..49a7a6e 100644 --- a/C3d/Include/mesh.h +++ b/C3d/Include/mesh.h @@ -152,7 +152,7 @@ public: // \ru Добавить себя в присланный полигональный объект mesh без копирования. \en Add itself to the given polygonal object "mesh" without copying. bool AddYourMesh( const MbStepData & stepData, const MbFormNote & note, MbMesh & mesh ) const override; // \ru Разрезать полигональный объект одной или двумя параллельными плоскостями. \en Cut polygonal form of an object by one or two parallel planes. - MbItem* CutMesh( const MbPlacement3D & cutPlace, double distance ) const override; + MbItem* CutMesh( const MbPlacement3D & cutPlace, double distance, const MbSNameMaker * = nullptr ) const override; // \ru Найти ближайший объект или имя ближайшего объекта. \en Find the nearest object or name of nearest object. // \note \ru В многопоточном режиме выполняется параллельно. \en In multithreaded mode runs in parallel. \~ bool NearestMesh( MbeSpaceType sType, MbeTopologyType tType, MbePlaneType pType, diff --git a/C3d/Include/mesh_plane_grid.h b/C3d/Include/mesh_plane_grid.h index 58c967a..7d2efce 100644 --- a/C3d/Include/mesh_plane_grid.h +++ b/C3d/Include/mesh_plane_grid.h @@ -15,7 +15,7 @@ // \ru - Вершина полигона \en - Vertex of a polygon // \ru - Многоугольник \en - Polygon // \ru - Аппроксимация плоской области треугольными пластинами \en - Approximation of a planar region by triangular plates -// \ru - Трингуляция двумерного региона \en - Triangulation of a two-dimensional region +// \ru - Триангуляция двумерного региона \en - Triangulation of a two-dimensional region // \ru - Выпуклая триангуляция неупорядоченного массива двумерных точек \en - Convex triangulation of unordered array of two-dimensional points // //////////////////////////////////////////////////////////////////////////////// @@ -300,7 +300,7 @@ protected: // \ru Нумерация соседних треугольников: \en Numeration of neighboring triangles: // \ru 0 - смежный через ребро на вершинах 0,1 \en 0 - adjacent at edge with vertices 0,1 // \ru 1 - смежный через ребро на вершинах 1,2 \en 1 - adjacent at edge with vertices 1,2 - // \ru 2 - смедный через ребра на вершинах 2,0 \en 2 - adjacent at edge with vertices 2,0 + // \ru 2 - смежный через ребра на вершинах 2,0 \en 2 - adjacent at edge with vertices 2,0 public: MbLinkedTri() : MbTri() { neighbors[0] = neighbors[1] = neighbors[2] = nullptr; }; @@ -329,15 +329,15 @@ inline bool MbLinkedTri::IsBoundary() const //------------------------------------------------------------------------------ // \ru Аппроксимация плоской области треугольными пластинами \en Approximation of planar region by triangular plates -// \ru Функция удаляет полигионы точек из массива \en The function removes polygons of points from the array +// \ru Функция удаляет полигоны точек из массива \en The function removes polygons of points from the array // --- MATH_FUNC (void) CalculatePlanarGrid( PArray< SArray > & poly, MbPlanarGrid & grid ); //------------------------------------------------------------------------------ -/** \brief \ru Трингуляция двумерного региона +/** \brief \ru Триангуляция двумерного региона \en Triangulation of a two-dimensional region \~ - \details \ru Трингуляция двумерного региона. + \details \ru Триангуляция двумерного региона. Регион region должен быть корректным (на некорректном работает неправильно) \en Triangulation of a two-dimensional region. 'region' region has to be correct (improper handling of incorrect ones) \~ diff --git a/C3d/Include/model_entity.h b/C3d/Include/model_entity.h index 7aab782..c452638 100644 --- a/C3d/Include/model_entity.h +++ b/C3d/Include/model_entity.h @@ -234,10 +234,12 @@ public : \en A local coordinate system which XY plane defines a cutting plane. \~ \param[in] distance - \ru Расстояние до параллельной режущей плоскости откладывается в отрицательную сторону оси Z локальной системы. \en Distance to a parallel cutting plane is measured in negative direction of Z-axis of local coordinate system. \~ + \param[in] names - \ru Именователь. + \en An object defining names generation in the operation. \~ \result \ru Возвращает новую модель полигональных объектов, лежащую под плоскость XY локальной системы координат на заданном расстоянии. \en Returns a new model of polygonal objects that lies under XY plane of local coordinate system at given distance. \~ */ - MbModel * CutMeshModel( const MbPlacement3D & cutPlace, double distance ) const; + MbModel * CutMeshModel( const MbPlacement3D & cutPlace, double distance, const MbSNameMaker * names = nullptr ) const; /** \brief \ru Найти ближайший объект или имя ближайшего объекта. \en Find the nearest object or name of the nearest object. \~ diff --git a/C3d/Include/model_item.h b/C3d/Include/model_item.h index 350b41a..533bc2e 100644 --- a/C3d/Include/model_item.h +++ b/C3d/Include/model_item.h @@ -238,11 +238,13 @@ public : \en A local coordinate system which XY plane defines a cutting plane. \~ \param[in] distance - \ru Расстояние до параллельной режущей плоскости откладывается в отрицательную сторону оси Z локальной системы. \en Distance to a parallel cutting plane is measured in negative direction of Z-axis of local coordinate system. \~ + \param[in] names - \ru Именователь. + \en An object defining names generation in the operation. \~ \result \ru Возвращает новый полигональный объект, лежащий под плоскость XY локальной системы координат на заданном расстоянии. \en Returns new polygonal object that located under XY-plane of local coordinate system at given distance. \~ \ingroup Model_Items */ - virtual MbItem * CutMesh( const MbPlacement3D & cutPlace, double distance ) const; + virtual MbItem * CutMesh( const MbPlacement3D & cutPlace, double distance, const MbSNameMaker * names = nullptr ) const; /** \brief \ru Найти ближайший объект или имя ближайшего объекта. \en Find the nearest object or name of the nearest object. \~ diff --git a/C3d/Include/model_tree_data.h b/C3d/Include/model_tree_data.h index b3f3745..77e654a 100644 --- a/C3d/Include/model_tree_data.h +++ b/C3d/Include/model_tree_data.h @@ -94,6 +94,7 @@ enum MbeItemDataType idtAttrInt32Vector, // MbInt32VectorAttribute at_Int32VectorAttribute idtAttrInt64Vector, // MbInt64VectorAttribute at_Int64VectorAttribute + idtAttrDoubleVector, // MbDoubleVectorAttribute at_DoubleVectorAttribute // \ru Новый тип должен добавляться непосредственно перед idtCount (после всех определенных ранее типов). // \en New type should be added just before idtCount (after all types defined before). @@ -667,6 +668,7 @@ MTREE_ATTR_DATALESS_CLASS(ItemAttrSTEPReferenceHolder, idtAttrSTEPReferenceHolde MTREE_ATTR_DATALESS_CLASS(ItemAttrBinary, idtAttrBinary); MTREE_ATTR_DATALESS_CLASS(ItemAttrInt32Vector, idtAttrInt32Vector) MTREE_ATTR_DATALESS_CLASS(ItemAttrInt64Vector, idtAttrInt64Vector) +MTREE_ATTR_DATALESS_CLASS(ItemAttrDoubleVector, idtAttrDoubleVector) MTREE_ATTR_DATALESS_CLASS(ItemAttrStrains, idtAttrStrains); MTREE_ATTR_DATALESS_CLASS(ItemAttrElasticity, idtAttrElasticity); MTREE_ATTR_DATALESS_CLASS(ItemAttrSheetFlanging, idtAttrSheetFlanging); diff --git a/C3d/Include/op_curve_parameter.h b/C3d/Include/op_curve_parameter.h index 7c77f3d..03c4627 100644 --- a/C3d/Include/op_curve_parameter.h +++ b/C3d/Include/op_curve_parameter.h @@ -727,7 +727,8 @@ private: c3d::SNameMakerSPtr _operName; ///< \ru Именователь операции. Всегда не ноль. \en An object defining names generation in the operation. It is always not nullptr. \~ bool _allowClosure; ///< \ru Разрешено ли замыкание. По умолчанию разрешено. \en Whether closure is allowed. It is allowed by default. \~ bool _extendAlongSurface; ///< \ru Удлинять вдоль поверхности. Действует только на поверхностные кривые (MbSurfaceCurve). \en Extend along the surface. It works only with MbSurfaceCurve. \~ - + c3d::ConstSurfaceSPtr _surface; ///< \ru Поверхность, на которой расположена кривая. Может быть nullptr. \en A surface, which the curve lies in. It can be nullptr. \~ + public: //------------------------------------------------------------------------------ @@ -815,15 +816,17 @@ public: /// \ru Получить именователь операции. \en Get the object defining names generation in the operation. \~ const MbSNameMaker & GetNameMaker() const { return *_operName; } - - /// \ru Разрешить замыкание удлиненной кривой. \en Allow closure of the extended curve. \~ - void AllowClosure( const bool allow ) { _allowClosure = allow; } - /// \ru Получить информацию о разрешении замкнутости. \en Get the information about closure allowing. \~ bool IsClosureAllowed() const { return _allowClosure; } /// \ru Удлинять поверхностные кривые вдоль поверхности. \en Extend surface curves along the surface. \~ - bool ExtensionAlongSurface() const { return _extendAlongSurface; } + bool IsExtensionAlongSurface() const { return (_extendAlongSurface && !_surface.is_null() ); } + + /// \ru Поверхность, на которой расположена кривая. Имеет смысл только в случае удлинения вдоль поверхности. В противном случае всегда nullptr. \en A surface, which the curve lies in. It makes a sense if the option "Along surface" is switched on. Otherwise it is always nullptr. \~ + const c3d::ConstSurfaceSPtr & GetSurface() const { return _surface; } + + /// \ru Минимальная величина зазора (в параметрическом пространстве) для случая, когда запрещено создания замкнутых кривых. \en Minimal gap value (in parametric space) for case when closed result curves are forbidden. \~ + static double GetMinUnclosedGap() { return Math::paramPrecision; } /// \ru Оператор присваивания. \en Assignment operator. \~ MbCurveExtensionParameters & operator=( const MbCurveExtensionParameters & other ); @@ -1217,6 +1220,7 @@ public: MbeFairSmoothing _fairing; ///< \ru Сглаживание. \en Smoothing of curve. \~ size_t _degree; ///< \ru Степень B-сплайновой кривой m ( 3 <= m <= 10). \en The degree m (3 <= m <= 10) of B-Spline curve. \~ double _scaleParam; ///< \ru Параметр репараметризации. \en Scaling parameter. + MbeFairCurvature _accountCurvature; ///< \ru Учет кривизны в концевых точках. \en Accounting for curvature at end points. \~ MbeFairWarning _warning; ///< \ru Предупреждение о работе. \en The operation warning. \~ MbResultType _error; ///< \ru Ошибка о работе. \en The operation error. \~ @@ -1229,7 +1233,7 @@ public: /// \ru Пустой конструктор. \en Empty constructor. MbFairChangeData() : MbPrecision(), _outFormat( fairFormat_Close ), _nSegments( 4 ), _numSegment( 0 ), _tParam( 0.5 ), - _fairing( fairSmooth_Yes ), _degree ( 8 ), _scaleParam( 1.0 ), + _fairing( fairSmooth_Yes ), _degree ( 8 ), _scaleParam( 1.0 ), _accountCurvature( fairCur_No ), #ifdef C3D_DEBUG_FAIR_CURVES prt( nullptr ), #endif diff --git a/C3d/Include/op_shell_parameter.h b/C3d/Include/op_shell_parameter.h index 468c327..0552844 100644 --- a/C3d/Include/op_shell_parameter.h +++ b/C3d/Include/op_shell_parameter.h @@ -1402,7 +1402,7 @@ public: , direction( 0.0, 0.0, 0.0 ) , origin ( 0.0, 0.0, 0.0 ) , value ( 0.0 ) - , tolerance( 1.0 ) + , tolerance( Math::metricAccuracy ) {} /// \ru Конструктор по способу модификации и вектору перемещения. \en Constructor by way of modification and movement vector. ModifyValues( MbeModifyingType w, const MbVector3D & p ) @@ -1410,10 +1410,10 @@ public: , direction( p ) , origin ( 0.0, 0.0, 0.0 ) , value ( 0.0 ) - , tolerance( 1.0 ) + , tolerance( Math::metricAccuracy ) {} /// \ru Конструктор по способу модификации и скалярному параметру. \en Constructor by way of modification and the scalar value. - ModifyValues( MbeModifyingType w, double val, double eps = 1.0 ) + ModifyValues( MbeModifyingType w, double val, double eps = Math::metricAccuracy ) : way ( w ) , direction( 0.0, 0.0, 0.0 ) , origin ( 0.0, 0.0, 0.0 ) diff --git a/C3d/Include/op_swept_parameter.h b/C3d/Include/op_swept_parameter.h index b1a9a34..c7cd047 100644 --- a/C3d/Include/op_swept_parameter.h +++ b/C3d/Include/op_swept_parameter.h @@ -1529,17 +1529,17 @@ private: class MATH_CLASS MbSectionRail { private: - std::vector edges; ///< \ru Направляющие рёбра (могут отсутствовать). \en The guide edges (may be empty). - std::vector edgeSide; ///< \ru С какой гранью ребра гладко стыковать поверхность (синхронно с edges). \en What face of edge should the surface join smoothly to (synchronously with edges). - std::vector edgeIndex; ///< \ru Номера направляющих рёбер (могут отсутствовать). \en The guide edge numbers (may be empty). - std::vector faces; ///< \ru Опорные грани (могут отсутствовать). \en The reference faces (may be empty). - std::vector faceSide; ///< \ru С каких сторон касаться поверхностей при form==cs_Linea (синхронно с faces). \en On which sides to touch surfaces when form==cs_Linea (synchronously with faces). - std::vector faceIndex; ///< \ru Номера опорных граней. \en The reference face numbers (may be empty). - std::vector curves; ///< \ru Направляющие кривые (могут отсутствовать). \en The guide curves (may be empty). - c3d::SpaceCurveSPtr track; ///< \ru Кривая, через которую должно пройти сечение (может отсутствовать). \en The curve that the section should pass through (may be nullptr). - c3d::FunctionSPtr function; ///< \ru Функция угла наклона, или длины, или радиуса (может отсутствовать). \en The function of the angle of inclination, or of the length, or of the fillet radius (may be nullptr). - ThreeStates state; ///< \ru Как использовать function: угол к хорде или направлению (ts_neutral), отклонение от касательной поверхности (ts_positive), отклонение от нормали к поверхности (ts_negative). - ///< \en How to use the function: the angle to chord or to direction (ts_neutral), deviation from tangent surface (ts_positive), deviation from normal to surface (ts_negative). + std::vector edges; ///< \ru Направляющие рёбра (могут отсутствовать). \en The guide edges (may be empty). \~ + std::vector edgeSide; ///< \ru С какой гранью ребра гладко стыковать поверхность (синхронно с edges). \en What face of edge should the surface join smoothly to (synchronously with edges). \~ + std::vector edgeIndex; ///< \ru Номера направляющих рёбер (могут отсутствовать). \en The guide edge numbers (may be empty). \~ + std::vector faces; ///< \ru Опорные грани (могут отсутствовать). \en The reference faces (may be empty). \~ + std::vector faceSide; ///< \ru С каких сторон касаться поверхностей при form==cs_Linea (синхронно с faces). \en On which sides to touch surfaces when form==cs_Linea (synchronously with faces). \~ + std::vector faceIndex; ///< \ru Номера опорных граней. \en The reference face numbers (may be empty). \~ + std::vector curves; ///< \ru Направляющие кривые (могут отсутствовать). \en The guide curves (may be empty). \~ + c3d::SpaceCurveSPtr track; ///< \ru Кривая, через которую должно пройти сечение (может отсутствовать). \en The curve that the section should pass through (may be nullptr). \~ + c3d::FunctionSPtr function; ///< \ru Функция угла наклона, или длины, или радиуса (может отсутствовать). \en The function of the angle of inclination, or of the length, or of the fillet radius (may be nullptr). \~ + ThreeStates state; ///< \ru Как использовать function: угол к хорде или направлению (ts_neutral), отклонение от касательной поверхности (ts_positive), отклонение от нормали к поверхности (ts_negative). \~ + ///< \en How to use the function: the angle to chord or to direction (ts_neutral), deviation from tangent surface (ts_positive), deviation from normal to surface (ts_negative). \~ public: /// \ru Конструктор по умолчанию. \en Empty constructor. @@ -1688,10 +1688,12 @@ public: // --- struct MATH_CLASS MbSectionRule { public: - c3d::FunctionSPtr discr; ///< \ru Функция управления сечением (дискриминант или радиус, может быть nullptr). \en Section control function (discriminant or radius). - c3d::SpaceCurveSPtr track; ///< \ru Кривая, через которую должно пройти сечение. \en The curve that the section should pass through. - c3d::SurfaceSPtr touch; ///< \ru Поверхность, которой должно касаться сечение. \en The surface that the section should touch. - c3d::ShellSPtr shell; ///< \ru Оболочка, которой должно касаться сечение. \en The shell that the section should touch. + c3d::FunctionSPtr discr; ///< \ru Функция управления сечением (дискриминант или радиус, может быть nullptr). \en Section control function (discriminant or radius). \~ + c3d::SpaceCurveSPtr track; ///< \ru Кривая, через которую должно пройти сечение. \en The curve that the section should pass through. \~ + c3d::SurfaceSPtr touch; ///< \ru Поверхность, которой должно касаться сечение. \en The surface that the section should touch. \~ + c3d::ShellSPtr shell; ///< \ru Оболочка, которой должно касаться сечение. \en The shell that the section should touch. \~ + MbeSectionShape shape; ///< \ru Форма сечения поверхности. \en The surface cross-section shape. \~ + double ratio; ///< \ru Или натяжение, или скос, или соотношение. \en Or tension, or bevel, or ratio. \~ public: /// \ru Конструктор по умолчанию. \en Empty constructor. @@ -1702,34 +1704,42 @@ public: MbSectionRule( MbCurve3D * cur ); /// \ru Конструктор по поверхности. \en The constructor by surface. MbSectionRule( MbSurface * sur ); - /// \ru Конструктор по оболочке. \en The constructor by shell. + /// \ru Конструктор по оболочке. \en The constructor by shell. \~ MbSectionRule( MbFaceShell * sur ); - /// \ru Конструктор копирования. \en Copy-constructor. + /// \ru Конструктор копирования. \en Copy-constructor. \~ MbSectionRule( const MbSectionRule & other ); - /// \ru Конструктор копирования. \en Copy-constructor. + /// \ru Конструктор копирования. \en Copy-constructor. \~ MbSectionRule( const MbSectionRule & other, MbRegDuplicate * ireg ); /// \ru Деструктор. \en Destructor. ~MbSectionRule(); public: - /// \ru Выдать функцию управления сечением. \en Get section control function. + /// \ru Выдать функцию управления сечением. \en Get section control function. \~ const MbFunction * GetFunction() const { return discr.get(); } - /// \ru Установить функцию управления сечением. \en Set section control function. - void SetFunction( MbFunction & f ); - void SetFunction( double f ); - /// \ru Выдать кривую управления сечением. \en Get section control curve. + /// \ru Установить функцию управления сечением. \en Set section control function. \~ + void SetFunction( MbFunction & f ); + void SetFunction( double f ); + /// \ru Выдать кривую управления сечением. \en Get section control curve. \~ const MbCurve3D * GetCurve() const { return track.get(); } - /// \ru Установить кривую управления сечением. \en Set section control curve. - void SetCurve( MbCurve3D & c ); - /// \ru Выдать поверхность управления сечением. \en Get section control surface. + /// \ru Установить кривую управления сечением. \en Set section control curve. \~ + void SetCurve( MbCurve3D & c ); + /// \ru Выдать поверхность управления сечением. \en Get section control surface. \~ const MbSurface * GetSurface() const { return touch.get(); } - /// \ru Установить поверхность управления сечением. \en Set section control surface. - void SetSurface( MbSurface & s ); - /// \ru Выдать оболочку управления сечением. \en Get section control shell. + /// \ru Установить поверхность управления сечением. \en Set section control surface. \~ + void SetSurface( MbSurface & s ); + /// \ru Выдать оболочку управления сечением. \en Get section control shell. \~ const MbFaceShell * GetShell() const { return shell.get(); } - /// \ru Установить оболочку управления сечением. \en Set section control shell. - void SetShell( MbFaceShell & s ); + /// \ru Установить оболочку управления сечением. \en Set section control shell. \~ + void SetShell( MbFaceShell & s ); + /// \ru Выдать форму сечения поверхности. \en Get cross-section shape. \~ + MbeSectionShape GetShape() const { return shape; } + /// \ru Установить форму сечения поверхности. \en Set cross-section shape. \~ + void SetShape( MbeSectionShape f ) { shape = f; } + /// \ru Выдать соотношение. \en Get the ratio. \~ + double GetRatio() const { return ratio; } + /// \ru Установить соотношение. \en Set the ratio. \~ + void SetRatio( double r ) { ratio = r; } /// \ru Преобразовать объект. \en Transform the object. \~ void Transform( const MbMatrix3D & matr, MbRegTransform * iReg = nullptr ); @@ -1744,7 +1754,7 @@ public: /// \ru Сделать объекты равным. \en Make objects equal. \~ bool SetEqual ( const MbSectionRule & other ); - /// \ru Оператор присваивания без копирования данных. \en Assignment operator without copying. + /// \ru Оператор присваивания без копирования данных. \en Assignment operator without copying. \~ void operator = ( const MbSectionRule & other ); KNOWN_OBJECTS_RW_REF_OPERATORS( MbSectionRule ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. @@ -1801,21 +1811,24 @@ public: class MATH_CLASS MbSectionData : public MbPrecision { private: - c3d::SpaceCurveSPtr spine; ///< \ru Опорная кривая. \en The reference curve. - MbeSectionShape form; ///< \ru Форма сечения поверхности. \en The surface cross-section shape. - MbSectionRail rail1; ///< \ru Данные начального края сечения. \en The data of the begining of section. - MbSectionRail rail2; ///< \ru Данные конечного края сечения. \en The data of the end of section. - c3d::SpaceCurveSPtr apexCurve; ///< \ru Кривая вершин (может отсутствовать). \en The apex curve (may be nullptr). - MbSectionRule descript; ///< \ru Функция управления сечением поверхности (радиус или дискриминант, может быть nullptr). \en The section control function (radius or discriminant). - SPtr pattern; ///< \ru Образующая кривая при form==cs_Shape (для других форм nullptr). \en Forming curve for form==cs_Shape (nullptr on other case). - MbVector3D direction; ///< \ru Направление, от которого отсчитывается угол при form==cs_Linea. \en The direction from which the angle is calculated when form==cs_Linea. - double uMin; ///< \ru Минимальное значение первого параметра. \en Minimal value of the first parameter. - double uMax; ///< \ru Максимальное значение первого параметра. \en Maximal value of the first parameter. - double buildSag; ///< \ru Угловое отклонение при движении по кривым и поверхностям. \en Angular deviation while moving along curves and surfaces. - double accuracy; ///< \ru Точность построения толерантных объектов. \en An accuracy of building tolerant objects. - uint32 count; ///< \ru Минимальное количество шагов по опорной кривой. \en Minimum number of steps along the reference curve. - bool check; ///< \ru Проверять самопересечение построенной поверхности. \en Check the self-intersection of the constructed surface (default false). - MbSNameMaker nameMaker; ///< \ru Именователь новых граней операции. \en An object defining names generation in the operation. + c3d::SpaceCurveSPtr spine; ///< \ru Опорная кривая. \en The reference curve. \~ + MbeSectionShape form; ///< \ru Форма сечения поверхности. \en The surface cross-section shape. \~ + MbSectionRail rail1; ///< \ru Данные начального края сечения. \en The data of the begining of section. \~ + MbSectionRail rail2; ///< \ru Данные конечного края сечения. \en The data of the end of section. \~ + c3d::SpaceCurveSPtr apexCurve; ///< \ru Кривая вершин (может отсутствовать). \en The apex curve (may be nullptr). \~ + MbSectionRule descript; ///< \ru Функция управления сечением поверхности (радиус или дискриминант, может быть nullptr). \en The section control function (radius or discriminant). \~ + SPtr pattern; ///< \ru Образующая кривая при form==cs_Shape (для других форм nullptr). \en Forming curve for form==cs_Shape (nullptr on other case). \~ + MbVector3D direction; ///< \ru Направление, от которого отсчитывается угол при form==cs_Linea. \en The direction from which the angle is calculated when form==cs_Linea. \~ + MbeSideShape sideShape; ///< \ru Форма обрезки боков поверхности. \en The form of cropping the sides of the surface. \~ + MbeFaceHandling handling; ///< \ru Обработка исходных опорных граней. \en The processing of initial reference faces. \~ + bool faceSplit; ///< \ru Разделять оболочку на грани по сегментам направляющих кривых. \en Divide the shell into faces by segments of guides. \~ + double uMin; ///< \ru Минимальное значение первого параметра. \en Minimal value of the first parameter. \~ + double uMax; ///< \ru Максимальное значение первого параметра. \en Maximal value of the first parameter. \~ + double buildSag; ///< \ru Угловое отклонение при движении по кривым и поверхностям. \en Angular deviation while moving along curves and surfaces. \~ + double accuracy; ///< \ru Точность построения толерантных объектов. \en An accuracy of building tolerant objects. \~ + uint32 count; ///< \ru Минимальное количество шагов по опорной кривой. \en Minimum number of steps along the reference curve. \~ + bool check; ///< \ru Проверять самопересечение построенной поверхности. \en Check the self-intersection of the constructed surface (default false). \~ + MbSNameMaker nameMaker; ///< \ru Именователь новых граней операции. \en An object defining names generation in the operation. \~ public: /// \ru Конструктор по умолчанию. \en Empty constructor. @@ -1999,6 +2012,14 @@ public: const MbSurface * GetDescriptSurface() const { return descript.GetSurface(); } /// \ru Выдать оболочку управления сечением. \en Get section control shell. const MbFaceShell * GetDescriptShell() const { return descript.GetShell(); } + /// \ru Выдать форму сечения поверхности. \en Get cross-section shape. + MbeSectionShape GetDescriptShape() const { return descript.GetShape(); } + /// \ru Установить форму сечения поверхности. \en Set cross-section shape. + void SetDescriptShape( MbeSectionShape f ) { descript.SetShape( f ); } + /// \ru Выдать соотношение. \en Get the ratio. \~ + double GetRatio() const { return descript.GetRatio(); } + /// \ru Установить соотношение. \en Set the ratio. \~ + void SetRatio( double r ) { descript.SetRatio( r ); } /// \ru Выдать образующую кривую. \en Get forming curve. const MbPolyCurve * GetPattern() const { return pattern.get(); } @@ -2010,6 +2031,18 @@ public: MbVector3D & SetDirection() { return direction; } /// \ru Установить направление, от которого отсчитывается угол. \en Set the direction from which the angle is calculated. void SetDirection( const MbVector3D & dir ) { direction = dir; } + /// \ru Выдать форму обрезки боков поверхности. \en Get the shape of cropping the sides of the surface. \~ + MbeSideShape GetSideShape() const { return sideShape; } + /// \ru Установить форму обрезки боков поверхности. \en Set the shape of cropping the sides of the surface. \~ + void SetSideShape( MbeSideShape s ) { sideShape = s; } + /// \ru Выдать обработку исходных опорных граней. \en Get the processing of initial reference faces. \~ + MbeFaceHandling GetFaceHandling() const { return handling; } + /// \ru Установить обработку исходных опорных граней. \en Set the processing of initial reference faces. \~ + void SetFaceHandling( MbeFaceHandling h ) { handling = h; } + /// \ru Разделять оболочку на грани по сегментам направляющих кривых? \en Is divide the shell into faces by segments of guides? \~ + bool GetFaceSplit() const { return faceSplit; } + /// \ru Установить деление оболочки на грани по сегментам направляющих кривых. \en Set division the shell into faces by segments of guides. + void SetFaceSplit( bool s ) { faceSplit = s; } /// \ru Минимальное значение первого параметра. \en Minimal value of the first parameter. double GetUMin() const { return uMin; } diff --git a/C3d/Include/part_solid.h b/C3d/Include/part_solid.h index daab194..15abffa 100644 --- a/C3d/Include/part_solid.h +++ b/C3d/Include/part_solid.h @@ -150,10 +150,10 @@ protected: // \ru Внутренние функции. \en Internal functions. /// \ru Установить измененность. \en Set modification. void SetChanged ( bool b ) const { changed = b; } -KNOWN_OBJECTS_RW_REF_OPERATORS_EX( MbPartSolidIndex, MATH_FUNC_EX ) -DECLARE_NEW_DELETE_CLASS( MbPartSolidIndex ) -OBVIOUS_PRIVATE_COPY ( MbPartSolidIndex ) -}; + KNOWN_OBJECTS_RW_REF_OPERATORS_EX( MbPartSolidIndex, MATH_FUNC_EX ) + DECLARE_NEW_DELETE_CLASS( MbPartSolidIndex ) + OBVIOUS_PRIVATE_COPY ( MbPartSolidIndex ) +}; // MbPartSolidIndex //------------------------------------------------------------------------------ @@ -382,9 +382,9 @@ private: // \ru Внутренние функции. \en Internal functions. // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. void operator = ( const MbPartSolidIndices & ); -KNOWN_OBJECTS_RW_REF_OPERATORS_EX( MbPartSolidIndices, MATH_FUNC_EX ) -DECLARE_NEW_DELETE_CLASS( MbPartSolidIndices ) -DECLARE_NEW_DELETE_CLASS_EX( MbPartSolidIndices ) + KNOWN_OBJECTS_RW_REF_OPERATORS_EX( MbPartSolidIndices, MATH_FUNC_EX ) + DECLARE_NEW_DELETE_CLASS( MbPartSolidIndices ) + DECLARE_NEW_DELETE_CLASS_EX( MbPartSolidIndices ) }; diff --git a/C3d/Include/sheet_metal_param.h b/C3d/Include/sheet_metal_param.h index d30b37e..16b4038 100644 --- a/C3d/Include/sheet_metal_param.h +++ b/C3d/Include/sheet_metal_param.h @@ -2586,7 +2586,7 @@ public: \ingroup Build_Parameters */ // --- -class MATH_CLASS MbStampParams : MbPrecision { +class MATH_CLASS MbStampParams : public MbPrecision { private: c3d::ConstFaceSPtr _face; ///< \ru Грань штамповки. Всегда не ноль. \en The face for stamping. It is always not nullptr.\~ const MbPlacement3D _placement; ///< \ru ЛСК контура штамповки. \en The local coordinate system for the stamping contour.\~ @@ -2694,7 +2694,7 @@ public: \ingroup Build_Parameters */ // --- -class MATH_CLASS MbSphericalStampParams : MbPrecision { +class MATH_CLASS MbSphericalStampParams : public MbPrecision { private: c3d::ConstFaceSPtr _face; ///< \ru Грань штамповки. Всегда не ноль. \en The face for stamping. It is always not nullptr.\~ const MbPlacement3D _placement; ///< \ru ЛСК контура штамповки. \en The local coordinate system for the stamping contour.\~ diff --git a/C3d/Include/surf_chamfer_surface.h b/C3d/Include/surf_chamfer_surface.h index 6b9d925..d7d8582 100644 --- a/C3d/Include/surf_chamfer_surface.h +++ b/C3d/Include/surf_chamfer_surface.h @@ -167,8 +167,8 @@ public: \en \name Functions for get of the group of data inside and outside the surface's domain of parameters. \{ */ void Explore( double & u, double & v, bool ext, - MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, - MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; + MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, + MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; /** \} */ /** \ru \name Функции движения по поверхности \en \name Functions of moving along the surface @@ -222,11 +222,12 @@ public: /** \} */ private: - void operator = ( const MbChamferSurface & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbChamferSurface & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbChamferSurface ) }; IMPL_PERSISTENT_OPS( MbChamferSurface ) + #endif // __SURF_CHAMFER_SURFACE_H diff --git a/C3d/Include/surf_channel_surface.h b/C3d/Include/surf_channel_surface.h index 4694d6b..2963a05 100644 --- a/C3d/Include/surf_channel_surface.h +++ b/C3d/Include/surf_channel_surface.h @@ -188,68 +188,69 @@ public: \en \name Functions of fillet surface with variable radius is normal or with preservation of edges \{ */ - /** \brief \ru Добавить точку в опорные кривые границы. - \en Add a point to the support curves of the boundary. \~ - \details \ru Добавить точку в опорные кривые границы.\n - Точка будет добавлена в кривую, если она имеет тип pt_LineSegment, pt_CubicSpline или pt_Hermit. - \en Add a point to the support curves of the boundary.\n - A point will be added into a curve if it has a type pt_LineSegment, pt_CubicSpline or pt_Hermit. \~ - \param[out] t1 - \ru Параметр точки на первой кривой (если add1 = true) - \en Parameter of a point on the first curve (if add1 equals true) \~ - \param[in] p1 - \ru Точка на первой кривой - \en Point on the first curve \~ - \param[in] add1 - \ru Нужно ли добавлять точку в первую кривую - \en Whether to add a point to the first curve \~ - \param[out] t2 - \ru Параметр точки на второй кривой (если add2 = true) - \en Parameter of a point on the second curve (if add2 equals true) \~ - \param[in] p2 - \ru Точка на второй кривой - \en Point on the second curve \~ - \param[in] add2 - \ru Нужно ли добавлять точку во вторую кривую - \en Whether to add a point to the second curve \~ - */ + /** \brief \ru Добавить точку в опорные кривые границы. + \en Add a point to the support curves of the boundary. \~ + \details \ru Добавить точку в опорные кривые границы.\n + Точка будет добавлена в кривую, если она имеет тип pt_LineSegment, pt_CubicSpline или pt_Hermit. + \en Add a point to the support curves of the boundary.\n + A point will be added into a curve if it has a type pt_LineSegment, pt_CubicSpline or pt_Hermit. \~ + \param[out] t1 - \ru Параметр точки на первой кривой (если add1 = true) + \en Parameter of a point on the first curve (if add1 equals true) \~ + \param[in] p1 - \ru Точка на первой кривой + \en Point on the first curve \~ + \param[in] add1 - \ru Нужно ли добавлять точку в первую кривую + \en Whether to add a point to the first curve \~ + \param[out] t2 - \ru Параметр точки на второй кривой (если add2 = true) + \en Parameter of a point on the second curve (if add2 equals true) \~ + \param[in] p2 - \ru Точка на второй кривой + \en Point on the second curve \~ + \param[in] add2 - \ru Нужно ли добавлять точку во вторую кривую + \en Whether to add a point to the second curve \~ + */ bool InsertPoints( double & t1, const MbCartPoint & p1, bool add1, - double & t2, const MbCartPoint & p2, bool add2 ) override; + double & t2, const MbCartPoint & p2, bool add2 ) override; - /** \brief \ru Проверить наличие полюса. - \en Check pole availability. \~ - \details \ru Проверить наличие полюса. - \en Check pole availability. \~ - \param[in] u - \ru Начальное приближение параметра по U для поиска полюса - \en Initial approximation of parameter U to search pole \~ - \param[in] bModify - \ru Флаг модификации поверхности \n - если true, то поверхность корректирует свои параметры по U - и соответственно им опорные кривые curve1 и curve2 - \en Flag of surface modification \n - if true, then the surface corrects its parameters along U - and according to them the support curves curve1 and curve2 \~ - \return \ru true - если нашли полюс - \en True - if pole has been found \~ - */ - bool CheckPole( double & u, bool bModify = true ); - /// \ru Получить функцию изменения радиуса. \en Get a function of radius changing. - const MbFunction & GetFunction() const { return *function; } - /// \ru Получить функцию изменения радиуса. \en Get a function of radius changing. - MbFunction & SetFunction() { return *function; } - /// \ru Заменить функцию изменения радиуса. \en Set a function of radius changing. - void SetFunction( MbFunction & funcNew ); // \ru (новая функция должна быть корректна) \en (new function must be correct) - /// \ru Построить функцию изменения радиуса от параметра u1 до параметра u2. \en Construct a function for changing the radius from parameter u1 to parameter u2. - MbFunction * MakeFunction( double u1, double u2 ) const; + /** \brief \ru Проверить наличие полюса. + \en Check pole availability. \~ + \details \ru Проверить наличие полюса. + \en Check pole availability. \~ + \param[in] u - \ru Начальное приближение параметра по U для поиска полюса + \en Initial approximation of parameter U to search pole \~ + \param[in] bModify - \ru Флаг модификации поверхности \n + если true, то поверхность корректирует свои параметры по U + и соответственно им опорные кривые curve1 и curve2 + \en Flag of surface modification \n + if true, then the surface corrects its parameters along U + and according to them the support curves curve1 and curve2 \~ + \return \ru true - если нашли полюс + \en True - if pole has been found \~ + */ + bool CheckPole( double & u, bool bModify = true ); + /// \ru Получить функцию изменения радиуса. \en Get a function of radius changing. + const MbFunction & GetFunction() const { return *function; } + /// \ru Получить функцию изменения радиуса. \en Get a function of radius changing. + MbFunction & SetFunction() { return *function; } + /// \ru Заменить функцию изменения радиуса. \en Set a function of radius changing. + void SetFunction( MbFunction & funcNew ); // \ru (новая функция должна быть корректна) \en (new function must be correct) + /// \ru Построить функцию изменения радиуса от параметра u1 до параметра u2. \en Construct a function for changing the radius from parameter u1 to parameter u2. + MbFunction * MakeFunction( double u1, double u2 ) const; /** \} */ private: // \ru Дать коэффициент для радиуса \en Get coefficient for radius double FunctionValue( double u ) const override; - void CheckPole(); // \ru Проверить полюса \en Check poles + void CheckPole(); // \ru Проверить полюса \en Check poles // \ru Добавить точку в опорные кривые границы поверхности с постоянной хордой. \en Add a point to the support curves of the boundary of surface with constant chord. \~ - bool InsertForSpan( double & t1, const MbCartPoint & p1, bool add1, + bool InsertForSpan( double & t1, const MbCartPoint & p1, bool add1, double & t2, const MbCartPoint & p2, bool add2 ); - void operator = ( const MbChannelSurface & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbChannelSurface & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbChannelSurface ) }; IMPL_PERSISTENT_OPS( MbChannelSurface ) + //------------------------------------------------------------------------------ // \ru Создать поверхность переменного радиуса \en Create surface with variable radius // --- @@ -272,4 +273,3 @@ MbSmoothSurface * CreateKerbChannelSurface( const MbSurface & surface1, SArray & uv, bool ext, MbRect2D * uvRange = nullptr ) const override; // \ru Пересечение с кривой. \en Intersection with curve. void CurveIntersection( const MbCurve3D & curv, SArray & uv, SArray & tt, - bool ext0, bool ext, bool touchInclude = false ) const override; + bool ext0, bool ext, bool touchInclude = false ) const override; // \ru Дать мимнимально различимую величину параметра. \en Get the minimum distinguishable value of parameter. double GetParamPrice() const override; @@ -306,9 +306,9 @@ public: void GetParamsToUnit( double u, double v, double & uParam, double & vParam ) const override; // \ru Дать приращение параметра u и параметра v, соответствующее единичной длине в пространстве. \en Get increment of parameters, corresponding to the unit length in space. // \ru Определение разбивки параметрической области поверхности вертикалями и горизонталями. \en Determine splitting of parametric region of surface by vertical and horizontal lines. - virtual void GetTesselation( const MbStepData & stepData, - double u1, double u2, double v1, double v2, - SArray & uu, SArray & vv ) const override; + void GetTesselation( const MbStepData & stepData, + double u1, double u2, double v1, double v2, + SArray & uu, SArray & vv ) const override; void CalculateGabarit( MbCube & ) const override; // \ru Рассчитать габарит поверхности. \en Calculate bounding box of surface. void CalculateLocalGabarit( const MbMatrix3D &, MbCube & ) const override; // \ru Рассчитать габарит относительно л.с.к. \en Calculate bounding box relative to the local coordinate system. @@ -340,39 +340,39 @@ public: /** \ru \name Функции конической поверхности \en \name Functions of conical surface \{ */ - /// \ru Получить внутренний радиус основания. \en Get internal radius of base. - double GetR() const { return radius; } - /// \ru Получить текущий внутренний радиус для параметра v без ограничений vmin, vmax. \en Get current internal radius for v parameter without constraints of vmin, vmax. - double GetR( double v ) const { return radius + tgAngleH * v; } - /// \ru Получить физический радиус. \en Get physical radius. - double GetRadius( double v ) const; - /// \ru Получить внутренний радиус для параметра v, равного 1.0. \en Get internal radius for v parameter equal to 1.0. - double GetUpperR() const { return radius + tgAngleH; } - /// \ru Установить внутренний радиус. \en Set an internal radius. - void SetR( double r ) { radius = r; } + /// \ru Получить внутренний радиус основания. \en Get internal radius of base. + double GetR() const { return radius; } + /// \ru Получить текущий внутренний радиус для параметра v без ограничений vmin, vmax. \en Get current internal radius for v parameter without constraints of vmin, vmax. + double GetR( double v ) const { return radius + tgAngleH * v; } + /// \ru Получить физический радиус. \en Get physical radius. + double GetRadius( double v ) const; + /// \ru Получить внутренний радиус для параметра v, равного 1.0. \en Get internal radius for v parameter equal to 1.0. + double GetUpperR() const { return radius + tgAngleH; } + /// \ru Установить внутренний радиус. \en Set an internal radius. + void SetR( double r ) { radius = r; } - /// \ru Установить угол. \en Set an angle. - void SetAngle ( const double & a ) { angle = a; tgAngleH = ( height * ::tan(a ) ); } - /// \ru Установить внутреннюю высоту. \en Set internal height. - void SetHeight( const double & h ) { height = h; tgAngleH = ( h * ::tan(angle) ); C3D_ASSERT( ::fabs(height) > LENGTH_EPSILON ); } - /// \ru Угол. \en Angle. - double GetAngle () const { return angle; } - /** \brief \ru Внутренняя высота. - \en Internal height. \~ - \details \ru Внутренняя высота. \n - Чтобы получить физическую высоту нужно внутреннюю высоту умножить - на параметрическую длину по V и - длину оси Z ЛСК поверхности. \n - \en Internal height. \n - To obtain the physical height you need to multiply the internal height - by the parametric length along V and - the length of the Z axis of the local coordinate system of the surface. \~ - */ - double GetHeight() const { return height; } - /// \ru Выдать физисечкую высоту. \en Get physical height. \~ - double GetRealHeight() const { return ( height * (vmax - vmin) * position.GetAxisZ().Length() ); } - /// \ru Тангенс угла, умноженный на внутреннюю высоту. \en Tangent of the angle multiplied by internal height. - double GetTgAngleH() const { return tgAngleH; } + /// \ru Установить угол. \en Set an angle. + void SetAngle ( const double & a ) { angle = a; tgAngleH = ( height * ::tan(a ) ); } + /// \ru Установить внутреннюю высоту. \en Set internal height. + void SetHeight( const double & h ) { height = h; tgAngleH = ( h * ::tan(angle) ); C3D_ASSERT( ::fabs(height) > LENGTH_EPSILON ); } + /// \ru Угол. \en Angle. + double GetAngle () const { return angle; } + /** \brief \ru Внутренняя высота. + \en Internal height. \~ + \details \ru Внутренняя высота. \n + Чтобы получить физическую высоту нужно внутреннюю высоту умножить + на параметрическую длину по V и + длину оси Z ЛСК поверхности. \n + \en Internal height. \n + To obtain the physical height you need to multiply the internal height + by the parametric length along V and + the length of the Z axis of the local coordinate system of the surface. \~ + */ + double GetHeight() const { return height; } + /// \ru Выдать физисечкую высоту. \en Get physical height. \~ + double GetRealHeight() const { return ( height * (vmax - vmin) * position.GetAxisZ().Length() ); } + /// \ru Тангенс угла, умноженный на внутреннюю высоту. \en Tangent of the angle multiplied by internal height. + double GetTgAngleH() const { return tgAngleH; } /** \brief \ru Проверка параметра v по отношению к полюсу. \en Check v parameter against pole. \~ @@ -403,14 +403,15 @@ public: private: inline void CheckParam( double & u, double & v ) const; // \ru Проверка параметров. \en Check parameters. // \ru Пересечение с прямолинейной кривой. \en Intersection with rectilinear curve. - bool StraightIntersection( const MbCurve3D & curv, SArray & uv, SArray & tt, bool ext0, bool ext ) const; - void operator = ( const MbConeSurface & ); // \ru Не реализовано. \en Not implemented. + bool StraightIntersection( const MbCurve3D & curv, SArray & uv, SArray & tt, bool ext0, bool ext ) const; + void operator = ( const MbConeSurface & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbConeSurface ) }; // MbConeSurface IMPL_PERSISTENT_OPS( MbConeSurface ) + //------------------------------------------------------------------------------ // \ru Проверка параметров \en Check parameters // --- diff --git a/C3d/Include/surf_coons_surface.h b/C3d/Include/surf_coons_surface.h index 1539850..fec3c96 100644 --- a/C3d/Include/surf_coons_surface.h +++ b/C3d/Include/surf_coons_surface.h @@ -165,9 +165,9 @@ public: MbResultType & resType ); /// \ru Инициализация поверхности Кунса заданной поверхностью Кунса. \en Initialization of Coons surface by specified Coons surface. - void Init( const MbCoonsPatchSurface & ); + void Init( const MbCoonsPatchSurface & ); /// \ru Инициализация поверхности Кунса по заданным кривым на поверхностях. \en Initialization of Coons surface by curves on surfaces. - bool Init( const MbCurve3D & crv0, + bool Init( const MbCurve3D & crv0, const MbCurve3D & crv1, const MbCurve3D & crv2, const MbCurve3D & crv3, @@ -265,8 +265,8 @@ public: \en \name Functions for get of the group of data inside and outside the surface's domain of parameters. \{ */ void Explore( double & u, double & v, bool ext, - MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, - MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; + MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, + MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; /** \} */ /** \ru \name Функции движения по поверхности @@ -314,19 +314,19 @@ public: /// \ru Получить кривую в параметрах поверхности по индексу (удалить после использования). \en Get curve in surface parameters by an index (delete after use). MbCurve * GetCurve2D( size_t ind ) const; - /// \ru Получить количество кривых. \en Get count of curves. - size_t GetCurvesCount() const { return COONS_COUNT; } //-V112 + /// \ru Получить количество кривых. \en Get count of curves. + size_t GetCurvesCount() const { return COONS_COUNT; } //-V112 const MbCartPoint3D * GetVertex() const { return vertex; } ///< \ru Выдать вершины P0, P1, P2. \en Get vertices P0, P1, P2. MbeCoonsSurfaceCalcType GetCalcType() const { return calcType; } ///< \ru Выдать способ расчёта поверхности. \en Get surface calculation type. /** \} */ - double GetT0Min() const { return t0min; } ///< \ru Минимальное значение параметра на кривой 0. \en Minimal value of parameter on curve 0. - double GetT0Max() const { return t0max; } ///< \ru Максимальное значение параметра на кривой 0. \en Maximal value of parameter on curve 0. - double GetT1Min() const { return t1min; } ///< \ru Минимальное значение параметра на кривой 1. \en Minimal value of parameter on curve 1. - double GetT1Max() const { return t1max; } ///< \ru Максимальное значение параметра на кривой 1. \en Maximal value of parameter on curve 1. - double GetT2Min() const { return t2min; } ///< \ru Минимальное значение параметра на кривой 2. \en Minimal value of parameter on curve 2. - double GetT2Max() const { return t2max; } ///< \ru Максимальное значение параметра на кривой 2. \en Maximal value of parameter on curve 2. - double GetT3Min() const { return t3min; } ///< \ru Минимальное значение параметра на кривой 3. \en Minimal value of parameter on curve 3. - double GetT3Max() const { return t3max; } ///< \ru Максимальное значение параметра на кривой 3. \en Maximal value of parameter on curve 3. + double GetT0Min() const { return t0min; } ///< \ru Минимальное значение параметра на кривой 0. \en Minimal value of parameter on curve 0. + double GetT0Max() const { return t0max; } ///< \ru Максимальное значение параметра на кривой 0. \en Maximal value of parameter on curve 0. + double GetT1Min() const { return t1min; } ///< \ru Минимальное значение параметра на кривой 1. \en Minimal value of parameter on curve 1. + double GetT1Max() const { return t1max; } ///< \ru Максимальное значение параметра на кривой 1. \en Maximal value of parameter on curve 1. + double GetT2Min() const { return t2min; } ///< \ru Минимальное значение параметра на кривой 2. \en Minimal value of parameter on curve 2. + double GetT2Max() const { return t2max; } ///< \ru Максимальное значение параметра на кривой 2. \en Maximal value of parameter on curve 2. + double GetT3Min() const { return t3min; } ///< \ru Минимальное значение параметра на кривой 3. \en Minimal value of parameter on curve 3. + double GetT3Max() const { return t3max; } ///< \ru Максимальное значение параметра на кривой 3. \en Maximal value of parameter on curve 3. /** \brief \ru Получить образующую кривую по индексу, если она точно совпадает с соответствующим краем поверхности. \en Get exact curve by index, if it coincides with the corresponding border of the surface. \~ @@ -348,32 +348,32 @@ public: \en Determines whether the pole at domain boundary by curve length determining boundary.\n Result of calculations can be obtained with help of GetPoleUMin, GetPoleUMax, GetPoleVMin, GetPoleVMax functions. \~ */ - void CheckPole(); + void CheckPole(); private: - void operator = ( const MbCoonsPatchSurface & ); // \ru Не реализовано. \en Not implemented. - void Setup(); - void SetupUVDerives(); - void CheckParams( double & u, double & v, bool ext = false ) const; // \ru Проверить и изменить при необходимости параметры. \en Check and correct parameters. - void CalculateTwist( double u, double v ) const; + void operator = ( const MbCoonsPatchSurface & ); // \ru Не реализовано. \en Not implemented. + void Setup(); + void SetupUVDerives(); + void CheckParams( double & u, double & v, bool ext = false ) const; // \ru Проверить и изменить при необходимости параметры. \en Check and correct parameters. + void CalculateTwist( double u, double v ) const; // \ru Определение местных координат. \en Determination of local coordinates. - void CalculateCoordinate( double & u, double & v, + void CalculateCoordinate( double & u, double & v, double & t0, double & t1, double & t2, double & t3 ) const; - void CalculatePoint ( double & u, double & v, + void CalculatePoint ( double & u, double & v, MbCartPoint3D * point, MbCartPoint3D * pointUV ) const; - void CalculateFirst ( double & u, double & v, + void CalculateFirst ( double & u, double & v, MbCartPoint3D * point, MbVector3D * first, MbCartPoint3D * pointUV, MbVector3D * firstUV ) const; - void CalculateThird ( double & u, double & v, + void CalculateThird ( double & u, double & v, MbCartPoint3D * point, MbVector3D * third, MbCartPoint3D * pointUV, MbVector3D * thirdUV ) const; - void CalculateExplore( double & u, double & v, + void CalculateExplore( double & u, double & v, MbCartPoint3D * point, MbVector3D * first, MbVector3D * second, MbCartPoint3D * pointUV, MbVector3D * firstUV, MbVector3D * secondUV ) const; // \ru Производные. \en Derivatives with respect to u and to v. - void Derivatives( double & u, double & v, MbVector3D & uDer, MbVector3D & vDer ) const; + void Derivatives( double & u, double & v, MbVector3D & uDer, MbVector3D & vDer ) const; // \ru Нормаль. \en Calculate surface normal with refinement on borders. - void Normal( double u, double v, MbVector3D & derU, MbVector3D & derV, MbVector3D & norm ) const; + void Normal( double u, double v, MbVector3D & derU, MbVector3D & derV, MbVector3D & norm ) const; inline void ParamPoint ( double w, double * t ) const; inline void ParamFirst ( double w, double * t ) const; inline void ParamSecond( double w, double * t ) const; @@ -381,22 +381,21 @@ private: // \ru Добавить матрицу поверхности. \en Add the matrix of the surface. inline void AddMatrix ( double u, double v, double * uu, double * vv, MbVector3D & p ) const; - void AddDeriveU ( double u, double v, MbVector3D & p ) const; - void AddDeriveV ( double u, double v, MbVector3D & p ) const; - void AddDeriveUU ( double u, double v, MbVector3D & p ) const; - void AddDeriveVV ( double u, double v, MbVector3D & p ) const; - void AddDeriveUV ( double u, double v, MbVector3D & p ) const; - void AddDeriveUUU( double u, double v, MbVector3D & p ) const; - void AddDeriveUUV( double u, double v, MbVector3D & p ) const; - void AddDeriveUVV( double u, double v, MbVector3D & p ) const; - void AddDeriveVVV( double u, double v, MbVector3D & p ) const; + void AddDeriveU ( double u, double v, MbVector3D & p ) const; + void AddDeriveV ( double u, double v, MbVector3D & p ) const; + void AddDeriveUU ( double u, double v, MbVector3D & p ) const; + void AddDeriveVV ( double u, double v, MbVector3D & p ) const; + void AddDeriveUV ( double u, double v, MbVector3D & p ) const; + void AddDeriveUUU( double u, double v, MbVector3D & p ) const; + void AddDeriveUUV( double u, double v, MbVector3D & p ) const; + void AddDeriveUVV( double u, double v, MbVector3D & p ) const; + void AddDeriveVVV( double u, double v, MbVector3D & p ) const; - void SpecifyNormalOnPole( MbVector3D & norm ) const; + void SpecifyNormalOnPole( MbVector3D & norm ) const; DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCoonsPatchSurface ) }; // MbCoonsSurface - IMPL_PERSISTENT_OPS( MbCoonsPatchSurface ) diff --git a/C3d/Include/surf_corner_surface.h b/C3d/Include/surf_corner_surface.h index 3dc1b19..65ae4ea 100644 --- a/C3d/Include/surf_corner_surface.h +++ b/C3d/Include/surf_corner_surface.h @@ -84,7 +84,7 @@ public: VISITING_CLASS( MbCornerSurface ); /// \ru Инициализация треугольной поверхности заданной треугольной поверхностью. \en Initialization of triangular surface by given triangular surface. - void Init( const MbCornerSurface &init ); + void Init( const MbCornerSurface &init ); /** \ru \name Общие функции геометрического объекта \en \name Common functions of a geometric object @@ -99,7 +99,7 @@ public: void Rotate( const MbAxis3D & axis, double angle, MbRegTransform * = nullptr ) override; // \ru Повернуть вокруг оси \en Rotate around an axis void CalculateSurfaceWire( const MbStepData & stepData, size_t beg, MbMesh & mesh, - size_t uMeshCount = c3d::WIRE_MAX, size_t vMeshCount = c3d::WIRE_MAX ) const override; + size_t uMeshCount = c3d::WIRE_MAX, size_t vMeshCount = c3d::WIRE_MAX ) const override; void GetProperties( MbProperties & ) override; // \ru Выдать свойства объекта \en Get properties of the object void SetProperties( const MbProperties & ) override; // \ru Записать свойства объекта \en Set properties of the object @@ -171,8 +171,8 @@ public: \en \name Functions for get of the group of data inside and outside the surface's domain of parameters. \{ */ void Explore( double & u, double & v, bool ext, - MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, - MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; + MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, + MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; /** \} */ /** \ru \name Функции движения по поверхности @@ -208,43 +208,45 @@ public: /// \ru Получить кривую по индексу. \en Get curve by an index. const MbCurve3D * GetCurve( size_t ind ) const; /// \ru Получить количество кривых. \en Get count of curves. - size_t GetCurvesCount() const { return 3; } //-V112 + size_t GetCurvesCount() const { return 3; } //-V112 const MbCartPoint3D * GetVertex() const { return vertex; } ///< \ru Выдать вершины P0, P1, P2. \en Get vertices P0, P1, P2. - double GetT0Min() const { return t0min; } ///< \ru Минимальное значение параметра на кривой 0. \en Minimal value of parameter on curve 0. - double GetT0Max() const { return t0max; } ///< \ru Максимальное значение параметра на кривой 0. \en Maximal value of parameter on curve 0. - double GetT1Min() const { return t1min; } ///< \ru Минимальное значение параметра на кривой 1. \en Minimal value of parameter on curve 1. - double GetT1Max() const { return t1max; } ///< \ru Максимальное значение параметра на кривой 1. \en Maximal value of parameter on curve 1. - double GetT2Min() const { return t2min; } ///< \ru Минимальное значение параметра на кривой 2. \en Minimal value of parameter on curve 2. - double GetT2Max() const { return t2max; } ///< \ru Максимальное значение параметра на кривой 2. \en Maximal value of parameter on curve 2. - double GetTMin( size_t ind ) const; ///< \ru Минимальное значение параметра на кривой с индексом ind. \en Get The minimal value of parameter on curve by index. - double GetTMax( size_t ind ) const; ///< \ru Максимальное значение параметра на кривой с индексом ind. \en Get The maximal value of parameter on curve by index. + double GetT0Min() const { return t0min; } ///< \ru Минимальное значение параметра на кривой 0. \en Minimal value of parameter on curve 0. + double GetT0Max() const { return t0max; } ///< \ru Максимальное значение параметра на кривой 0. \en Maximal value of parameter on curve 0. + double GetT1Min() const { return t1min; } ///< \ru Минимальное значение параметра на кривой 1. \en Minimal value of parameter on curve 1. + double GetT1Max() const { return t1max; } ///< \ru Максимальное значение параметра на кривой 1. \en Maximal value of parameter on curve 1. + double GetT2Min() const { return t2min; } ///< \ru Минимальное значение параметра на кривой 2. \en Minimal value of parameter on curve 2. + double GetT2Max() const { return t2max; } ///< \ru Максимальное значение параметра на кривой 2. \en Maximal value of parameter on curve 2. + double GetTMin( size_t ind ) const; ///< \ru Минимальное значение параметра на кривой с индексом ind. \en Get The minimal value of parameter on curve by index. + double GetTMax( size_t ind ) const; ///< \ru Максимальное значение параметра на кривой с индексом ind. \en Get The maximal value of parameter on curve by index. /** \} */ private: - void Init(); - inline void CalculateCoordinate( double & u, double & v, bool ext, - double & s0, double & s1, double & s2, - double & c0, double & c1, double & c2, - double & t0, double & t1, double & t2 ) const; - void CalculatePoint ( double & u, double & v, bool ext, - MbCartPoint3D & point ) const; - void CalculateFirst ( double & u, double & v, bool ext, - MbVector3D * first ) const; - void CalculateSecond( double & u, double & v, bool ext, - MbVector3D * second ) const; - void CalculateThird ( double & u, double & v, bool ext, - MbVector3D * second, MbVector3D * third ) const; - void CalculateExplore( double & u, double & v, bool ext, - MbCartPoint3D * point, MbVector3D * first, MbVector3D * second ) const; - bool GetNormalFactor( MbVector3D & norm ) const; // \ru Нормаль в точке с параметрами u=0. \en Normal at u=0. - void Derivatives( double u, double v, bool ext, MbVector3D & uDer, MbVector3D & vDer ) const; // \ru Ппроизводные. \en Derivatives with respect to u and to v. - void operator = ( const MbCornerSurface & ); // \ru Не реализовано. \en Not implemented. + void Init(); + inline + void CalculateCoordinate( double & u, double & v, bool ext, + double & s0, double & s1, double & s2, + double & c0, double & c1, double & c2, + double & t0, double & t1, double & t2 ) const; + void CalculatePoint ( double & u, double & v, bool ext, + MbCartPoint3D & point ) const; + void CalculateFirst ( double & u, double & v, bool ext, + MbVector3D * first ) const; + void CalculateSecond( double & u, double & v, bool ext, + MbVector3D * second ) const; + void CalculateThird ( double & u, double & v, bool ext, + MbVector3D * second, MbVector3D * third ) const; + void CalculateExplore( double & u, double & v, bool ext, + MbCartPoint3D * point, MbVector3D * first, MbVector3D * second ) const; + bool GetNormalFactor( MbVector3D & norm ) const; // \ru Нормаль в точке с параметрами u=0. \en Normal at u=0. + void Derivatives( double u, double v, bool ext, MbVector3D & uDer, MbVector3D & vDer ) const; // \ru Ппроизводные. \en Derivatives with respect to u and to v. + void operator = ( const MbCornerSurface & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCornerSurface ) }; // MbCornerSurface IMPL_PERSISTENT_OPS( MbCornerSurface ) + //------------------------------------------------------------------------------ // \ru Определение местных координат \en Determination of local coordinates // --- diff --git a/C3d/Include/surf_cover_surface.h b/C3d/Include/surf_cover_surface.h index a8deef2..92e29e1 100644 --- a/C3d/Include/surf_cover_surface.h +++ b/C3d/Include/surf_cover_surface.h @@ -91,7 +91,7 @@ public: VISITING_CLASS( MbCoverSurface ); /// \ru Инициализация билинейной поверхности заданной билинейной поверхностью. \en Initialization of bilinear surface by given bilinear surface. - void Init( const MbCoverSurface & ); + void Init( const MbCoverSurface & ); /** \ru \name Общие функции геометрического объекта \en \name Common functions of a geometric object @@ -174,8 +174,8 @@ public: \en \name Functions for get of the group of data inside and outside the surface's domain of parameters. \{ */ void Explore( double & u, double & v, bool ext, - MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, - MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; + MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, + MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; /** \} */ /** \ru \name Функции движения по поверхности @@ -219,18 +219,18 @@ public: /// \ru Получить кривую в параметрах поверхности по индексу (удалить после использования). \en Get curve in surface parameters by an index (delete after use). MbCurve * GetCurve2D( size_t ind ) const; /// \ru Получить количество кривых. \en Get count of curves. - size_t GetCurvesCount() const { return 4; } //-V112 + size_t GetCurvesCount() const { return 4; } //-V112 const MbCartPoint3D * GetVertex() const { return vertex; } ///< \ru Выдать вершины P0, P1, P2. \en Get vertices P0, P1, P2. - double GetT0Min() const { return t0min; } ///< \ru Минимальное значение параметра на кривой 0. \en Minimal value of parameter on curve 0. - double GetT0Max() const { return t0max; } ///< \ru Максимальное значение параметра на кривой 0. \en Maximal value of parameter on curve 0. - double GetT1Min() const { return t1min; } ///< \ru Минимальное значение параметра на кривой 1. \en Minimal value of parameter on curve 1. - double GetT1Max() const { return t1max; } ///< \ru Максимальное значение параметра на кривой 1. \en Maximal value of parameter on curve 1. - double GetT2Min() const { return t2min; } ///< \ru Минимальное значение параметра на кривой 2. \en Minimal value of parameter on curve 2. - double GetT2Max() const { return t2max; } ///< \ru Максимальное значение параметра на кривой 2. \en Maximal value of parameter on curve 2. - double GetT3Min() const { return t3min; } ///< \ru Минимальное значение параметра на кривой 3. \en Minimal value of parameter on curve 3. - double GetT3Max() const { return t3max; } ///< \ru Максимальное значение параметра на кривой 3. \en Maximal value of parameter on curve 3. - double GetTMin( size_t ind ) const; ///< \ru Минимальное значение параметра на кривой с индексом ind. \en Get The minimal value of parameter on curve by index. - double GetTMax( size_t ind ) const; ///< \ru Максимальное значение параметра на кривой с индексом ind. \en Get The maximal value of parameter on curve by index. + double GetT0Min() const { return t0min; } ///< \ru Минимальное значение параметра на кривой 0. \en Minimal value of parameter on curve 0. + double GetT0Max() const { return t0max; } ///< \ru Максимальное значение параметра на кривой 0. \en Maximal value of parameter on curve 0. + double GetT1Min() const { return t1min; } ///< \ru Минимальное значение параметра на кривой 1. \en Minimal value of parameter on curve 1. + double GetT1Max() const { return t1max; } ///< \ru Максимальное значение параметра на кривой 1. \en Maximal value of parameter on curve 1. + double GetT2Min() const { return t2min; } ///< \ru Минимальное значение параметра на кривой 2. \en Minimal value of parameter on curve 2. + double GetT2Max() const { return t2max; } ///< \ru Максимальное значение параметра на кривой 2. \en Maximal value of parameter on curve 2. + double GetT3Min() const { return t3min; } ///< \ru Минимальное значение параметра на кривой 3. \en Minimal value of parameter on curve 3. + double GetT3Max() const { return t3max; } ///< \ru Максимальное значение параметра на кривой 3. \en Maximal value of parameter on curve 3. + double GetTMin( size_t ind ) const; ///< \ru Минимальное значение параметра на кривой с индексом ind. \en Get The minimal value of parameter on curve by index. + double GetTMax( size_t ind ) const; ///< \ru Максимальное значение параметра на кривой с индексом ind. \en Get The maximal value of parameter on curve by index. /** \brief \ru Получить образующую кривую по индексу, если она точно совпадает с соответствующим краем поверхности. \en Get exact curve by index, if it coincides with the corresponding border of the surface. \~ @@ -252,7 +252,7 @@ public: \en Determines whether the pole at domain boundary by curve length determining boundary.\n Result of calculations can be obtained with help of GetPoleUMin, GetPoleUMax, GetPoleVMin, GetPoleVMax functions. \~ */ - void CheckPole(); + void CheckPole(); /** \brief \ru Корректировка параметров. \en Correct parameters. \~ \details \ru Загоняет параметры, выходящие за область определения в область определения,\n @@ -263,22 +263,21 @@ public: inline void CheckParam( double & u, double & v ) const; private: - void operator = ( const MbCoverSurface & ); // \ru Не реализовано. \en Not implemented. - bool Init(); + void operator = ( const MbCoverSurface & ); // \ru Не реализовано. \en Not implemented. + bool Init(); // \ru Определение местных координат. \en Determination of local coordinates. - void CalculateCoordinate( double & u, double & v, bool ext, + void CalculateCoordinate( double & u, double & v, bool ext, double & t0, double & t1, double & t2, double & t3 ) const; - void CalculatePoint ( double & u, double & v, bool ext, MbCartPoint3D * point ) const; - void CalculateFirst ( double & u, double & v, bool ext, MbCartPoint3D * point, MbVector3D * first ) const; - void CalculateSecond( double & u, double & v, bool ext, MbVector3D * second ) const; - void CalculateThird ( double & u, double & v, bool ext, MbVector3D * third ) const; - void CalculateExplore( double & u, double & v, bool ext, - MbCartPoint3D * point, MbVector3D * first, MbVector3D * second ) const; + void CalculatePoint ( double & u, double & v, bool ext, MbCartPoint3D * point ) const; + void CalculateFirst ( double & u, double & v, bool ext, MbCartPoint3D * point, MbVector3D * first ) const; + void CalculateSecond( double & u, double & v, bool ext, MbVector3D * second ) const; + void CalculateThird ( double & u, double & v, bool ext, MbVector3D * third ) const; + void CalculateExplore( double & u, double & v, bool ext, + MbCartPoint3D * point, MbVector3D * first, MbVector3D * second ) const; DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCoverSurface ) }; // MbCoverSurface - IMPL_PERSISTENT_OPS( MbCoverSurface ) diff --git a/C3d/Include/surf_curve_bounded_surface.h b/C3d/Include/surf_curve_bounded_surface.h index 6e338e1..7c8f3bc 100644 --- a/C3d/Include/surf_curve_bounded_surface.h +++ b/C3d/Include/surf_curve_bounded_surface.h @@ -169,10 +169,10 @@ public : bool IsUClosed() const override; // \ru Замкнута ли гладко поверхность по параметру u без учета граничного контура. \en Whether the surface is smoothly closed by parameter u without regard to the boundary contour. bool IsVClosed() const override; // \ru Замкнута ли гладко поверхность по параметру v без учета граничного контура. \en Whether the surface is smoothly closed by parameter v without regard to the boundary contour. - bool IsUTouch() const override; // \ru Замкнута ли фактически поверхность по параметру u независимо от гладкости. \en Whether the surface is actually closed by parameter u regardless of the smoothness. - bool IsVTouch() const override; // \ru Замкнута ли фактически поверхность по параметру v независимо от гладкости. \en Whether the surface is actually closed by parameter v regardless of the smoothness. - bool IsUPeriodic() const override; // \ru Замкнута ли гладко поверхность по параметру u. \en Whether the surface is smoothly closed by parameter u. - bool IsVPeriodic() const override; // \ru Замкнута ли гладко поверхность по параметру v. \en Whether the surface is smoothly closed by parameter v. + bool IsUTouch() const override; // \ru Замкнута ли фактически поверхность по параметру u независимо от гладкости. \en Whether the surface is actually closed by parameter u regardless of the smoothness. + bool IsVTouch() const override; // \ru Замкнута ли фактически поверхность по параметру v независимо от гладкости. \en Whether the surface is actually closed by parameter v regardless of the smoothness. + bool IsUPeriodic() const override; // \ru Замкнута ли гладко поверхность по параметру u. \en Whether the surface is smoothly closed by parameter u. + bool IsVPeriodic() const override; // \ru Замкнута ли гладко поверхность по параметру v. \en Whether the surface is smoothly closed by parameter v. double GetUPeriod() const override; // \ru Период для замкнутой поверхности или 0. \en Period for closed surface or 0. double GetVPeriod() const override; // \ru Период для замкнутой поверхности или 0. \en Period for closed surface or 0. @@ -233,13 +233,13 @@ public : \en \name Functions for get of the group of data inside and outside the surface's domain of parameters. \{ */ void Explore( double & u, double & v, bool ext, - MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, - MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; + MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, + MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; // \ru Значения производных в точке \en Values of derivatives at point - virtual void _PointNormal( double u, double v, - MbCartPoint3D & pnt, MbVector3D & deru, MbVector3D & derv, - MbVector3D & norm, MbVector3D & noru, MbVector3D & norv, - MbVector3D & deruu, MbVector3D & dervv, MbVector3D & deruv ) const override; + void _PointNormal( double u, double v, + MbCartPoint3D & pnt, MbVector3D & deru, MbVector3D & derv, + MbVector3D & norm, MbVector3D & noru, MbVector3D & norv, + MbVector3D & deruu, MbVector3D & dervv, MbVector3D & deruv ) const override; /** \} */ /** \ru \name Функции движения по поверхности \en \name Functions of moving along the surface @@ -288,7 +288,7 @@ public : MbCurve3D * CurveUV( const MbLineSegment &, bool bApprox = true ) const override; // \ru Пространственная копия линии по параметрической линии. \en Spatial copy of line by parametric line. MbeItemLocation PointClassification( const MbCartPoint &, bool ignoreClosed = false ) const override; // \ru Находится ли точка в области, принадлежащей поверхности. \en Whether the point is in region belonging to the surface. - double DistanceToBorder ( const MbCartPoint &, double & eps ) const override; // \ru Параметрическое расстояние до ближайшей границы. \en Parametric distance to the nearest boundary. + double DistanceToBorder( const MbCartPoint &, double & eps ) const override; // \ru Параметрическое расстояние до ближайшей границы. \en Parametric distance to the nearest boundary. // \ru Определение точек пересечения кривой с контурами поверхности. \en Determine intersection points of a curve with the contours on the surface. size_t CurveClassification( const MbCurve & curve, SArray & tcurv, SArray & dir ) const override; @@ -303,7 +303,7 @@ public : \return \ru Количество точек пересечения. \en The number of points. \~ */ - size_t SegmentIntersection( const MbCurve & pCurve, SArray & curveParams, double epsilon = Math::metricEpsilon ) const; + size_t SegmentIntersection( const MbCurve & pCurve, SArray & curveParams, double epsilon = Math::metricEpsilon ) const; // \ru Найти ближайшую проекцию точки на поверхность. \en Find the nearest projection of a point onto the surface. bool NearPointProjection( const MbCartPoint3D & p, double & u, double & v, bool ext, MbRect2D * uvRange = nullptr ) const override; // \ru Ближайшая проекция точки на поверхность. \en The nearest point projection onto the surface. @@ -311,10 +311,10 @@ public : void DirectPointProjection( const MbCartPoint3D & p, const MbVector3D & vect, SArray & uv, bool ext, MbRect2D * uvRange = nullptr ) const override; // \ru Вce точки пересечения поверхности и кривой. \en All the points of intersection of a surface and a curve. void CurveIntersection( const MbCurve3D & curv, SArray & uv, SArray & tt, - bool ext0, bool ext, bool touchInclude = false ) const override; + bool ext0, bool ext, bool touchInclude = false ) const override; // \ru Уточнение параметров точки линии очерка поверхности. \en Refinement of parameters of point of isocline curve of the surface. MbeNewtonResult SilhouetteNewton( const MbVector3D & eye, bool perspective, const MbAxis3D * axis, MbeParamDir switchPar, - double funcEpsilon, size_t iterLimit, double & u, double & v, bool ext ) const override; + double funcEpsilon, size_t iterLimit, double & u, double & v, bool ext ) const override; // \ru Подобные ли поверхности для объединения (слива). \en Whether the surfaces to union (joining) are similar. bool IsSimilarToSurface( const MbSurface & surf, VERSION version, double precision = METRIC_PRECISION ) const override; bool IsSpecialSimilarToSurface( const MbSurface & surf, VERSION version, double precision = METRIC_PRECISION ) const override; @@ -327,9 +327,9 @@ public : bool CreateNormalPlacements ( const MbVector3D & axisZ, double angle, SArray & places, VERSION version = Math::DefaultMathVersion() ) const override; bool CreateTangentPlacements( const MbVector3D & axisZ, SArray & places ) const override; // \ru Определение разбивки параметрической области поверхности вертикалями и горизонталями. \en Determine splitting of parametric region of surface by vertical and horizontal lines. - virtual void GetTesselation( const MbStepData & stepData, - double u1, double u2, double v1, double v2, - SArray & uu, SArray & vv ) const override; + void GetTesselation( const MbStepData & stepData, + double u1, double u2, double v1, double v2, + SArray & uu, SArray & vv ) const override; // \ru Расчёт площади области определения параметров. \en Calculate area of parameter domain. double ParamArea() const override; @@ -352,7 +352,7 @@ public : void GetParamsToUnit( double u, double v, double & uParam, double & vParam ) const override; // \ru Дать приращение параметра u и параметра v, соответствующее единичной длине в пространстве. \en Get increment of parameters, corresponding to the unit length in space. void CalculateSurfaceWire( const MbStepData & stepData, size_t beg, MbMesh & mesh, - size_t uMeshCount = c3d::WIRE_MAX, size_t vMeshCount = c3d::WIRE_MAX ) const override; // \ru Рассчитать сетку. \en Calculate mesh. + size_t uMeshCount = c3d::WIRE_MAX, size_t vMeshCount = c3d::WIRE_MAX ) const override; // \ru Рассчитать сетку. \en Calculate mesh. size_t GetUMeshCount() const override; // \ru Выдать количество полигонов по u. \en Get the count of polygons by u. size_t GetVMeshCount() const override; // \ru Выдать количество полигонов по v. \en Get the count of polygons by v. @@ -400,19 +400,19 @@ public : \param[in] i - \ru Индекс сегмента \en Index of segment \~ */ - MbCurve * SetSegment ( size_t number, size_t i ); + MbCurve * SetSegment ( size_t number, size_t i ); - /// \ru Выдать число контуров. \en Get the count of contours. - size_t GetCurvesCount() const { return curves.Count(); } - /// \ru Выдать число сегментов в контуре с номером i \en Get the count of segments of i-th contour - size_t GetSegmentsCount( size_t i ) const; + /// \ru Выдать число контуров. \en Get the count of contours. + size_t GetCurvesCount() const { return curves.Count(); } + /// \ru Выдать число сегментов в контуре с номером i \en Get the count of segments of i-th contour + size_t GetSegmentsCount( size_t i ) const; /** \brief \ru Добавить контур. \en Add a contour. \~ \details \ru Создает контур, ограничивающий поверхность, если число контуров = 0 \en Creates a contour bounding a surface if count of contours is equal to 0 \~ */ - void AddOuterContour(); + void AddOuterContour(); /** \brief \ru Удалить контур. \en Remove contour. \~ \details \ru Удаляет указанный контур. @@ -420,7 +420,7 @@ public : \param[in] cntr - \ru Удаляемый контур \en Contour to remove \~ */ - void DeleteContour( MbContourOnSurface * cntr ); + void DeleteContour( MbContourOnSurface * cntr ); /** \brief \ru Заменить контур. \en Replace contour. \~ \details \ru Заменить контур. @@ -430,15 +430,15 @@ public : \param[in] cntr - \ru Новый контур \en New contour \~ */ - bool ChangeContour( size_t index, MbContourOnSurface * cntr ); + bool ChangeContour( size_t index, MbContourOnSurface * cntr ); /// \ru Заменить базовую поверхность. \en Replace base surface. - bool ChangeSurface( const MbSurface & newsurf ); + bool ChangeSurface( const MbSurface & newsurf ); /// \ru Заменить базовую поверхность на ее копию. \en Replace base surface with its copy. - void NewBasisSurface(); + void NewBasisSurface(); /// \ru Вычислить параметрические границы поверхности без сброса габарита. \en Calculate parametric bounds of surface without resetting the bounding box. - void CalculateUVLimitsOnly(); + void CalculateUVLimitsOnly(); /// \ru Вычислить параметрические границы поверхности с пересчетом габарита. \en Calculate parametric bounds of surface with recalculation of the bounding box. - void CalculateUVLimits(); + void CalculateUVLimits(); /** \brief \ru Расширить параметрические границы базовой поверхности. \en Extend parametric bounds of base surface. \~ @@ -447,7 +447,7 @@ public : \en If it is possible, then parametric bounds of base surface are extended so\n that the parametric bounds of surface bounded by curves are inside of them. \~ */ - void SetBasisSurfaceUVLimits(); + void SetBasisSurfaceUVLimits(); /** \brief \ru Проверить, входят ли параметры в параметрические границы поверхности. \en Check, whether the parameters are in parametric bounds of surface. \~ @@ -458,42 +458,42 @@ public : */ inline void CheckParam( double & u, double & v ) const; - /** \brief \ru Ориентировать ограничивающие контуры. - \en Orient bounding contours. \~ - \details \ru Ориентирует внешний контур против часовой стрелки, внутренние контуры - по часовой стрелке. - \en External contour is oriented counterclockwise, internal contours - clockwise. \~ - \return \ru Возвращает площадь параметрической области поверхности. - \en Returns area of parametric region of surface. \~ - \warning \ru В конструкторах не вызывается, так как предполагается, что на вход поступает правильный набор контуров, \n - а сама функция ориентирования требует много времени на ее выполнение. - \en In constructors isn't called as it is supposed that given the correct set of contours,\n - but function of orientation needs a lot of time for its execution. \~ + /** \brief \ru Ориентировать ограничивающие контуры. + \en Orient bounding contours. \~ + \details \ru Ориентирует внешний контур против часовой стрелки, внутренние контуры - по часовой стрелке. + \en External contour is oriented counterclockwise, internal contours - clockwise. \~ + \return \ru Возвращает площадь параметрической области поверхности. + \en Returns area of parametric region of surface. \~ + \warning \ru В конструкторах не вызывается, так как предполагается, что на вход поступает правильный набор контуров, \n + а сама функция ориентирования требует много времени на ее выполнение. + \en In constructors isn't called as it is supposed that given the correct set of contours,\n + but function of orientation needs a lot of time for its execution. \~ - */ - double NormalizeCurvesOrientation(); + */ + double NormalizeCurvesOrientation(); - // \ru Не используется \en Not used \~ bool SetCurveEqual( const MbSpaceItem & ); // Сделать равными контуры. \en Make contours equal. - // \ru Не используется \en Not used \~ bool IsCurveEqual ( const MbSpaceItem & ) const; // Являются ли объекты подобными. \en Whether the objects are equal. - /// \ru Удалить все контуры. \en Remove all the contours. - void DeleteCurves(); - /** \brief \ru Добавить контур. - \en Add a contour. \~ - \details \ru Добавить контур. После добавления нужно вызвать CalculateUVLimits(). - \en Add a contour. After addition it is necessary to call CalculateUVLimits(). \~ - */ - void AddCurve( MbContourOnSurface & contour ); - /** \brief \ru Добавить контур. - \en Add a contour. \~ - \details \ru Добавить контур. После добавления нужно вызвать CalculateUVLimits(). - \en Add a contour. After addition it is necessary to call CalculateUVLimits(). \~ - */ - void AddCurve( MbContour & contour ); - /** \brief \ru Добавить контур. - \en Add a contour. \~ - \details \ru Добавить контур. После добавления не нужно вызвать CalculateUVLimits(). - \en Add a contour. After addition it isn't necessary to call CalculateUVLimits(). \~ - */ - void AddContour( MbContour & contour ) { AddCurve( contour ); CalculateUVLimits(); } + // \ru Не используется \en Not used \~ bool SetCurveEqual( const MbSpaceItem & ); // Сделать равными контуры. \en Make contours equal. + // \ru Не используется \en Not used \~ bool IsCurveEqual ( const MbSpaceItem & ) const; // Являются ли объекты подобными. \en Whether the objects are equal. + /// \ru Удалить все контуры. \en Remove all the contours. + void DeleteCurves(); + /** \brief \ru Добавить контур. + \en Add a contour. \~ + \details \ru Добавить контур. После добавления нужно вызвать CalculateUVLimits(). + \en Add a contour. After addition it is necessary to call CalculateUVLimits(). \~ + */ + void AddCurve( MbContourOnSurface & contour ); + /** \brief \ru Добавить контур. + \en Add a contour. \~ + \details \ru Добавить контур. После добавления нужно вызвать CalculateUVLimits(). + \en Add a contour. After addition it is necessary to call CalculateUVLimits(). \~ + */ + void AddCurve( MbContour & contour ); + /** \brief \ru Добавить контур. + \en Add a contour. \~ + \details \ru Добавить контур. После добавления не нужно вызвать CalculateUVLimits(). + \en Add a contour. After addition it isn't necessary to call CalculateUVLimits(). \~ + */ + void AddContour( MbContour & contour ) { AddCurve( contour ); CalculateUVLimits(); } /** \brief \ru Дать контур, ограничивающий поверхность, по его индексу. \en Get contour bounding surface by its index. \~ @@ -522,36 +522,37 @@ public : \en Get contour bounding surface by its index. Without index checking. It is recommended to use the SetCurve function with index checking. \~ */ - MbContourOnSurface *_SetCurve ( size_t ind ) { return curves[ind]; } + MbContourOnSurface *_SetCurve ( size_t ind ) { return curves[ind]; } /// \ru Переместить кривую с индексом ind в нулевую позицию массива. \en Move a curve with the 'ind' index to a zero position of the array. - void ReplaceOuterCurveBy( size_t ind ); + void ReplaceOuterCurveBy( size_t ind ); /// \ru Найти двумерную кривую и заменить ее на другую. \en Find two-dimensional curve and replace it with another one. - bool ChangeCurve2D( MbCurve & oldCrv, MbCurve * newCrv ); + bool ChangeCurve2D( MbCurve & oldCrv, MbCurve * newCrv ); /// \ru Слить двумерные сегменты в контурах. \en Merge two-dimensional segments in contours. - void MergeSegments( double eps = Math::LengthEps ); + void MergeSegments( double eps = Math::LengthEps ); /// \ru Копия объекта со старой базовой поверхностью. \en Copy of object with old base surface. - MbCurveBoundedSurface & CurvesDuplicate() const { return *new MbCurveBoundedSurface( this ); } + MbCurveBoundedSurface & CurvesDuplicate() const { return *new MbCurveBoundedSurface( this ); } /// \ru Проверить на замкнутость по u или v по внешнему контуру. \en Check closeness by u or v using outer contour. - bool CheckTouchByContour( bool byU ) const; + bool CheckTouchByContour( bool byU ) const; /** \} */ protected: - bool CreateRectTree() const; ///< \ru Создать и инициализировать дерево поиска. \en Create and initialize the search tree. - void DeleteRectTree() const; ///< \ru Удалить дерево поиска. \en Delete search tree. - void DeleteSearchTree() const; ///< \ru Удалить дерево поиска. \en Delete search tree. + bool CreateRectTree() const; ///< \ru Создать и инициализировать дерево поиска. \en Create and initialize the search tree. + void DeleteRectTree() const; ///< \ru Удалить дерево поиска. \en Delete search tree. + void DeleteSearchTree() const; ///< \ru Удалить дерево поиска. \en Delete search tree. private: - // \ru Управление распределением памяти в массиве segments \en Control of memory allocation in the array "segments" - // \ru Не используется \en Not used \~ void CurvesReserve( size_t additionalSpace ) { curves.Reserve( additionalSpace ); } // Зарезервировать место под столько элементов. \en Reserve memory for so many elements. - // \ru Не используется \en Not used \~ void CurvesAdjust () { curves.Adjust(); } // Удалить лишнюю память. \en Remove unnecessary memory. + // \ru Управление распределением памяти в массиве segments \en Control of memory allocation in the array "segments" + // \ru Не используется \en Not used \~ void CurvesReserve( size_t additionalSpace ) { curves.Reserve( additionalSpace ); } // Зарезервировать место под столько элементов. \en Reserve memory for so many elements. + // \ru Не используется \en Not used \~ void CurvesAdjust () { curves.Adjust(); } // Удалить лишнюю память. \en Remove unnecessary memory. - void operator = ( const MbCurveBoundedSurface & ); // \ru Не реализовано !!! \en Not implemented!!! + void operator = ( const MbCurveBoundedSurface & ); // \ru Не реализовано !!! \en Not implemented!!! DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCurveBoundedSurface ) }; IMPL_PERSISTENT_OPS( MbCurveBoundedSurface ) + //------------------------------------------------------------------------------ // \ru Проверить, входят ли параметры в параметрические границы поверхности. \en Check, whether the parameters are in parametric bounds of surface. // --- diff --git a/C3d/Include/surf_cylinder_surface.h b/C3d/Include/surf_cylinder_surface.h index 21ef808..c1bd946 100644 --- a/C3d/Include/surf_cylinder_surface.h +++ b/C3d/Include/surf_cylinder_surface.h @@ -113,39 +113,39 @@ public: \en \name Initialization functions \{ */ /// \ru Инициализация по цилиндрической поверхности. \en Initialization by cylindrical surface. - void Init( const MbCylinderSurface & init ); + void Init( const MbCylinderSurface & init ); /// \ru Инициализация по локальной системе координат, радиусу и высоте. \en Initialization by a local coordinate system, radius and height. - void Init( const MbPlacement3D & place, double r, double h ); + void Init( const MbPlacement3D & place, double r, double h ); - /** \brief \ru Инициализация по отрезку и точке. - \en Initialization by segment and point. \~ - \details \ru Инициализация по отрезку и точке. \n - Высота цилиндра определяется длиной отрезка seg. \n - Ось определяется отрезком seg. \n - Радиус цилиндра равен расстоянию от точки point до оси. - \en Initialization by segment and point. \n - Height of cylinder is determined by length of 'seg' segment. \n - Axis is determined by 'seg' segment. \n - Radius of cylinder is equal to distance from 'point' point to axis. \~ - */ - void Init( const MbLineSegment3D & seg, const MbCartPoint3D & point ); + /** \brief \ru Инициализация по отрезку и точке. + \en Initialization by segment and point. \~ + \details \ru Инициализация по отрезку и точке. \n + Высота цилиндра определяется длиной отрезка seg. \n + Ось определяется отрезком seg. \n + Радиус цилиндра равен расстоянию от точки point до оси. + \en Initialization by segment and point. \n + Height of cylinder is determined by length of 'seg' segment. \n + Axis is determined by 'seg' segment. \n + Radius of cylinder is equal to distance from 'point' point to axis. \~ + */ + void Init( const MbLineSegment3D & seg, const MbCartPoint3D & point ); - /** \brief \ru Построение цилиндра радиуса r как сопряжение двух плоскостей в указанном месте. - \en Construction of cylinder of radius 'r' as conjugation of two planes at specified place. \~ - \details \ru Построение цилиндра радиуса r, касающегося двух плоскостей plane1 и plane2 - \en Construction of cylinder of radius 'r' tangent to two planes 'plane1' and 'plane2' \~ - \param[in] plane1 - \ru Первая плоскость - \en First plane \~ - \param[in] plane2 - \ru Вторая плоскость - \en Second plane \~ - \param[in] side1 - \ru Если > 0, то цилиндр над первой плоскостью, если < 0, то цилиндр под первой плоскстью - \en If it is greater than 0, then cylinder is above first plane, if it is less than 0, then cylinder is under first plane \~ - \param[in] side2 - \ru Если > 0, то цилиндр над второй плоскостью, если < 0, то цилиндр под второй плоскстью - \en If it is greater than 0, then cylinder is above second plane, if it is less than 0, then cylinder is under second plane \~ - \param[in] r - \ru Радиус цилиндра - \en Radius of cylinder \~ - */ - bool Init( const MbPlane & plane1, const MbPlane & plane2, int side1, int side2, double r ); + /** \brief \ru Построение цилиндра радиуса r как сопряжение двух плоскостей в указанном месте. + \en Construction of cylinder of radius 'r' as conjugation of two planes at specified place. \~ + \details \ru Построение цилиндра радиуса r, касающегося двух плоскостей plane1 и plane2 + \en Construction of cylinder of radius 'r' tangent to two planes 'plane1' and 'plane2' \~ + \param[in] plane1 - \ru Первая плоскость + \en First plane \~ + \param[in] plane2 - \ru Вторая плоскость + \en Second plane \~ + \param[in] side1 - \ru Если > 0, то цилиндр над первой плоскостью, если < 0, то цилиндр под первой плоскстью + \en If it is greater than 0, then cylinder is above first plane, if it is less than 0, then cylinder is under first plane \~ + \param[in] side2 - \ru Если > 0, то цилиндр над второй плоскостью, если < 0, то цилиндр под второй плоскстью + \en If it is greater than 0, then cylinder is above second plane, if it is less than 0, then cylinder is under second plane \~ + \param[in] r - \ru Радиус цилиндра + \en Radius of cylinder \~ + */ + bool Init( const MbPlane & plane1, const MbPlane & plane2, int side1, int side2, double r ); /** \} */ /** \ru \name Общие функции геометрического объекта \en \name Common functions of a geometric object @@ -220,12 +220,12 @@ public: \en \name Functions for get of the group of data inside and outside the surface's domain of parameters. \{ */ void Explore( double & u, double & v, bool ext, - MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, - MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; - virtual void _PointNormal( double u, double v, - MbCartPoint3D & pnt, MbVector3D & deru, MbVector3D & derv, - MbVector3D & norm, MbVector3D & noru, MbVector3D & norv, - MbVector3D & deruu, MbVector3D & dervv, MbVector3D & deruv ) const override; // \ru Значения производных в точке \en Values of derivatives at point + MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, + MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; + void _PointNormal( double u, double v, + MbCartPoint3D & pnt, MbVector3D & deru, MbVector3D & derv, + MbVector3D & norm, MbVector3D & noru, MbVector3D & norv, + MbVector3D & deruu, MbVector3D & dervv, MbVector3D & deruv ) const override; // \ru Значения производных в точке \en Values of derivatives at point /** \} */ /** \ru \name Функции движения по поверхности \en \name Functions of moving along the surface @@ -261,14 +261,14 @@ public: // \ru Определение точки касания поверхностей с одним неподвижным параметром. \en Determination of tangency point of surfaces with one fixed parameter. MbeNewtonResult SurfaceTangentNewton( const MbSurface & surf1, MbeParamDir switchPar, double funcEpsilon, size_t iterLimit, - double & u0, double & v0, double & u1, double & v1, bool ext0, bool ext1 ) const override; + double & u0, double & v0, double & u1, double & v1, bool ext0, bool ext1 ) const override; // \ru Определение точки пересечения цилиндрической поверхности и кривой. \en Determination of intersection point of cylindrical surface and curve. MbeNewtonResult CurveIntersectNewton( const MbCurve3D & curve, double funcEpsilon, size_t iterLimit, - double & u, double & v, double & t, bool ext0, bool ext1 ) const override; + double & u, double & v, double & t, bool ext0, bool ext1 ) const override; // \ru Определение точки касания цилиндрической поверхности и кривой. \en Determination of tangency point of cylindrical surface and curve. MbeNewtonResult CurveTangentNewton( const MbCurve3D & curv, double funcEpsilon, size_t iterLimit, - double & u, double & v, double & t, bool ext0, bool ext1 ) const override; + double & u, double & v, double & t, bool ext0, bool ext1 ) const override; // \ru Дать мимнимально различимую величину параметра. \en Get the minimum distinguishable value of parameter. double GetParamPrice() const override; @@ -294,9 +294,9 @@ public: void GetParamsToUnit( double u, double v, double & uParam, double & vParam ) const override; // \ru Дать приращение параметра u и параметра v, соответствующее единичной длине в пространстве. \en Get increment of parameters, corresponding to the unit length in space. // \ru Определение разбивки параметрической области поверхности вертикалями и горизонталями. \en Determine splitting of parametric region of surface by vertical and horizontal lines. - virtual void GetTesselation( const MbStepData & stepData, - double u1, double u2, double v1, double v2, - SArray & uu, SArray & vv ) const override; + void GetTesselation( const MbStepData & stepData, + double u1, double u2, double v1, double v2, + SArray & uu, SArray & vv ) const override; void CalculateGabarit( MbCube & ) const override; // \ru Рассчитать габарит поверхности. \en Calculate bounding box of surface. void CalculateLocalGabarit( const MbMatrix3D &, MbCube & ) const override; // \ru Рассчитать габарит относительно л.с.к. \en Calculate bounding box relative to the local coordinate system. @@ -323,42 +323,44 @@ public: /** \ru \name Функции цилиндрической поверхности \en \name Functions of the cylindrical surface \{ */ - /// \ru Получить внутренний радиус. \en Get internal radius. - double GetR() const { return radius; } - /// \ru Установить внутренний радиус. \en Set an internal radius. - void SetR( double r ) { radius = r; SetDirtyGabarit(); } + /// \ru Получить внутренний радиус. \en Get internal radius. + double GetR() const { return radius; } + /// \ru Установить внутренний радиус. \en Set an internal radius. + void SetR( double r ) { radius = r; SetDirtyGabarit(); } - /// \ru Изменение внутренней высоты. \en Change internal height. - void SetHeight( double h ) { height = h; SetDirtyGabarit(); } - /** \brief \ru Внутренняя высота. - \en Internal height. \~ - \details \ru Внутренняя высота. \n - Чтобы получить физическую высоту нужно внутреннюю высоту умножить - на параметрическую длину по V и - длину оси Z ЛСК поверхности. \n - \en Internal height. \n - To obtain the physical height you need to multiply the internal height - by the parametric length along V and - the length of the Z axis of the local coordinate system of the surface. \~ - */ - double GetHeight() const { return height; } - /// \ru Выдать физическую высоту. \en Get physical height. \~ - double GetRealHeight() const { return ( height * (vmax - vmin) * position.GetAxisZ().Length() ); } + /// \ru Изменение внутренней высоты. \en Change internal height. + void SetHeight( double h ) { height = h; SetDirtyGabarit(); } - /// \ru Дать точку на оси цилиндра. \en Get point on axis of cylinder. - void GetAxisPoint( double v, MbCartPoint3D & pnt ) const; + /** \brief \ru Внутренняя высота. + \en Internal height. \~ + \details \ru Внутренняя высота. \n + Чтобы получить физическую высоту нужно внутреннюю высоту умножить + на параметрическую длину по V и + длину оси Z ЛСК поверхности. \n + \en Internal height. \n + To obtain the physical height you need to multiply the internal height + by the parametric length along V and + the length of the Z axis of the local coordinate system of the surface. \~ + */ + double GetHeight() const { return height; } + /// \ru Выдать физическую высоту. \en Get physical height. \~ + double GetRealHeight() const { return ( height * (vmax - vmin) * position.GetAxisZ().Length() ); } + + /// \ru Дать точку на оси цилиндра. \en Get point on axis of cylinder. + void GetAxisPoint( double v, MbCartPoint3D & pnt ) const; /** \} */ private: inline void CheckParam( double & u, double & v ) const; // \ru Проверить параметры. \en Check parameters. // \ru Пересечение с прямолинейной кривой. \en Intersection with rectilinear curve. - bool StraightIntersection( const MbCurve3D & curv, SArray & uv, SArray & tt, bool ext0, bool ext ) const; - void operator = ( const MbCylinderSurface & ); // \ru Не реализовано. \en Not implemented. + bool StraightIntersection( const MbCurve3D & curv, SArray & uv, SArray & tt, bool ext0, bool ext ) const; + void operator = ( const MbCylinderSurface & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCylinderSurface ) }; IMPL_PERSISTENT_OPS( MbCylinderSurface ) + //------------------------------------------------------------------------------ // \ru Проверить параметры \en Check parameters // --- diff --git a/C3d/Include/surf_elementary_surface.h b/C3d/Include/surf_elementary_surface.h index 4356cfc..2ea4f97 100644 --- a/C3d/Include/surf_elementary_surface.h +++ b/C3d/Include/surf_elementary_surface.h @@ -183,30 +183,31 @@ public: \param[out] ww - \ru Контейнер с параметрами \en Container with parameters \~ */ - void AddTesselation( double step, size_t maxCount, double w1, double w2, SArray & ww ) const; + void AddTesselation( double step, size_t maxCount, double w1, double w2, SArray & ww ) const; - /// \ru Локальная система координат. \en A local coordinate system. + /// \ru Локальная система координат. \en A local coordinate system. const MbPlacement3D & GetPlacement() const { return position; } - /// \ru Установить локальную систему координат. \en Set the local coordinate system. - void InitPlacement( MbPlacement3D & p ) { position.Init( p ); } - /// \ru Является ли система координат ортонормированной. \en Whether the coordinate system is orthonormalized. - bool IsPositionNormal() const { return ( !position.IsAffine() ); } - /// \ru Является ли система координат ортогональной и изотропной по осям. \en Whether the coordinate system is orthogonal and isotropic by the axes. - bool IsPositionIsotropic() const { return ( position.IsIsotropic() ); } - /// \ru Является ли система координат ортогональной с равными по длине осями X,Y. \en Whether the coordinate system is orthogonal with X and Y axes equal by length. - bool IsPositionCircular() const { return ( position.IsCircular() ); } + /// \ru Установить локальную систему координат. \en Set the local coordinate system. + void InitPlacement( MbPlacement3D & p ) { position.Init( p ); } + /// \ru Является ли система координат ортонормированной. \en Whether the coordinate system is orthonormalized. + bool IsPositionNormal() const { return ( !position.IsAffine() ); } + /// \ru Является ли система координат ортогональной и изотропной по осям. \en Whether the coordinate system is orthogonal and isotropic by the axes. + bool IsPositionIsotropic() const { return ( position.IsIsotropic() ); } + /// \ru Является ли система координат ортогональной с равными по длине осями X,Y. \en Whether the coordinate system is orthogonal with X and Y axes equal by length. + bool IsPositionCircular() const { return ( position.IsCircular() ); } /** \} */ protected: - void Init_( const MbElementarySurface & ); // \ru Габарит и position \en Bounding box and 'position' + void Init_( const MbElementarySurface & ); // \ru Габарит и position \en Bounding box and 'position' private: - void operator = ( const MbElementarySurface & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbElementarySurface & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS( MbElementarySurface ) }; IMPL_PERSISTENT_OPS( MbElementarySurface ) + //------------------------------------------------------------------------------- // \ru Проверить и итерационно уточнить проекцию точки на поверхность по направлению \en Check and refine point projection onto the surface by direction iteratively // \ru (вспомогательная функция StraightIntersection у конуса и сферы) \en (an auxiliary function StraightIntersection of cone and sphere) diff --git a/C3d/Include/surf_elevation_surface.h b/C3d/Include/surf_elevation_surface.h index f4a500a..9796168 100644 --- a/C3d/Include/surf_elevation_surface.h +++ b/C3d/Include/surf_elevation_surface.h @@ -163,10 +163,9 @@ public: \en \name Functions for get of the group of data inside and outside the surface's domain of parameters. \{ */ void Explore( double & u, double & v, bool ext, - MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, - MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; + MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, + MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; /** \} */ - /** \ru \name Функции движения по поверхности \en \name Functions of moving along the surface \{ */ @@ -192,59 +191,69 @@ public: size_t GetVMeshCount() const override; // \ru Выдать количество полигонов по v \en Get the count of polygons by v + // \ru Нахождение проекции точки на поверхность в направлении вектора. Для внутреннего использования. \en Finding of point projections to the surface in direction of the vector. For internal use only. + MbeNewtonResult DirectPointProjectionNewton( const MbCartPoint3D & p, const MbVector3D & _vect, size_t iterLimit, + double & u, double & v, double & w, bool ext ) const override; + /** \} */ + /** \ru \name Функции поверхности, проходящей через заданное семейство кривых, с направляющей. + \en \name Functions lofted surface with guide curve. + \{ */ + /// \ru Вернуть направляющую кривую. \en Return spine (guide) curve. const MbCurve3D & GetSpineCurve() const { C3D_ASSERT( spine != nullptr ); return *spine; } - /// \ru Вернуть направляющую кривую. \en Return spine (guide) curve. + /// \ru Вернуть способ расчёта точек на поверхности. \en Return way of calculating of points on the surface. bool IsSimilarToEvolution() const { return isSimToEvol; } - -private: - void Init( VERSION version ); // \ru Инициализация данных \en Data initialization - void SpineInit(); - void ProfilePoint( ptrdiff_t i, double v, bool pole, // \ru Полюс. \en Pole. - const MbCartPoint3D & sPoint, - const MbVector3D & point, - MbVector3D & derives0 ) const; - void ProfileExplore( ptrdiff_t i, double v, bool pole, // \ru Полюс. \en Pole. - const MbCartPoint3D & sPoint, - const MbVector3D & sFirst, - const MbVector3D * sSecond, - const MbVector3D * points, - MbVector3D * derives0, - MbVector3D * derives1, - MbVector3D * derives2 ) const; - void ProfileSurface( ptrdiff_t i, double v, bool pole, // \ru Полюс. \en Pole. - uint uDeg, uint vDeg, - const MbCartPoint3D & spinePoint, - const MbVector3D & spineFirst, - const MbVector3D & spineSecond, - const MbVector3D & spineThird, - const MbVector3D * points, - MbVector3D * derives0, - MbVector3D * derives1, - MbVector3D * derives2, - MbVector3D * derives3 ) const; // \ru Определение массива производных для i-го сечения \en Determination of array of derivatives for i-th section - void CalculatePoint( double & u, double & v, bool ext, MbCartPoint3D & point ) const; - void CalculateExplore( double & u, double & v, bool ext, - MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, - MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer ) const; - void CalculateSurface( double & u, double & v, bool ext, uint uDeg, uint vDeg, - MbVector3D & der ) const; - void CalculateLikeLofted( double & u, double & v, bool ext, - size_t uDer, size_t vDer, MbCartPoint3D & point ) const; - void ExploreLikeLofted( double & u, double & v, bool ext, - MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, - MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer ) const; - inline void CheckParam( double & u, double & v, bool ext ) const; - void CheckParam( double & u, bool ext ) const; + /** \} */ - void operator = ( const MbElevationSurface & ); // \ru Не реализовано. \en Not implemented. +private: + void Init( VERSION version ); // \ru Инициализация данных \en Data initialization + void SpineInit(); + void ProfilePoint( ptrdiff_t i, double v, bool pole, // \ru Полюс. \en Pole. + const MbCartPoint3D & sPoint, + const MbVector3D & point, + MbVector3D & derives0 ) const; + void ProfileExplore( ptrdiff_t i, double v, bool pole, // \ru Полюс. \en Pole. + const MbCartPoint3D & sPoint, + const MbVector3D & sFirst, + const MbVector3D * sSecond, + const MbVector3D * points, + MbVector3D * derives0, + MbVector3D * derives1, + MbVector3D * derives2 ) const; + void ProfileSurface( ptrdiff_t i, double v, bool pole, // \ru Полюс. \en Pole. + uint uDeg, uint vDeg, + const MbCartPoint3D & spinePoint, + const MbVector3D & spineFirst, + const MbVector3D & spineSecond, + const MbVector3D & spineThird, + const MbVector3D * points, + MbVector3D * derives0, + MbVector3D * derives1, + MbVector3D * derives2, + MbVector3D * derives3 ) const; // \ru Определение массива производных для i-го сечения \en Determination of array of derivatives for i-th section + void CalculatePoint( double & u, double & v, bool ext, MbCartPoint3D & point ) const; + void CalculateExplore( double & u, double & v, bool ext, + MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, + MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer ) const; + void CalculateSurface( double & u, double & v, bool ext, uint uDeg, uint vDeg, + MbVector3D & der ) const; + void CalculateLikeLofted( double & u, double & v, bool ext, + size_t uDer, size_t vDer, MbCartPoint3D & point ) const; + void ExploreLikeLofted( double & u, double & v, bool ext, + MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, + MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer ) const; + inline void CheckParam( double & u, double & v, bool ext ) const; + void CheckParam( double & u, bool ext ) const; + + void operator = ( const MbElevationSurface & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbElevationSurface ) }; IMPL_PERSISTENT_OPS( MbElevationSurface ) + //------------------------------------------------------------------------------ // \ru Проверить параметры. \en Check parameters. // --- diff --git a/C3d/Include/surf_evolution_surface.h b/C3d/Include/surf_evolution_surface.h index d7efe0e..cef029f 100644 --- a/C3d/Include/surf_evolution_surface.h +++ b/C3d/Include/surf_evolution_surface.h @@ -197,8 +197,8 @@ public: \en \name Functions for get of the group of data inside and outside the surface's domain of parameters. \{ */ void Explore( double & u, double & v, bool ext, - MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, - MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; + MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, + MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; /** \} */ /** \ru \name Функции движения по поверхности \en \name Functions of moving along the surface @@ -241,9 +241,9 @@ public: bool GetMatrixToSurface( const MbSurface & surf, MbMatrix & matr, VERSION version, double precision = METRIC_PRECISION ) const override; bool GetCenterLines( std::vector & clCurves ) const override; // \ru Дать осевые (центральные) линии для поверхности. \en Get center lines of a surface. // \ru Определение разбивки параметрической области поверхности вертикалями и горизонталями. \en Determine splitting of parametric region of surface by vertical and horizontal lines. - virtual void GetTesselation( const MbStepData & stepData, - double u1, double u2, double v1, double v2, - SArray & uu, SArray & vv ) const override; + void GetTesselation( const MbStepData & stepData, + double u1, double u2, double v1, double v2, + SArray & uu, SArray & vv ) const override; bool IsSpinePeriodic() const override; // \ru Периодичность направляющей. \en Periodicity of a guide curve. size_t GetUMeshCount() const override; // \ru Выдать количество полигонов по u. \en Get the count of polygons by u. @@ -256,41 +256,42 @@ public: \en \name Functions of the evolution surface \{ */ - /** \brief \ru Определение матрицы переноса для образующей. - \en Determination of translation matrix for generating curve. \~ - \details \ru Определение матрицы переноса для образующей по параметру направляющей. - \en Determination of translation matrix for generating curve by parameter of guide curve. \~ - \param[in] v - \ru Параметр на направляющей - \en Parameter on the guide curve \~ - \param[in] matr - \ru Матрица-результат - \en Matrix-result \~ - */ - void TransformMatrix( double v, MbMatrix3D & matr ) const; + /** \brief \ru Определение матрицы переноса для образующей. + \en Determination of translation matrix for generating curve. \~ + \details \ru Определение матрицы переноса для образующей по параметру направляющей. + \en Determination of translation matrix for generating curve by parameter of guide curve. \~ + \param[in] v - \ru Параметр на направляющей + \en Parameter on the guide curve \~ + \param[in] matr - \ru Матрица-результат + \en Matrix-result \~ + */ + void TransformMatrix( double v, MbMatrix3D & matr ) const; - /// \ru Направляющая. \en Guide curve. - const MbSpine & GetSpine() const { return *spine; } + /// \ru Направляющая. \en Guide curve. + const MbSpine & GetSpine() const { return *spine; } - /// \ru Направляющая кривая. \en The spine (guide) curve. - const MbCurve3D & GetSpineCurve() const { return spine->GetCurve(); } - /// \ru Центр тяжести образующей. \en Center of gravity of generating curve. - const MbCartPoint3D & GetOrigin() const { return origin; } + /// \ru Направляющая кривая. \en The spine (guide) curve. + const MbCurve3D & GetSpineCurve() const { return spine->GetCurve(); } + /// \ru Центр тяжести образующей. \en Center of gravity of generating curve. + const MbCartPoint3D & GetOrigin() const { return origin; } - /// \ru Дать направляющую кривую для изменения. \en Get guide curve for editing. - MbCurve3D & SetSpineCurve() { return spine->SetCurve(); } - /// \ru Задать центр тяжести образующей. \en Set center of gravity of generating curve. - void SetOrigin( const MbCartPoint3D & p ) { origin = p; SetDirtyGabarit(); } + /// \ru Дать направляющую кривую для изменения. \en Get guide curve for editing. + MbCurve3D & SetSpineCurve() { return spine->SetCurve(); } + /// \ru Задать центр тяжести образующей. \en Set center of gravity of generating curve. + void SetOrigin( const MbCartPoint3D & p ) { origin = p; SetDirtyGabarit(); } /** \} */ protected : - void Init(); + void Init(); private: - void operator = ( const MbEvolutionSurface & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbEvolutionSurface & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbEvolutionSurface ) }; IMPL_PERSISTENT_OPS( MbEvolutionSurface ) + //------------------------------------------------------------------------------ /** \brief \ru Создать кинематическую поверхность. \en Create an evolution surface. \~ diff --git a/C3d/Include/surf_exaction_surface.h b/C3d/Include/surf_exaction_surface.h index 74bfdb0..27a632d 100644 --- a/C3d/Include/surf_exaction_surface.h +++ b/C3d/Include/surf_exaction_surface.h @@ -41,17 +41,17 @@ class MATH_CLASS MbContourOnSurface; // --- class MATH_CLASS MbExactionSurface : public MbEvolutionSurface { private: - MbVector3D normal0; ///< \ru Вектор нормали к плоскости стыковки в начальной точке. \en A vector of normal to the plane of connection at the start point. - MbVector3D normal1; ///< \ru Вектор нормали к плоскости стыковки в конечной точке. \en A vector of normal to the plane of connection at the end point. - double angle0; ///< \ru Угол излома в начальной точке направляющей. \en Angle of break at start point of guide curve. - double angle1; ///< \ru Угол излома в конечной точке направляющей. \en Angle of break at end point of guide curve. - MbVector3D move0; ///< \ru Касательный вектор сдвига начальных точек. \en Tangent vector of translation of start points. - MbVector3D move1; ///< \ru Касательный вектор сдвига конечных точек. \en Tangent vector of translation of end points. - bool mode0; ///< \ru true, если вектор move0 не равен нулю. \en True if 'move0' vector isn't equal to zero. - bool mode1; ///< \ru true, если вектор move1 не равен нулю. \en True if 'move1' vector isn't equal to zero. - MbVector3D factorX; ///< \ru Сомножитель векторного произведения для касательной к образующей curve (нормаль плоскости эскиза). \en The multiplier of the vector product for the tangent of the generating 'curve' (the scetch normal). - double rangeX; ///< \ru Эквидистантное смещение точек образующей кривой в конце траектории. \en The offset range of generating curve on the end of spine curve. - bool modeX; ///< \ru true, если вектор 'factorX' не равен нулю. \en True if 'factorX' vector isn't equal to zero. + MbVector3D normal0; ///< \ru Вектор нормали к плоскости стыковки в начальной точке. \en A vector of normal to the plane of connection at the start point. + MbVector3D normal1; ///< \ru Вектор нормали к плоскости стыковки в конечной точке. \en A vector of normal to the plane of connection at the end point. + double angle0; ///< \ru Угол излома в начальной точке направляющей. \en Angle of break at start point of guide curve. + double angle1; ///< \ru Угол излома в конечной точке направляющей. \en Angle of break at end point of guide curve. + MbVector3D move0; ///< \ru Касательный вектор сдвига начальных точек. \en Tangent vector of translation of start points. + MbVector3D move1; ///< \ru Касательный вектор сдвига конечных точек. \en Tangent vector of translation of end points. + bool mode0; ///< \ru true, если вектор move0 не равен нулю. \en True if 'move0' vector isn't equal to zero. + bool mode1; ///< \ru true, если вектор move1 не равен нулю. \en True if 'move1' vector isn't equal to zero. + MbVector3D factorX; ///< \ru Сомножитель векторного произведения для касательной к образующей curve (нормаль плоскости эскиза). \en The multiplier of the vector product for the tangent of the generating 'curve' (the scetch normal). + double rangeX; ///< \ru Эквидистантное смещение точек образующей кривой в конце траектории. \en The offset range of generating curve on the end of spine curve. + bool modeX; ///< \ru true, если вектор 'factorX' не равен нулю. \en True if 'factorX' vector isn't equal to zero. public: @@ -147,8 +147,8 @@ public: \en \name Functions for get of the group of data inside and outside the surface's domain of parameters. \{ */ void Explore( double & u, double & v, bool ext, - MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, - MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; + MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, + MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; /** \} */ /** \ru \name Общие функции поверхности \en \name Common functions of surface @@ -170,35 +170,36 @@ public: /** \ru \name Функции кинематической поверхности с адаптацией \en \name Functions of sweep with guide curve surface with rotating ends. \{ */ - /// \ru Признак наличия ненулевого касательного вектора сдвига начальных точек. \en Attribute of existence of non-zero tangent vector of translation of start points. - bool GetMode0() const { return mode0; } - /// \ru Признак наличия ненулевого касательного вектора сдвига конечных точек. \en Attribute of existence of non-zero tangent vector of translation of end points. - bool GetMode1() const { return mode1; } - /// \ru Угол излома в начальной точке направляющей. \en Angle of break at start point of guide curve. - double GetBegAngle() const { return angle0; } - /// \ru Угол излома в конечной точке направляющей. \en Angle of break at end point of guide curve. - double GetEndAngle() const { return angle1; } + /// \ru Признак наличия ненулевого касательного вектора сдвига начальных точек. \en Attribute of existence of non-zero tangent vector of translation of start points. + bool GetMode0() const { return mode0; } + /// \ru Признак наличия ненулевого касательного вектора сдвига конечных точек. \en Attribute of existence of non-zero tangent vector of translation of end points. + bool GetMode1() const { return mode1; } + /// \ru Угол излома в начальной точке направляющей. \en Angle of break at start point of guide curve. + double GetBegAngle() const { return angle0; } + /// \ru Угол излома в конечной точке направляющей. \en Angle of break at end point of guide curve. + double GetEndAngle() const { return angle1; } /** \} */ private: - void Init(); - void InitEnd(); - void PrepareTangent(); - void AddTangent0( double & v, MbVector3D & ) const; - void AddTangentV( MbVector3D & ) const; - void AddOffsetX0( double & v, const MbVector3D & first, MbVector3D & r ) const; - void AddOffsetXU( double & v, MbVector3D & first, const MbVector3D & second ) const; - void AddOffsetXUU( double & v, const MbVector3D & first, MbVector3D & second, const MbVector3D & third ) const; - void AddOffsetXV( const MbVector3D & derive, MbVector3D & r ) const; - void AddOffsetXUV( const MbVector3D & first, const MbVector3D & second, MbVector3D & r ) const; + void Init(); + void InitEnd(); + void PrepareTangent(); + void AddTangent0( double & v, MbVector3D & ) const; + void AddTangentV( MbVector3D & ) const; + void AddOffsetX0( double & v, const MbVector3D & first, MbVector3D & r ) const; + void AddOffsetXU( double & v, MbVector3D & first, const MbVector3D & second ) const; + void AddOffsetXUU( double & v, const MbVector3D & first, MbVector3D & second, const MbVector3D & third ) const; + void AddOffsetXV( const MbVector3D & derive, MbVector3D & r ) const; + void AddOffsetXUV( const MbVector3D & first, const MbVector3D & second, MbVector3D & r ) const; - void operator = ( const MbExactionSurface & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbExactionSurface & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbExactionSurface ) }; IMPL_PERSISTENT_OPS( MbExactionSurface ) + //------------------------------------------------------------------------------ // \ru Проверка на самопересечение кинематической поверхности \en Check for self-intersection of sweep with guide curve surface // \ru Если изменится расчет точек кинематической поверхности, то надо переделывать \en If calculation of points of a sweep with guide curve surface changes, then it is necessary to remake @@ -209,6 +210,7 @@ bool FindSelfIntersections( const MbCurve3D & curve3d, //bool natur, VERSION version ); + //------------------------------------------------------------------------------ // \ru Проверить корректность кинематики по движении по замкнутому контуру \en Check correctness of kinematics while moving along closed contour // \ru (путем трансформации копии образующего контура по направляющем сегментам \en (by transformation of copy of generating contour along guide segments @@ -218,7 +220,7 @@ bool CheckClosingContour( const MbContourOnSurface & contourOnSurface, // \ru const MbSpine & baseSpine, // \ru Направляющий контур \en Guide contour const SArray & childSpines, // \ru Сегменты направляющей \en Segments of guide curve //bool natur, // \ru Тип привязки тела \en Type of binding of solid - bool closedShell ); // \ru Замкнутость результирующей оболочки \en Closedness of resultant shell + bool closedShell ); // \ru Замкнутость результирующей оболочки \en Closedness of resultant shell //------------------------------------------------------------------------------ diff --git a/C3d/Include/surf_expansion_surface.h b/C3d/Include/surf_expansion_surface.h index 7ead228..0e17bd4 100644 --- a/C3d/Include/surf_expansion_surface.h +++ b/C3d/Include/surf_expansion_surface.h @@ -156,8 +156,8 @@ public: \en \name Functions for get of the group of data inside and outside the surface's domain of parameters. \{ */ void Explore( double & u, double & v, bool ext, - MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, - MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; + MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, + MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; /** \} */ /** \ru \name Функции движения по поверхности \en \name Functions of moving along the surface @@ -191,10 +191,9 @@ public: bool CreateNormalPlacements ( const MbVector3D & axisZ, double angle, SArray & places, VERSION version = Math::DefaultMathVersion() ) const override; bool CreateTangentPlacements( const MbVector3D & axisZ, SArray & places ) const override; // \ru Определение разбивки параметрической области поверхности вертикалями и горизонталями. \en Determine splitting of parametric region of surface by vertical and horizontal lines. - virtual void GetTesselation( const MbStepData & stepData, - double u1, double u2, double v1, double v2, - SArray & uu, SArray & vv ) const override; - + void GetTesselation( const MbStepData & stepData, + double u1, double u2, double v1, double v2, + SArray & uu, SArray & vv ) const override; // \ru Подобные ли поверхности для объединения (слива) (геометрическое совпадение). \en Whether the surfaces to union (joining) are similar (geometric coincidence). bool IsSimilarToSurface( const MbSurface & surf, VERSION version, double precision = METRIC_PRECISION ) const override; @@ -207,35 +206,35 @@ public: \en \name Functions of plane-parallel surface \{ */ - /** \brief \ru Определение вектора переноса образующей. - \en Determination of translation vector for generating curve. \~ - \details \ru Определение вектора переноса образующей по параметру на направляющей. - \en Determination of translation vector for generating curve by parameter of guide curve. \~ - \param[in] v - \ru Параметр на направляющей - \en Parameter on the guide curve \~ - \param[in] vect - \ru Вектор-результат - \en Vector-result \~ - */ - void TransformVector( double & v, MbVector3D & vect ) const; + /** \brief \ru Определение вектора переноса образующей. + \en Determination of translation vector for generating curve. \~ + \details \ru Определение вектора переноса образующей по параметру на направляющей. + \en Determination of translation vector for generating curve by parameter of guide curve. \~ + \param[in] v - \ru Параметр на направляющей + \en Parameter on the guide curve \~ + \param[in] vect - \ru Вектор-результат + \en Vector-result \~ + */ + void TransformVector( double & v, MbVector3D & vect ) const; - /// \ru Направляющая кривая. \en The spine (guide) curve. - const MbCurve3D & GetSpineCurve() const { return *spine; } - /// \ru Центр тяжести образующей. \en Center of gravity of generating curve. - const MbCartPoint3D & GetOrigin() const { return origin; } - /// \ru Вторая образующая кривая. \en The second generating curve. - const MbCurve3D * GetBrink() const { return brink; } + /// \ru Направляющая кривая. \en The spine (guide) curve. + const MbCurve3D & GetSpineCurve() const { return *spine; } + /// \ru Центр тяжести образующей. \en Center of gravity of generating curve. + const MbCartPoint3D & GetOrigin() const { return origin; } + /// \ru Вторая образующая кривая. \en The second generating curve. + const MbCurve3D * GetBrink() const { return brink; } inline double BrinkParameterFrom( const double & u ) const; inline double BrinkParameterInto( const double & t ) const; - /// \ru Дать направляющую кривую для изменения. \en Get guide curve for editing. - MbCurve3D & SetSpineCurve() { return *spine; } - /// \ru Изменение центра тяжести образующей. \en Change center of gravity of generating curve. - void SetOrigin( const MbCartPoint3D & p ) { origin = p; SetDirtyGabarit(); } + /// \ru Дать направляющую кривую для изменения. \en Get guide curve for editing. + MbCurve3D & SetSpineCurve() { return *spine; } + /// \ru Изменение центра тяжести образующей. \en Change center of gravity of generating curve. + void SetOrigin( const MbCartPoint3D & p ) { origin = p; SetDirtyGabarit(); } /** \} */ private: - void Init(); - void operator = ( const MbExpansionSurface & ); // \ru Не реализовано. \en Not implemented. + void Init(); + void operator = ( const MbExpansionSurface & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbExpansionSurface ) }; diff --git a/C3d/Include/surf_exploration_surface.h b/C3d/Include/surf_exploration_surface.h index b82bd5a..6a1ee56 100644 --- a/C3d/Include/surf_exploration_surface.h +++ b/C3d/Include/surf_exploration_surface.h @@ -127,8 +127,8 @@ public: \en \name Functions for get of the group of data inside and outside the surface's domain of parameters. \{ */ void Explore( double & u, double & v, bool ext, - MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, - MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; + MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, + MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; /** \} */ /** \ru \name Функции движения по поверхности \en \name Functions of moving along the surface @@ -148,9 +148,9 @@ public: MbCurve3D * CurveV( double u, MbRect1D *pRgn, bool bApprox = true ) const override; // \ru Пространственная копия линии u = const. \en Spatial copy of 'u = const'-line. // \ru Определение разбивки параметрической области поверхности вертикалями и горизонталями. \en Determine splitting of parametric region of surface by vertical and horizontal lines. - virtual void GetTesselation( const MbStepData & stepData, - double u1, double u2, double v1, double v2, - SArray & uu, SArray & vv ) const override; + void GetTesselation( const MbStepData & stepData, + double u1, double u2, double v1, double v2, + SArray & uu, SArray & vv ) const override; size_t GetUCount() const override; // \ru Количество разбиений по параметру u для проверки событий. \en The number of splittings by u-parameter for a check of events. size_t GetVCount() const override; // \ru Количество разбиений по параметру v для проверки событий. \en The number of splittings by v-parameter for a check of events. @@ -182,10 +182,10 @@ public: MbFunction & _scaling, MbFunction & _winding ); protected : - void Init(); + void Init(); private: - void operator = ( const MbExplorationSurface & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbExplorationSurface & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbExplorationSurface ) }; diff --git a/C3d/Include/surf_extrusion_surface.h b/C3d/Include/surf_extrusion_surface.h index 8b2bd6b..1f30194 100644 --- a/C3d/Include/surf_extrusion_surface.h +++ b/C3d/Include/surf_extrusion_surface.h @@ -129,8 +129,8 @@ public: \en \name Functions for get of the group of data inside and outside the surface's domain of parameters. \{ */ void Explore( double & u, double & v, bool ext, - MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, - MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; + MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, + MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; /** \} */ /** \ru \name Функции движения по поверхности \en \name Functions of moving along the surface @@ -166,7 +166,7 @@ public: bool NearPointProjection ( const MbCartPoint3D & p, double & u, double & v, bool ext, MbRect2D * uvRange = nullptr ) const override; // \ru Ближайшая проекция точки на поверхность. \en The nearest point projection onto the surface. // \ru Пересечение с кривой. \en Intersection with curve. void CurveIntersection( const MbCurve3D & curv, SArray & uv, SArray & tt, - bool ext0, bool ext, bool touchInclude = false ) const override; + bool ext0, bool ext, bool touchInclude = false ) const override; void CalculateGabarit( MbCube & ) const override; // \ru Выдать габарит. \en Get the bounding box. void CalculateLocalGabarit( const MbMatrix3D &, MbCube & ) const override; // \ru Рассчитать габарит относительно л.с.к. \en Calculate bounding box relative to the local coordinate system. @@ -189,9 +189,9 @@ public: MbeParamDir GetFilletDirection() const override; // \ru Направление поверхности скругления. \en Direction of fillet surface. // \ru Определение разбивки параметрической области поверхности вертикалями и горизонталями. \en Determine splitting of parametric region of surface by vertical and horizontal lines. - virtual void GetTesselation( const MbStepData & stepData, - double u1, double u2, double v1, double v2, - SArray & uu, SArray & vv ) const override; + void GetTesselation( const MbStepData & stepData, + double u1, double u2, double v1, double v2, + SArray & uu, SArray & vv ) const override; size_t GetUMeshCount() const override; // \ru Выдать количество полигонов по u. \en Get the count of polygons by u. size_t GetVMeshCount() const override; // \ru Выдать количество полигонов по v. \en Get the count of polygons by v. @@ -205,34 +205,34 @@ public: /// \ru Направление выдавливания. \en A direction of extrusion. const MbVector3D & GetDirection() const { return direction; } /// \ru Длина выдаливания. \en A length of extrusion. - double GetDistance () const { return distance; } + double GetDistance () const { return distance; } /// \ru Изменить направление выдавливания на противоположное. \en Change direction of extrusion to opposite. - void InvertDirection() { direction.Invert(); SetDirtyGabarit(); } + void InvertDirection() { direction.Invert(); SetDirtyGabarit(); } - /** \brief \ru Создание эквидистантной поверхности. - \en Create an offset surface. \~ - \details \ru Создание поверхности типа st_OffsetSurface, совпадающей с данной поверхностью.\n - Если образующая кривая является эквидистантной кривой на плоскости, - то, используя ее базовую кривую в качестве образующей, создается поверхность - выдавливания и по ней эквидистантная поверхность.\n - Поверхность строится в случае, если направление выдавливания - перпендикулярно плоскости образующей кривой.\n - Используется только в конвертерах. - \en Create surface of st_OffsetSurface type coinciding with current surface.\n - If generating curve is offset curve on plane, - then using its base curve as generating curve the extrusion surface - and offset surface by it are created.\n - Surface is created if direction of extrusion - is perpendicular to plane of generating curve.\n - Used only in converters. \~ - */ - MbOffsetSurface * GetSurfaceFromPlaneCurveOffset() const; + /** \brief \ru Создание эквидистантной поверхности. + \en Create an offset surface. \~ + \details \ru Создание поверхности типа st_OffsetSurface, совпадающей с данной поверхностью.\n + Если образующая кривая является эквидистантной кривой на плоскости, + то, используя ее базовую кривую в качестве образующей, создается поверхность + выдавливания и по ней эквидистантная поверхность.\n + Поверхность строится в случае, если направление выдавливания + перпендикулярно плоскости образующей кривой.\n + Используется только в конвертерах. + \en Create surface of st_OffsetSurface type coinciding with current surface.\n + If generating curve is offset curve on plane, + then using its base curve as generating curve the extrusion surface + and offset surface by it are created.\n + Surface is created if direction of extrusion + is perpendicular to plane of generating curve.\n + Used only in converters. \~ + */ + MbOffsetSurface * GetSurfaceFromPlaneCurveOffset() const; /** \} */ private: // \ru Пересечение с прямолинейной кривой. \en Intersection with rectilinear curve. - bool StraightIntersection( const MbCurve3D & curv, SArray & uv, SArray & tt, bool ext0, bool ext ) const; - void operator = ( const MbExtrusionSurface & ); // \ru Не реализовано. \en Not implemented. + bool StraightIntersection( const MbCurve3D & curv, SArray & uv, SArray & tt, bool ext0, bool ext ) const; + void operator = ( const MbExtrusionSurface & ); // \ru Не реализовано. \en Not implemented. protected: inline void CheckParam( double &u, double &v ) const; // \ru Проверить параметры. \en Check parameters. @@ -241,6 +241,7 @@ protected: IMPL_PERSISTENT_OPS( MbExtrusionSurface ) + //------------------------------------------------------------------------------ // \ru Проверить параметры. \en Check parameters. // --- diff --git a/C3d/Include/surf_fillet_surface.h b/C3d/Include/surf_fillet_surface.h index 263ae5a..f519d18 100644 --- a/C3d/Include/surf_fillet_surface.h +++ b/C3d/Include/surf_fillet_surface.h @@ -246,13 +246,13 @@ public: \en \name Functions for get of the group of data inside and outside the surface's domain of parameters. \{ */ void Explore( double & u, double & v, bool ext, - MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, - MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; + MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, + MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; // \ru Вычислить значения всех производных в точке. \en Calculate all derivatives at point. \~ void _PointNormal( double u, double v, - MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, - MbVector3D & norm, MbVector3D & uNorm, MbVector3D & vNorm, - MbVector3D & uuDer, MbVector3D & vvDer, MbVector3D & uvDer ) const override; + MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, + MbVector3D & norm, MbVector3D & uNorm, MbVector3D & vNorm, + MbVector3D & uuDer, MbVector3D & vvDer, MbVector3D & uvDer ) const override; /** \} */ /** \ru \name Функции движения по поверхности \en \name Functions of moving along the surface @@ -278,12 +278,12 @@ public: bool ChangeCarrierBorne( const MbSurface & item, MbSurface & init, const MbMatrix & matr ) override; // \ru Изменение носимых элементов. \en Change a carrier elements. // \ru Нахождениe точки касания поверхностей \en Searching of surfaces tangency point MbeNewtonResult SurfaceTangentNewton( const MbSurface &, MbeParamDir switchPar, double funcEpsilon, size_t iterLimit, - double &u0, double &v0, double &u1, double &v1, - bool ext0, bool ext1 ) const override; + double &u0, double &v0, double &u1, double &v1, + bool ext0, bool ext1 ) const override; // \ru Проекции точки на поверхность. \en The point projections onto the surface. MbeNewtonResult PointProjectionNewton( const MbCartPoint3D & p, size_t iterLimit, - double & u, double & v, bool ext ) const override; // \ru Функция для нахождения проекции точки на поверхность. \en Function for searching the point projection onto the surface. + double & u, double & v, bool ext ) const override; // \ru Функция для нахождения проекции точки на поверхность. \en Function for searching the point projection onto the surface. bool NearPointProjection ( const MbCartPoint3D & p, double & u, double & v, bool ext, MbRect2D * uvRange = nullptr ) const override; // \ru Ближайшая проекция точки на поверхность. \en The nearest point projection onto the surface. double GetFilletRadius( const MbCartPoint3D & p ) const override; // \ru Является ли поверхность скруглением. \en Whether the surface is fillet. @@ -313,296 +313,295 @@ public: double GetDistance( bool s ) const override; // \ru Дать радиус со знаком. \en Get radius with a sign. // \ru Объединить поверхности путём включения поверхности init в данную поверхность. \en Unite surfaces by inclusion of 'init' surface into current surface. bool SurfacesCombine( const MbSurfaceIntersectionCurve & edge, - const MbSurface & init, bool add, MbMatrix & matr, - const MbSurfaceIntersectionCurve * seam ) override; + const MbSurface & init, bool add, MbMatrix & matr, + const MbSurfaceIntersectionCurve * seam ) override; /// \ru Дать коэффициент для радиуса. \en Get coefficient for radius. double DistanceRatio( bool firstCurve, MbCartPoint3D & p, double distance ) const override; // \ru Определение разбивки параметрической области поверхности вертикалями и горизонталями. \en Determine splitting of parametric region of surface by vertical and horizontal lines. - virtual void GetTesselation( const MbStepData & stepData, - double u1, double u2, double v1, double v2, - SArray & uu, SArray & vv ) const override; + void GetTesselation( const MbStepData & stepData, + double u1, double u2, double v1, double v2, + SArray & uu, SArray & vv ) const override; /** \} */ /** \ru \name Функции поверхности скругления \en \name Functions of fillet surface \{ */ - /** \brief \ru Веса точек средней кривой. - \en Weights of points of mid-curve. \~ - \details \ru Веса точек средней кривой. - \en Weights of points of mid-curve. \~ - \param[in] u - \ru Параметр на средней кривой (по направлению U) - \en Parameter on mid-curve (by U direction) \~ - */ - double GetWeight( double u ) const; + /** \brief \ru Веса точек средней кривой. + \en Weights of points of mid-curve. \~ + \details \ru Веса точек средней кривой. + \en Weights of points of mid-curve. \~ + \param[in] u - \ru Параметр на средней кривой (по направлению U) + \en Parameter on mid-curve (by U direction) \~ + */ + double GetWeight( double u ) const; - /** \brief \ru Угол раствора дуги. - \en Arc opening angle. \~ - \details \ru Угол раствора дуги. - \en Arc opening angle. \~ - \param[in] u - \ru Параметр по направлению U - \en Parameter by U direction \~ - \return \ru Угол раствора - \en Angle of opening \~ - */ - double GetAngle( double u ) const; // \ru Дать угол раствора дуги v \en Get v arc opening angle + /** \brief \ru Угол раствора дуги. + \en Arc opening angle. \~ + \details \ru Угол раствора дуги. + \en Arc opening angle. \~ + \param[in] u - \ru Параметр по направлению U + \en Parameter by U direction \~ + \return \ru Угол раствора + \en Angle of opening \~ + */ + double GetAngle( double u ) const; // \ru Дать угол раствора дуги v \en Get v arc opening angle - /** \brief \ru Ось поверхности в данной точке. - \en Axis of surface at given point. \~ - \details \ru Ось поверхности в данной точке. - \en Axis of surface at given point. \~ - \param[in] u - \ru Параметр по направлению U - \en Parameter by U direction \~ - \param[out] axis - \ru Результат - ось вращения - \en Result - rotation axis \~ - */ - double GetLocalAxis ( double u, MbAxis3D & axis ) const; // \ru Дать ось поверхности в данной точке \en Get axis of surface at given point + /** \brief \ru Ось поверхности в данной точке. + \en Axis of surface at given point. \~ + \details \ru Ось поверхности в данной точке. + \en Axis of surface at given point. \~ + \param[in] u - \ru Параметр по направлению U + \en Parameter by U direction \~ + \param[out] axis - \ru Результат - ось вращения + \en Result - rotation axis \~ + */ + double GetLocalAxis ( double u, MbAxis3D & axis ) const; // \ru Дать ось поверхности в данной точке \en Get axis of surface at given point - /** \brief \ru Дать точку на оси. - \en Get point on axis. \~ - \details \ru Дать точку на оси. - \en Get point on axis. \~ - \param[in] u - \ru Параметр по направлению U - \en Parameter by U direction \~ - \param[out] p1 - \ru Точка на первой опорной кривой по параметру U - \en Point on first support curve by U parameter \~ - \param[out] p2 - \ru Точка на второй опорной кривой по параметру U - \en Point on second support curve by U parameter \~ - \param[out] p0 - \ru Точка на кривой пересечения касательных к поверхностям по параметру u (точка на оси) - \en Point on intersection curve of tangents to surfaces by u parameter (point on axis) \~ - */ - void GetCentrePoint( double u, MbCartPoint3D &p1, MbCartPoint3D &p2, MbCartPoint3D &p0 ) const; + /** \brief \ru Дать точку на оси. + \en Get point on axis. \~ + \details \ru Дать точку на оси. + \en Get point on axis. \~ + \param[in] u - \ru Параметр по направлению U + \en Parameter by U direction \~ + \param[out] p1 - \ru Точка на первой опорной кривой по параметру U + \en Point on first support curve by U parameter \~ + \param[out] p2 - \ru Точка на второй опорной кривой по параметру U + \en Point on second support curve by U parameter \~ + \param[out] p0 - \ru Точка на кривой пересечения касательных к поверхностям по параметру u (точка на оси) + \en Point on intersection curve of tangents to surfaces by u parameter (point on axis) \~ + */ + void GetCentrePoint( double u, MbCartPoint3D &p1, MbCartPoint3D &p2, MbCartPoint3D &p0 ) const; - /** \brief \ru Дать среднюю точку. - \en Get the mid-point. \~ - \details \ru Дать среднюю точку. - \en Get the mid-point. \~ - \param[in] u - \ru Параметр по направлению U - \en Parameter by U direction \~ - \param[out] p1 - \ru Точка на первой опорной кривой по параметру U - \en Point on first support curve by U parameter \~ - \param[out] p2 - \ru Точка на второй опорной кривой по параметру U - \en Point on second support curve by U parameter \~ - \param[out] p0 - \ru Средняя точка - \en Mid-point \~ - \param[out] w - \ru Вес полученной средней точки - \en Weight of obtained mid-point \~ - */ - bool GetMiddlePoint( double u, MbCartPoint3D &p1, MbCartPoint3D &p2, MbCartPoint3D &p0, double &w ) const; + /** \brief \ru Дать среднюю точку. + \en Get the mid-point. \~ + \details \ru Дать среднюю точку. + \en Get the mid-point. \~ + \param[in] u - \ru Параметр по направлению U + \en Parameter by U direction \~ + \param[out] p1 - \ru Точка на первой опорной кривой по параметру U + \en Point on first support curve by U parameter \~ + \param[out] p2 - \ru Точка на второй опорной кривой по параметру U + \en Point on second support curve by U parameter \~ + \param[out] p0 - \ru Средняя точка + \en Mid-point \~ + \param[out] w - \ru Вес полученной средней точки + \en Weight of obtained mid-point \~ + */ + bool GetMiddlePoint( double u, MbCartPoint3D &p1, MbCartPoint3D &p2, MbCartPoint3D &p0, double &w ) const; - // \ru Если параметризация равномерная, то на продолжении по V замыкается и период зависит от U \en If parameterization is uniform, then it is closed on extension by V and period depends on U - /** \brief \ru Период по направлению V. - \en Period by direction V. \~ - \details \ru Период по направлению V.\n - Если параметризация поверхности равномерная, то период по направлению V зависит от параметра U. - \en Period by direction V.\n - If parameterization of surface is uniform, then period by direction V depends on U parameter. \~ - \param[in] u - \ru Параметр по направлению U - \en Parameter by U direction \~ - \return \ru Период для заданного параметра - \en Period for given parameter \~ - */ - double GetVPeriod( double u ) const; + // \ru Если параметризация равномерная, то на продолжении по V замыкается и период зависит от U \en If parameterization is uniform, then it is closed on extension by V and period depends on U + /** \brief \ru Период по направлению V. + \en Period by direction V. \~ + \details \ru Период по направлению V.\n + Если параметризация поверхности равномерная, то период по направлению V зависит от параметра U. + \en Period by direction V.\n + If parameterization of surface is uniform, then period by direction V depends on U parameter. \~ + \param[in] u - \ru Параметр по направлению U + \en Parameter by U direction \~ + \return \ru Период для заданного параметра + \en Period for given parameter \~ + */ + double GetVPeriod( double u ) const; - /// \ru Кривая пересечения касательных к поверхностям. \en Intersection curve of tangents to surfaces. - const MbCurve3D & GetCurve0() const { return *curve0; } + /// \ru Кривая пересечения касательных к поверхностям. \en Intersection curve of tangents to surfaces. + const MbCurve3D & GetCurve0() const { return *curve0; } - /** \brief \ru Скругление не круговое. - \en Fillet isn't circular. \~ - \details \ru Скругление не круговое. - \en Fillet isn't circular. \~ - \return \ru true, если радиусы скруглений для поверхностей не равны - \en True if surfaces fillet radii aren't equal \~ - */ - bool IsEllipse() const { return (fabs(fabs(distance1) - fabs(distance2))>=LENGTH_EPSILON); } // \ru Не равные радиусы \en Not equal radii + /** \brief \ru Скругление не круговое. + \en Fillet isn't circular. \~ + \details \ru Скругление не круговое. + \en Fillet isn't circular. \~ + \return \ru true, если радиусы скруглений для поверхностей не равны + \en True if surfaces fillet radii aren't equal \~ + */ + bool IsEllipse() const { return (fabs(fabs(distance1) - fabs(distance2))>=LENGTH_EPSILON); } // \ru Не равные радиусы \en Not equal radii - /// \ru Параметризация по дуге равномерная. \en Uniform arc length parameterization. - bool IsEven() const { return even; } + /// \ru Параметризация по дуге равномерная. \en Uniform arc length parameterization. + bool IsEven() const { return even; } - /** \brief \ru Однородная ли поверхность скругления. - \en Whether the fillet surface is homogeneous. \~ - \details \ru Однородная ли поверхность скругления. Поверхность скругления без сохранения кромки. - \en Whether the fillet surface is homogeneous. Fillet surface without preservation of fillet. \~ - \return \ru false, если одна из кривых curve1 или curve2 является кромкой - \en False if one of curve1 or curve2 curves is fillet \~ - */ - bool IsFilletSurface() const { return equable; } + /** \brief \ru Однородная ли поверхность скругления. + \en Whether the fillet surface is homogeneous. \~ + \details \ru Однородная ли поверхность скругления. Поверхность скругления без сохранения кромки. + \en Whether the fillet surface is homogeneous. Fillet surface without preservation of fillet. \~ + \return \ru false, если одна из кривых curve1 или curve2 является кромкой + \en False if one of curve1 or curve2 curves is fillet \~ + */ + bool IsFilletSurface() const { return equable; } - /** \brief \ru Коническое сечение общего вида. - \en General conic section. \~ - \details \ru Коническое сечение общего вида. - \en General conic section. \~ - \return \ru false, если сечение поверхности скругления является дугой окружности - \en False if section of fillet surface is circular arc \~ - */ - bool IsConic() const { return ( ::fabs(conic - c3d::_ARC_) >= EPSILON ); } // \ru Коническое сечение общего вида \en General conic section + /** \brief \ru Коническое сечение общего вида. + \en General conic section. \~ + \details \ru Коническое сечение общего вида. + \en General conic section. \~ + \return \ru false, если сечение поверхности скругления является дугой окружности + \en False if section of fillet surface is circular arc \~ + */ + bool IsConic() const { return ( ::fabs(conic - c3d::_ARC_) >= EPSILON ); } // \ru Коническое сечение общего вида \en General conic section - /** \brief \ru Коэффициент формы. - \en Coefficient of shape. \~ - \details \ru Коэффициент формы сечения поверхности скругления.\n - Изменяется от 0.05 до 0.95, при 0 сечение является дугой окружности. - \en Coefficient of shape of section of fillet surface.\n - Is changed between 0.05 and 0.95, if 0, then section is circular arc. \~ - \return \ru Коэффициент - \en Coefficient \~ - */ - double Conic() const { return conic; } + /** \brief \ru Коэффициент формы. + \en Coefficient of shape. \~ + \details \ru Коэффициент формы сечения поверхности скругления.\n + Изменяется от 0.05 до 0.95, при 0 сечение является дугой окружности. + \en Coefficient of shape of section of fillet surface.\n + Is changed between 0.05 and 0.95, if 0, then section is circular arc. \~ + \return \ru Коэффициент + \en Coefficient \~ + */ + double Conic() const { return conic; } - /** \brief \ru Поверхность скругления с сохранением кромки. - \en Fillet surface with preservation of fillet. \~ - \details \ru Поверхность скругления с сохранением кромки. - \en Fillet surface with preservation of fillet. \~ - \return \ru true, если одна из кривых curve1 или curve2 является кромкой - \en True if one of curve1 or curve2 curves is fillet \~ - */ - bool IsKerbSurface() const { return !equable; } + /** \brief \ru Поверхность скругления с сохранением кромки. + \en Fillet surface with preservation of fillet. \~ + \details \ru Поверхность скругления с сохранением кромки. + \en Fillet surface with preservation of fillet. \~ + \return \ru true, если одна из кривых curve1 или curve2 является кромкой + \en True if one of curve1 or curve2 curves is fillet \~ + */ + bool IsKerbSurface() const { return !equable; } - /** \brief \ru Является ли первая кривая кромкой. - \en Whether the first curve is fillet. \~ - \details \ru Является ли первая кривая кромкой. - \en Whether the first curve is fillet. \~ - \return \ru true, если первая кривая является кромкой - \en True if the first curve is fillet. \~ - */ - bool ByFirstCurve() const { return byCurve1; } + /** \brief \ru Является ли первая кривая кромкой. + \en Whether the first curve is fillet. \~ + \details \ru Является ли первая кривая кромкой. + \en Whether the first curve is fillet. \~ + \return \ru true, если первая кривая является кромкой + \en True if the first curve is fillet. \~ + */ + bool ByFirstCurve() const { return byCurve1; } - /** \brief \ru Установить поверхность скругления типа с сохранением кромки. - \en Set fillet surface with preservation of fillet. - Need to call this->Init0() after this method \~ - \details \ru Установить поверхность скругления с сохранением кромки и указать определяющую кривую на поверхности. - Далее нужно вызвать метод this->Init0(). - \en Set fillet surface with preservation of fillet. \~ - \param[in] bc1 - \ru Определяющая кривая на поверхности: curve1 (bc1 = true), curve2 (bc1 = false). - \en General curve on surface: curve1 (bc1 = true), curve2 (bc1 = false). \~ - */ - void SetKerbSurface( bool bc1 ) { if ( equable ) { equable = false; byCurve1 = bc1; } } + /** \brief \ru Установить поверхность скругления типа с сохранением кромки. + \en Set fillet surface with preservation of fillet. + Need to call this->Init0() after this method \~ + \details \ru Установить поверхность скругления с сохранением кромки и указать определяющую кривую на поверхности. + Далее нужно вызвать метод this->Init0(). + \en Set fillet surface with preservation of fillet. \~ + \param[in] bc1 - \ru Определяющая кривая на поверхности: curve1 (bc1 = true), curve2 (bc1 = false). + \en General curve on surface: curve1 (bc1 = true), curve2 (bc1 = false). \~ + */ + void SetKerbSurface( bool bc1 ) { if ( equable ) { equable = false; byCurve1 = bc1; } } - // \ru Выдать функцию весов точек средней кривой curve0. \en Get weight function for points of mid-curve (curve0). - const MbFunction * GetWeights() const; - // \ru Установить функцию весов точек средней кривой curve0. \en Set weight function for points of mid-curve (curve0). - bool SetWeights( MbFunction & func ); + // \ru Выдать функцию весов точек средней кривой curve0. \en Get weight function for points of mid-curve (curve0). + const MbFunction * GetWeights() const; + // \ru Установить функцию весов точек средней кривой curve0. \en Set weight function for points of mid-curve (curve0). +bool SetWeights( MbFunction & func ); - MbCurve3D * GetSpine() const; - void SetSpine( MbCurve3D * ); + MbCurve3D * GetSpine() const; + void SetSpine( MbCurve3D * ); /** \} */ protected: - void WeightKoefficient( double & w ) const; // \ru Вычисление веса при заданном коэффициенте \en Calculation of weight at given coefficient - void InitFilletSurface ( const MbFilletSurface & init ); - void CalculateCurve( double wmin, double wmax, bool insertPoints ); - double CalculateVParam( const MbCartPoint3D & p, double u ) const; // \ru Нахождение параметра v проекции точки на вырожденную поверхность \en Searching of v parameter of point projection onto degenerate surface + void WeightKoefficient( double & w ) const; // \ru Вычисление веса при заданном коэффициенте \en Calculation of weight at given coefficient + void InitFilletSurface ( const MbFilletSurface & init ); + void CalculateCurve( double wmin, double wmax, bool insertPoints ); + double CalculateVParam( const MbCartPoint3D & p, double u ) const; // \ru Нахождение параметра v проекции точки на вырожденную поверхность \en Searching of v parameter of point projection onto degenerate surface protected: - // \ru Вычисление точки \en Calculation of a point -// void CalculateSurface( double u ) const; + // \ru Вычисление точки \en Calculation of a point +// void CalculateSurface( double u ) const; // \ru Дать коэффициент для радиуса \en Get coefficient for radius virtual double FunctionValue( double u ) const; - void CalculateData ( double & u, double & v, - MbCartPoint3D & uPoint0, MbCartPoint3D & uPoint1, MbCartPoint3D & uPoint2, // \ru Точки на кривых curve0, curve1, curve2. \en Points on curve0, curve1, curve2. - MbVector3D * uFirst0, MbVector3D * uFirst1, MbVector3D * uFirst2, // \ru Производные кривых curve0, curve1, curve2. \en Derivatives of curve0, curve1, curve2. - MbVector3D * uSecond0, MbVector3D * uSecond1, MbVector3D * uSecond2, // \ru Производные кривых curve0, curve1, curve2. \en Derivatives of curve0, curve1, curve2. - double & uWeight, double * wFirst, double * wSecond, // \ru Вес и его производные средней точки uPoint0. \en The weight and it derivatives of the mid-point uPoint0. - double & uP0, double & uP1, double & uP2, double & uPw, // \ru Коэффициенты точек uPoint0, uPoint1, uPoint2. \en Coefficients of points uPoint0, uPoint1, uPoint2. - double & uF0, double & uF1, double & uF2, double & uFw ) const; // \ru Коэффициенты производных uFirst0, uFirst1, uFirst2. \en Coefficients of derivatives uFirst0, uFirst1, uFirst2. - void InitSpineDerives(); - void CalculatePointOn ( double & v, - const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, - const double & uWeight, - const double & uP0, const double & uP1, const double & uP2, const double & uPw, - MbCartPoint3D & ) const; // \ru Точка на поверхности. \en The point on the surface. - void CalculateDeriveU ( double & v, - const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, - const MbVector3D & uFirst0, const MbVector3D & uFirst1, const MbVector3D & uFirst2, - const double & uWeight, const double & wFirst, - const double & uP0, const double & uP1, const double & uP2, const double & uPw, - MbVector3D & ) const; // \ru Первая производная по u. \en The first derivative with respect to u. - void CalculateDeriveV ( double & v, - const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, - const double & uWeight, - const double & uP0, const double & uP1, const double & uP2, const double & uPw, - const double & uF0, const double & uF1, const double & uF2, const double & uFw, - MbVector3D & ) const; // \ru Первая производная по v. \en The first derivative with respect to v. - void CalculateDeriveUU ( double & v, - const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, - const MbVector3D & uFirst0, const MbVector3D & uFirst1, const MbVector3D & uFirst2, - const MbVector3D & uSecond0, const MbVector3D & uSecond1, MbVector3D &uSecond2, - const double & uWeight, const double & wFirst, const double & wSecond, - const double & uP0, const double & uP1, const double & uP2, const double & uPw, - MbVector3D & ) const; // \ru Вторая производная по u. \en The second derivative with respect to u. - void CalculateDeriveVV ( double & v, - const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, - const double & uWeight, - const double & uP0, const double & uP1, const double & uP2, const double & uPw, - const double & uF0, const double & uF1, const double & uF2, const double & uFw, - MbVector3D & ) const; // \ru Вторая производная по v. \en The second derivative with respect to v. - void CalculateDeriveUV ( double & v, - const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, - const MbVector3D & uFirst0, const MbVector3D & uFirst1, const MbVector3D & uFirst2, - const double & uWeight, const double & wFirst, - const double & uP0, const double & uP1, const double & uP2, const double & uPw, - const double & uF0, const double & uF1, const double & uF2, const double & uFw, - MbVector3D & ) const; // \ru Вторая производная по uv. \en The second derivative with respect to uv. - void CalculateDeriveUUU( double & u, double & v, - const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, - const MbVector3D & uFirst0, const MbVector3D & uFirst1, const MbVector3D & uFirst2, - const MbVector3D & uSecond0, const MbVector3D & uSecond1, MbVector3D &uSecond2, - const double & uWeight, const double & wFirst, const double & wSecond, - const double & uP0, const double & uP1, const double & uP2, const double & uPw, - MbVector3D & ) const; - void CalculateDeriveUUV( double & v, - const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, - const MbVector3D & uFirst0, const MbVector3D & uFirst1, const MbVector3D & uFirst2, - const MbVector3D & uSecond0, const MbVector3D & uSecond1, MbVector3D &uSecond2, - const double & uWeight, const double & wFirst, const double & wSecond, - const double & uP0, const double & uP1, const double & uP2, const double & uPw, - const double & uF0, const double & uF1, const double & uF2, const double & uFw, - MbVector3D & ) const; - void CalculateDeriveUVV( double & v, - const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, - const MbVector3D & uFirst0, const MbVector3D & uFirst1, const MbVector3D & uFirst2, - const double & uWeight, const double & wFirst, - const double & uP0, const double & uP1, const double & uP2, const double & uPw, - const double & uF0, const double & uF1, const double & uF2, const double & uFw, - MbVector3D & ) const; - void CalculateDeriveVVV( double & v, - const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, - const double & uWeight, - const double & uP0, const double & uP1, const double & uP2, const double & uPw, - const double & uF0, const double & uF1, const double & uF2, const double & uFw, - MbVector3D & ) const; - void CalculateNormal ( double & u, double & v, - const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, - const MbVector3D & uFirst0, const MbVector3D & uFirst1, const MbVector3D & uFirst2, - const double & uWeight, const double & wFirst, - const double & uP0, const double & uP1, const double & uP2, const double & uPw, - const double & uF0, const double & uF1, const double & uF2, const double & uFw, - MbVector3D & ) const; // \ru Нормаль. \en Normal. - void CalculateNormalU ( double & u, double & v, - const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, - const MbVector3D & uFirst0, const MbVector3D & uFirst1, const MbVector3D & uFirst2, - const MbVector3D & uSecond0, const MbVector3D & uSecond1, MbVector3D &uSecond2, - const double & uWeight, const double & wFirst, const double & wSecond, - const double & uP0, const double & uP1, const double & uP2, const double & uPw, - const double & uF0, const double & uF1, const double & uF2, const double & uFw, - MbVector3D & ) const; // \ru Производная нормали. \en The derivative of normal. - void CalculateNormalV ( double & u, double & v, - const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, - const MbVector3D & uFirst0, const MbVector3D & uFirst1, const MbVector3D & uFirst2, - const double & uWeight, const double & wFirst, - const double & uP0, const double & uP1, const double & uP2, const double & uPw, - const double & uF0, const double & uF1, const double & uF2, const double & uFw, - MbVector3D & ) const; // \ru Производная нормали. \en The derivative of normal. + void CalculateData ( double & u, double & v, + MbCartPoint3D & uPoint0, MbCartPoint3D & uPoint1, MbCartPoint3D & uPoint2, // \ru Точки на кривых curve0, curve1, curve2. \en Points on curve0, curve1, curve2. + MbVector3D * uFirst0, MbVector3D * uFirst1, MbVector3D * uFirst2, // \ru Производные кривых curve0, curve1, curve2. \en Derivatives of curve0, curve1, curve2. + MbVector3D * uSecond0, MbVector3D * uSecond1, MbVector3D * uSecond2, // \ru Производные кривых curve0, curve1, curve2. \en Derivatives of curve0, curve1, curve2. + double & uWeight, double * wFirst, double * wSecond, // \ru Вес и его производные средней точки uPoint0. \en The weight and it derivatives of the mid-point uPoint0. + double & uP0, double & uP1, double & uP2, double & uPw, // \ru Коэффициенты точек uPoint0, uPoint1, uPoint2. \en Coefficients of points uPoint0, uPoint1, uPoint2. + double & uF0, double & uF1, double & uF2, double & uFw ) const; // \ru Коэффициенты производных uFirst0, uFirst1, uFirst2. \en Coefficients of derivatives uFirst0, uFirst1, uFirst2. + void InitSpineDerives(); + void CalculatePointOn ( double & v, + const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, + const double & uWeight, + const double & uP0, const double & uP1, const double & uP2, const double & uPw, + MbCartPoint3D & ) const; // \ru Точка на поверхности. \en The point on the surface. + void CalculateDeriveU ( double & v, + const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, + const MbVector3D & uFirst0, const MbVector3D & uFirst1, const MbVector3D & uFirst2, + const double & uWeight, const double & wFirst, + const double & uP0, const double & uP1, const double & uP2, const double & uPw, + MbVector3D & ) const; // \ru Первая производная по u. \en The first derivative with respect to u. + void CalculateDeriveV ( double & v, + const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, + const double & uWeight, + const double & uP0, const double & uP1, const double & uP2, const double & uPw, + const double & uF0, const double & uF1, const double & uF2, const double & uFw, + MbVector3D & ) const; // \ru Первая производная по v. \en The first derivative with respect to v. + void CalculateDeriveUU ( double & v, + const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, + const MbVector3D & uFirst0, const MbVector3D & uFirst1, const MbVector3D & uFirst2, + const MbVector3D & uSecond0, const MbVector3D & uSecond1, MbVector3D &uSecond2, + const double & uWeight, const double & wFirst, const double & wSecond, + const double & uP0, const double & uP1, const double & uP2, const double & uPw, + MbVector3D & ) const; // \ru Вторая производная по u. \en The second derivative with respect to u. + void CalculateDeriveVV ( double & v, + const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, + const double & uWeight, + const double & uP0, const double & uP1, const double & uP2, const double & uPw, + const double & uF0, const double & uF1, const double & uF2, const double & uFw, + MbVector3D & ) const; // \ru Вторая производная по v. \en The second derivative with respect to v. + void CalculateDeriveUV ( double & v, + const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, + const MbVector3D & uFirst0, const MbVector3D & uFirst1, const MbVector3D & uFirst2, + const double & uWeight, const double & wFirst, + const double & uP0, const double & uP1, const double & uP2, const double & uPw, + const double & uF0, const double & uF1, const double & uF2, const double & uFw, + MbVector3D & ) const; // \ru Вторая производная по uv. \en The second derivative with respect to uv. + void CalculateDeriveUUU( double & u, double & v, + const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, + const MbVector3D & uFirst0, const MbVector3D & uFirst1, const MbVector3D & uFirst2, + const MbVector3D & uSecond0, const MbVector3D & uSecond1, MbVector3D &uSecond2, + const double & uWeight, const double & wFirst, const double & wSecond, + const double & uP0, const double & uP1, const double & uP2, const double & uPw, + MbVector3D & ) const; + void CalculateDeriveUUV( double & v, + const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, + const MbVector3D & uFirst0, const MbVector3D & uFirst1, const MbVector3D & uFirst2, + const MbVector3D & uSecond0, const MbVector3D & uSecond1, MbVector3D &uSecond2, + const double & uWeight, const double & wFirst, const double & wSecond, + const double & uP0, const double & uP1, const double & uP2, const double & uPw, + const double & uF0, const double & uF1, const double & uF2, const double & uFw, + MbVector3D & ) const; + void CalculateDeriveUVV( double & v, + const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, + const MbVector3D & uFirst0, const MbVector3D & uFirst1, const MbVector3D & uFirst2, + const double & uWeight, const double & wFirst, + const double & uP0, const double & uP1, const double & uP2, const double & uPw, + const double & uF0, const double & uF1, const double & uF2, const double & uFw, + MbVector3D & ) const; + void CalculateDeriveVVV( double & v, + const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, + const double & uWeight, + const double & uP0, const double & uP1, const double & uP2, const double & uPw, + const double & uF0, const double & uF1, const double & uF2, const double & uFw, + MbVector3D & ) const; + void CalculateNormal ( double & u, double & v, + const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, + const MbVector3D & uFirst0, const MbVector3D & uFirst1, const MbVector3D & uFirst2, + const double & uWeight, const double & wFirst, + const double & uP0, const double & uP1, const double & uP2, const double & uPw, + const double & uF0, const double & uF1, const double & uF2, const double & uFw, + MbVector3D & ) const; // \ru Нормаль. \en Normal. + void CalculateNormalU ( double & u, double & v, + const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, + const MbVector3D & uFirst0, const MbVector3D & uFirst1, const MbVector3D & uFirst2, + const MbVector3D & uSecond0, const MbVector3D & uSecond1, MbVector3D &uSecond2, + const double & uWeight, const double & wFirst, const double & wSecond, + const double & uP0, const double & uP1, const double & uP2, const double & uPw, + const double & uF0, const double & uF1, const double & uF2, const double & uFw, + MbVector3D & ) const; // \ru Производная нормали. \en The derivative of normal. + void CalculateNormalV ( double & u, double & v, + const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, + const MbVector3D & uFirst0, const MbVector3D & uFirst1, const MbVector3D & uFirst2, + const double & uWeight, const double & wFirst, + const double & uP0, const double & uP1, const double & uP2, const double & uPw, + const double & uF0, const double & uF1, const double & uF2, const double & uFw, + MbVector3D & ) const; // \ru Производная нормали. \en The derivative of normal. - // \ru Проверка параметров. \en Check parameters. - void CheckUParam( double & u ) const; - void CheckVParam( double & v ) const; + // \ru Проверка параметров. \en Check parameters. + void CheckUParam( double & u ) const; + void CheckVParam( double & v ) const; - void operator = ( const MbFilletSurface & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbFilletSurface & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbFilletSurface ) }; // MbFilletSurface - IMPL_PERSISTENT_OPS( MbFilletSurface ) diff --git a/C3d/Include/surf_gregory_surface.h b/C3d/Include/surf_gregory_surface.h index f20dda9..1dbbd33 100644 --- a/C3d/Include/surf_gregory_surface.h +++ b/C3d/Include/surf_gregory_surface.h @@ -152,8 +152,8 @@ public: \en \name Functions for get of the group of data inside and outside the surface's domain of parameters. \{ */ void Explore( double & u, double & v, bool ext, - MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, - MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; + MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, + MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; /** \} */ /** \ru \name Функции движения по поверхности. @@ -173,33 +173,31 @@ public: /** \} */ private: - // \ru Проверить параметры и в случае выхода за пределы загнать в область определения. - // \en Check parameters and if it is out of limits, then move it to domain. - void CheckParams( double & u, double & v ) const; - // \ru Проверить параметры и в случае захода за полюс или выходе за период загнать в область определения. - // \en Check parameters and if it is out of pole or it is out of period, then drive it to the domain region. - void CheckParamsEx( double & u, double & v ) const; + // \ru Проверить параметры и в случае выхода за пределы загнать в область определения. // \en Check parameters and if it is out of limits, then move it to domain. + void CheckParams( double & u, double & v ) const; + // \ru Проверить параметры и в случае захода за полюс или выходе за период загнать в область определения. // \en Check parameters and if it is out of pole or it is out of period, then drive it to the domain region. + void CheckParamsEx( double & u, double & v ) const; - // \ru Определить местные координаты области поверхности. \en Determine local coordinates of surface region. - void LocalCoordinate( double u, double v, double & ul, double & vl, size_t & i, MbTriWorkingData * pd ) const; - // \ru Вычислить вспомогательные векторы производных в узлах кривых. \en Calculate auxiliary vectors of derivatives at nodes of curves. - void CalculateVertex( const size_t & i, MbTriWorkingData * pd ) const; - // \ru Вычислить вспомогательные вектора производных вдоль кривых патча. \en Calculate auxiliary vectors of derivatives along curves of patch. - void CalculateAlong0( const double & ul, const double & vl, const size_t & patch, MbTriWorkingData * pd ) const; - void CalculateAlong1( const double & ul, const size_t & patch, MbTriWorkingData * pd ) const; - void CalculateAlong2( const double & vl, const size_t & patch, MbTriWorkingData * pd ) const; - // \ru Производные в локальных координатах. \en Derivatives in the local coordinates. - void DerU ( const double & ul, const double & vl, MbTriWorkingData * pd, MbVector3D & vect ) const; // \ru Первая производная по u. \en First derivative with respect to u. - void DerV ( const double & ul, const double & vl, MbTriWorkingData * pd, MbVector3D & vect ) const; // \ru Первая производная по v. \en First derivative with respect to v. - void DerUU ( const double & ul, const double & vl, MbTriWorkingData * pd, MbVector3D & vect ) const; // \ru Вторая производная по u. \en Second derivative with respect to u. - void DerVV ( const double & ul, const double & vl, MbTriWorkingData * pd, MbVector3D & vect ) const; // \ru Вторая производная по v. \en Second derivative with respect to v. - void DerUV ( const double & ul, const double & vl, MbTriWorkingData * pd, MbVector3D & vect ) const; // \ru Вторая производная по uv. \en Second derivative with respect to uv. - void DerUUU( const double & ul, const double & vl, MbTriWorkingData * pd, MbVector3D & vect ) const; // \ru Третья производная. \en Third derivative. - void DerUUV( const double & ul, const double & vl, MbTriWorkingData * pd, MbVector3D & vect ) const; // \ru Третья производная. \en Third derivative. - void DerUVV( const double & ul, const double & vl, MbTriWorkingData * pd, MbVector3D & vect ) const; // \ru Третья производная. \en Third derivative. - void DerVVV( const double & ul, const double & vl, MbTriWorkingData * pd, MbVector3D & vect ) const; // \ru Третья производная. \en Third derivative. - // \ru Вычислить нормаль. \en Normal calculation. - void ExactNormal( double u, double v, const MbVector3D & derU, const MbVector3D & derV, MbVector3D & norm ) const; + // \ru Определить местные координаты области поверхности. \en Determine local coordinates of surface region. + void LocalCoordinate( double u, double v, double & ul, double & vl, size_t & i, MbTriWorkingData * pd ) const; + // \ru Вычислить вспомогательные векторы производных в узлах кривых. \en Calculate auxiliary vectors of derivatives at nodes of curves. + void CalculateVertex( const size_t & i, MbTriWorkingData * pd ) const; + // \ru Вычислить вспомогательные вектора производных вдоль кривых патча. \en Calculate auxiliary vectors of derivatives along curves of patch. + void CalculateAlong0( const double & ul, const double & vl, const size_t & patch, MbTriWorkingData * pd ) const; + void CalculateAlong1( const double & ul, const size_t & patch, MbTriWorkingData * pd ) const; + void CalculateAlong2( const double & vl, const size_t & patch, MbTriWorkingData * pd ) const; + // \ru Производные в локальных координатах. \en Derivatives in the local coordinates. + void DerU ( const double & ul, const double & vl, MbTriWorkingData * pd, MbVector3D & vect ) const; // \ru Первая производная по u. \en First derivative with respect to u. + void DerV ( const double & ul, const double & vl, MbTriWorkingData * pd, MbVector3D & vect ) const; // \ru Первая производная по v. \en First derivative with respect to v. + void DerUU ( const double & ul, const double & vl, MbTriWorkingData * pd, MbVector3D & vect ) const; // \ru Вторая производная по u. \en Second derivative with respect to u. + void DerVV ( const double & ul, const double & vl, MbTriWorkingData * pd, MbVector3D & vect ) const; // \ru Вторая производная по v. \en Second derivative with respect to v. + void DerUV ( const double & ul, const double & vl, MbTriWorkingData * pd, MbVector3D & vect ) const; // \ru Вторая производная по uv. \en Second derivative with respect to uv. + void DerUUU( const double & ul, const double & vl, MbTriWorkingData * pd, MbVector3D & vect ) const; // \ru Третья производная. \en Third derivative. + void DerUUV( const double & ul, const double & vl, MbTriWorkingData * pd, MbVector3D & vect ) const; // \ru Третья производная. \en Third derivative. + void DerUVV( const double & ul, const double & vl, MbTriWorkingData * pd, MbVector3D & vect ) const; // \ru Третья производная. \en Third derivative. + void DerVVV( const double & ul, const double & vl, MbTriWorkingData * pd, MbVector3D & vect ) const; // \ru Третья производная. \en Third derivative. + // \ru Вычислить нормаль. \en Normal calculation. + void ExactNormal( double u, double v, const MbVector3D & derU, const MbVector3D & derV, MbVector3D & norm ) const; DECLARE_PERSISTENT_CLASS_NEW_DEL( MbGregorySurface ) @@ -208,6 +206,7 @@ OBVIOUS_PRIVATE_COPY( MbGregorySurface ) IMPL_PERSISTENT_OPS( MbGregorySurface ) + //------------------------------------------------------------------------------ // \ru Проверить параметры и в случае выхода за пределы загнать в область определения. \en Check parameters and if it is out of limits, then move it to domain. // --- @@ -237,4 +236,5 @@ inline void MbGregorySurface::CheckParamsEx( double & u, double & v ) const v = 0.0; } + #endif // __SURF_GREGORY_SURFACE_H diff --git a/C3d/Include/surf_grid_surface.h b/C3d/Include/surf_grid_surface.h index 1b827db..9c64d0b 100644 --- a/C3d/Include/surf_grid_surface.h +++ b/C3d/Include/surf_grid_surface.h @@ -259,8 +259,8 @@ public: \en \name Functions for get of the group of data inside and outside the surface's domain of parameters. \{ */ void Explore( double & u, double & v, bool ext, - MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, - MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; + MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, + MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; /** \} */ // \ru Функции движения по поверхности \en Functions of moving along the surface double StepU( double u, double v, double sag ) const override; // \ru Вычисление шага аппроксимации с учетом радиуса кривизны по U \en Calculation of the approximation step with consideration of the curvature radius by U @@ -297,43 +297,43 @@ public: void CalculateSurfaceGrid( const MbStepData & stepData, bool sense, MbGrid & grid ) const override; // \ru Определение разбивки параметрической области поверхности вертикалями и горизонталями. \en Determine splitting of parametric region of surface by vertical and horizontal lines. void GetTesselation( const MbStepData & stepData, - double u1, double u2, double v1, double v2, - SArray & uu, SArray & vv ) const override; + double u1, double u2, double v1, double v2, + SArray & uu, SArray & vv ) const override; // \ru Пересчитать нормали в вершинах. \en Normals Calculation on vertex. virtual void Normalize(); - size_t GetBoundariesCount() const { return boundary.size(); } // \ru Выдать количество граничных двумерных кривых. \en Get the two-dimensional boundary curves count. + size_t GetBoundariesCount() const { return boundary.size(); } // \ru Выдать количество граничных двумерных кривых. \en Get the two-dimensional boundary curves count. MbContour & MakeContour( bool sense ) const override; // \ru Выдать граничных двумерный контур. \en Get the two-dimensional boundary contour. MbCurve & MakeSegment( size_t i, bool sense ) const override; // \ru Дать граничную двумерную кривую. \en Get the two-dimensional boundary curve. - /// \ru Инициализация объекта по другому такому же. \en Initialization of a object by same other object. - void Init( const MbGridSurface & init ); + /// \ru Инициализация объекта по другому такому же. \en Initialization of a object by same other object. + void Init( const MbGridSurface & init ); - /// \ru Выдать количество точек. \en Get the number of points. - size_t PointsCount() const { return points.size(); } - /// \ru Выдать количество нормалей. \en Get the number of normals. - size_t NormalsCount() const { return normals.size(); } - /// \ru Выдать количество параметров. \en Get the number of parameters. - size_t ParamsCount() const { return params.size(); } - // \ru Выдать количество треугольников. \en Get the number of triangles. - size_t TrianglesCount() const { return triangles.size(); } - // \ru Выдать количество граничных кривых. \en Get the number of boundary curves. - size_t BoundariesCount() const { return boundary.size(); } + /// \ru Выдать количество точек. \en Get the number of points. + size_t PointsCount() const { return points.size(); } + /// \ru Выдать количество нормалей. \en Get the number of normals. + size_t NormalsCount() const { return normals.size(); } + /// \ru Выдать количество параметров. \en Get the number of parameters. + size_t ParamsCount() const { return params.size(); } + // \ru Выдать количество треугольников. \en Get the number of triangles. + size_t TrianglesCount() const { return triangles.size(); } + // \ru Выдать количество граничных кривых. \en Get the number of boundary curves. + size_t BoundariesCount() const { return boundary.size(); } - // \ru Добавить в контейнер параметры в опорных точках поверхности. \en Get the parameters to container. - void GetParams( std::vector & paramsVector ) const; - // \ru Добавить в контейнер опорные точки. \en Get the points to container. - void GetPoints( std::vector & pointsVector ) const; - // \ru Добавить в контейнер нормали в опорных точках. \en Add the normals to container. - void GetNormals( std::vector & normalsVector ) const; - // \ru Добавить в контейнер треугольники. \en Add the triangles to container. - void GetTriangles( std::vector & tVector ) const; - // \ru Добавить в контейнер треугольники. \en Add the triangles to container. - void GetTriangles( std::vector & tVector ) const; - // \ru Добавить в контейнер граничные кривые. \en Add the boundary curves of surface parameters region. - void GetBoundaries( std::vector & bVector ) const; + // \ru Добавить в контейнер параметры в опорных точках поверхности. \en Get the parameters to container. + void GetParams( std::vector & paramsVector ) const; + // \ru Добавить в контейнер опорные точки. \en Get the points to container. + void GetPoints( std::vector & pointsVector ) const; + // \ru Добавить в контейнер нормали в опорных точках. \en Add the normals to container. + void GetNormals( std::vector & normalsVector ) const; + // \ru Добавить в контейнер треугольники. \en Add the triangles to container. + void GetTriangles( std::vector & tVector ) const; + // \ru Добавить в контейнер треугольники. \en Add the triangles to container. + void GetTriangles( std::vector & tVector ) const; + // \ru Добавить в контейнер граничные кривые. \en Add the boundary curves of surface parameters region. + void GetBoundaries( std::vector & bVector ) const; - /// \ru Создание поверхности. \en Creatying of surface. + /// \ru Создание поверхности. \en Creatying of surface. template static MbGridSurface * Create( const Params & _params , const Points & _points @@ -353,55 +353,55 @@ public: } private: - /// \ru Инициализация. \en Initialization. - void Init( bool bound = true ); - // \ru Инициализация граничных кривых. \en Initialization of boundary curves. - void MakeBoundary(); - // \ru Выдать треугольник. \en Get triangle. - MbTrigon & GetTriangle( size_t i ) { return triangles[i]; } - void PointOn ( double & u, double & v, bool ext, MbCartPoint3D & p ) const; // \ru Точка на поверхности \en Point on the surface - void DeriveU ( double & u, double & v, bool ext, MbVector3D & der ) const; // \ru Первая производная по u \en First derivative with respect to u - void DeriveV ( double & u, double & v, bool ext, MbVector3D & der ) const; // \ru Первая производная по v \en First derivative with respect to v - void DeriveUU ( double & u, double & v, bool ext, MbVector3D & der ) const; // \ru Вторая производная по u \en Second derivative with respect to u - void DeriveVV ( double & u, double & v, bool ext, MbVector3D & der ) const; // \ru Вторая производная по v \en Second derivative with respect to v - void DeriveUV ( double & u, double & v, bool ext, MbVector3D & der ) const; // \ru Вторая производная по uv \en Second derivative with respect to uv - void DeriveUUU( double & u, double & v, bool ext, MbVector3D & der ) const; // \ru Третья производная \en Third derivative - void DeriveUUV( double & u, double & v, bool ext, MbVector3D & der ) const; // \ru Третья производная \en Third derivative - void DeriveUVV( double & u, double & v, bool ext, MbVector3D & der ) const; // \ru Третья производная \en Third derivative - void DeriveVVV( double & u, double & v, bool ext, MbVector3D & der ) const; // \ru Третья производная \en Third derivative - // \ru Выставить взаимные связи триангуляции. \en Set mutual connections of triangulation. - bool SetTrigonNeihbours(); - // \ru Поиск ближайшего треугольника для инициализации данных ячейки. \en Search nearest triangle for initialization of data of cell. - void FindNearest( size_t i, size_t j, std::vector & indecies, - double uDelta, double vDelta, double u, double v ); - // \ru Добавить ближайший треугольник в ячейку. \en Add nearest triangle to cell. - bool AddNearest( size_t i, size_t j, size_t ind ); - // \ru Вычислить индекс ближайшего треугольника и барицентрические координаты точки для него. \en Calculate barycentric coordinates of the nearest trianle. - size_t FindIndex( const double & u, const double & v, double & a, double & b, double & c, double & d ) const; - // \ru Расстояние до треугольника. \en The distance to a triangle. - double RangeToTriangle( size_t ind, const double & u, const double & v, double eps, - double & a, double & b, double & c, double & d ) const; - // \ru Расстояние до треугольника. \en The distance to a triangle. - double DistanceToTriangle( size_t ind, const double & u, const double & v, double eps, - MbCartPoint & p ) const; - // \ru Проверка параметров. \en Check parameters. - void CheckParam( double & u, double & v ) const; - // \ru Выдать данные триангуляции. \en Get triangulation data. - void GetTriangleData( size_t tIndex, - size_t & index1, size_t & index2, size_t & index3, - size_t & neigh1, size_t & neigh2, size_t & neigh3, - MbCartPoint & param1, MbCartPoint & param2, MbCartPoint & param3, - MbCartPoint3D & point1, MbCartPoint3D & point2, MbCartPoint3D & point3, - MbVector3D & normal1, MbVector3D & normal2, MbVector3D & normal3 ) const; - // \ru Выдать данные триангуляции соседнего треугольника. \en Get neighbour triangulation data. - bool GetNeighbourData( double u, double v, - size_t neigh1, size_t neigh2, size_t neigh3, - double & aCalc, double & bCalc, double & cCalc, double & deter, double & portion, - MbCartPoint & param1, MbCartPoint & param2, MbCartPoint & param3, - MbCartPoint3D & point1, MbCartPoint3D & point2, MbCartPoint3D & point3, - MbVector3D & normal1, MbVector3D & normal2, MbVector3D & normal3 ) const; - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbGridSurface & ); + /// \ru Инициализация. \en Initialization. + void Init( bool bound = true ); + // \ru Инициализация граничных кривых. \en Initialization of boundary curves. + void MakeBoundary(); + // \ru Выдать треугольник. \en Get triangle. + MbTrigon & GetTriangle( size_t i ) { return triangles[i]; } + void PointOn ( double & u, double & v, bool ext, MbCartPoint3D & p ) const; // \ru Точка на поверхности \en Point on the surface + void DeriveU ( double & u, double & v, bool ext, MbVector3D & der ) const; // \ru Первая производная по u \en First derivative with respect to u + void DeriveV ( double & u, double & v, bool ext, MbVector3D & der ) const; // \ru Первая производная по v \en First derivative with respect to v + void DeriveUU ( double & u, double & v, bool ext, MbVector3D & der ) const; // \ru Вторая производная по u \en Second derivative with respect to u + void DeriveVV ( double & u, double & v, bool ext, MbVector3D & der ) const; // \ru Вторая производная по v \en Second derivative with respect to v + void DeriveUV ( double & u, double & v, bool ext, MbVector3D & der ) const; // \ru Вторая производная по uv \en Second derivative with respect to uv + void DeriveUUU( double & u, double & v, bool ext, MbVector3D & der ) const; // \ru Третья производная \en Third derivative + void DeriveUUV( double & u, double & v, bool ext, MbVector3D & der ) const; // \ru Третья производная \en Third derivative + void DeriveUVV( double & u, double & v, bool ext, MbVector3D & der ) const; // \ru Третья производная \en Third derivative + void DeriveVVV( double & u, double & v, bool ext, MbVector3D & der ) const; // \ru Третья производная \en Third derivative + // \ru Выставить взаимные связи триангуляции. \en Set mutual connections of triangulation. + bool SetTrigonNeihbours(); + // \ru Поиск ближайшего треугольника для инициализации данных ячейки. \en Search nearest triangle for initialization of data of cell. + void FindNearest( size_t i, size_t j, std::vector & indecies, + double uDelta, double vDelta, double u, double v ); + // \ru Добавить ближайший треугольник в ячейку. \en Add nearest triangle to cell. + bool AddNearest( size_t i, size_t j, size_t ind ); + // \ru Вычислить индекс ближайшего треугольника и барицентрические координаты точки для него. \en Calculate barycentric coordinates of the nearest trianle. + size_t FindIndex( const double & u, const double & v, double & a, double & b, double & c, double & d ) const; + // \ru Расстояние до треугольника. \en The distance to a triangle. + double RangeToTriangle( size_t ind, const double & u, const double & v, double eps, + double & a, double & b, double & c, double & d ) const; + // \ru Расстояние до треугольника. \en The distance to a triangle. + double DistanceToTriangle( size_t ind, const double & u, const double & v, double eps, + MbCartPoint & p ) const; + // \ru Проверка параметров. \en Check parameters. + void CheckParam( double & u, double & v ) const; + // \ru Выдать данные триангуляции. \en Get triangulation data. + void GetTriangleData( size_t tIndex, + size_t & index1, size_t & index2, size_t & index3, + size_t & neigh1, size_t & neigh2, size_t & neigh3, + MbCartPoint & param1, MbCartPoint & param2, MbCartPoint & param3, + MbCartPoint3D & point1, MbCartPoint3D & point2, MbCartPoint3D & point3, + MbVector3D & normal1, MbVector3D & normal2, MbVector3D & normal3 ) const; + // \ru Выдать данные триангуляции соседнего треугольника. \en Get neighbour triangulation data. + bool GetNeighbourData( double u, double v, + size_t neigh1, size_t neigh2, size_t neigh3, + double & aCalc, double & bCalc, double & cCalc, double & deter, double & portion, + MbCartPoint & param1, MbCartPoint & param2, MbCartPoint & param3, + MbCartPoint3D & point1, MbCartPoint3D & point2, MbCartPoint3D & point3, + MbVector3D & normal1, MbVector3D & normal2, MbVector3D & normal3 ) const; + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbGridSurface & ); DECLARE_PERSISTENT_CLASS_NEW_DEL( MbGridSurface ) }; // MbGridSurface diff --git a/C3d/Include/surf_join_surface.h b/C3d/Include/surf_join_surface.h index f655672..c3e6cdd 100644 --- a/C3d/Include/surf_join_surface.h +++ b/C3d/Include/surf_join_surface.h @@ -87,8 +87,8 @@ private: void CreateVars(); void InitVars (); void FreeVars (); - private: - void operator = ( const MbJoinSurfaceAuxiliaryData & ); + private: + void operator = ( const MbJoinSurfaceAuxiliaryData & ); }; mutable CacheManager cache; @@ -160,60 +160,63 @@ public: VISITING_CLASS( MbJoinSurface ); public: - /** \brief \ru Инициализация поверхности соединения. - \en Initialization of surface of the joint. \~ - \details \ru Инициализация поверхности соединения по набору кривых. Кривые должны быть непересекающиеся.\n - Этот факт в функции не проверяется. Порядок поверхности не изменяется. - \en Initialization of surface of the joint by set of curves. Curves shouldn't be intersected.\n - This fact isn't checked in the function. Surface order doesn't changed. \~ - \param[in] initCurves - \ru Список кривых, на которых натягивается поверхность. - \en List of of curves which the surface is tensed on. \~ - \param[in] sameCurves - \ru Определяет, надо ли делать копии кривых:\n - true - использовать в объекте пришедшие в конструктор кривые не дублируя,\n - false - использовать копии кривых. - \en Determines whether to copy curves:\n - true - use curves given in the constructor in object without copying,\n - false - use copies of curves. \~ - */ - void Init( const RPArray & initCurves, bool sameCurves ); - /** \brief \ru Инициализация поверхности соединения. - \en Initialization of surface of the joint. \~ - \details \ru Инициализация поверхности соединения по набору кривых и порядку поверхности. Кривые должны быть непересекающиеся.\n - Этот факт в функции не проверяется. Порядок поверхности не изменяется. - \en Initialization of surface of the joint by set of curves and order of surface. Curves shouldn't be intersected.\n - This fact isn't checked in the function. Surface order doesn't changed. \~ - \param[in] initCurves - \ru Список кривых, на которых натягивается поверхность. - \en List of of curves which the surface is tensed on. \~ - \param[in] initDegree - \ru Порядок поверхности по v.\n - \en Surface order by v.\n \~ - \param[in] sameCurves - \ru Определяет, надо ли делать копии кривых:\n - true - использовать в объекте пришедшие в конструктор кривые не дублируя,\n - false - использовать копии кривых. - \en Determines whether to copy curves:\n - true - use curves given in the constructor in object without copying,\n - false - use copies of curves. \~ - */ - bool Init( const RPArray & initCurves, ptrdiff_t initDegree, bool sameCurves ); - /** \brief \ru Инициализация поверхности соединения. - \en Initialization of surface of the joint. \~ - \details \ru Инициализация поверхности соединения по набору кривых, порядку поверхности и узловому вектору.\n - Кривые должны быть непересекающиеся. Этот факт в функции не проверяется. Порядок поверхности не изменяется. - \en Initialization of surface of the joint by set of curves, order of surface and knot vector.\n - Curves shouldn't be intersected. This fact isn't checked in the function. Surface order doesn't changed. \~ - \param[in] initCurves - \ru Список кривых, на которых натягивается поверхность. - \en List of of curves which the surface is tensed on. \~ - \param[in] initDegree - \ru Порядок поверхности по v. - \en Surface order by v. \~ - \param[in] initKnots - \ru Узловой вектор по v. - \en A knot vector by v. \~ - \param[in] sameCurves - \ru Определяет, надо ли делать копии кривых:\n - true - использовать в объекте пришедшие в конструктор кривые не дублируя,\n - false - использовать копии кривых. - \en Determines whether to copy curves:\n - true - use curves given in the constructor in object without copying,\n - false - use copies of curves. \~ - */ - bool Init( const RPArray & initCurves, ptrdiff_t initDegree, const SArray & initKnots, bool sameCurves ); + + /** \brief \ru Инициализация поверхности соединения. + \en Initialization of surface of the joint. \~ + \details \ru Инициализация поверхности соединения по набору кривых. Кривые должны быть непересекающиеся.\n + Этот факт в функции не проверяется. Порядок поверхности не изменяется. + \en Initialization of surface of the joint by set of curves. Curves shouldn't be intersected.\n + This fact isn't checked in the function. Surface order doesn't changed. \~ + \param[in] initCurves - \ru Список кривых, на которых натягивается поверхность. + \en List of of curves which the surface is tensed on. \~ + \param[in] sameCurves - \ru Определяет, надо ли делать копии кривых:\n + true - использовать в объекте пришедшие в конструктор кривые не дублируя,\n + false - использовать копии кривых. + \en Determines whether to copy curves:\n + true - use curves given in the constructor in object without copying,\n + false - use copies of curves. \~ + */ + + void Init( const RPArray & initCurves, bool sameCurves ); + /** \brief \ru Инициализация поверхности соединения. + \en Initialization of surface of the joint. \~ + \details \ru Инициализация поверхности соединения по набору кривых и порядку поверхности. Кривые должны быть непересекающиеся.\n + Этот факт в функции не проверяется. Порядок поверхности не изменяется. + \en Initialization of surface of the joint by set of curves and order of surface. Curves shouldn't be intersected.\n + This fact isn't checked in the function. Surface order doesn't changed. \~ + \param[in] initCurves - \ru Список кривых, на которых натягивается поверхность. + \en List of of curves which the surface is tensed on. \~ + \param[in] initDegree - \ru Порядок поверхности по v.\n + \en Surface order by v.\n \~ + \param[in] sameCurves - \ru Определяет, надо ли делать копии кривых:\n + true - использовать в объекте пришедшие в конструктор кривые не дублируя,\n + false - использовать копии кривых. + \en Determines whether to copy curves:\n + true - use curves given in the constructor in object without copying,\n + false - use copies of curves. \~ + */ + bool Init( const RPArray & initCurves, ptrdiff_t initDegree, bool sameCurves ); + + /** \brief \ru Инициализация поверхности соединения. + \en Initialization of surface of the joint. \~ + \details \ru Инициализация поверхности соединения по набору кривых, порядку поверхности и узловому вектору.\n + Кривые должны быть непересекающиеся. Этот факт в функции не проверяется. Порядок поверхности не изменяется. + \en Initialization of surface of the joint by set of curves, order of surface and knot vector.\n + Curves shouldn't be intersected. This fact isn't checked in the function. Surface order doesn't changed. \~ + \param[in] initCurves - \ru Список кривых, на которых натягивается поверхность. + \en List of of curves which the surface is tensed on. \~ + \param[in] initDegree - \ru Порядок поверхности по v. + \en Surface order by v. \~ + \param[in] initKnots - \ru Узловой вектор по v. + \en A knot vector by v. \~ + \param[in] sameCurves - \ru Определяет, надо ли делать копии кривых:\n + true - использовать в объекте пришедшие в конструктор кривые не дублируя,\n + false - использовать копии кривых. + \en Determines whether to copy curves:\n + true - use curves given in the constructor in object without copying,\n + false - use copies of curves. \~ + */ + bool Init( const RPArray & initCurves, ptrdiff_t initDegree, const SArray & initKnots, bool sameCurves ); /** \ru \name Общие функции геометрического объекта \en \name Common functions of a geometric object @@ -293,8 +296,8 @@ public: \en \name Functions for get of the group of data inside and outside the surface's domain of parameters. \{ */ void Explore( double & u, double & v, bool ext, - MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, - MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; + MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, + MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; /** \} */ /** \ru \name Функции движения по поверхности @@ -318,80 +321,82 @@ public: MbSurface * NurbsSurface( const MbNurbsParameters & uParam, const MbNurbsParameters & vParam ) const override; MbSurface * Offset( double d, bool same ) const override; // \ru Построить смещенную поверхность \en Create a shifted surface - /// \ru Изменение степени NURBS кривой по v. \en Change degree of NURBS curve by v. - void ChangeDegree ( ptrdiff_t newDegree ); - /// \ru Получить количество базовых кривых. \en Get count of base curves. - size_t GetCurvesCount () const; - /// \ru Получить кривую с индeксом k. \en Get curve with 'k' index. + /// \ru Изменение степени NURBS кривой по v. \en Change degree of NURBS curve by v. + void ChangeDegree ( ptrdiff_t newDegree ); + /// \ru Получить количество базовых кривых. \en Get count of base curves. + size_t GetCurvesCount () const; + /// \ru Получить кривую с индeксом k. \en Get curve with 'k' index. const MbCurve3D * GetCurve( size_t k ) const; const SArray & GetKnots() const { return knots; } ///< \ru Получить значения узлов для сплайна по v. \en Get knot values for spline by v. - /** \brief \ru Получить список начальных или конечных базовых точек кривых. - \en Get list of start or end base points of curves. \~ - \details \ru Получить список начальных или конечных базовых точек кривых.\n - \en Get list of start or end base points of curves.\n \~ - \param[in] isFirstPoints - \ru Определяет конечные или начальные точки запрошены: true - начальные, false - конечные.\n - \en Determines start or end points were requested: true - start, false - end.\n \~ - \param[in] points - \ru Список, в который помещаются найденные точки. \n - Порядок точек соответствует порядку кривых в списке curves. - \en List to store found points. \n - Order of points corresponds to order of curves in 'curves' list. \~ - \return \ru false и список points остается пустым,\n - если хотя бы одна кривая не имеет базовых точек (не отрезок и не кривая, заданная точками). - \en False then 'points' list remains empty,\n - if at least one curve has no base points (not segment and not curve given by points). \~ - */ - bool GetCurvesBasePoints( bool isFirstPoints, SArray & points ) const; - /** \brief \ru Изменить крайние базовые точки кривых. - \en Change end base points of curves. \~ - \details \ru Базовые точки можно изменить в том случае, если все кривые, на которые натянута поверхность,\n - являются отрезками или кривыми, заданными точками. - \en Base points can be changed in case of all curves which the surface is tensed on\n - are segments or curves given by points. \~ - \param[in] isFirstPoints - \ru Определяет конечные или начальные точки запрошены: true - начальные, false - конечные.\n - \en Determines start or end points were requested: true - start, false - end.\n \~ - \param[in] points - \ru Список, в который помещаются новые значения базовых точек.\n - Порядок точек соответствует порядку кривых в списке curves. - \en List to store new values of base points.\n - Order of points corresponds to order of curves in 'curves' list. \~ - \return \ru false и список points остается пустым,\n - если хотя бы одна кривая не имеет базовых точек (не отрезок и не кривая, заданная точками). - \en False then 'points' list remains empty,\n - if at least one curve has no base points (not segment and not curve given by points). \~ - */ - bool SetCurvesBasePoints( bool isFirstPoints, SArray & points ); + /** \brief \ru Получить список начальных или конечных базовых точек кривых. + \en Get list of start or end base points of curves. \~ + \details \ru Получить список начальных или конечных базовых точек кривых.\n + \en Get list of start or end base points of curves.\n \~ + \param[in] isFirstPoints - \ru Определяет конечные или начальные точки запрошены: true - начальные, false - конечные.\n + \en Determines start or end points were requested: true - start, false - end.\n \~ + \param[in] points - \ru Список, в который помещаются найденные точки. \n + Порядок точек соответствует порядку кривых в списке curves. + \en List to store found points. \n + Order of points corresponds to order of curves in 'curves' list. \~ + \return \ru false и список points остается пустым,\n + если хотя бы одна кривая не имеет базовых точек (не отрезок и не кривая, заданная точками). + \en False then 'points' list remains empty,\n + if at least one curve has no base points (not segment and not curve given by points). \~ + */ + + bool GetCurvesBasePoints( bool isFirstPoints, SArray & points ) const; + /** \brief \ru Изменить крайние базовые точки кривых. + \en Change end base points of curves. \~ + \details \ru Базовые точки можно изменить в том случае, если все кривые, на которые натянута поверхность,\n + являются отрезками или кривыми, заданными точками. + \en Base points can be changed in case of all curves which the surface is tensed on\n + are segments or curves given by points. \~ + \param[in] isFirstPoints - \ru Определяет конечные или начальные точки запрошены: true - начальные, false - конечные.\n + \en Determines start or end points were requested: true - start, false - end.\n \~ + \param[in] points - \ru Список, в который помещаются новые значения базовых точек.\n + Порядок точек соответствует порядку кривых в списке curves. + \en List to store new values of base points.\n + Order of points corresponds to order of curves in 'curves' list. \~ + \return \ru false и список points остается пустым,\n + если хотя бы одна кривая не имеет базовых точек (не отрезок и не кривая, заданная точками). + \en False then 'points' list remains empty,\n + if at least one curve has no base points (not segment and not curve given by points). \~ + */ + bool SetCurvesBasePoints( bool isFirstPoints, SArray & points ); /** \} */ DECLARE_PERSISTENT_CLASS_NEW_DEL( MbJoinSurface ) private: - void operator = ( const MbJoinSurface & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbJoinSurface & ); // \ru Не реализовано. \en Not implemented. - void ResetTCalc(); - bool CheckData ( const SArray & newKnots, ptrdiff_t newDegree ); // \ru Проверить корректность данных для NURBS \en Check correctness of data for NURBS - void ChangeKnots ( const ptrdiff_t newDegree, const bool closed, SArray & newKnots ); // \ru Изменить массив узлов, если изменилась степень сплайна \en Change array of knots if degree of spline was changed - void CreateTempVars( MbJoinSurfaceAuxiliaryData * ucache ) const; - void InitTempVars ( MbJoinSurfaceAuxiliaryData * ucache ) const; - void FreeTempVars ( MbJoinSurfaceAuxiliaryData * ucache ) const; - void PreparePointsData( ptrdiff_t lIndex, ptrdiff_t derNum, MbJoinSurfaceAuxiliaryData * ucache ) const; - void PreparePointList ( const double u, ptrdiff_t derNumberU, MbJoinSurfaceAuxiliaryData * ucache ) const; - void CheckPointData ( const MbeSurfaceDerivativeType derUVNumber, double & u, double & v, MbVector3D & vect, MbJoinSurfaceAuxiliaryData * ucache ) const; - ptrdiff_t GetUDerNumber( const MbeSurfaceDerivativeType derUVNumber ) const; - ptrdiff_t GetVDerNumber( const MbeSurfaceDerivativeType derUVNumber ) const; - void CheckPole(); - void CheckParams ( double & u, double & v ) const; - void PoleDerive ( double u, double v, MbVector3D & vDerU, MbVector3D & vDerV ) const; - double DeviationStep( double u, double v, double angle ) const; - double StepD ( double u, double v, double sag, bool checkAngle, double angle ) const; - // \ru Вычисление точки и производных поверхности. \en Calculation of the point and derivatives of the surface. \~ - void ExploreVector( SArray & points, SArray & vectors, - ptrdiff_t lIndex, ptrdiff_t derNum, MbVector3D & vect, MbJoinSurfaceAuxiliaryData * ucache ) const; + void ResetTCalc(); + bool CheckData ( const SArray & newKnots, ptrdiff_t newDegree ); // \ru Проверить корректность данных для NURBS \en Check correctness of data for NURBS + void ChangeKnots ( const ptrdiff_t newDegree, const bool closed, SArray & newKnots ); // \ru Изменить массив узлов, если изменилась степень сплайна \en Change array of knots if degree of spline was changed + void CreateTempVars( MbJoinSurfaceAuxiliaryData * ucache ) const; + void InitTempVars ( MbJoinSurfaceAuxiliaryData * ucache ) const; + void FreeTempVars ( MbJoinSurfaceAuxiliaryData * ucache ) const; + void PreparePointsData( ptrdiff_t lIndex, ptrdiff_t derNum, MbJoinSurfaceAuxiliaryData * ucache ) const; + void PreparePointList ( const double u, ptrdiff_t derNumberU, MbJoinSurfaceAuxiliaryData * ucache ) const; + void CheckPointData ( const MbeSurfaceDerivativeType derUVNumber, double & u, double & v, MbVector3D & vect, MbJoinSurfaceAuxiliaryData * ucache ) const; + ptrdiff_t GetUDerNumber( const MbeSurfaceDerivativeType derUVNumber ) const; + ptrdiff_t GetVDerNumber( const MbeSurfaceDerivativeType derUVNumber ) const; + void CheckPole(); + void CheckParams ( double & u, double & v ) const; + void PoleDerive ( double u, double v, MbVector3D & vDerU, MbVector3D & vDerV ) const; + double DeviationStep( double u, double v, double angle ) const; + double StepD ( double u, double v, double sag, bool checkAngle, double angle ) const; + // \ru Вычисление точки и производных поверхности. \en Calculation of the point and derivatives of the surface. \~ + void ExploreVector( SArray & points, SArray & vectors, + ptrdiff_t lIndex, ptrdiff_t derNum, MbVector3D & vect, MbJoinSurfaceAuxiliaryData * ucache ) const; }; IMPL_PERSISTENT_OPS( MbJoinSurface ) + //------------------------------------------------------------------------------ // \ru Проверить параметры и в случае захода за полюс загнать в полюсную область \en Check parameters and if it is out of pole, then drive it to pole region // --- diff --git a/C3d/Include/surf_lofted_surface.h b/C3d/Include/surf_lofted_surface.h index 0996da0..57a5af4 100644 --- a/C3d/Include/surf_lofted_surface.h +++ b/C3d/Include/surf_lofted_surface.h @@ -279,8 +279,8 @@ public: \en \name Functions for get of the group of data inside and outside the surface's domain of parameters. \{ */ void Explore( double & u, double & v, bool ext, - MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, - MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; + MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, + MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; /** \} */ /** \ru \name Функции движения по поверхности @@ -317,9 +317,9 @@ public: size_t GetVMeshCount() const override; // \ru Выдать количество полигонов по v \en Get the count of polygons by v // \ru Определение разбивки параметрической области поверхности вертикалями и горизонталями \en Determine splitting of parametric region of surface by vertical and horizontal lines - virtual void GetTesselation( const MbStepData & stepData, - double u1, double u2, double v1, double v2, - SArray & uu, SArray & vv ) const override; + void GetTesselation( const MbStepData & stepData, + double u1, double u2, double v1, double v2, + SArray & uu, SArray & vv ) const override; // \ru Найти ближайшую проекцию точки на поверхность или ее продолжение по заданному начальному приближению. \en Find the neares projection of a point onto the surface. bool NearPointProjection ( const MbCartPoint3D & pnt, double & u, double & v, bool ext, MbRect2D * uvRange = nullptr ) const override; @@ -339,7 +339,7 @@ public: void CheckSurfParams( double & u, double & v ) const override; /// \ru Получить количество кривых, на которых построена поверхность \en Get count of curves which the surface is constructed by - ptrdiff_t CurvesCount() const { return (ptrdiff_t)uCurves.Count(); } + ptrdiff_t CurvesCount() const { return (ptrdiff_t)uCurves.Count(); } /** \brief \ru Получить кривую по номеру. \en Get curve by an index. \~ @@ -370,7 +370,7 @@ public: \return \ru Значение параметра. \en A parameter value. \~ */ - double GetParam( ptrdiff_t ind ) const { return (ind >= 0 && ind < (ptrdiff_t)vParams.Count()) ? vParams[ind] : 0.0; } + double GetParam( ptrdiff_t ind ) const { return (ind >= 0 && ind < (ptrdiff_t)vParams.Count()) ? vParams[ind] : 0.0; } /** \brief \ru Заполнить массив параметрами. \en Fill an array by parameters. \~ \details \ru Заполнить массив параметрами. \n @@ -378,7 +378,7 @@ public: \param[in,out] params - \ru Множество для заполнения параметрами. \en A set to fill by parameters. \~ */ - void GetParams( SArray & params ) const { params = vParams; } + void GetParams( SArray & params ) const { params = vParams; } /** \brief \ru Заполнить массив признаков одинаковых кривых. \en Fill array of attributes of similar curves. \~ \details \ru Заполнить массив признаков одинаковых кривых. \n @@ -386,14 +386,14 @@ public: \param[in,out] labels - \ru Множество для заполнения. \en A set to fill. \~ */ - void GetLabels( SArray & labels ) const { labels = vLabels; } + void GetLabels( SArray & labels ) const { labels = vLabels; } /// \ru Направление производной в начале незамкнутой поверхности. Если не задано, то нулевой длины. \en The direction of derivative at the beginning of the open surface. If it isn't set, then its length is zero. const MbVector3D & GetDerive1() const { return border1.derive; } ///< \ru Направление производной в конце незамкнутой поверхности. Если не задано, то нулевой длины. \en The direction of derivative at the end of the open surface. If it isn't set, then its length is zero. const MbVector3D & GetDerive2() const { return border2.derive; } - bool IsEqualLabels() const; ///< \ru Определить, есть ли одинаковые кривые. \en Determine whether there are similar curves. + bool IsEqualLabels() const; ///< \ru Определить, есть ли одинаковые кривые. \en Determine whether there are similar curves. /** \brief \ru Определить, есть ли кривые, одинаковые с кривой под номером ind. \en Determine whether there are curves similar to curve with 'ind' index. \~ \details \ru Определить, есть ли кривые, одинаковые с кривой под номером ind. \n @@ -403,7 +403,7 @@ public: \return \ru true - Если в массиве есть кривые, одинаковые с кривой под номером ind. \en True - If there are curves similar to curve with 'ind' index in array. \~ */ - bool IsEqualLabels( ptrdiff_t ind ) const; + bool IsEqualLabels( ptrdiff_t ind ) const; /** \brief \ru Определить, можно ли создать эквидистантную поверхность. @@ -423,9 +423,9 @@ public: \return \ru true - Если в можно создать эквидистантную поверхность. \en True - If it is possible to create an offset surface. \~ */ - bool IsPossibleCreateThin( double h, - double uLimBeg, double uLimEnd, - double vLimBeg, double vLimEnd ) const; + bool IsPossibleCreateThin( double h, + double uLimBeg, double uLimEnd, + double vLimBeg, double vLimEnd ) const; /** \brief \ru Согласовать массивы признаков одинаковости кривых у смежных поверхностей. \en Match arrays of attributes of similarity of curves between adjacent surfaces. \~ \details \ru Согласовать массивы признаков одинаковости кривых у смежных поверхностей. \n @@ -435,7 +435,7 @@ public: \return \ru true - Если есть изменения в массиве признаков кривых хотя бы одной поверхности. \en True - If there are changes in array of attributes of curves of at least one surface. \~ */ - bool AgreeLabels( MbLoftedSurface & surf ); + bool AgreeLabels( MbLoftedSurface & surf ); /** \brief \ru Установлена ли нормаль на конце. \en Is the normal set at the end. \~ \details \ru Установлена ли нормаль на конце. \n @@ -445,11 +445,11 @@ public: \return \ru true - Нормаль установлена. \en True - The Normal installed. \~ */ - bool IsSetNormal( bool atStart ) { return atStart ? border1.setNormal : border2.setNormal; } + bool IsSetNormal( bool atStart ) { return atStart ? border1.setNormal : border2.setNormal; } /** \} */ protected: - void CheckParam( double & u, bool ext ) const; // \ru Корректировка параметров. \en Correct parameters. \~ + void CheckParam( double & u, bool ext ) const; // \ru Корректировка параметров. \en Correct parameters. \~ /** \brief \ru Определение местных координат области поверхности. \en Determination of local coordinates of a surface region. \~ \details \ru Определение местных координат области поверхности. \n @@ -469,7 +469,7 @@ protected: \param[in,out] t2 - \ru Значение параметра для кривой j2. \en Value of parameter for j2 curve. \~ */ - void LocalCoordinate( double & v, ptrdiff_t & j1, ptrdiff_t & j2, double & y1, double & y2, double & t1, double & t2 ) const; + void LocalCoordinate( double & v, ptrdiff_t & j1, ptrdiff_t & j2, double & y1, double & y2, double & t1, double & t2 ) const; /** \brief \ru Определение массива векторов кривой. \en Determination of the array of curve vectors. \~ \details \ru Определение массива векторов кривой. \n @@ -483,8 +483,8 @@ protected: \param[in] ext - \ru Можно ли продолжить кривую за границы области определения ее параметра. \en Whether it is possible to extend curve out of its parametric domain bounds. \~ */ - void CalculateCurve( ptrdiff_t i, double u, MbVector3D & point, bool ext, size_t numb ) const; - void CalculateCurve( ptrdiff_t i, double u, MbVector3D & pnt, MbVector3D & fir, MbVector3D * sec, bool ext ) const; + void CalculateCurve( ptrdiff_t i, double u, MbVector3D & point, bool ext, size_t numb ) const; + void CalculateCurve( ptrdiff_t i, double u, MbVector3D & pnt, MbVector3D & fir, MbVector3D * sec, bool ext ) const; /** \brief \ru Определение массива векторов параметрa u для точки на поверхности с координатами (u, v). \en Determination of array of vectors of u parameter for point on surface with coordinates (u, v). \~ \details \ru Определение массива векторов параметрa u для точки на поверхности с координатами (u, v). \n @@ -502,15 +502,15 @@ protected: \param[in] ext - \ru Можно ли продолжить поверхность за границы области определения ее параметров. \en Whether it is possible to extend surface out of its parametric domain bounds. \~ */ - void CalculateSurface( double & u, ptrdiff_t j1, ptrdiff_t j2, - double t1, double t2, bool ext, size_t numb, - MbVector3D & point1, MbVector3D & point2, - MbVector3D & vector1, MbVector3D & vector2, bool correctVectors = true ) const; - void CalculateExplore( double & u, ptrdiff_t j1, ptrdiff_t j2, - double t1, double t2, bool ext, bool boolsecond, - MbVector3D * point1, MbVector3D * point2, - MbVector3D * vector1, MbVector3D * vector2, - double * tLoft ) const; + void CalculateSurface( double & u, ptrdiff_t j1, ptrdiff_t j2, + double t1, double t2, bool ext, size_t numb, + MbVector3D & point1, MbVector3D & point2, + MbVector3D & vector1, MbVector3D & vector2, bool correctVectors = true ) const; + void CalculateExplore( double & u, ptrdiff_t j1, ptrdiff_t j2, + double t1, double t2, bool ext, bool boolsecond, + MbVector3D * point1, MbVector3D * point2, + MbVector3D * vector1, MbVector3D * vector2, + double * tLoft ) const; void ParamPoint ( double y1, double y2, double t1, double t2, double * tLoft ) const; void ParamFirst ( double y1, double y2, double t1, double t2, double * tLoft ) const; @@ -524,24 +524,25 @@ protected: \en Determines whether the pole at domain boundary by curve length determining boundary.\n Result of calculations can be obtained with help of GetPoleUMin, GetPoleUMax, GetPoleVMin, GetPoleVMax functions. \~ */ - bool CheckPoles( MbLoftedSurfaceAuxiliaryData * ) const; // \ru Проверка полюсов на кривых \en Check poles on curves + bool CheckPoles( MbLoftedSurfaceAuxiliaryData * ) const; // \ru Проверка полюсов на кривых \en Check poles on curves private: - void Init( bool close ); - bool IsSimilarCurves( ptrdiff_t i1, ptrdiff_t i2 ) const; // \ru Определение одинаковых кривых \en Determination of similar curves - bool IsSimilarLabels( ptrdiff_t i1, ptrdiff_t i2 ) const; // \ru Определение одинаковых кривых по меткам. \en Determination of similar curves by labels. - void InitLabels(); // \ru Инициализация признаков одинаковых кривых. \en Initialization of attributes of similar curves. + void Init( bool close ); + bool IsSimilarCurves( ptrdiff_t i1, ptrdiff_t i2 ) const; // \ru Определение одинаковых кривых \en Determination of similar curves + bool IsSimilarLabels( ptrdiff_t i1, ptrdiff_t i2 ) const; // \ru Определение одинаковых кривых по меткам. \en Determination of similar curves by labels. + void InitLabels(); // \ru Инициализация признаков одинаковых кривых. \en Initialization of attributes of similar curves. - void InitNormalCondition( double derFactor, const MbVector3D & directSurf, bool isStart); // \ru Инициализация структуры граничных условий в случае установки нормали. \en Initialization structure of boundary conditions in the case of the normal setup. + void InitNormalCondition( double derFactor, const MbVector3D & directSurf, bool isStart); // \ru Инициализация структуры граничных условий в случае установки нормали. \en Initialization structure of boundary conditions in the case of the normal setup. MbVector3D DirByGivenNormal ( bool isStart, const MbVector3D & point1, const MbVector3D & point2 ) const; // \ru Определить вектор направления с заданной нормалью. \en Determine the direction vector with a given normal. - void operator = ( const MbLoftedSurface & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbLoftedSurface & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbLoftedSurface ) }; IMPL_PERSISTENT_OPS( MbLoftedSurface ) + //------------------------------------------------------------------------------ // \ru Корректировка параметров. \en Correct parameters. \~ // --- @@ -701,7 +702,7 @@ inline void MbLoftedSurface::ParamThird( double t1, double t2, double * tLoft ) */ // --- bool CreateLoftedParams( const RPArray & uCurves, - bool vcls, + bool vcls, SArray & vParams, SArray * tiePnts, VERSION version ); diff --git a/C3d/Include/surf_mesh_surface.h b/C3d/Include/surf_mesh_surface.h index e72f130..e851529 100644 --- a/C3d/Include/surf_mesh_surface.h +++ b/C3d/Include/surf_mesh_surface.h @@ -27,9 +27,11 @@ class MATH_CLASS MbSurfaceContiguousData; class MbRectPatchBaseData; class MbCoonsPatchData; + typedef std::map MapCurveParam; typedef std::map MapCrosses; + //------------------------------------------------------------------------------ /** \brief \ru Версия реализации поверхности на сетке кривых. \en Version of implementation of surface constructed by the grid curves. \~ @@ -366,7 +368,7 @@ private: MbeMeshSurfaceVersion vers, uint8( &orders )[2], MbeTransversCalculationType (&ttypes)[4] ); #ifdef C3D_DEBUG // \ru Проверить согласованность производых. \en Check the consistency of the derivatives. - bool TestSurfaceDerivatives() const; + bool TestSurfaceDerivatives() const; #endif // C3D_DEBUG protected: /// \ru Конструктор-копия. \en Copy constructor. @@ -469,8 +471,8 @@ public: \en \name Functions for get of the group of data inside and outside the surface's domain of parameters. \{ */ void Explore( double & u, double & v, bool ext, - MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, - MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; + MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, + MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; /** \} */ /** \ru \name Функции движения по поверхности @@ -513,10 +515,11 @@ public: */ void CheckSurfParams( double & u, double & v ) const override; - /// \ru Вернуть количество кривых в первом семействе. \en Get count of curves of first family. - size_t GetUCurvesCount() const { return uCurves.Count(); } - /// \ru Вернуть количество кривых во втором семействе. \en Get count of curves of second family. - size_t GetVCurvesCount() const { return vCurves.Count(); } + /// \ru Вернуть количество кривых в первом семействе. \en Get count of curves of first family. + size_t GetUCurvesCount() const { return uCurves.Count(); } + /// \ru Вернуть количество кривых во втором семействе. \en Get count of curves of second family. + size_t GetVCurvesCount() const { return vCurves.Count(); } + /** \brief \ru Получить кривую с индексом ind из первого семейства. \en Get curve with 'ind' index from first family. \~ \details \ru Получить кривую с индексом ind из первого семейства. \n @@ -526,7 +529,8 @@ public: \return \ru Кривая или nullptr, если значение ind выходит за диапазон возможных индексов массиве кривых. \en Curve or nullptr if value of 'ind' is out of range of possible indices of array of curves. \~ */ - const MbCurve3D * GetUCurve( size_t ind ) const { return ( ind < uCurves.Count()) ? uCurves[ind] : nullptr; } + const MbCurve3D * GetUCurve( size_t ind ) const { return ( ind < uCurves.Count()) ? uCurves[ind] : nullptr; } + /** \brief \ru Получить кривую с индексом ind из второго семейства. \en Get curve with 'ind' index from second family. \~ \details \ru Получить кривую с индексом ind из второго семейства. \n @@ -536,7 +540,8 @@ public: \return \ru Кривая или nullptr, если значение ind выходит за диапазон возможных индексов массиве кривых. \en Curve or nullptr if value of 'ind' is out of range of possible indices of array of curves. \~ */ - const MbCurve3D * GetVCurve( size_t ind ) const { return ( ind < vCurves.Count()) ? vCurves[ind] : nullptr; } + const MbCurve3D * GetVCurve( size_t ind ) const { return ( ind < vCurves.Count()) ? vCurves[ind] : nullptr; } + /** \brief \ru Получить значение параметра, соответствующего кривой с индексом ind из первого семейства. \en Get value of parameter corresponding to curve with 'ind' index from first family. \~ \details \ru Получить значение параметра, соответствующего кривой с индексом ind из первого семейства.\n @@ -546,7 +551,8 @@ public: \return \ru Значение параметра или 0, если значение ind выходит за диапазон возможных индексов массиве кривых. \en Value of parameter or 0 if value of 'ind' is out of range of possible indices of array of curves. \~ */ - double GetUParam( size_t ind ) const { return ( ind < uParams.Count()) ? uParams[ind] : 0; } + double GetUParam( size_t ind ) const { return ( ind < uParams.Count()) ? uParams[ind] : 0; } + /** \brief \ru Получить значение параметра, соответствующего кривой с индексом ind из второго семейства. \en Get value of parameter corresponding to curve with 'ind' index from second family. \~ \details \ru Получить значение параметра, соответствующего кривой с индексом ind из второго семейства.\n @@ -556,7 +562,40 @@ public: \return \ru Значение параметра или 0, если значение ind выходит за диапазон возможных индексов массиве кривых. \en Value of parameter or 0 if value of 'ind' is out of range of possible indices of array of curves. \~ */ - double GetVParam( size_t ind ) const { return ( ind < vParams.Count()) ? vParams[ind] : 0; } + double GetVParam( size_t ind ) const { return ( ind < vParams.Count()) ? vParams[ind] : 0; } + + /** \brief \ru Получить указатель на функцию перехода к параметрам первого семейства, соответствующую кривой с + индексом ind из первого семейства. + \en Get a transformation to parameters of first family corresponding to curve with 'ind' index from + first family. \~ + \details \ru Получить указатель на функцию перехода к параметрам первого семейства, соответствующую кривой с + индексом ind из первого семейства.\n + \en Get a transformation to parameters of first family corresponding to curve with 'ind' index from + first family\n \~ + \param[in] ind - \ru Номер кривой в массиве. + \en Index of curve in array. \~ + \return \ru Указатель на функцию перехода к параметру или nullptr, если значение ind выходит за диапазон + возможных индексов массива функций перехода к параметрам первого семейства. + \en Pointer to transformation to parameter or nullptr if value of 'ind' is out of range of possible + indices of array of transformation to parameters of first family. \~ + */ + const MbFunction * GetTUParam( size_t ind ) const { return ( ind < tuParams.Count()) ? tuParams[ind] : nullptr; } + /** \brief \ru Получить указатель на функцию перехода к параметрам второго семейства, соответствующую кривой с + индексом ind из второго семейства. + \en Get a transformation to parameters of second family corresponding to curve with 'ind' index from + second family. \~ + \details \ru Получить указатель на функцию перехода к параметрам второго семейства, соответствующую кривой с + индексом ind из второго семейства.\n + \en Get a transformation to parameters of second family corresponding to curve with 'ind' index from + second family\n \~ + \param[in] ind - \ru Номер кривой в массиве. + \en Index of curve in array. \~ + \return \ru Указатель на функцию перехода к параметру или nullptr, если значение ind выходит за диапазон + возможных индексов массива функций перехода к параметрам второго семейства. + \en Pointer to transformation to parameter or nullptr if value of 'ind' is out of range of possible + indices of array of transformation to parameters of second family. \~ + */ + const MbFunction * GetTVParam( size_t ind ) const { return ( ind < tvParams.Count()) ? tvParams[ind] : nullptr; } /** \brief \ru Заполнить массив параметров по u. \en Fill array of parameters by u. \~ \details \ru Заполнить массив параметров по u.\n @@ -564,7 +603,8 @@ public: \param[in,out] params - \ru Множество параметров. \en Set of parameters. \~ */ - void GetUParams( SArray & params ) const { params = uParams; } + void GetUParams( SArray & params ) const { params = uParams; } + /** \brief \ru Заполнить массив параметров по v. \en Fill array of parameters by v. \~ \details \ru Заполнить массив параметров по v.\n @@ -572,7 +612,7 @@ public: \param[in,out] params - \ru Множество параметров. \en Set of parameters. \~ */ - void GetVParams( SArray & params ) const { params = vParams; } + void GetVParams( SArray & params ) const { params = vParams; } /** \brief \ru Проверить выставленный тип сопряжения. \en Check mating type. \~ @@ -585,7 +625,7 @@ public: \return \ru Возвращает true, если такой тип сопряжения установлен. \en Returns true if this mating type is set. \~ */ - bool IsMatingType( MbeMatingType t, size_t n ) const; + bool IsMatingType( MbeMatingType t, size_t n ) const; /** \brief \ru Получить версию алгоритма расчета поверхности. \en Get version of the algorithm for calculating the surface. \~ @@ -594,226 +634,225 @@ public: \return \ru Версию алгоритма расчета поверхности. \en The version of the algorithm for calculating the surface. \~ */ - MbeMeshSurfaceVersion GetSurfaceVersion() const { return version; } + MbeMeshSurfaceVersion GetSurfaceVersion() const { return version; } private: - void AddCurvesRef(); - void ReleaseCurves(); - // \ru Инициализация из конструктора. \en Initialization from the constructor. - void Init( RPArray & initU, RPArray & initV, SArray * parsU, SArray * parsV, - bool uClosed, bool vClosed, bool g2, bool same, const SArray * types, MbeMeshSurfaceVersion vers ); - void Init( bool calcParams, bool callFromMultiPatchGenerator, - c3d::DoubleVector * tuCurvePars, c3d::DoubleVector * tvCurvePars ); - bool CheckPoles( MbMeshSurfaceAuxiliaryData * ) const; // \ru Инициализировать полюсы на границе параметрической области. \en Initialize poles on the border of parameters area. + void AddCurvesRef(); + void ReleaseCurves(); + // \ru Инициализация из конструктора. \en Initialization from the constructor. + void Init( RPArray & initU, RPArray & initV, SArray * parsU, SArray * parsV, + bool uClosed, bool vClosed, bool g2, bool same, const SArray * types, MbeMeshSurfaceVersion vers ); + void Init( bool calcParams, bool callFromMultiPatchGenerator, + c3d::DoubleVector * tuCurvePars, c3d::DoubleVector * tvCurvePars ); + bool CheckPoles( MbMeshSurfaceAuxiliaryData * ) const; // \ru Инициализировать полюсы на границе параметрической области. \en Initialize poles on the border of parameters area. - // \ru Аналоги публичных функций для внутреннего использования (используют присланный кэш). \en Analongs of public functions for internal use (use the sent cache). - bool GetPoleUMin( MbMeshSurfaceAuxiliaryData * ) const; // \ru Существует ли полюс на границе параметрической области \en Whether there is pole on boundary of parametric region - bool GetPoleUMax( MbMeshSurfaceAuxiliaryData * ) const; // \ru Существует ли полюс на границе параметрической области \en Whether there is pole on boundary of parametric region - bool GetPoleVMin( MbMeshSurfaceAuxiliaryData * ) const; // \ru Существует ли полюс на границе параметрической области \en Whether there is pole on boundary of parametric region - bool GetPoleVMax( MbMeshSurfaceAuxiliaryData * ) const; // \ru Существует ли полюс на границе параметрической области \en Whether there is pole on boundary of parametric region - void _DeriveU( double u, double v, MbVector3D & p, MbMeshSurfaceAuxiliaryData * ) const; // \ru Первая производная по u \en First derivative with respect to u - void _DeriveV( double u, double v, MbVector3D & p, MbMeshSurfaceAuxiliaryData * ) const; // \ru Первая производная по v \en First derivative with respect to v - void DeriveU( double & u, double & v, MbVector3D & p, MbMeshSurfaceAuxiliaryData * ) const; // \ru Первая производная по u \en First derivative with respect to u - void DeriveV( double & u, double & v, MbVector3D & p, MbMeshSurfaceAuxiliaryData * ) const; // \ru Первая производная по v \en First derivative with respect to v - void DeriveUU( double & u, double & v, MbVector3D & p, MbMeshSurfaceAuxiliaryData * ) const; // \ru Вторая производная по u \en Second derivative with respect to u - void DeriveVV( double & u, double & v, MbVector3D & p, MbMeshSurfaceAuxiliaryData * ) const; // \ru Вторая производная по v \en Second derivative with respect to v - void DeriveUV( double & u, double & v, MbVector3D & p, MbMeshSurfaceAuxiliaryData * ) const; // \ru Вторая производная по uv \en Second derivative with respect to uv - void DeriveUUU( double & u, double & v, MbVector3D & p, MbMeshSurfaceAuxiliaryData * ) const; // \ru Третья производная \en Third derivative - void DeriveUUV( double & u, double & v, MbVector3D & p, MbMeshSurfaceAuxiliaryData * ) const; // \ru Третья производная \en Third derivative - void DeriveUVV( double & u, double & v, MbVector3D & p, MbMeshSurfaceAuxiliaryData * ) const; // \ru Третья производная \en Third derivative - void DeriveVVV( double & u, double & v, MbVector3D & p, MbMeshSurfaceAuxiliaryData * ) const; // \ru Третья производная \en Third derivative - bool IsLineU( MbMeshSurfaceAuxiliaryData * ) const; // \ru Если true все производные по U выше первой равны нулю \en If true, then all the derivatives by U higher the first one are equal to zero - bool IsLineV( MbMeshSurfaceAuxiliaryData * ) const; // \ru Если true все производные по V выше первой равны нулю \en If true, then all the derivatives by V higher the first one are equal to zero - void _PointOn( double u, double v, MbCartPoint3D & p, MbMeshSurfaceAuxiliaryData * ) const; // \ru Точка на поверхности \en Point on the surface - void PointOn( double & u, double & v, MbCartPoint3D & p, MbMeshSurfaceAuxiliaryData * ) const; // \ru Точка на поверхности \en Point on the surface + // \ru Аналоги публичных функций для внутреннего использования (используют присланный кэш). \en Analongs of public functions for internal use (use the sent cache). + bool GetPoleUMin( MbMeshSurfaceAuxiliaryData * ) const; // \ru Существует ли полюс на границе параметрической области \en Whether there is pole on boundary of parametric region + bool GetPoleUMax( MbMeshSurfaceAuxiliaryData * ) const; // \ru Существует ли полюс на границе параметрической области \en Whether there is pole on boundary of parametric region + bool GetPoleVMin( MbMeshSurfaceAuxiliaryData * ) const; // \ru Существует ли полюс на границе параметрической области \en Whether there is pole on boundary of parametric region + bool GetPoleVMax( MbMeshSurfaceAuxiliaryData * ) const; // \ru Существует ли полюс на границе параметрической области \en Whether there is pole on boundary of parametric region + void _DeriveU( double u, double v, MbVector3D & p, MbMeshSurfaceAuxiliaryData * ) const; // \ru Первая производная по u \en First derivative with respect to u + void _DeriveV( double u, double v, MbVector3D & p, MbMeshSurfaceAuxiliaryData * ) const; // \ru Первая производная по v \en First derivative with respect to v + void DeriveU( double & u, double & v, MbVector3D & p, MbMeshSurfaceAuxiliaryData * ) const; // \ru Первая производная по u \en First derivative with respect to u + void DeriveV( double & u, double & v, MbVector3D & p, MbMeshSurfaceAuxiliaryData * ) const; // \ru Первая производная по v \en First derivative with respect to v + void DeriveUU( double & u, double & v, MbVector3D & p, MbMeshSurfaceAuxiliaryData * ) const; // \ru Вторая производная по u \en Second derivative with respect to u + void DeriveVV( double & u, double & v, MbVector3D & p, MbMeshSurfaceAuxiliaryData * ) const; // \ru Вторая производная по v \en Second derivative with respect to v + void DeriveUV( double & u, double & v, MbVector3D & p, MbMeshSurfaceAuxiliaryData * ) const; // \ru Вторая производная по uv \en Second derivative with respect to uv + void DeriveUUU( double & u, double & v, MbVector3D & p, MbMeshSurfaceAuxiliaryData * ) const; // \ru Третья производная \en Third derivative + void DeriveUUV( double & u, double & v, MbVector3D & p, MbMeshSurfaceAuxiliaryData * ) const; // \ru Третья производная \en Third derivative + void DeriveUVV( double & u, double & v, MbVector3D & p, MbMeshSurfaceAuxiliaryData * ) const; // \ru Третья производная \en Third derivative + void DeriveVVV( double & u, double & v, MbVector3D & p, MbMeshSurfaceAuxiliaryData * ) const; // \ru Третья производная \en Third derivative + bool IsLineU( MbMeshSurfaceAuxiliaryData * ) const; // \ru Если true все производные по U выше первой равны нулю \en If true, then all the derivatives by U higher the first one are equal to zero + bool IsLineV( MbMeshSurfaceAuxiliaryData * ) const; // \ru Если true все производные по V выше первой равны нулю \en If true, then all the derivatives by V higher the first one are equal to zero + void _PointOn( double u, double v, MbCartPoint3D & p, MbMeshSurfaceAuxiliaryData * ) const; // \ru Точка на поверхности \en Point on the surface + void PointOn( double & u, double & v, MbCartPoint3D & p, MbMeshSurfaceAuxiliaryData * ) const; // \ru Точка на поверхности \en Point on the surface - // \ru Определить местные координаты области поверхности. \en Determine local coordinates of surface region. - void LocalCoordinate( double u, double v, double & ul, double & vl, size_t & i0,size_t & j0,size_t & i1, size_t & j1, MbMeshSurfaceAuxiliaryData * ucache = nullptr ) const; - void LocalCoordinate_v2( double u, double v, double & ul, double & vl, size_t & i0, size_t & j0, size_t & i1, size_t & j1, size_t ord, MbMeshSurfaceAuxiliaryData * ucache ) const; - void LocalCoordinate_v4( double u, double v, size_t ordU, size_t ordV, MbMeshSurfaceAuxiliaryData * ucache ) const; - void LocalCoordinate_v5( double u, double v, size_t ordU, size_t ordV, MbMeshSurfaceAuxiliaryData * ucache ) const; + // \ru Определить местные координаты области поверхности. \en Determine local coordinates of surface region. + void LocalCoordinate( double u, double v, double & ul, double & vl, size_t & i0,size_t & j0,size_t & i1, size_t & j1, MbMeshSurfaceAuxiliaryData * ucache = nullptr ) const; + void LocalCoordinate_v2( double u, double v, double & ul, double & vl, size_t & i0, size_t & j0, size_t & i1, size_t & j1, size_t ord, MbMeshSurfaceAuxiliaryData * ucache ) const; + void LocalCoordinate_v4( double u, double v, size_t ordU, size_t ordV, MbMeshSurfaceAuxiliaryData * ucache ) const; + void LocalCoordinate_v5( double u, double v, size_t ordU, size_t ordV, MbMeshSurfaceAuxiliaryData * ucache ) const; // \ru Рассчитать параметры для границы патча. \en Calculate parameters for the patch boundary. - void PatchBoundExplore_v4( const MbCurve3D * curve, const MbFunction * fn, - double par, size_t bnd, MbeMatingType tp, MbeTransversCalculationType ttp, - MbCoonsPatchData & pd, ptrdiff_t ord, ptrdiff_t tOrd ) const; - // \ru Вернуть изолинию на поверхности для указанного параметра. - MbCurve3D * CurveUV_v4( bool dirU, double sPar, MbRect1D * pRgn, bool bApprox ) const; // \ru Пространственная копия линии u(v) = const. \en Spatial copy of line u(v) = const. + void PatchBoundExplore_v4( const MbCurve3D * curve, const MbFunction * fn, + double par, size_t bnd, MbeMatingType tp, MbeTransversCalculationType ttp, + MbCoonsPatchData & pd, ptrdiff_t ord, ptrdiff_t tOrd ) const; + // \ru Вернуть изолинию на поверхности для указанного параметра. + MbCurve3D * CurveUV_v4( bool dirU, double sPar, MbRect1D * pRgn, bool bApprox ) const; // \ru Пространственная копия линии u(v) = const. \en Spatial copy of line u(v) = const. + // \ru Вычислить вспомогательные вектора производных вдоль U кривых патча. \en Calculate auxiliary vectors of derivatives along U curves of patch. + void CalculateAlongU( const double & ul, const size_t & j0, const size_t & j1, MbMeshSurfaceAuxiliaryData * ucache ) const; + void CalculateAlongU_v2( const double & u, const size_t & j0, const size_t & j1, size_t indP, MbMeshSurfaceAuxiliaryData * ucache ) const; + // \ru Вычислить вспомогательные вектора производных вдоль V кривых патча. \en Calculate auxiliary vectors of derivatives along V curves of patch. + void CalculateAlongV( const double & vl, const size_t & i0, const size_t & i1, MbMeshSurfaceAuxiliaryData * ucache ) const; + void CalculateAlongV_v2( const double & v, const size_t & i0, const size_t & i1, size_t indP, MbMeshSurfaceAuxiliaryData * ucache ) const; + // \ru Вычислить вспомогательные вектора производных в узлах кривых. \en Calculate auxiliary vectors of derivatives at nodes of curves. + void CalculateVertex( const size_t & i0, const size_t & j0, const size_t & i1, const size_t & j1, MbMeshSurfaceAuxiliaryData * ucache ) const; + void CalculateVertex_v2( const size_t & i0, const size_t & j0, const size_t & i1, const size_t & j1, MbMeshSurfaceAuxiliaryData * ucache ) const; + // \ru Вычислить дополнительные вспомогательные вектора производных в узлах кривых. Для 1-й версии поверхности. \en Calculate additional auxiliary vectors of derivatives at nodes of curves. For 1-st version of surface. + void AdditionalCalculateVertex( size_t i0, size_t j0, size_t i1, size_t j1, MbMeshSurfaceAuxiliaryData * ucache ) const; + // \ru Создать массив смешанных производных. \en Create an array of mixed derivatives. + void CreateTwists (); + void CreateTwists_v1( const MapCrosses & crosses, const MapCrosses & outCrosses ); + void CreateTwists_v4( const MapCrosses & crosses, const MapCrosses & outCrosses ); + // \ru Создать массив смешанных производных. \en Create an array of mixed derivatives. + void InitTwistsArrays(); + // \ru Подготовить смешанные производные на границах сопряжения. \en Prepare mixed derivatives at the boundaries of the mating. + void PrepareBoundaryTwists_v4( bool g2, bool read ); + void PrepareBoundaryTwists_v5( MbMeshSurface *( *adjSurf )[3][3], size_t ord ); + // \ru Определить тип интерполяции для границ сопряжения. \en Set interpolation type for mating boundaries. + void SetTransversalTypes_v5( size_t ord ); + // \ru Рассчитать смешанные производные более высокого пояркда + // по разностной схеме с поверхности более низкого порядка. + void CalculateTwists_v4( MbMeshSurface *(*adjSurf)[3], SArray (*extBounds)[4], size_t ord ); + void CalculateTwists_v5( MbMeshSurface *( *adjSurf )[3][3], SArray( *extBounds )[4], bool g2 ); + // \ru Выполнить преобразование по матрице векторов boundTwists. + // \en Perform a transformation on the matrix of vectors boundTwists. + void TransformTwists_v5( const MbMatrix3D & matr ); + // \ru Проверить гладкость стыковки с соседней поверхностью по указанной кривой. + // \en Check the smoothness of the connection with the adjacent surface according to the specified curve. + bool CheckSmoothnessOfCurve( bool byU, size_t curveInd, bool isBegin, const MbMeshSurface & adjSurf, bool checkC2 ) const; + // \ru Получить данные кэша. \en Get cache data. + MbCoonsPatchData * GetPatchData_v4(); + const MbCoonsPatchData * GetPatchData_v4() const; - // \ru Вычислить вспомогательные вектора производных вдоль U кривых патча. \en Calculate auxiliary vectors of derivatives along U curves of patch. - void CalculateAlongU( const double & ul, const size_t & j0, const size_t & j1, MbMeshSurfaceAuxiliaryData * ucache ) const; - void CalculateAlongU_v2( const double & u, const size_t & j0, const size_t & j1, size_t indP, MbMeshSurfaceAuxiliaryData * ucache ) const; - // \ru Вычислить вспомогательные вектора производных вдоль V кривых патча. \en Calculate auxiliary vectors of derivatives along V curves of patch. - void CalculateAlongV( const double & vl, const size_t & i0, const size_t & i1, MbMeshSurfaceAuxiliaryData * ucache ) const; - void CalculateAlongV_v2( const double & v, const size_t & i0, const size_t & i1, size_t indP, MbMeshSurfaceAuxiliaryData * ucache ) const; - // \ru Вычислить вспомогательные вектора производных в узлах кривых. \en Calculate auxiliary vectors of derivatives at nodes of curves. - void CalculateVertex( const size_t & i0, const size_t & j0, const size_t & i1, const size_t & j1, MbMeshSurfaceAuxiliaryData * ucache ) const; - void CalculateVertex_v2( const size_t & i0, const size_t & j0, const size_t & i1, const size_t & j1, MbMeshSurfaceAuxiliaryData * ucache ) const; - // \ru Вычислить дополнительные вспомогательные вектора производных в узлах кривых. Для 1-й версии поверхности. \en Calculate additional auxiliary vectors of derivatives at nodes of curves. For 1-st version of surface. - void AdditionalCalculateVertex( size_t i0, size_t j0, size_t i1, size_t j1, MbMeshSurfaceAuxiliaryData * ucache ) const; - // \ru Создать массив смешанных производных. \en Create an array of mixed derivatives. - void CreateTwists (); - void CreateTwists_v1( const MapCrosses & crosses, const MapCrosses & outCrosses ); - void CreateTwists_v4( const MapCrosses & crosses, const MapCrosses & outCrosses ); - // \ru Создать массив смешанных производных. \en Create an array of mixed derivatives. - void InitTwistsArrays(); - // \ru Подготовить смешанные производные на границах сопряжения. \en Prepare mixed derivatives at the boundaries of the mating. - void PrepareBoundaryTwists_v4( bool g2, bool read ); - void PrepareBoundaryTwists_v5( MbMeshSurface *( *adjSurf )[3][3], size_t ord ); - // \ru Определить тип интерполяции для границ сопряжения. \en Set interpolation type for mating boundaries. - void SetTransversalTypes_v5( size_t ord ); - // \ru Рассчитать смешанные производные более высокого пояркда - // по разностной схеме с поверхности более низкого порядка. - void CalculateTwists_v4( MbMeshSurface *(*adjSurf)[3], SArray (*extBounds)[4], size_t ord ); - void CalculateTwists_v5( MbMeshSurface *( *adjSurf )[3][3], SArray( *extBounds )[4], bool g2 ); - // \ru Выполнить преобразование по матрице векторов boundTwists. - // \en Perform a transformation on the matrix of vectors boundTwists. - void TransformTwists_v5( const MbMatrix3D & matr ); - // \ru Проверить гладкость стыковки с соседней поверхностью по указанной кривой. - // \en Check the smoothness of the connection with the adjacent surface according to the specified curve. - bool CheckSmoothnessOfCurve( bool byU, size_t curveInd, bool isBegin, const MbMeshSurface & adjSurf, bool checkC2 ) const; - // \ru Получить данные кэша. \en Get cache data. - MbCoonsPatchData * GetPatchData_v4(); - const MbCoonsPatchData * GetPatchData_v4() const; + // \ru Аппроксимировать смешанную производную. \en Approximate mixed derivative. + void ApproxTwistBilinear ( size_t iL, size_t iR, size_t jD, size_t jU, size_t iCent, size_t jCent, MbVector3D & resTwist ); + void ApproxTwistBilinear_v1( size_t iCent, size_t jCent, MbVector3D & resTwist ); + void ApproximateOneCornerTwist_v1( size_t iL, size_t iR, size_t jD, size_t jU, size_t corner, MbVector3D & resTwist ) const; + void ApproxTwistBilinear_v3( ptrdiff_t i, ptrdiff_t j, MbVector3D & resTwist, const MapCrosses & crosses, const MapCrosses & outCrosses ); + // \ru Рассчитать частную производную в вершине ячейки. \en Calculate the partial derivative at the top of the cell. + void CalculateCellDerivative_v3( MbVector3D & res, bool dirU, ptrdiff_t uind, ptrdiff_t vind, bool isOut, + const MapCrosses & crosses, const MapCrosses & outCrosses ) const; + // \ru Рассчитать координаты вершины ячейки. \en Calculate cell vertex coordinates. + void CalculateCellPoint_v3( MbCartPoint3D & res, ptrdiff_t uind, ptrdiff_t vind, const MapCrosses & crosses ) const; + // \ru Вычислить вспомогательные массивы трансверсальных производных. \en Calculate auxiliary arrays of transversal derivatives. + void CalculateTransDiffs ( double ul, double vl, size_t i0, size_t j0, size_t i1, size_t j1, MbMeshSurfaceAuxiliaryData * ucache ) const; + // \ru Вычислить выводящую производную с линии V = const и ее первые производные по U. \en Calculate leading out derivative from 'V = const'-line and its first derivatives by U. + void CalculateVDiffs ( double ul, double vl, size_t i0, size_t j0, bool dir, + MbVector3D & res, + MbVector3D & resDer1, + MbVector3D & resDer2 ) const; + // \ru Вычислить выводящую производную с линии U = const и ее первые производные по V. \en Calculate leading out derivative from 'U = const'-line and its first derivatives by V. + void CalculateUDiffs ( double ul, double vl, size_t i0, size_t j0, bool dir, + MbVector3D & res, + MbVector3D & resDer1, + MbVector3D & resDer2 ) const; + // \ru Вычислить выводящую производную с линии U (V) = const и ее первые производные по V (U). \en Calculate leading out derivative from 'U (V) = const'-line and its first derivatives by V (U). + void CalcTransvDiffs_v1( bool uDir, double par, size_t ind, bool leftOrDown, + MbVector3D & res, + MbVector3D & resDer1, + MbVector3D & resDer2, + MbVector3D & resDer3, MbMeshSurfaceAuxiliaryData * ucache ) const; + void CalcTransvDiffs_v2( bool uDir, double par, double apar, size_t ind, size_t indt, bool leftOrDown, + MbVector3D & res, + MbVector3D & resDer1, + MbVector3D & resDer2, + MbVector3D & resDer3, size_t ord, MbMeshSurfaceAuxiliaryData * ucache ) const; + // \ru Аппроксимация нормали вдоль U - линии. \en Approximation of normal along U - line. + bool NormalAlongV ( double ul, double vl, size_t i0, size_t j0, bool dir, + MbVector3D & res, + MbVector3D & resDer1, + MbVector3D & resDer2 ) const; + // \ru Аппроксимация нормали вдоль V - линии. \en Approximation of normal along V - line. + bool NormalAlongU ( double ul, double vl, size_t i0, size_t j0, bool dir, + MbVector3D & res, + MbVector3D & resDer1, + MbVector3D & resDer2 ) const; + // \ru Вычислить выводящую производную с линии V = const и ее первые производные по U. \en Calculate leading out derivative from 'V = const'-line and its first derivatives by U. + void NormalVDiffs ( double ul, double vl, size_t i0, size_t j0, bool dir, + MbVector3D & res, + MbVector3D & resDer1, + MbVector3D & resDer2 ) const; + // \ru Вычислить выводящую производную с линии U = const и ее первые производные по V. \en Calculate leading out derivative from 'U = const'-line and its first derivatives by V. + void NormalUDiffs ( double ul, double vl, size_t i0, size_t j0, bool dir, + MbVector3D & res, + MbVector3D & resDer1, + MbVector3D & resDer2 ) const; + // \ru Вычислить выводящие производные с учетом сопряжения к поверхности. \en Calculate leading out derivatives with consideration of conjugation to surface. + void SurfaceDiff ( const MbCurve3D & srfCrv, uint type, double ul, double vl, + size_t i0, size_t j0, size_t i1, size_t j1, + bool leftOrDown, // \ru Где происходит сам стык. \en Where is a joint. + bool uDir, // \ru Вдоль какого направления направлена кривая. \en Which direction the curve is directed along. + MbVector3D & first, + MbVector3D & secnd, + MbVector3D & third, MbMeshSurfaceAuxiliaryData * ucache ) const; + // \ru Вычислить выводящую производную и ей сопутствующие производные вдоль кривой. \en Calculate leading out derivative and its associated derivatives along curve. + void SurfaceTangent ( const MbCurve3D & surfCrv, // \ru Кривая, к поверхности которой вычисляется производная \en Curve which surface the derivative is calculated to + const MbVector3D * coons, // \ru Массив выводящих производных обычного патча Кунса \en Array of leading out derivatives of ordinary Coons patch + size_t border, // \ru Порядковый номер сопрягаемой границы \en Serial number of conjugated boundary + double tCurve, // \ru Параметр на кривой \en Parameter on the curve + double paramLoc, // \ru Параметр патча, соответствующий параметру на кривой \en Patch parameter corresponding to parameter on curve + double dt, // (dt / d(paramLoc)) + MbVector3D & res, // \ru Сам вектор \en Vector + MbVector3D & resDiff, // \ru Его первая производная \en Its first derivative + MbVector3D & resDiff2, MbMeshSurfaceAuxiliaryData * ucache ) const; + void PureSurfTangent( const MbCurve3D & surfCrv, + const MbVector3D * coons, + size_t border, + double tCurve, + double dt, + MbVector3D & res, + MbVector3D & resDiff, + MbVector3D * resDiff2 ) const; + void SurfaceNormal ( const MbCurve3D & srfCrv, + const MbVector3D * coons, // \ru Массив выводящих производных обычного патча Кунса \en Array of leading out derivatives of ordinary Coons patch + size_t border, // \ru Порядковый номер сопрягаемой границы \en Serial number of conjugated boundary + double tCurve, + double paramLoc, + double dt, + MbVector3D & res, // \ru Сам вектор \en Vector + MbVector3D & resDiff, // \ru Производная вектора вдоль кривой ( по paramLoc ) \en Derivative of vector along curve ( by paramLoc ) + MbVector3D & resDiff2, MbMeshSurfaceAuxiliaryData * ucache ) const ; + void PureSurfNormal ( const MbCurve3D & surfCrv, + const MbVector3D * coons, + size_t border, + double tCurve, + double dt, + MbVector3D & res, + MbVector3D & resDiff, + MbVector3D * resDiff2 ) const; + // \ru Нормализовать массивы пересечений \en Normalize arrays of intersections + void NormalizeIntersection(); - // \ru Аппроксимировать смешанную производную. \en Approximate mixed derivative. - void ApproxTwistBilinear ( size_t iL, size_t iR, size_t jD, size_t jU, size_t iCent, size_t jCent, MbVector3D & resTwist ); - void ApproxTwistBilinear_v1( size_t iCent, size_t jCent, MbVector3D & resTwist ); - void ApproximateOneCornerTwist_v1( size_t iL, size_t iR, size_t jD, size_t jU, size_t corner, MbVector3D & resTwist ) const; - void ApproxTwistBilinear_v3( ptrdiff_t i, ptrdiff_t j, MbVector3D & resTwist, const MapCrosses & crosses, const MapCrosses & outCrosses ); - // \ru Рассчитать частную производную в вершине ячейки. \en Calculate the partial derivative at the top of the cell. - void CalculateCellDerivative_v3( MbVector3D & res, bool dirU, ptrdiff_t uind, ptrdiff_t vind, bool isOut, - const MapCrosses & crosses, const MapCrosses & outCrosses ) const; - // \ru Рассчитать координаты вершины ячейки. \en Calculate cell vertex coordinates. - void CalculateCellPoint_v3( MbCartPoint3D & res, ptrdiff_t uind, ptrdiff_t vind, const MapCrosses & crosses ) const; - // \ru Вычислить вспомогательные массивы трансверсальных производных. \en Calculate auxiliary arrays of transversal derivatives. - void CalculateTransDiffs ( double ul, double vl, size_t i0, size_t j0, size_t i1, size_t j1, MbMeshSurfaceAuxiliaryData * ucache ) const; - // \ru Вычислить выводящую производную с линии V = const и ее первые производные по U. \en Calculate leading out derivative from 'V = const'-line and its first derivatives by U. - void CalculateVDiffs ( double ul, double vl, size_t i0, size_t j0, bool dir, - MbVector3D & res, - MbVector3D & resDer1, - MbVector3D & resDer2 ) const; - // \ru Вычислить выводящую производную с линии U = const и ее первые производные по V. \en Calculate leading out derivative from 'U = const'-line and its first derivatives by V. - void CalculateUDiffs ( double ul, double vl, size_t i0, size_t j0, bool dir, - MbVector3D & res, - MbVector3D & resDer1, - MbVector3D & resDer2 ) const; - // \ru Вычислить выводящую производную с линии U (V) = const и ее первые производные по V (U). \en Calculate leading out derivative from 'U (V) = const'-line and its first derivatives by V (U). - void CalcTransvDiffs_v1( bool uDir, double par, size_t ind, bool leftOrDown, - MbVector3D & res, - MbVector3D & resDer1, - MbVector3D & resDer2, - MbVector3D & resDer3, MbMeshSurfaceAuxiliaryData * ucache ) const; - void CalcTransvDiffs_v2( bool uDir, double par, double apar, size_t ind, size_t indt, bool leftOrDown, - MbVector3D & res, - MbVector3D & resDer1, - MbVector3D & resDer2, - MbVector3D & resDer3, size_t ord, MbMeshSurfaceAuxiliaryData * ucache ) const; - // \ru Аппроксимация нормали вдоль U - линии. \en Approximation of normal along U - line. - bool NormalAlongV ( double ul, double vl, size_t i0, size_t j0, bool dir, - MbVector3D & res, - MbVector3D & resDer1, - MbVector3D & resDer2 ) const; - // \ru Аппроксимация нормали вдоль V - линии. \en Approximation of normal along V - line. - bool NormalAlongU ( double ul, double vl, size_t i0, size_t j0, bool dir, - MbVector3D & res, - MbVector3D & resDer1, - MbVector3D & resDer2 ) const; - // \ru Вычислить выводящую производную с линии V = const и ее первые производные по U. \en Calculate leading out derivative from 'V = const'-line and its first derivatives by U. - void NormalVDiffs ( double ul, double vl, size_t i0, size_t j0, bool dir, - MbVector3D & res, - MbVector3D & resDer1, - MbVector3D & resDer2 ) const; - // \ru Вычислить выводящую производную с линии U = const и ее первые производные по V. \en Calculate leading out derivative from 'U = const'-line and its first derivatives by V. - void NormalUDiffs ( double ul, double vl, size_t i0, size_t j0, bool dir, - MbVector3D & res, - MbVector3D & resDer1, - MbVector3D & resDer2 ) const; - // \ru Вычислить выводящие производные с учетом сопряжения к поверхности. \en Calculate leading out derivatives with consideration of conjugation to surface. - void SurfaceDiff ( const MbCurve3D & srfCrv, uint type, double ul, double vl, - size_t i0, size_t j0, size_t i1, size_t j1, - bool leftOrDown, // \ru Где происходит сам стык. \en Where is a joint. - bool uDir, // \ru Вдоль какого направления направлена кривая. \en Which direction the curve is directed along. - MbVector3D & first, - MbVector3D & secnd, - MbVector3D & third, MbMeshSurfaceAuxiliaryData * ucache ) const; - // \ru Вычислить выводящую производную и ей сопутствующие производные вдоль кривой. \en Calculate leading out derivative and its associated derivatives along curve. - void SurfaceTangent ( const MbCurve3D & surfCrv, // \ru Кривая, к поверхности которой вычисляется производная \en Curve which surface the derivative is calculated to - const MbVector3D * coons, // \ru Массив выводящих производных обычного патча Кунса \en Array of leading out derivatives of ordinary Coons patch - size_t border, // \ru Порядковый номер сопрягаемой границы \en Serial number of conjugated boundary - double tCurve, // \ru Параметр на кривой \en Parameter on the curve - double paramLoc, // \ru Параметр патча, соответствующий параметру на кривой \en Patch parameter corresponding to parameter on curve - double dt, // (dt / d(paramLoc)) - MbVector3D & res, // \ru Сам вектор \en Vector - MbVector3D & resDiff, // \ru Его первая производная \en Its first derivative - MbVector3D & resDiff2, MbMeshSurfaceAuxiliaryData * ucache ) const; - void PureSurfTangent( const MbCurve3D & surfCrv, - const MbVector3D * coons, - size_t border, - double tCurve, - double dt, - MbVector3D & res, - MbVector3D & resDiff, - MbVector3D * resDiff2 ) const; - void SurfaceNormal ( const MbCurve3D & srfCrv, - const MbVector3D * coons, // \ru Массив выводящих производных обычного патча Кунса \en Array of leading out derivatives of ordinary Coons patch - size_t border, // \ru Порядковый номер сопрягаемой границы \en Serial number of conjugated boundary - double tCurve, - double paramLoc, - double dt, - MbVector3D & res, // \ru Сам вектор \en Vector - MbVector3D & resDiff, // \ru Производная вектора вдоль кривой ( по paramLoc ) \en Derivative of vector along curve ( by paramLoc ) - MbVector3D & resDiff2, MbMeshSurfaceAuxiliaryData * ucache ) const ; - void PureSurfNormal ( const MbCurve3D & surfCrv, - const MbVector3D * coons, - size_t border, - double tCurve, - double dt, - MbVector3D & res, - MbVector3D & resDiff, - MbVector3D * resDiff2 ) const; - // \ru Нормализовать массивы пересечений \en Normalize arrays of intersections - void NormalizeIntersection(); + // \ru Определить индексы в массиве точек пересечения для кривых по направлению U \en Determine indices in array of intersection points for curves by U direction + void DefineEndTUIndices( size_t i0, size_t j0, size_t i1, size_t j1, + size_t & k0min, size_t & k0max, + size_t & k2min, size_t & k2max ) const; + // \ru Определить индексы в массиве точек пересечения для кривых по направлению V \en Determine indices in array of intersection points for curves by V direction + void DefineEndTVIndices( size_t i0, size_t j0, size_t i1, size_t j1, + size_t & k1min, size_t & k1max, + size_t & k3min, size_t & k3max ) const; - // \ru Определить индексы в массиве точек пересечения для кривых по направлению U \en Determine indices in array of intersection points for curves by U direction - void DefineEndTUIndices( size_t i0, size_t j0, size_t i1, size_t j1, - size_t & k0min, size_t & k0max, - size_t & k2min, size_t & k2max ) const; - // \ru Определить индексы в массиве точек пересечения для кривых по направлению V \en Determine indices in array of intersection points for curves by V direction - void DefineEndTVIndices( size_t i0, size_t j0, size_t i1, size_t j1, - size_t & k1min, size_t & k1max, - size_t & k3min, size_t & k3max ) const; - - // \ru Определить параметры пересечений для U направления \en Determine parameters of intersections for U direction - void DefineEndTUPars( size_t i0, size_t j0, size_t i1, size_t j1, - double & t0min, double & t0max, - double & t2min, double & t2max, bool dir = true ) const; - // \ru Определить параметры пересечений для V направления \en Determine parameters of intersections for V direction - void DefineEndTVPars( size_t i0, size_t j0, size_t i1, size_t j1, - double & t1min, double & t1max, - double & t3min, double & t3max, bool dir = true ) const; + // \ru Определить параметры пересечений для U направления \en Determine parameters of intersections for U direction + void DefineEndTUPars( size_t i0, size_t j0, size_t i1, size_t j1, + double & t0min, double & t0max, + double & t2min, double & t2max, bool dir = true ) const; + // \ru Определить параметры пересечений для V направления \en Determine parameters of intersections for V direction + void DefineEndTVPars( size_t i0, size_t j0, size_t i1, size_t j1, + double & t1min, double & t1max, + double & t3min, double & t3max, bool dir = true ) const; - void ExactNormal( double u, double v, const MbVector3D & uDer, const MbVector3D & vDer, MbVector3D & nor, MbMeshSurfaceAuxiliaryData * ) const; + void ExactNormal( double u, double v, const MbVector3D & uDer, const MbVector3D & vDer, MbVector3D & nor, MbMeshSurfaceAuxiliaryData * ) const; - // \ru Проверить параметры и в случае выхода за пределы загнать в область определения. - // \en Check parameters and if it is out of limits, then drive it to domain - void CheckParams( double & u, double & v ) const; - // \ru Проверить параметры и в случае захода за полюс или выходе за период загнать в область определения. - // \en Check parameters and if it is out of pole or it is out of period, then drive it to the domain region. - void CheckParamsEx( double & u, double & v, MbMeshSurfaceAuxiliaryData * ucache ) const; - // \ru Попытаться вычислить шаг по U, исходя из шагов по соответствующим операторам Loft-ов \en Try to calculate step by U through steps of corresponding Loft operators - bool SurfDeviationStepU( double & u, double & v, double ang, double & resStep, MbMeshSurfaceAuxiliaryData * ucache ) const; - // \ru Попытаться вычислить шаг по V, исходя из шага по соответствующим операторам Loft-ов \en Try to calculate step by V through steps of corresponding Loft operators - bool SurfDeviationStepV( double & u, double & v, double ang, double & resStepv, MbMeshSurfaceAuxiliaryData * ucache ) const; - // \ru Создать таблицу пересечений для дополнительных кривых. \en Create an intersection table for additional curves. - void CreateCurvesCrossTable( MapCrosses & crosses, MapCrosses & outCrosses ); - // \ru Создать функции перехода к параметрам кривых. \en Create functions for mapping to curve parameters. - void CreateParamFunctions( bool dirU, const MapCrosses & crosses ); - // \ru Расчет производных в точке для образующей кривой. \en Calculation of derivatives at a point for a generating curve. - void GeneratrixCurveExplore_v3( bool dirU, size_t ind, double t, - MbCartPoint3D & p, MbVector3D & fir, MbVector3D & sec, MbVector3D & thir ) const; - // \ru Инициализировать массивы расширения. \en Init expansion arrays. - void InitExtArrays( const bool (*adjPatch)[4] = nullptr ); + // \ru Проверить параметры и в случае выхода за пределы загнать в область определения. + // \en Check parameters and if it is out of limits, then drive it to domain + void CheckParams( double & u, double & v ) const; + // \ru Проверить параметры и в случае захода за полюс или выходе за период загнать в область определения. + // \en Check parameters and if it is out of pole or it is out of period, then drive it to the domain region. + void CheckParamsEx( double & u, double & v, MbMeshSurfaceAuxiliaryData * ucache ) const; + // \ru Попытаться вычислить шаг по U, исходя из шагов по соответствующим операторам Loft-ов \en Try to calculate step by U through steps of corresponding Loft operators + bool SurfDeviationStepU( double & u, double & v, double ang, double & resStep, MbMeshSurfaceAuxiliaryData * ucache ) const; + // \ru Попытаться вычислить шаг по V, исходя из шага по соответствующим операторам Loft-ов \en Try to calculate step by V through steps of corresponding Loft operators + bool SurfDeviationStepV( double & u, double & v, double ang, double & resStepv, MbMeshSurfaceAuxiliaryData * ucache ) const; + // \ru Создать таблицу пересечений для дополнительных кривых. \en Create an intersection table for additional curves. + void CreateCurvesCrossTable( MapCrosses & crosses, MapCrosses & outCrosses ); + // \ru Создать функции перехода к параметрам кривых. \en Create functions for mapping to curve parameters. + void CreateParamFunctions( bool dirU, const MapCrosses & crosses ); + // \ru Расчет производных в точке для образующей кривой. \en Calculation of derivatives at a point for a generating curve. + void GeneratrixCurveExplore_v3( bool dirU, size_t ind, double t, + MbCartPoint3D & p, MbVector3D & fir, MbVector3D & sec, MbVector3D & thir ) const; + // \ru Инициализировать массивы расширения. \en Init expansion arrays. + void InitExtArrays( const bool (*adjPatch)[4] = nullptr ); /** \} */ @@ -823,6 +862,7 @@ OBVIOUS_PRIVATE_COPY( MbMeshSurface ) IMPL_PERSISTENT_OPS( MbMeshSurface ) + //------------------------------------------------------------------------------ // \ru Проверить параметры и в случае выхода за пределы загнать в область определения \en Check parameters and if it is out of limits, then drive it to domain // --- @@ -894,5 +934,4 @@ inline void MbMeshSurface::CheckParamsEx( double & u, double & v, MbMeshSurfaceA } - #endif // __SURF_MESH_SURFACE_H diff --git a/C3d/Include/surf_offset_surface.h b/C3d/Include/surf_offset_surface.h index e0c3917..249fd2e 100644 --- a/C3d/Include/surf_offset_surface.h +++ b/C3d/Include/surf_offset_surface.h @@ -165,33 +165,33 @@ public: /** \ru \name Функции инициализации \en \name Initialization functions \{ */ - /** \brief \ru Инициализация по смещению и приращениям параметров. - \en Initialization by offset and increments of parameters. \~ - \details \ru Инициализация по смещению и приращениям параметров.\n - Приращение параметров нужно использовать для изменения области определения поверхности относительно базовой поверхности. - \en Initialization by offset and increments of parameters.\n - Increment of parameters needs to be used for change of surface domain relative to base surface. \~ - \param[in] d0 - \ru Величина смещения offsetUminVmin. - \en Offset distance offsetUminVmin. \~ - \param[in] d1 - \ru Величина смещения offsetUmaxVmin. - \en Offset distance offsetUmaxVmin. \~ - \param[in] d2 - \ru Величина смещения offsetUminVmax. - \en Offset distance offsetUminVmax. \~ - \param[in] d3 - \ru Величина смещения offsetUmaxVmax. - \en Offset distance offsetUmaxVmax. \~ - \param[in] t - \ru Тип смещения точек: константный, линейный или кубический. - \en The offset type: constant, or linear, or cubic. \~ - \param[in] u0 - \ru Изменение umin параметра - \en The change of umin parameter \~ - \param[in] u1 - \ru Изменение umax параметра - \en The change of umax parameter \~ - \param[in] v0 - \ru Изменение umin параметра - \en The change of umin parameter \~ - \param[in] v1 - \ru Изменение umax параметра - \en The change of umax parameter \~ - */ - void Init( double d0, double d1, double d2, double d3, MbeOffsetType t, double u0, double u1, double v0, double v1 ); - void Init( double d, double u0, double u1, double v0, double v1 ); + /** \brief \ru Инициализация по смещению и приращениям параметров. + \en Initialization by offset and increments of parameters. \~ + \details \ru Инициализация по смещению и приращениям параметров.\n + Приращение параметров нужно использовать для изменения области определения поверхности относительно базовой поверхности. + \en Initialization by offset and increments of parameters.\n + Increment of parameters needs to be used for change of surface domain relative to base surface. \~ + \param[in] d0 - \ru Величина смещения offsetUminVmin. + \en Offset distance offsetUminVmin. \~ + \param[in] d1 - \ru Величина смещения offsetUmaxVmin. + \en Offset distance offsetUmaxVmin. \~ + \param[in] d2 - \ru Величина смещения offsetUminVmax. + \en Offset distance offsetUminVmax. \~ + \param[in] d3 - \ru Величина смещения offsetUmaxVmax. + \en Offset distance offsetUmaxVmax. \~ + \param[in] t - \ru Тип смещения точек: константный, линейный или кубический. + \en The offset type: constant, or linear, or cubic. \~ + \param[in] u0 - \ru Изменение umin параметра + \en The change of umin parameter \~ + \param[in] u1 - \ru Изменение umax параметра + \en The change of umax parameter \~ + \param[in] v0 - \ru Изменение umin параметра + \en The change of umin parameter \~ + \param[in] v1 - \ru Изменение umax параметра + \en The change of umax parameter \~ + */ + void Init( double d0, double d1, double d2, double d3, MbeOffsetType t, double u0, double u1, double v0, double v1 ); + void Init( double d, double u0, double u1, double v0, double v1 ); /** \} */ /** \ru \name Общие функции геометрического объекта \en \name Common functions of a geometric object @@ -282,12 +282,12 @@ public: \en \name Functions for get of the group of data inside and outside the surface's domain of parameters. \{ */ void Explore( double & u, double & v, bool ext, - MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, - MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; - virtual void _PointNormal( double u, double v, - MbCartPoint3D & pnt, MbVector3D & deru, MbVector3D & derv, - MbVector3D & norm, MbVector3D & noru, MbVector3D & norv, - MbVector3D & deruu, MbVector3D & dervv, MbVector3D & deruv ) const override; // \ru Значения производных в точке. \en Values of derivatives at point. + MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, + MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; + void _PointNormal( double u, double v, + MbCartPoint3D & pnt, MbVector3D & deru, MbVector3D & derv, + MbVector3D & norm, MbVector3D & noru, MbVector3D & norv, + MbVector3D & deruu, MbVector3D & dervv, MbVector3D & deruv ) const override; // \ru Значения производных в точке. \en Values of derivatives at point. /** \} */ /** \ru \name Функции движения по поверхности \en \name Functions of moving along the surface @@ -321,9 +321,9 @@ public: bool IsSpecialSimilarToSurface( const MbSurface & surf, VERSION version, double precision = METRIC_PRECISION ) const override; // \ru Специальный случай \en Special case // \ru Определение разбивки параметрической области поверхности вертикалями и горизонталями. \en Determine splitting of parametric region of surface by vertical and horizontal lines. - virtual void GetTesselation( const MbStepData & stepData, - double u1, double u2, double v1, double v2, - SArray & uu, SArray & vv ) const override; + void GetTesselation( const MbStepData & stepData, + double u1, double u2, double v1, double v2, + SArray & uu, SArray & vv ) const override; size_t GetUMeshCount() const override; // \ru Выдать количество полигонов по u. \en Get the count of polygons by u. size_t GetVMeshCount() const override; // \ru Выдать количество полигонов по v. \en Get the count of polygons by v. @@ -337,6 +337,10 @@ public: bool IsLineU () const override; // \ru Если true все производные по U выше первой равны нулю. \en If true, then all the derivatives by U higher the first one are equal to zero. bool IsLineV () const override; // \ru Если true все производные по V выше первой равны нулю. \en If true, then all the derivatives by V higher the first one are equal to zero. + // \ru Нахождение проекции точки на поверхность в направлении вектора. Для внутреннего использования. \en Finding of point projections to the surface in direction of the vector. For internal use only. + MbeNewtonResult DirectPointProjectionNewton( const MbCartPoint3D & p, const MbVector3D & _vect, size_t iterLimit, + double & u, double & v, double & w, bool ext ) const override; + // \ru Найти все проекции точки на поверхность вдоль вектора в любом из двух направлений. \en Find all a point projection onto the surface along a vector in either of two directions. void DirectPointProjection( const MbCartPoint3D & pnt, const MbVector3D & vect, SArray & uv, bool ext, MbRect2D * uvRange = nullptr ) const override; @@ -358,81 +362,81 @@ public: \en \name Functions of the offset surface \{ */ - // \ru Тип смещения точек. \en The type of points offset. - MbeOffsetType GetOffsetType() const { return type; } - // \ru Постоянное ли смещение точек? \en Is const the offset type? - bool IsConstOffset() const { return ( (type == off_Empty) || (type == off_Const) ); } - // \ru Величина смещения. \en The offset distance. - double GetDistance( size_t i ) const { - i = i % 4; - if ( i == 1 ) return offsetUmaxVmin; - else - if ( i == 2 ) return offsetUminVmax; - else - if ( i == 3 ) return offsetUmaxVmax; - return offsetUminVmin; - } - // \ru Средняя величина смещения. \en The average offset distance. - double GetDistance() const { return ( offsetUminVmin + offsetUmaxVmin + offsetUminVmax + offsetUmaxVmax ) / 4; } + // \ru Тип смещения точек. \en The type of points offset. + MbeOffsetType GetOffsetType() const { return type; } + // \ru Постоянное ли смещение точек? \en Is const the offset type? + bool IsConstOffset() const { return ( (type == off_Empty) || (type == off_Const) ); } + // \ru Величина смещения. \en The offset distance. + double GetDistance( size_t i ) const { + i = i % 4; + if ( i == 1 ) return offsetUmaxVmin; + else + if ( i == 2 ) return offsetUminVmax; + else + if ( i == 3 ) return offsetUmaxVmax; + return offsetUminVmin; + } + // \ru Средняя величина смещения. \en The average offset distance. + double GetDistance() const { return ( offsetUminVmin + offsetUmaxVmin + offsetUminVmax + offsetUmaxVmax ) / 4; } - /** \brief \ru Установить величины смещения. - \en Set offset distances. \~ - \param[in] d - \ru Новая величина смещения - \en New offset distance \~ - */ - void SetDistance( double d, size_t i ); - // \ru Установить постоянную величину смещения. Set new constant offset distance. - void SetDistance( double d ); + /** \brief \ru Установить величины смещения. + \en Set offset distances. \~ + \param[in] d - \ru Новая величина смещения + \en New offset distance \~ + */ + void SetDistance( double d, size_t i ); + // \ru Установить постоянную величину смещения. Set new constant offset distance. + void SetDistance( double d ); - /** \brief \ru Проверить корректность точки поверхности. - \en Check the correctness of the point of a surface. \~ - \details \ru Проверить корректность точки поверхности по кривизне подложки.\n - Точка считается некорректной, если в ней поверхность самопересекается или имеет излом. - \en Check the correctness of the point of a surface by curvature of substrate.\n - Point is considered incorrect if a surface is self-intersected or has a break in it. \~ - \param[in] uv - \ru Точка для проверки - \en Point to check \~ - \return \ru true, если точка корректная - \en True if point is correct \~ - */ - bool IsCurvatureValid( const MbCartPoint & uv ) const; + /** \brief \ru Проверить корректность точки поверхности. + \en Check the correctness of the point of a surface. \~ + \details \ru Проверить корректность точки поверхности по кривизне подложки.\n + Точка считается некорректной, если в ней поверхность самопересекается или имеет излом. + \en Check the correctness of the point of a surface by curvature of substrate.\n + Point is considered incorrect if a surface is self-intersected or has a break in it. \~ + \param[in] uv - \ru Точка для проверки + \en Point to check \~ + \return \ru true, если точка корректная + \en True if point is correct \~ + */ + bool IsCurvatureValid( const MbCartPoint & uv ) const; /** \} */ private: - void CheckParam ( double & u, double & v ) const; // \ru Проверка параметров (попадание в пределы). \en Check parameters (being in limits). - void CheckExtParam( double & u, double & v, MbOffsetSurfaceAuxiliaryData * ucache ) const; // \ru Проверка параметров (на наличие полюсов). \en Check parameters (for presence of poles). - void CheckPoles ( MbOffsetSurfaceAuxiliaryData * ) const; // \ru Проверить наличие полюсов на краях поверхности \en Check presence of poles on surface boundaries - void CheckPole ( double param, bool isU, MbeSurfacePoleType & poleType, CommonMutex* lock, MbOffsetSurfaceAuxiliaryData * ) const; + void CheckParam ( double & u, double & v ) const; // \ru Проверка параметров (попадание в пределы). \en Check parameters (being in limits). + void CheckExtParam( double & u, double & v, MbOffsetSurfaceAuxiliaryData * ucache ) const; // \ru Проверка параметров (на наличие полюсов). \en Check parameters (for presence of poles). + void CheckPoles ( MbOffsetSurfaceAuxiliaryData * ) const; // \ru Проверить наличие полюсов на краях поверхности \en Check presence of poles on surface boundaries + void CheckPole ( double param, bool isU, MbeSurfacePoleType & poleType, CommonMutex* lock, MbOffsetSurfaceAuxiliaryData * ) const; // \ru Вычисление эквидистанты и её производных. \en The offset calculation and it derivatives calculation. - double Offset0 ( double u, double v ) const; - double OffsetU ( double u, double v ) const; - double OffsetV ( double u, double v ) const; - double OffsetUU ( double u, double v ) const; - double OffsetUV ( double u, double v ) const; - double OffsetVV ( double u, double v ) const; - double OffsetUUU( double u, double v ) const; - double OffsetUUV( double u, double v ) const; - double OffsetUVV( double u, double v ) const; - double OffsetVVV( double u, double v ) const; + double Offset0 ( double u, double v ) const; + double OffsetU ( double u, double v ) const; + double OffsetV ( double u, double v ) const; + double OffsetUU ( double u, double v ) const; + double OffsetUV ( double u, double v ) const; + double OffsetVV ( double u, double v ) const; + double OffsetUUU( double u, double v ) const; + double OffsetUUV( double u, double v ) const; + double OffsetUVV( double u, double v ) const; + double OffsetVVV( double u, double v ) const; - // \ru Точка на расширенной поверхности. \en The point on the extended surface. - void _PointOn( double u, double v, MbCartPoint3D &, MbOffsetSurfaceAuxiliaryData * ) const; + // \ru Точка на расширенной поверхности. \en The point on the extended surface. + void _PointOn( double u, double v, MbCartPoint3D &, MbOffsetSurfaceAuxiliaryData * ) const; - // \ru Частные случаи поверхностей. \en Special cases of surfaces. - MbSplineSurface * CasePlane ( double, double, double, double, bool ) const; - MbSplineSurface * CaseCylinder ( double, double, double, double, bool ) const; - MbSplineSurface * CaseCone ( double, double, double, double, bool ) const; - MbSplineSurface * CaseSphere ( double, double, double, double, bool ) const; - MbSplineSurface * CaseTorus ( double, double, double, double, bool ) const; - MbSplineSurface * CaseFillets ( double, double, double, double, bool ) const; - MbSplineSurface * CaseLine ( double, double, double, double, bool ) const; - MbSplineSurface * CaseRevolution( double, double, double, double, bool ) const; - MbSplineSurface * CaseExtrusion ( double, double, double, double, bool ) const; - MbSplineSurface * CaseSwept ( double, double, double, double, bool ) const; - MbSplineSurface * CaseLofted ( double, double, double, double, bool ) const; - MbSplineSurface * CaseArbitrary ( double, double, double, double, bool ) const; + // \ru Частные случаи поверхностей. \en Special cases of surfaces. + MbSplineSurface * CasePlane ( double, double, double, double, bool ) const; + MbSplineSurface * CaseCylinder ( double, double, double, double, bool ) const; + MbSplineSurface * CaseCone ( double, double, double, double, bool ) const; + MbSplineSurface * CaseSphere ( double, double, double, double, bool ) const; + MbSplineSurface * CaseTorus ( double, double, double, double, bool ) const; + MbSplineSurface * CaseFillets ( double, double, double, double, bool ) const; + MbSplineSurface * CaseLine ( double, double, double, double, bool ) const; + MbSplineSurface * CaseRevolution( double, double, double, double, bool ) const; + MbSplineSurface * CaseExtrusion ( double, double, double, double, bool ) const; + MbSplineSurface * CaseSwept ( double, double, double, double, bool ) const; + MbSplineSurface * CaseLofted ( double, double, double, double, bool ) const; + MbSplineSurface * CaseArbitrary ( double, double, double, double, bool ) const; - void operator = ( const MbOffsetSurface & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbOffsetSurface & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbOffsetSurface ) }; diff --git a/C3d/Include/surf_plane.h b/C3d/Include/surf_plane.h index d3bb071..0b659eb 100644 --- a/C3d/Include/surf_plane.h +++ b/C3d/Include/surf_plane.h @@ -64,146 +64,146 @@ public: /** \ru \name Функции инициализации \en \name Initialization functions \{ */ - /// \ru Инициализация по плоскости. \en Initialization by plane. - void Init( const MbPlane & ); + /// \ru Инициализация по плоскости. \en Initialization by plane. + void Init( const MbPlane & ); - /** \brief \ru Инициализация по системе координат и расстоянию. - \en Initialization by coordinate system and distance. \~ - \details \ru Инициализация плоскости системой координат init co сдвигом на - расстояние distance в направлении нормали (оси Z). - \en Initialization by coordinate system and translation by - the distance 'distance' in direction of the normal vector (Z axis). \~ - \param[in] init - \ru Система координат - \en Coordinate system \~ - \param[in] distance - \ru Расстояние - \en Distance \~ - */ - void Init( const MbPlacement3D & init, double distance ); + /** \brief \ru Инициализация по системе координат и расстоянию. + \en Initialization by coordinate system and distance. \~ + \details \ru Инициализация плоскости системой координат init co сдвигом на + расстояние distance в направлении нормали (оси Z). + \en Initialization by coordinate system and translation by + the distance 'distance' in direction of the normal vector (Z axis). \~ + \param[in] init - \ru Система координат + \en Coordinate system \~ + \param[in] distance - \ru Расстояние + \en Distance \~ + */ + void Init( const MbPlacement3D & init, double distance ); - /** \brief \ru Инициализация по точке и системе координат. - \en Initialization by point and coordinate system. \~ - \details \ru Инициализация по точке и системе координат.\n - В результате получаем плоскость с правой системой координат. - \en Initialization by point and coordinate system.\n - The result is a plane with right coordinate system. \~ - \param[in] p - \ru Точка, определяет положение начала системы координат плоскости - \en A point, it defines location of the plane origin. \~ - \param[in] init - \ru Система координат, определяет направление осей Z, X - \en A coordinate system, it defines direction of Z and X axes. \~ - */ - void Init( const MbCartPoint3D & p, const MbPlacement3D & init ); + /** \brief \ru Инициализация по точке и системе координат. + \en Initialization by point and coordinate system. \~ + \details \ru Инициализация по точке и системе координат.\n + В результате получаем плоскость с правой системой координат. + \en Initialization by point and coordinate system.\n + The result is a plane with right coordinate system. \~ + \param[in] p - \ru Точка, определяет положение начала системы координат плоскости + \en A point, it defines location of the plane origin. \~ + \param[in] init - \ru Система координат, определяет направление осей Z, X + \en A coordinate system, it defines direction of Z and X axes. \~ + */ + void Init( const MbCartPoint3D & p, const MbPlacement3D & init ); - /** \brief \ru Инициализация по точке. - \en Initialize by point. \~ - \details \ru Инициализация по точке.\n - В результате получаем плоскость с правой системой координат.\n - Направление осей координат Z, X остается. - \en Initialization by point.\n - The result is a plane with right coordinate system.\n - Directions of Z and X axes remain. \~ - \param[in] p - \ru Точка, определяет положение начала системы координат плоскости - \en A point, it defines location of the plane origin. \~ - */ - void Init( const MbCartPoint3D & p ); + /** \brief \ru Инициализация по точке. + \en Initialize by point. \~ + \details \ru Инициализация по точке.\n + В результате получаем плоскость с правой системой координат.\n + Направление осей координат Z, X остается. + \en Initialization by point.\n + The result is a plane with right coordinate system.\n + Directions of Z and X axes remain. \~ + \param[in] p - \ru Точка, определяет положение начала системы координат плоскости + \en A point, it defines location of the plane origin. \~ + */ + void Init( const MbCartPoint3D & p ); - /** \brief \ru Инициализация по системе координат, углу, кривой и параметру. - \en Initialization by coordinate system, angle, curve and parameter. \~ - \details \ru Инициализация по системе координат, углу, кривой и параметру.\n - В случае успеха получаем плоскость:\n - с правой системой координат;\n - центр системы координат определяет точка кривой curve с параметром t;\n - направление оси X показывает вектор производной кривой curve в точке с параметром t;\n - направление оси Z показывает ось Z системы координат init, повернутая вокруг оси с направлением - - осью X на угол angle. - \en Initialization by coordinate system, angle, curve and parameter.\n - In case of success we get a plane:\n - with right coordinate system,\n - center of coordinate system is defined by a point on a curve 'curve' with parameter t;\n - direction of the axis X is defined by the derivative vector of a curve 'curve' in the point with parameter t;\n - direction of Z axis is defined by Z axis of the coordinate system 'init' rotated around the axis with the direction of - X axis by the angle 'angle'. \~ - \param[in] init - \ru Система координат - \en Coordinate system \~ - \param[in] ang - \ru Угол - \en Angle \~ - \param[in] curve - \ru Кривая - \en Curve \~ - \param[in] t - \ru Параметр на кривой - \en Parameter on curve \~ - \return \ru true в случае успеха - \en Returns true in case of success. \~ - */ - bool Init( const MbPlacement3D & init, double ang, MbCurve3D & curve, double t = 0 ); + /** \brief \ru Инициализация по системе координат, углу, кривой и параметру. + \en Initialization by coordinate system, angle, curve and parameter. \~ + \details \ru Инициализация по системе координат, углу, кривой и параметру.\n + В случае успеха получаем плоскость:\n + с правой системой координат;\n + центр системы координат определяет точка кривой curve с параметром t;\n + направление оси X показывает вектор производной кривой curve в точке с параметром t;\n + направление оси Z показывает ось Z системы координат init, повернутая вокруг оси с направлением - + осью X на угол angle. + \en Initialization by coordinate system, angle, curve and parameter.\n + In case of success we get a plane:\n + with right coordinate system,\n + center of coordinate system is defined by a point on a curve 'curve' with parameter t;\n + direction of the axis X is defined by the derivative vector of a curve 'curve' in the point with parameter t;\n + direction of Z axis is defined by Z axis of the coordinate system 'init' rotated around the axis with the direction of + X axis by the angle 'angle'. \~ + \param[in] init - \ru Система координат + \en Coordinate system \~ + \param[in] ang - \ru Угол + \en Angle \~ + \param[in] curve - \ru Кривая + \en Curve \~ + \param[in] t - \ru Параметр на кривой + \en Parameter on curve \~ + \return \ru true в случае успеха + \en Returns true in case of success. \~ + */ + bool Init( const MbPlacement3D & init, double ang, MbCurve3D & curve, double t = 0 ); - /** \brief \ru Инициализация по точке, кривой и параметру. - \en Initialization by point, curve and parameter. \~ - \details \ru Инициализация по точке, кривой и параметру.\n - В случае успеха получаем плоскость:\n - с началом координат в точке на кривой curve с параметром t;\n - направление оси X показывает вектор производной кривой в точке с параметром t;\n - направление оси Y показывает вектор из точки на кривой в точку p. - \en Initialization by point, curve and parameter.\n - In case of success we get a plane:\n - with origin at the point of the curve with parameter t;\n - direction of the axis X is defined by the derivative vector of a curve in the point with parameter t;\n - direction of Y axis is defined by the vector from the point on the curve to point p. \~ - \param[in] p - \ru Точка - \en Point \~ - \param[in] curve - \ru Кривая - \en Curve \~ - \param[in] t - \ru Параметр на кривой - \en Parameter on curve \~ - \return \ru true в случае успеха - \en Returns true in case of success. \~ - */ - bool Init( const MbCartPoint3D & p, MbCurve3D & curve, double t = 0 ); + /** \brief \ru Инициализация по точке, кривой и параметру. + \en Initialization by point, curve and parameter. \~ + \details \ru Инициализация по точке, кривой и параметру.\n + В случае успеха получаем плоскость:\n + с началом координат в точке на кривой curve с параметром t;\n + направление оси X показывает вектор производной кривой в точке с параметром t;\n + направление оси Y показывает вектор из точки на кривой в точку p. + \en Initialization by point, curve and parameter.\n + In case of success we get a plane:\n + with origin at the point of the curve with parameter t;\n + direction of the axis X is defined by the derivative vector of a curve in the point with parameter t;\n + direction of Y axis is defined by the vector from the point on the curve to point p. \~ + \param[in] p - \ru Точка + \en Point \~ + \param[in] curve - \ru Кривая + \en Curve \~ + \param[in] t - \ru Параметр на кривой + \en Parameter on curve \~ + \return \ru true в случае успеха + \en Returns true in case of success. \~ + */ + bool Init( const MbCartPoint3D & p, MbCurve3D & curve, double t = 0 ); - /** \brief \ru Инициализация по точке, перпендикулярно кривой. - \en Initialization by point, perpendicularly to curve. \~ - \details \ru Инициализация по точке, перпендикулярно кривой. - \en Initialization by point, perpendicularly to curve. \~ - \param[in] p - \ru Точка - \en Point \~ - \param[in] curve - \ru Кривая - \en Curve \~ - \param[in] checkPlanar - \ru Использовать информацию о кривой, если он плоская. - \en Use curve information, if it's planar. \~ - */ - bool Init( const MbCurve3D & curve, const MbCartPoint3D & p, bool checkPlanar ); + /** \brief \ru Инициализация по точке, перпендикулярно кривой. + \en Initialization by point, perpendicularly to curve. \~ + \details \ru Инициализация по точке, перпендикулярно кривой. + \en Initialization by point, perpendicularly to curve. \~ + \param[in] p - \ru Точка + \en Point \~ + \param[in] curve - \ru Кривая + \en Curve \~ + \param[in] checkPlanar - \ru Использовать информацию о кривой, если он плоская. + \en Use curve information, if it's planar. \~ + */ + bool Init( const MbCurve3D & curve, const MbCartPoint3D & p, bool checkPlanar ); - /// \ru Инициализация по локальной системе координат. \en Initialization by local coordinate system. - void Init( const MbPlacement3D & ); - /// \ru Инициализация по прямой и точке. \en Initialization by line and point. - bool Init( const MbLine3D &, const MbCartPoint3D & ); - /// \ru Инициализация по прямой и вектору. \en Initialization by line and vector. - bool Init( const MbLine3D &, const MbVector3D & ); + /// \ru Инициализация по локальной системе координат. \en Initialization by local coordinate system. + void Init( const MbPlacement3D & ); + /// \ru Инициализация по прямой и точке. \en Initialization by line and point. + bool Init( const MbLine3D &, const MbCartPoint3D & ); + /// \ru Инициализация по прямой и вектору. \en Initialization by line and vector. + bool Init( const MbLine3D &, const MbVector3D & ); - /** \brief \ru Инициализация по двум прямым. - \en Initialization by two lines. \~ - \details \ru Инициализация по двум прямым. - В случа успеха инициализирует плоскость по первой прямой - и вектору - направлению второй прямой. - \en Initialization by two lines. - In case of success it initializes a plane by the first line - and direction of the second line. \~ - \param[in] line1 - \ru Первая прямая - \en First line. \~ - \param[in] line2 - \ru Вторая прямая - \en Second line \~ - */ - bool Init( const MbLine3D & line1, const MbLine3D & line2 ); + /** \brief \ru Инициализация по двум прямым. + \en Initialization by two lines. \~ + \details \ru Инициализация по двум прямым. + В случа успеха инициализирует плоскость по первой прямой + и вектору - направлению второй прямой. + \en Initialization by two lines. + In case of success it initializes a plane by the first line + and direction of the second line. \~ + \param[in] line1 - \ru Первая прямая + \en First line. \~ + \param[in] line2 - \ru Вторая прямая + \en Second line \~ + */ + bool Init( const MbLine3D & line1, const MbLine3D & line2 ); - /// \ru Инициализация плоскости по трем точкам. \en Initialization of plane by three points. - bool Init( const MbCartPoint3D & c0, const MbCartPoint3D & c1, const MbCartPoint3D & c2 ); + /// \ru Инициализация плоскости по трем точкам. \en Initialization of plane by three points. + bool Init( const MbCartPoint3D & c0, const MbCartPoint3D & c1, const MbCartPoint3D & c2 ); - /** \brief \ru Инициализация по плейсменту и версии. - \en Initialization by placement and version. \~ - \details \ru Инициализация по плейсменту и версии. - \en Initialization by placement and version. \~ - \warning \ru Только для использования в КОМПАС-3D. - \en This can be used only in KOMPAS-3D. \~ - */ - void Update( const MbPlacement3D &, VERSION version ); // \ru Жёсткая привязка к плейсменту(детали) \en Rigid binding to a placement (a part) + /** \brief \ru Инициализация по плейсменту и версии. + \en Initialization by placement and version. \~ + \details \ru Инициализация по плейсменту и версии. + \en Initialization by placement and version. \~ + \warning \ru Только для использования в КОМПАС-3D. + \en This can be used only in KOMPAS-3D. \~ + */ + void Update( const MbPlacement3D &, VERSION version ); // \ru Жёсткая привязка к плейсменту(детали) \en Rigid binding to a placement (a part) /** \} */ /** \ru \name Общие функции геометрического объекта \en \name Common functions of a geometric object @@ -276,12 +276,12 @@ public: \en \name Functions for get of the group of data inside and outside the surface's domain of parameters. \{ */ void Explore( double & u, double & v, bool ext, - MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, - MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; - virtual void _PointNormal( double u, double v, - MbCartPoint3D & pnt, MbVector3D & deru, MbVector3D & derv, - MbVector3D & norm, MbVector3D & noru, MbVector3D & norv, - MbVector3D & deruu, MbVector3D & dervv, MbVector3D & deruv ) const override; // \ru Значения производных в точке. \en Values of derivatives at point. + MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, + MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; + void _PointNormal( double u, double v, + MbCartPoint3D & pnt, MbVector3D & deru, MbVector3D & derv, + MbVector3D & norm, MbVector3D & noru, MbVector3D & norv, + MbVector3D & deruu, MbVector3D & dervv, MbVector3D & deruv ) const override; // \ru Значения производных в точке. \en Values of derivatives at point. /** \} */ /** \ru \name Функции движения по поверхности \en \name Function of moving on surface @@ -329,11 +329,11 @@ public: // \ru Пересечения с кривой. \en Intersection with a curve. virtual MbeNewtonResult CurveIntersectNewton( const MbCurve3D &, double funcEpsilon, size_t limit, double & u, double & v, double & t, bool ext0, bool ext ) const override; // \ru Нахождениe точки пересечения c кривой. \en Search of a point of intersection with curve. - virtual void CurveIntersection ( const MbCurve3D &, SArray & uv, SArray & tt, - bool ext0, bool ext, bool touchInclude = false ) const override; // \ru Все точки пересечения плоскости и кривой. \en All points of intersection between a plane and a curve. + void CurveIntersection( const MbCurve3D &, SArray & uv, SArray & tt, + bool ext0, bool ext, bool touchInclude = false ) const override; // \ru Все точки пересечения плоскости и кривой. \en All points of intersection between a plane and a curve. // \ru Пересечение с поверхностью. \en Intersection with surface. - virtual MbeNewtonResult SurfaceIntersectNewton( const MbSurface & surf, MbeParamDir switchPar, double funcEpsilon, size_t limit, - double & u0, double & v0, double & u1, double & v1, bool ext0, bool ext1 ) const override; + MbeNewtonResult SurfaceIntersectNewton( const MbSurface & surf, MbeParamDir switchPar, double funcEpsilon, size_t limit, + double & u0, double & v0, double & u1, double & v1, bool ext0, bool ext1 ) const override; // \ru Подобные ли поверхности для объединения (слива). \en Whether the surfaces are similar to merge. bool IsSimilarToSurface( const MbSurface & surf, VERSION version, double precision = METRIC_PRECISION ) const override; // \ru Дать двумерную матрицу преобразования из своей параметрической области в параметрическую область surf. \en Get two-dimensional matrix of transformation from its parametric region to the parametric region of 'surf'. @@ -349,9 +349,9 @@ public: void GetParamsToUnit( double u, double v, double & uParam, double & vParam ) const override; // \ru Дать приращение параметра u и параметра v, соответствующее единичной длине в пространстве. \en Get increment of parameters, corresponding to the unit length in space. // \ru Определение разбивки параметрической области поверхности вертикалями и горизонталями. \en Determine a splitting of parametric region of a surface by verticals and horizontals. - virtual void GetTesselation( const MbStepData & stepData, - double u1, double u2, double v1, double v2, - SArray & uu, SArray & vv ) const override; + void GetTesselation( const MbStepData & stepData, + double u1, double u2, double v1, double v2, + SArray & uu, SArray & vv ) const override; void CalculateGabarit( MbCube &gab ) const override; // \ru Выдать габарит поверхности. \en Get bounding box of surface. void CalculateLocalGabarit( const MbMatrix3D &, MbCube & ) const override; // \ru Рассчитать габарит относительно л.с.к. \en Calculate bounding box relative to the local coordinate system. @@ -376,120 +376,121 @@ public: /** \ru \name Функции плоскости \en \name Functions of plane. \{ */ - /// \ru Пересекается ли габаритный куб поверхности с плоскостью. \en Whether the bounding cube of a surface intersects a plane. - bool CubeIntersection( const MbSurface & ) const; - /// \ru Пересекается ли плоскость с кубом. \en Whether a plane intersects a cube. - bool Intersect( const MbCube & c ) const; + /// \ru Пересекается ли габаритный куб поверхности с плоскостью. \en Whether the bounding cube of a surface intersects a plane. + bool CubeIntersection( const MbSurface & ) const; + /// \ru Пересекается ли плоскость с кубом. \en Whether a plane intersects a cube. + bool Intersect( const MbCube & c ) const; - /** \brief \ru Установить пределы поверхности. - \en Set surface limits. \~ - \details \ru Установить пределы поверхности квадратом с центром в начале координат - и стороной, равной 2 * d. - \en Set surface limits by the square with a center in origin - and a side equal to 2 * d. \~ - */ - void SetLimit( double d ) { umax = vmax = ::fabs(d); umin = vmin = -::fabs(d); } + /** \brief \ru Установить пределы поверхности. + \en Set surface limits. \~ + \details \ru Установить пределы поверхности квадратом с центром в начале координат + и стороной, равной 2 * d. + \en Set surface limits by the square with a center in origin + and a side equal to 2 * d. \~ + */ + void SetLimit( double d ) { umax = vmax = ::fabs(d); umin = vmin = -::fabs(d); } - /** \brief \ru Установить пределы поверхности. - \en Set surface limits. \~ - \details \ru Установить пределы поверхности прямоугольником с центром в начале координат, - шириной, равной 2 * u, и высотой, равной 2 * v. - \en Set surface limits by the rectangle with a center in origin, - width equal to 2 * u and height equal to 2 * v. \~ - */ - void SetLimit( double u, double v ) { umax = ::fabs(u); vmax = ::fabs(v); umin = -umax; vmin = -vmax; } + /** \brief \ru Установить пределы поверхности. + \en Set surface limits. \~ + \details \ru Установить пределы поверхности прямоугольником с центром в начале координат, + шириной, равной 2 * u, и высотой, равной 2 * v. + \en Set surface limits by the rectangle with a center in origin, + width equal to 2 * u and height equal to 2 * v. \~ + */ + void SetLimit( double u, double v ) { umax = ::fabs(u); vmax = ::fabs(v); umin = -umax; vmin = -vmax; } - /** \brief \ru Включить проекцию куба. - \en Include a cube projection. \~ - \details \ru Расширить пределы плоскости, добавив проекцию куба. - \en Extend the plane limits by adding of the cube projection. \~ - */ - bool IncludeCube( const MbCube & ); + /** \brief \ru Включить проекцию куба. + \en Include a cube projection. \~ + \details \ru Расширить пределы плоскости, добавив проекцию куба. + \en Extend the plane limits by adding of the cube projection. \~ + */ + bool IncludeCube( const MbCube & ); - /** \brief \ru Установить проекцию куба. - \en Set cube projection. \~ - \details \ru Изменить пределы плоскости на проекцию куба на плоскость. - \en Change the limits of plane to the cube projection on plane. \~ - */ - bool AssignCube ( const MbCube & ); + /** \brief \ru Установить проекцию куба. + \en Set cube projection. \~ + \details \ru Изменить пределы плоскости на проекцию куба на плоскость. + \en Change the limits of plane to the cube projection on plane. \~ + */ + bool AssignCube ( const MbCube & ); - /// \ru Синус угла прямой с плоскостью. \en A sine of an angle between the line and the plane. - double GetNormalAngle( const MbLine3D & line ) const; - /// \ru Матрица для преобразования симметрии относительно плоскости. \en The matrix of symmetry transformation relative to the plane - void Symmetry ( MbMatrix3D & m ) const { position.Symmetry(m); } - /// \ru Инвертировать нормаль плоскости. \en Invert the normal of plane. - void Invert( MbMatrix * = nullptr, MbRegTransform * ireg = nullptr ); + /// \ru Синус угла прямой с плоскостью. \en A sine of an angle between the line and the plane. + double GetNormalAngle( const MbLine3D & line ) const; + /// \ru Матрица для преобразования симметрии относительно плоскости. \en The matrix of symmetry transformation relative to the plane + void Symmetry ( MbMatrix3D & m ) const { position.Symmetry(m); } + /// \ru Инвертировать нормаль плоскости. \en Invert the normal of plane. + void Invert( MbMatrix * = nullptr, MbRegTransform * ireg = nullptr ); - /// \ru Сделать систему координат правой. \en Make the coordinate system right. - void SetRightPlacement() { position.SetRight(); SetDirtyGabarit(); } + /// \ru Сделать систему координат правой. \en Make the coordinate system right. + void SetRightPlacement() { position.SetRight(); SetDirtyGabarit(); } - /** \brief \ru Совместить с плейсментом. - \en Match with the placement. \~ - \details \ru Совместить с плейсментом путем вращения до параллельности и перемещения вдоль нормали плейсмента.\n - Центром плоскости становится проекция центра системы координат p.\n - Ось Z плоскости сохраняется.\n - Осью X плоскости становится проекция оси X системы координат p. - \en Match with the placement by rotation till the parallelism and translation along placement normal. - The projection of the coordinate system p origin becomes the center of a plane.\n - The axis Z of a plane remains.\n - The projection X axis of the coordinate system p becomes the axis X of the plane. \~ - \warning \ru Только для использования в КОМПАС-3D. - \en This can be used only in KOMPAS-3D. \~ - */ - void AdaptToPlace( const MbPlacement3D & p ) { position.AdaptToPlace(p); SetDirtyGabarit(); } + /** \brief \ru Совместить с плейсментом. + \en Match with the placement. \~ + \details \ru Совместить с плейсментом путем вращения до параллельности и перемещения вдоль нормали плейсмента.\n + Центром плоскости становится проекция центра системы координат p.\n + Ось Z плоскости сохраняется.\n + Осью X плоскости становится проекция оси X системы координат p. + \en Match with the placement by rotation till the parallelism and translation along placement normal. + The projection of the coordinate system p origin becomes the center of a plane.\n + The axis Z of a plane remains.\n + The projection X axis of the coordinate system p becomes the axis X of the plane. \~ + \warning \ru Только для использования в КОМПАС-3D. + \en This can be used only in KOMPAS-3D. \~ + */ + void AdaptToPlace( const MbPlacement3D & p ) { position.AdaptToPlace(p); SetDirtyGabarit(); } - /// \ru Установить систему координат. \en Set the coordinate system. - void SetPlacement( const MbPlacement3D & p ) { position.Init(p); SetDirtyGabarit(); } + /// \ru Установить систему координат. \en Set the coordinate system. + void SetPlacement( const MbPlacement3D & p ) { position.Init(p); SetDirtyGabarit(); } - /** \brief \ru Точки пересечения плоскости и плоской кривой. - \en Intersection points of a plane and a planar curve. \~ - \details \ru Точки пересечения плоскости и плоской кривой. - \en Intersection points of a plane and a planar curve. \~ - \param[in] curvePlace - \ru Плейсмент кривой - \en Curve placement \~ - \param[in] curve - \ru Кривая - \en Curve \~ - \param[out] uv - \ru Точки пересечения на плоскости - \en Intersection points on plane \~ - \param[out] tt - \ru Параметры точек пересечения на кривой - \en Parameters of intersection points on curve \~ - \param[in] ext0 - \ru Признак поиска точек пересечения на продолжении плоскости - \en An attribute of search of intersection points on the plane extension \~ - \param[in] ext - \ru Признак поиска точек пересечения на продолжении кривой - \en An attribute of search of intersection points on the curve extension \~ - \param[in] touchInclude - \ru true, если нужны точки касания - \en True if tangency points are required \~ - */ - void PlaneCurveIntersection( const MbPlacement3D & curvePlace, MbCurve & curve, - SArray & uv, SArray & tt, - bool ext0, bool ext, bool touchInclude = false ) const; + /** \brief \ru Точки пересечения плоскости и плоской кривой. + \en Intersection points of a plane and a planar curve. \~ + \details \ru Точки пересечения плоскости и плоской кривой. + \en Intersection points of a plane and a planar curve. \~ + \param[in] curvePlace - \ru Плейсмент кривой + \en Curve placement \~ + \param[in] curve - \ru Кривая + \en Curve \~ + \param[out] uv - \ru Точки пересечения на плоскости + \en Intersection points on plane \~ + \param[out] tt - \ru Параметры точек пересечения на кривой + \en Parameters of intersection points on curve \~ + \param[in] ext0 - \ru Признак поиска точек пересечения на продолжении плоскости + \en An attribute of search of intersection points on the plane extension \~ + \param[in] ext - \ru Признак поиска точек пересечения на продолжении кривой + \en An attribute of search of intersection points on the curve extension \~ + \param[in] touchInclude - \ru true, если нужны точки касания + \en True if tangency points are required \~ + */ + void PlaneCurveIntersection( const MbPlacement3D & curvePlace, MbCurve & curve, + SArray & uv, SArray & tt, + bool ext0, bool ext, bool touchInclude = false ) const; - // \ru Подобные ли поверхности для объединения (слива) проверкой по угловым точкам \en Whether surfaces are similar to merge with check by angular points - /** \brief \ru Подобны ли плоскости для объединения. - \en Whether planes are similar to merge. \~ - \details \ru Подобны ли плоскости для объединения. - \en Whether planes are similar to merge. \~ - \param[in] plane - \ru Вторая плоскость - \en Second plane \~ - \param[in] rect0 - \ru Область параметров на первой плоскости - \en Parameter region on the first plane \~ - \param[in] rect1 - \ru Область параметров на второй плоскости - \en Parameter region on the second plane \~ - */ - bool IsSimilarPlanes( const MbPlane & plane, const MbRect & rect0, const MbRect & rect1 ) const; + // \ru Подобные ли поверхности для объединения (слива) проверкой по угловым точкам \en Whether surfaces are similar to merge with check by angular points + /** \brief \ru Подобны ли плоскости для объединения. + \en Whether planes are similar to merge. \~ + \details \ru Подобны ли плоскости для объединения. + \en Whether planes are similar to merge. \~ + \param[in] plane - \ru Вторая плоскость + \en Second plane \~ + \param[in] rect0 - \ru Область параметров на первой плоскости + \en Parameter region on the first plane \~ + \param[in] rect1 - \ru Область параметров на второй плоскости + \en Parameter region on the second plane \~ + */ + bool IsSimilarPlanes( const MbPlane & plane, const MbRect & rect0, const MbRect & rect1 ) const; - /// \ru Является ли габарит плоскости вырожденным. \en Whether the bounding box of a plane is degenerate. - bool IsAreaDegenerate() const; + /// \ru Является ли габарит плоскости вырожденным. \en Whether the bounding box of a plane is degenerate. + bool IsAreaDegenerate() const; /** \} */ private: - void operator = ( const MbPlane & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbPlane & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbPlane ) }; // MbPlane IMPL_PERSISTENT_OPS( MbPlane ) + //------------------------------------------------------------------------------ // \ru Пересечение с граничным прямоугольником \en Intersection with the bounding rectangle. // --- diff --git a/C3d/Include/surf_polysurface.h b/C3d/Include/surf_polysurface.h index 7d8b9e9..d35e3f9 100644 --- a/C3d/Include/surf_polysurface.h +++ b/C3d/Include/surf_polysurface.h @@ -145,243 +145,246 @@ public: virtual void Rebuild() = 0; /// \ru Вернуть количество строк в матрице точек. \en Return rows count in points matrix. - size_t GetPointsLines () const { return points.Lines(); } + size_t GetPointsLines () const { return points.Lines(); } /// \ru Вернуть количество столбцов в матрице точек. \en Return columns count in points matrix. - size_t GetPointsColumns() const { return points.Columns(); } - /** \brief \ru Выдать точку, расположенную в i строке, j колонке. - \en Get the point located at row i and column j. \~ - \details \ru Выдать точку, расположенную в i строке, j колонке.\n - \en Get the point located at row i and column j.\n \~ - \param[in] i - \ru Строка. - \en String. \~ - \param[in] j - \ru Колонка. - \en Column. \~ - \param[in,out] pnt - \ru Запрашиваемая точка. - \en Requested point. \~ - */ - void GetPoint ( size_t i, size_t j, MbCartPoint3D & pnt ) const { pnt = points( i, j ); } - /** \brief \ru Сдвинуть точку, расположенную в i строке, j колонке на заданный вектор. - \en Translate the point located at row i and column j by the given vector. \~ - \details \ru Сдвинуть точку, расположенную в i строке, j колонке на заданный вектор.\n - \en Translate the point located at row i and column j by the given vector.\n \~ - \param[in] i - \ru Строка. - \en String. \~ - \param[in] j - \ru Колонка. - \en Column. \~ - \param[in] v - \ru Вектор перемещения точки. - \en A vector of point translation. \~ - */ - void MovePoint( size_t i, size_t j, const MbVector3D & v ) { points(i,j).Move(v); } + size_t GetPointsColumns() const { return points.Columns(); } + /** \brief \ru Выдать точку, расположенную в i строке, j колонке. + \en Get the point located at row i and column j. \~ + \details \ru Выдать точку, расположенную в i строке, j колонке.\n + \en Get the point located at row i and column j.\n \~ + \param[in] i - \ru Строка. + \en String. \~ + \param[in] j - \ru Колонка. + \en Column. \~ + \param[in,out] pnt - \ru Запрашиваемая точка. + \en Requested point. \~ + */ + void GetPoint ( size_t i, size_t j, MbCartPoint3D & pnt ) const { pnt = points( i, j ); } + /** \brief \ru Сдвинуть точку, расположенную в i строке, j колонке на заданный вектор. + \en Translate the point located at row i and column j by the given vector. \~ + \details \ru Сдвинуть точку, расположенную в i строке, j колонке на заданный вектор.\n + \en Translate the point located at row i and column j by the given vector.\n \~ + \param[in] i - \ru Строка. + \en String. \~ + \param[in] j - \ru Колонка. + \en Column. \~ + \param[in] v - \ru Вектор перемещения точки. + \en A vector of point translation. \~ + */ + void MovePoint( size_t i, size_t j, const MbVector3D & v ) { points(i,j).Move(v); } - /// \ru Получить количество колонок. \en Get count of columns. - size_t GetPointsUCount() const { return ucount; } - /// \ru Получить количество строк. \en Get count of rows. - size_t GetPointsVCount() const { return vcount; } - /** \brief \ru Заполнить матрицу точек. - \en Fill points matrix. \~ - \details \ru Заполнить матрицу точек.\n - \en Fill points matrix.\n \~ - \param[in] pnts - \ru Матрица точек. - \en Matrix of points. \~ - */ - bool GetPoints( Array2 & pnts ) const { return pnts.Init( points ); } - /** \brief \ru Выдать массив отрезков. - \en Get the array of segments. \~ - \details \ru В функции строятся все горизонтальные отрезки между соседними точками и все вертикальные отрезки между соседними точками. - \en The function constructs all horizontal segments between neighboring points and all vertical segments between neighboring points. \~ - \param[in] segments - \ru Множество для хранения отрезков. - \en Set for segments storage. \~ - */ - void GetLineSegments( RPArray & segments ) const; + /// \ru Получить количество колонок. \en Get count of columns. + size_t GetPointsUCount() const { return ucount; } + /// \ru Получить количество строк. \en Get count of rows. + size_t GetPointsVCount() const { return vcount; } + + /** \brief \ru Заполнить матрицу точек. + \en Fill points matrix. \~ + \details \ru Заполнить матрицу точек.\n + \en Fill points matrix.\n \~ + \param[in] pnts - \ru Матрица точек. + \en Matrix of points. \~ + */ + bool GetPoints( Array2 & pnts ) const { return pnts.Init( points ); } + + /** \brief \ru Выдать массив отрезков. + \en Get the array of segments. \~ + \details \ru В функции строятся все горизонтальные отрезки между соседними точками и все вертикальные отрезки между соседними точками. + \en The function constructs all horizontal segments between neighboring points and all vertical segments between neighboring points. \~ + \param[in] segments - \ru Множество для хранения отрезков. + \en Set for segments storage. \~ + */ + void GetLineSegments( RPArray & segments ) const; + /** \} */ /** \ru \name Функции, предоставляющие интерфейс поверхности для сплайновой формы. \en \name Functions performing an interface for a surface of spline form. \{ */ - /** \brief \ru Получить узловой вектор по выбранному параметру. - \en Get a knots vector by the chosen parameter. \~ - \details \ru Получить узловой вектор по выбранному параметру.\n - \en Get a knots vector by the chosen parameter.\n \~ - \param[in] isU - \ru Определяет, по какой координате запрашивается узловой вектор: true - по u, false - по v. - \en Determines the requested coordinate of a knot vector: true - u, false - v. \~ - \param[in,out] knots - \ru Матрица для хранения узлового вектора. - \en Matrix for knot vector storage. \~ - */ + /** \brief \ru Получить узловой вектор по выбранному параметру. + \en Get a knots vector by the chosen parameter. \~ + \details \ru Получить узловой вектор по выбранному параметру.\n + \en Get a knots vector by the chosen parameter.\n \~ + \param[in] isU - \ru Определяет, по какой координате запрашивается узловой вектор: true - по u, false - по v. + \en Determines the requested coordinate of a knot vector: true - u, false - v. \~ + \param[in,out] knots - \ru Матрица для хранения узлового вектора. + \en Matrix for knot vector storage. \~ + */ virtual void GetKnots( bool isU, SArray & knots ) const = 0; - /** \brief \ru Получить матрицу весов вершин. - \en Get the matrix of vertices weights. \~ - \details \ru Получить матрицу весов вершин.\n - \en Get the matrix of vertices weights.\n \~ - \param[in,out] wts - \ru Матрица для заполнения значений весов. - \en A matrix for weights values filling. \~ - */ + /** \brief \ru Получить матрицу весов вершин. + \en Get the matrix of vertices weights. \~ + \details \ru Получить матрицу весов вершин.\n + \en Get the matrix of vertices weights.\n \~ + \param[in,out] wts - \ru Матрица для заполнения значений весов. + \en A matrix for weights values filling. \~ + */ virtual void GetWeights( Array2 & wts ) const = 0; - /** \brief \ru Вернуть массив узловых точек и их видимость для операции редактирования как сплайна. - \en Return an array of knot points and their visibility for the operation of editing as spline. \~ - \details \ru Вернуть массив узловых точек и их видимость для операции редактирования как сплайна.\n - \en Return an array of knot points and their visibility for the operation of editing as spline.\n \~ - \param[in,out] params - \ru Матрица контрольных точек с указанием видимости каждой контрольной точки для редактирования. - \en A matrix of control points with specifying of visibility of each control point for editing. \~ - */ + /** \brief \ru Вернуть массив узловых точек и их видимость для операции редактирования как сплайна. + \en Return an array of knot points and their visibility for the operation of editing as spline. \~ + \details \ru Вернуть массив узловых точек и их видимость для операции редактирования как сплайна.\n + \en Return an array of knot points and their visibility for the operation of editing as spline.\n \~ + \param[in,out] params - \ru Матрица контрольных точек с указанием видимости каждой контрольной точки для редактирования. + \en A matrix of control points with specifying of visibility of each control point for editing. \~ + */ virtual void GetPointsWithVisible ( Array2 & params ) const = 0; - /** \brief \ru Вычисление точек на поверхности, соответствующих узлам. - \en Calculation of points on surface corresponding to knots. \~ - \details \ru Вычисление точек на поверхности, соответствующих узлам.\n - \en Calculation of points on surface corresponding to knots.\n \~ - \param[in,out] params - \ru Матрица для хранения точек на поверхности, соответствующих контрольным точкам. - \en A matrix for keeping of points on surface corresponding to control points. \~ - */ + /** \brief \ru Вычисление точек на поверхности, соответствующих узлам. + \en Calculation of points on surface corresponding to knots. \~ + \details \ru Вычисление точек на поверхности, соответствующих узлам.\n + \en Calculation of points on surface corresponding to knots.\n \~ + \param[in,out] params - \ru Матрица для хранения точек на поверхности, соответствующих контрольным точкам. + \en A matrix for keeping of points on surface corresponding to control points. \~ + */ virtual void CalculateUVParameters( Array2 & params ) const = 0; - /** \brief \ru Вычисление точки на поверхности, соответствующей контрольной точке. - \en Calculation of point on surface corresponding to control point. \~ - \details \ru Вычисление точки на поверхности, соответствующей контрольной точке.\n - \en Calculation of point on surface corresponding to control point.\n \~ - \param[in] uIndex - \ru Столбец контрольной точки. - \en A column of control point. \~ - \param[in] vIndex - \ru Строка контрольной точки. - \en A row of control point. \~ - \param[in,out] point - \ru Точка на поверхности. - \en A point on surface. \~ - \return \ru true, если точка на поверхности успешно найдена. - \en True if a point on surface was successfully found. \~ - */ + /** \brief \ru Вычисление точки на поверхности, соответствующей контрольной точке. + \en Calculation of point on surface corresponding to control point. \~ + \details \ru Вычисление точки на поверхности, соответствующей контрольной точке.\n + \en Calculation of point on surface corresponding to control point.\n \~ + \param[in] uIndex - \ru Столбец контрольной точки. + \en A column of control point. \~ + \param[in] vIndex - \ru Строка контрольной точки. + \en A row of control point. \~ + \param[in,out] point - \ru Точка на поверхности. + \en A point on surface. \~ + \return \ru true, если точка на поверхности успешно найдена. + \en True if a point on surface was successfully found. \~ + */ virtual bool CalculateUVParameterForKnot( size_t uIndex, size_t vIndex, MbCartPoint & point ) const = 0; - /** \brief \ru Удаление столбца контрольных точек без изменения поверхности. - \en Deletion of a column of control points without changing of a surface. \~ - \details \ru Удаление столбца контрольных точек без изменения поверхности.\n - \en Deletion of a column of control points without changing of a surface.\n \~ - \param[in] rowId - \ru Номер первого удаляемого столбца. - \en Index of the first deleted column. \~ - \param[in] num - \ru Количество удаляемых столбцов. - \en Count of deleted columns. \~ - \param[in] absEps - \ru Погрешность аппроксимации. - \en Approximation tolerance. \~ - \return \ru Число столбцов, которые удалось удалить. - \en Count of columns which are succeeded to delete. \~ - */ + /** \brief \ru Удаление столбца контрольных точек без изменения поверхности. + \en Deletion of a column of control points without changing of a surface. \~ + \details \ru Удаление столбца контрольных точек без изменения поверхности.\n + \en Deletion of a column of control points without changing of a surface.\n \~ + \param[in] rowId - \ru Номер первого удаляемого столбца. + \en Index of the first deleted column. \~ + \param[in] num - \ru Количество удаляемых столбцов. + \en Count of deleted columns. \~ + \param[in] absEps - \ru Погрешность аппроксимации. + \en Approximation tolerance. \~ + \return \ru Число столбцов, которые удалось удалить. + \en Count of columns which are succeeded to delete. \~ + */ virtual size_t RemoveUKnots( ptrdiff_t & rowId, ptrdiff_t num = 1, double absEps = Math::lengthEpsilon ) = 0; - /** \brief \ru Удаление строки контрольных точек без изменения поверхности. - \en Deletion of a row of control points without changing of a surface. \~ - \details \ru Удаление строки контрольных точек без изменения поверхности.\n - \en Deletion of a row of control points without changing of a surface.\n \~ - \param[in] rowId - \ru Номер первой удаляемой строки. - \en Index of the first deleted row. \~ - \param[in] num - \ru Количество удаляемых строк. - \en Count of deleted rows. \~ - \param[in] absEps - \ru Погрешность аппроксимации. - \en Approximation tolerance. \~ - \return \ru Число строк, которые удалось удалить. - \en Count of rows which are succeeded to delete. \~ - */ + /** \brief \ru Удаление строки контрольных точек без изменения поверхности. + \en Deletion of a row of control points without changing of a surface. \~ + \details \ru Удаление строки контрольных точек без изменения поверхности.\n + \en Deletion of a row of control points without changing of a surface.\n \~ + \param[in] rowId - \ru Номер первой удаляемой строки. + \en Index of the first deleted row. \~ + \param[in] num - \ru Количество удаляемых строк. + \en Count of deleted rows. \~ + \param[in] absEps - \ru Погрешность аппроксимации. + \en Approximation tolerance. \~ + \return \ru Число строк, которые удалось удалить. + \en Count of rows which are succeeded to delete. \~ + */ virtual size_t RemoveVKnots( ptrdiff_t & rowId, ptrdiff_t num = 1, double absEps = Math::lengthEpsilon ) = 0; - /** \brief \ru Вставка ряда после ряда с номером idBegin без изменения поверхности по u. - \en Insertion of a row after the row with the index idBegin without changing of a surface by u. \~ - \details \ru Вставка ряда после ряда с номером idBegin без изменения поверхности по u.\n - \en Insertion of a row after the row with the index idBegin without changing of a surface by u.\n \~ - \param[in] idBegin - \ru Номер ряда, после которого будет вставлен новый ряд. - \en An index of the row a new row will be inserted after. \~ - \param[in] num - \ru Количество вставляемых рядов. - \en Count of inserted rows. \~ - */ + /** \brief \ru Вставка ряда после ряда с номером idBegin без изменения поверхности по u. + \en Insertion of a row after the row with the index idBegin without changing of a surface by u. \~ + \details \ru Вставка ряда после ряда с номером idBegin без изменения поверхности по u.\n + \en Insertion of a row after the row with the index idBegin without changing of a surface by u.\n \~ + \param[in] idBegin - \ru Номер ряда, после которого будет вставлен новый ряд. + \en An index of the row a new row will be inserted after. \~ + \param[in] num - \ru Количество вставляемых рядов. + \en Count of inserted rows. \~ + */ virtual void InsertUKnotsInRegion( ptrdiff_t idBegin, ptrdiff_t num = 1 ) = 0; - /** \brief \ru Вставка ряда после ряда с номером idBegin без изменения поверхности по v. - \en Insertion of a row after the row with the index idBegin without changing of a surface by v. \~ - \details \ru Вставка ряда после ряда с номером idBegin без изменения поверхности по v.\n - \en Insertion of a row after the row with the index idBegin without changing of a surface by v.\n \~ - \param[in] idBegin - \ru Номер ряда, после которого будет вставлен новый ряд. - \en An index of the row a new row will be inserted after. \~ - \param[in] num - \ru Количество вставляемых рядов. - \en Count of inserted rows. \~ - */ + /** \brief \ru Вставка ряда после ряда с номером idBegin без изменения поверхности по v. + \en Insertion of a row after the row with the index idBegin without changing of a surface by v. \~ + \details \ru Вставка ряда после ряда с номером idBegin без изменения поверхности по v.\n + \en Insertion of a row after the row with the index idBegin without changing of a surface by v.\n \~ + \param[in] idBegin - \ru Номер ряда, после которого будет вставлен новый ряд. + \en An index of the row a new row will be inserted after. \~ + \param[in] num - \ru Количество вставляемых рядов. + \en Count of inserted rows. \~ + */ virtual void InsertVKnotsInRegion( ptrdiff_t idBegin, ptrdiff_t num = 1 ) = 0; - /** \brief \ru Изменить порядок nurbs путем перестроения поверхности с помощью функции NurbsSurface. - \en Change the order of NURBS by construction of a surface by the function NurbsSurface. \~ - \details \ru Изменить порядок nurbs путем перестроения поверхности с помощью функции NurbsSurface.\n - \en Change the order of NURBS by construction of a surface by the function NurbsSurface.\n \~ - \param[in] newDegree - \ru Новый порядок поверхности по u. - \en New surface degree by u. \~ - \return \ru true, если аппроксимация выполнена успешно. - \en True if approximation is succeeded. \~ - */ + /** \brief \ru Изменить порядок nurbs путем перестроения поверхности с помощью функции NurbsSurface. + \en Change the order of NURBS by construction of a surface by the function NurbsSurface. \~ + \details \ru Изменить порядок nurbs путем перестроения поверхности с помощью функции NurbsSurface.\n + \en Change the order of NURBS by construction of a surface by the function NurbsSurface.\n \~ + \param[in] newDegree - \ru Новый порядок поверхности по u. + \en New surface degree by u. \~ + \return \ru true, если аппроксимация выполнена успешно. + \en True if approximation is succeeded. \~ + */ virtual bool ChangeUDegreeApprox ( size_t newDegree ) = 0; - /** \brief \ru Изменить порядок nurbs путем перестроения поверхности с помощью функции NurbsSurface. - \en Change the order of NURBS by construction of a surface by the function NurbsSurface. \~ - \details \ru Изменить порядок nurbs путем перестроения поверхности с помощью функции NurbsSurface.\n - \en Change the order of NURBS by construction of a surface by the function NurbsSurface.\n \~ - \param[in] newDegree - \ru Новый порядок поверхности по v. - \en New surface degree by v. \~ - \return \ru true, если аппроксимация выполнена успешно. - \en True if approximation is succeeded. \~ - */ + /** \brief \ru Изменить порядок nurbs путем перестроения поверхности с помощью функции NurbsSurface. + \en Change the order of NURBS by construction of a surface by the function NurbsSurface. \~ + \details \ru Изменить порядок nurbs путем перестроения поверхности с помощью функции NurbsSurface.\n + \en Change the order of NURBS by construction of a surface by the function NurbsSurface.\n \~ + \param[in] newDegree - \ru Новый порядок поверхности по v. + \en New surface degree by v. \~ + \return \ru true, если аппроксимация выполнена успешно. + \en True if approximation is succeeded. \~ + */ virtual bool ChangeVDegreeApprox ( size_t newDegree ) = 0; - /** \brief \ru Изменить порядок и количество узлов nurbs путем перестроения поверхности с помощью функции NurbsSurface. - \en Change the order and the number of knots of NURBS by construction of a surface by the function NurbsSurface. \~ - \details \ru Изменить порядок и количество узлов nurbs путем перестроения поверхности с помощью функции NurbsSurface.\n - \en Change the order and the number of knots of NURBS by construction of a surface by the function NurbsSurface.\n \~ - \param[in] nUDegree - \ru Новый порядок поверхности по u. - \en New surface degree by u. \~ - \param[in] nVDegree - \ru Новый порядок поверхности по v. - \en New surface degree by v. \~ - \param[in] nUCount - \ru Количество контрольных точек по u. - \en A number of control points in U direction. \~ - \param[in] nVCount - \ru Количество контрольных точек по v. - \en A number of control points in V direction. \~ - \return \ru true, если аппроксимация выполнена успешно. - \en True if approximation is succeeded. \~ - */ + /** \brief \ru Изменить порядок и количество узлов nurbs путем перестроения поверхности с помощью функции NurbsSurface. + \en Change the order and the number of knots of NURBS by construction of a surface by the function NurbsSurface. \~ + \details \ru Изменить порядок и количество узлов nurbs путем перестроения поверхности с помощью функции NurbsSurface.\n + \en Change the order and the number of knots of NURBS by construction of a surface by the function NurbsSurface.\n \~ + \param[in] nUDegree - \ru Новый порядок поверхности по u. + \en New surface degree by u. \~ + \param[in] nVDegree - \ru Новый порядок поверхности по v. + \en New surface degree by v. \~ + \param[in] nUCount - \ru Количество контрольных точек по u. + \en A number of control points in U direction. \~ + \param[in] nVCount - \ru Количество контрольных точек по v. + \en A number of control points in V direction. \~ + \return \ru true, если аппроксимация выполнена успешно. + \en True if approximation is succeeded. \~ + */ virtual bool ChangeParametersApprox ( size_t nUDegree, size_t nVDegree, ptrdiff_t nUCount, ptrdiff_t nVCount ) = 0; - /** \brief \ru Вычисление фиксированных контрольных точек. - \en Calculation of fixed control points. \~ - \details \ru Вычисление узлов, которые должны быть неподвижны, чтобы при деформации поверхности кривые из - заданного массива не деформаровались. - \en Calculation of knots which should be fixed to forbid the deformation of curves in the given array when a surface - deforms. \~ - \param[in] curves - \ru Множество кривых. - \en A set of curves. \~ - \param[in,out] fixedPoints - \ru Матрица, в которую заносятся данные о необходимости фиксации узлов - для сохранения кривых. Если элемент матрицы равен true - соответствующая ему - контрольная точка должна быть фиксирована. - \en A matrix where the data about necessity of angles fixation is written - to save curves. If an element of matrix equals true then the control point - corresponding to it should be fixed. \~ - \return \ru true, вычисления выполнены успешно. - \en True if calculations are successfully performed. \~ - */ + /** \brief \ru Вычисление фиксированных контрольных точек. + \en Calculation of fixed control points. \~ + \details \ru Вычисление узлов, которые должны быть неподвижны, чтобы при деформации поверхности кривые из + заданного массива не деформаровались. + \en Calculation of knots which should be fixed to forbid the deformation of curves in the given array when a surface + deforms. \~ + \param[in] curves - \ru Множество кривых. + \en A set of curves. \~ + \param[in,out] fixedPoints - \ru Матрица, в которую заносятся данные о необходимости фиксации узлов + для сохранения кривых. Если элемент матрицы равен true - соответствующая ему + контрольная точка должна быть фиксирована. + \en A matrix where the data about necessity of angles fixation is written + to save curves. If an element of matrix equals true then the control point + corresponding to it should be fixed. \~ + \return \ru true, вычисления выполнены успешно. + \en True if calculations are successfully performed. \~ + */ virtual bool CalculateFixedPoints( const RPArray & curves, Array2 & fixedPoints ) const = 0; - /** \brief \ru Вычисление доли смещения узлов при перемещении со сглаживанием. - \en Calculation of a shift part of knots during the translation with blending. \~ - \details \ru Известно перемещение одной контрольной точки. Перемещение остальных точек, помеченных как подвижные в - матрице movedPoints, зависит от направления ее перемещения, расстояния точки от линии перемещения (moveVector) - и функции сглаживания. Есть три режима сглаживания: выпуклый, вогнутый и плавный переход. - \en A translation of one control point is known. Translation of other points which marked as movable in - the matrix movedPoints depends on the direction of its translation, the distance from the points to the translation line (moveVector) - and the function of blending. There are three modes of blending: convex, concave and smooth transition. \~ - \param[in] movedPoints - \ru Матрица, содержащая данные о перемещаемых точках. - Если элемент матрицы равен 1 - соответствующая ему контрольная точка может быть перемещена, - иначе - неподвижна. - \en A matrix containing data about moved points. - If an element of the matrix equals 1 then the corresponding control point can be moved, - otherwise - it is fixed. \~ - \param[in] uIndex - \ru Столбец перемещаемой контрольной точки, относительно которой будет сглаживание. - \en A column of a moved control point relative to which there will be the blending. \~ - \param[in] vIndex - \ru Строка перемещаемой контрольной точки, относительно которой будет сглаживание. - \en A row of a moved control point relative to which there will be the blending. \~ - \param[in] moveVector - \ru Вектор, по направлению которого смещается контрольная точка. - \en A vector in direction of which the control point is translated. \~ - \param[in] smoothType - \ru Тип сглаживания. \n - dst_None - без сглаживания, dst_Convex - выпуклый, dst_Concave - вогнутый, dst_Smooth - плавный переход. - \en The type of blending. \n - dst_None - no blending, dst_Convex - convex, dst_Concave - concave, dst_Smooth - smooth transition. \~ - \param[in] smoothDegree - \ru Степень функции сглаживания. Положительное число. - \en A degree of the blending function. A positive value. \~ - \param[in,out] partsPoints - \ru Матрица с данными о долях смещения каждой точки относительно смещения перемещаемой точки. - \en A matrix with the data about a part of shift of each point relative to the moved point. \~ - \return \ru true, если вычисления проведены успешно. - \en True if the calculations were successfully performed.. \~ - */ + /** \brief \ru Вычисление доли смещения узлов при перемещении со сглаживанием. + \en Calculation of a shift part of knots during the translation with blending. \~ + \details \ru Известно перемещение одной контрольной точки. Перемещение остальных точек, помеченных как подвижные в + матрице movedPoints, зависит от направления ее перемещения, расстояния точки от линии перемещения (moveVector) + и функции сглаживания. Есть три режима сглаживания: выпуклый, вогнутый и плавный переход. + \en A translation of one control point is known. Translation of other points which marked as movable in + the matrix movedPoints depends on the direction of its translation, the distance from the points to the translation line (moveVector) + and the function of blending. There are three modes of blending: convex, concave and smooth transition. \~ + \param[in] movedPoints - \ru Матрица, содержащая данные о перемещаемых точках. + Если элемент матрицы равен 1 - соответствующая ему контрольная точка может быть перемещена, + иначе - неподвижна. + \en A matrix containing data about moved points. + If an element of the matrix equals 1 then the corresponding control point can be moved, + otherwise - it is fixed. \~ + \param[in] uIndex - \ru Столбец перемещаемой контрольной точки, относительно которой будет сглаживание. + \en A column of a moved control point relative to which there will be the blending. \~ + \param[in] vIndex - \ru Строка перемещаемой контрольной точки, относительно которой будет сглаживание. + \en A row of a moved control point relative to which there will be the blending. \~ + \param[in] moveVector - \ru Вектор, по направлению которого смещается контрольная точка. + \en A vector in direction of which the control point is translated. \~ + \param[in] smoothType - \ru Тип сглаживания. \n + dst_None - без сглаживания, dst_Convex - выпуклый, dst_Concave - вогнутый, dst_Smooth - плавный переход. + \en The type of blending. \n + dst_None - no blending, dst_Convex - convex, dst_Concave - concave, dst_Smooth - smooth transition. \~ + \param[in] smoothDegree - \ru Степень функции сглаживания. Положительное число. + \en A degree of the blending function. A positive value. \~ + \param[in,out] partsPoints - \ru Матрица с данными о долях смещения каждой точки относительно смещения перемещаемой точки. + \en A matrix with the data about a part of shift of each point relative to the moved point. \~ + \return \ru true, если вычисления проведены успешно. + \en True if the calculations were successfully performed.. \~ + */ virtual bool CalculatePartsForSpecMove( const Array2 & movedPoints, size_t uIndex, size_t vIndex, const MbVector3D & moveVector, @@ -390,7 +393,7 @@ public: Array2 & partsPoints ) const = 0; private: - void operator = ( const MbPolySurface & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbPolySurface & ); // \ru Не реализовано. \en Not implemented. /** \} */ DECLARE_PERSISTENT_CLASS( MbPolySurface ) @@ -398,4 +401,5 @@ private: IMPL_PERSISTENT_OPS( MbPolySurface ) + #endif // __SURF_POLYSURFACE_H diff --git a/C3d/Include/surf_revolution_surface.h b/C3d/Include/surf_revolution_surface.h index 6f0ab9d..8c063bd 100644 --- a/C3d/Include/surf_revolution_surface.h +++ b/C3d/Include/surf_revolution_surface.h @@ -207,8 +207,8 @@ public: \en \name Functions for get of the group of data inside and outside the surface's domain of parameters. \{ */ void Explore( double & u, double & v, bool ext, - MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, - MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; + MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, + MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; /** \} */ /** \ru \name Функции движения по поверхности \en \name Function of moving on surface @@ -263,9 +263,9 @@ public: bool GetCylinderAxis( MbAxis3D & axis ) const override; // \ru Дать ось поверхности. \en Get the axis of a surface. bool GetCenterLines( std::vector & clCurves ) const override; // \ru Дать осевые (центральные) линии для поверхности. \en Get center lines of a surface. // \ru Определение разбивки параметрической области поверхности вертикалями и горизонталями. \en Determine a splitting of parametric region of a surface by verticals and horizontals. - virtual void GetTesselation( const MbStepData & stepData, - double u1, double u2, double v1, double v2, - SArray & uu, SArray & vv ) const override; + void GetTesselation( const MbStepData & stepData, + double u1, double u2, double v1, double v2, + SArray & uu, SArray & vv ) const override; // \ru Существует ли полюс на границе параметрической области. \en Whether a pole exists on parametric region boundary. bool GetPoleUMin() const override; bool GetPoleUMax() const override; @@ -278,60 +278,60 @@ public: /** \ru \name Функции поверхности вращения \en \name Function of revolution surface. \{ */ - double GetAngle() const { return vmax - vmin; } ///< \ru Угол вращения. \en Rotation angle. + double GetAngle() const { return vmax - vmin; } ///< \ru Угол вращения. \en Rotation angle. MbAxis3D GetAxis () const; ///< \ru Ось вращения. \en Rotation axis. const MbCartPoint3D & GetOrigin() const { return position.GetOrigin(); } ///< \ru Центр локальной системы координат. \en Center of the local coordinate system. const MbVector3D & GetAxisZ () const { return position.GetAxisZ(); } ///< \ru Направление оси вращения. \en Rotation axis direction. const MbPlacement3D & GetPlacement() const { return position; } ///< \ru Локальная система координат. \en Local coordinate system. - void SetAxis( const MbAxis3D & initAxis ); ///< \ru Установить ось вращения. \en Set rotation axis. + void SetAxis( const MbAxis3D & initAxis ); ///< \ru Установить ось вращения. \en Set rotation axis. - /// \ru Лежит ли образующая кривая в плоскости, содержащей ось вращения. \en Whether generating curve lies on a plane containing the rotation axis. - bool IsPlaneData() const { return planeData; } + /// \ru Лежит ли образующая кривая в плоскости, содержащей ось вращения. \en Whether generating curve lies on a plane containing the rotation axis. + bool IsPlaneData() const { return planeData; } - /** \brief \ru Единичный вектор - направление оси X локальной системы координат. - \en Unit vector - direction of the X axis of the local coordinate system. \~ - \details \ru Единичный вектор - направление оси X локальной системы координат.\n - В случае, если образующая кривая лежит в плоскости, содержащей ось вращения, - вектор является единичным вектором в плоскости образующей кривой. - \en Unit vector - direction of the X axis of the local coordinate system.\n - In a case when generating curve lies on a plane containing rotation axis - the vector is a unit vector in a plane of generating curve. \~ - \param[out] axis - \ru Вектор - результат - \en A vector - the result \~ - \result \ru true, если образующая кривая лежит в плоскости, содержащей ось вращеOния, и - локальная система координат поверхности является ортогональной и изотропной по осям. - \en True if generating curve lies on a plane containing rotation axis and - the local coordinate system of a surface is orthogonal and isotropic by the axes. \~ - */ - bool GetPlaneDataAxis( MbVector3D & axis ) const; + /** \brief \ru Единичный вектор - направление оси X локальной системы координат. + \en Unit vector - direction of the X axis of the local coordinate system. \~ + \details \ru Единичный вектор - направление оси X локальной системы координат.\n + В случае, если образующая кривая лежит в плоскости, содержащей ось вращения, + вектор является единичным вектором в плоскости образующей кривой. + \en Unit vector - direction of the X axis of the local coordinate system.\n + In a case when generating curve lies on a plane containing rotation axis + the vector is a unit vector in a plane of generating curve. \~ + \param[out] axis - \ru Вектор - результат + \en A vector - the result \~ + \result \ru true, если образующая кривая лежит в плоскости, содержащей ось вращеOния, и + локальная система координат поверхности является ортогональной и изотропной по осям. + \en True if generating curve lies on a plane containing rotation axis and + the local coordinate system of a surface is orthogonal and isotropic by the axes. \~ + */ + bool GetPlaneDataAxis( MbVector3D & axis ) const; - /** \brief \ru Создание эквидистантной поверхности. - \en Creation of an offset surface. \~ - \details \ru Создание поверхности типа st_OffsetSurface, совпадающей с данной поверхностью.\n - Если образующая кривая является эквидистантной кривой на плоскости, - то, используя ее базовую кривую в качестве образующей, создается поверхность - вращения и по ней эквидистантная поверхность.\n - Поверхность строится в случае, если образующая кривая лежит в плоскости, содержащей ось вращения.\n - Используется только в конвертерах. - \en Creation of a surface of the type OffsetSurface coincident with the given surface. \n - If the generating curve is an offset curve on a plane - then using its basis curve as generatrix a revolution surface is created - and an offset surface is created by it. \n - A surface is constructed in case when generating curve lies on a plane containing rotation axis. \n - This is used only in converters. \~ - */ - MbOffsetSurface * GetSurfaceFromPlaneCurveOffset() const; + /** \brief \ru Создание эквидистантной поверхности. + \en Creation of an offset surface. \~ + \details \ru Создание поверхности типа st_OffsetSurface, совпадающей с данной поверхностью.\n + Если образующая кривая является эквидистантной кривой на плоскости, + то, используя ее базовую кривую в качестве образующей, создается поверхность + вращения и по ней эквидистантная поверхность.\n + Поверхность строится в случае, если образующая кривая лежит в плоскости, содержащей ось вращения.\n + Используется только в конвертерах. + \en Creation of a surface of the type OffsetSurface coincident with the given surface. \n + If the generating curve is an offset curve on a plane + then using its basis curve as generatrix a revolution surface is created + and an offset surface is created by it. \n + A surface is constructed in case when generating curve lies on a plane containing rotation axis. \n + This is used only in converters. \~ + */ + MbOffsetSurface * GetSurfaceFromPlaneCurveOffset() const; - /// \ru Дать максимальный радиус поверхности, если это возможно. \en Get maximum radius of surface if it possible or null. - double GetMaxRadius() const; + /// \ru Дать максимальный радиус поверхности, если это возможно. \en Get maximum radius of surface if it possible or null. + double GetMaxRadius() const; /** \} */ private: // \ru Внутренние функции поверхности. \en Internal functions of surface. - void Init( const MbCartPoint3D & origin, const MbVector3D & axisZ, double v1, double v2 ); // \ru Продолжение конструктора. \en Continuation of constructor. - void InitNormDeltaU(); // \ru Посчитать величины отступа от uMin и uMax при подсчете нормали. \en Calculate indent values from uMin and uMax when calculation of a normal vector. - void InitPosition( const MbCartPoint3D & origin, const MbVector3D & axisZ ); - void ExactNormal( double u, double v, const MbVector3D & derU, const MbVector3D & derV, MbVector3D & nor ) const; // \ru Нормаль. \en Normal. - void CheckPoles(); // \ru Проверить полюса. \en Check poles. + void Init( const MbCartPoint3D & origin, const MbVector3D & axisZ, double v1, double v2 ); // \ru Продолжение конструктора. \en Continuation of constructor. + void InitNormDeltaU(); // \ru Посчитать величины отступа от uMin и uMax при подсчете нормали. \en Calculate indent values from uMin and uMax when calculation of a normal vector. + void InitPosition( const MbCartPoint3D & origin, const MbVector3D & axisZ ); + void ExactNormal( double u, double v, const MbVector3D & derU, const MbVector3D & derV, MbVector3D & nor ) const; // \ru Нормаль. \en Normal. + void CheckPoles(); // \ru Проверить полюса. \en Check poles. inline void CheckParam ( double &u, double &v ) const; // \ru Проверить параметры. \en Check parameters. inline void CheckParam_( double &u ) const; // \ru Проверить параметр. \en Check parameter. inline void RotateVector ( double sinV, double cosV, MbVector3D & v ) const; @@ -345,6 +345,7 @@ private: // \ru Внутренние функции поверхности. \en IMPL_PERSISTENT_OPS( MbRevolutionSurface ) + //------------------------------------------------------------------------------ // \ru Проверить параметры \en Check parameters // --- diff --git a/C3d/Include/surf_ruled_surface.h b/C3d/Include/surf_ruled_surface.h index 7b8130e..60e1692 100644 --- a/C3d/Include/surf_ruled_surface.h +++ b/C3d/Include/surf_ruled_surface.h @@ -187,8 +187,8 @@ public: \en \name Functions for get of the group of data inside and outside the surface's domain of parameters. \{ */ void Explore( double & u, double & v, bool ext, - MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, - MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; + MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, + MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; /** \} */ /** \ru \name Функции движения по поверхности \en \name Functions of moving along the surface @@ -218,7 +218,7 @@ public: // \ru Пересечение с кривой. \en Intersection with curve. void CurveIntersection( const MbCurve3D & curv, SArray & uv, SArray & tt, - bool ext0, bool ext, bool touchInclude = false ) const override; + bool ext0, bool ext, bool touchInclude = false ) const override; void CalculateGabarit( MbCube & ) const override; // \ru Выдать габарит. \en Get the bounding box. void CalculateLocalGabarit( const MbMatrix3D &, MbCube & ) const override; // \ru Рассчитать габарит относительно л.с.к.. \en Calculate bounding box relative to the local coordinate system. @@ -249,9 +249,9 @@ public: bool GetPoleVMax() const override; bool IsPole( double u, double v, double paramPrecision = PARAM_PRECISION ) const override; // \ru Является ли точка особенной. \en Whether the point is special. // \ru Определение разбивки параметрической области поверхности вертикалями и горизонталями. \en Determine splitting of parametric region of surface by vertical and horizontal lines. - virtual void GetTesselation( const MbStepData & stepData, - double u1, double u2, double v1, double v2, - SArray & uu, SArray & vv ) const override; + void GetTesselation( const MbStepData & stepData, + double u1, double u2, double v1, double v2, + SArray & uu, SArray & vv ) const override; bool IsLineU() const override; // \ru Если true все производные по U выше первой равны нулю. \en If true, then all the derivatives by U higher the first one are equal to zero. bool IsLineV() const override; // \ru Если true все производные по V выше первой равны нулю. \en If true, then all the derivatives by V higher the first one are equal to zero. @@ -277,15 +277,15 @@ private: inline void CheckParam( double & u, double & v ) const; // \ru Проверить параметры. \en Check parameters. inline void CheckPoleParam( double & u, double & v ) const; - void InitNormDeltaU(); // \ru Посчитать величины отступа от uMin и uMax при подсчете нормали \en Calculate indent values from uMin and uMax in calculation of normal - void InitTabooUV(); // \ru Вычислить ограничения по u и v \en Calculate constraints by u and v + void InitNormDeltaU(); // \ru Посчитать величины отступа от uMin и uMax при подсчете нормали \en Calculate indent values from uMin and uMax in calculation of normal + void InitTabooUV(); // \ru Вычислить ограничения по u и v \en Calculate constraints by u and v // \ru Пересечение с прямолинейной кривой \en Intersection with rectilinear curve - bool StraightIntersection( const MbCurve3D & curv, SArray & uv, SArray & tt, + bool StraightIntersection( const MbCurve3D & curv, SArray & uv, SArray & tt, bool ext0, bool ext ) const; RuledSurfaceType CheckType(); MbConeSurface * GetConeSurface( bool checkParams ) const; - bool IsPlane() const; // \ru НЕ ИСПОЛЬЗОВАТЬ СНАРУЖИ !!! \en NOT USE OUTSIDE !!! - void BreakPoints( bool forCurve, double precision = ANGLE_REGION ); // \ru Определение точек излома направляющих. \en Determination of the break points of the guides. + bool IsPlane() const; // \ru НЕ ИСПОЛЬЗОВАТЬ СНАРУЖИ !!! \en NOT USE OUTSIDE !!! + void BreakPoints( bool forCurve, double precision = ANGLE_REGION ); // \ru Определение точек излома направляющих. \en Determination of the break points of the guides. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbRuledSurface ) OBVIOUS_PRIVATE_COPY( MbRuledSurface ) @@ -293,6 +293,7 @@ OBVIOUS_PRIVATE_COPY( MbRuledSurface ) IMPL_PERSISTENT_OPS( MbRuledSurface ) + //------------------------------------------------------------------------------ // \ru Проверить параметры \en Check parameters // --- diff --git a/C3d/Include/surf_section_surface.h b/C3d/Include/surf_section_surface.h index 94a72cc..96e5cc7 100644 --- a/C3d/Include/surf_section_surface.h +++ b/C3d/Include/surf_section_surface.h @@ -298,8 +298,8 @@ public: // \ru Функции доступа к группе данных для работы внутри и вне области определения параметров поверхности. // \en Functions for get of the group of data inside and outside the surface's domain of parameters. void Explore( double & u, double & v, bool ext, - MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, - MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; + MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, + MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; /** \} */ /** \ru \name Функции движения по поверхности @@ -353,9 +353,9 @@ public: ThreeStates Salient() const override; // \ru Определение разбивки параметрической области поверхности вертикалями и горизонталями. \en Determine splitting of parametric region of surface by vertical and horizontal lines. - virtual void GetTesselation( const MbStepData & stepData, - double u1, double u2, double v1, double v2, - SArray & uu, SArray & vv ) const override; + void GetTesselation( const MbStepData & stepData, + double u1, double u2, double v1, double v2, + SArray & uu, SArray & vv ) const override; //virtual bool IsSpinePeriodic() const; // \ru Периодичность направляющей. \en Periodicity of a reference curve. size_t GetUMeshCount() const override; // \ru Выдать количество полигонов по u. \en Get the count of polygons by u. @@ -366,116 +366,116 @@ public: \en \name Functions of the mutable section surface. \{ */ - /// \ru Дать опорный спайн. \en Get reference spine. - const MbSpine & GetSpine() const { return *spine; } - /// \ru Дать опорную кривую. \en Get reference curve. - const MbCurve3D & GetSpineCurve() const { return spine->GetCurve(); } - /// \ru Дать первую направляющую кривую (может быть nullptr). \en Get first guide curve (may be nullptr). - const MbCurve3D * GetGuide1() const { return guide1; } - /// \ru Дать вторую направляющую кривую (может быть nullptr). \en Get second guide curve (may be nullptr). - const MbCurve3D * GetGuide2() const { return guide2; } - /// \ru Дать кривую вершин (может отсутствовать). \en Get apex curve (may be nullptr). - const MbCurve3D * GetApexCurve() const { return ( curves.size() > 0 ) ? curves[0] : nullptr; } - /// \ru Дать дополнительную направляющую кривую (может отсутствовать). \en Get additional guide curve (may be absence). - const MbCurve3D * GetCurve( size_t i ) const { return ( i < curves.size() ) ? curves[i] : nullptr; } - /// \ru Дать функцию управления сечением (радиус или дискриминант, может быть nullptr)). \en Get section control function (radius or discriminant, may be nullptr). - const MbFunction * GetFunction() const { return function; } - /// \ru Дать образующую кривую при form==cs_Shape (для других форм nullptr). \en Get forming curve for form==cs_Shape (nullptr on other case). - const MbPolyCurve * GetPattern() const { return pattern; } - /// \ru Дать форму сечения поверхности при фиксированном втором параметре. \en Get the surface cross-section shape with the second parameter fixed. - MbeSectionShape GetForm() const { return form; } - /// \ru Дать параметры опорной кривой, для которых направляющие терпят излом. \en Get parameters of the reference curve for which the guides have a break. - void GetBreakVParams( std::vector & vParams ) const; + /// \ru Дать опорный спайн. \en Get reference spine. + const MbSpine & GetSpine() const { return *spine; } + /// \ru Дать опорную кривую. \en Get reference curve. + const MbCurve3D & GetSpineCurve() const { return spine->GetCurve(); } + /// \ru Дать первую направляющую кривую (может быть nullptr). \en Get first guide curve (may be nullptr). + const MbCurve3D * GetGuide1() const { return guide1; } + /// \ru Дать вторую направляющую кривую (может быть nullptr). \en Get second guide curve (may be nullptr). + const MbCurve3D * GetGuide2() const { return guide2; } + /// \ru Дать кривую вершин (может отсутствовать). \en Get apex curve (may be nullptr). + const MbCurve3D * GetApexCurve() const { return ( curves.size() > 0 ) ? curves[0] : nullptr; } + /// \ru Дать дополнительную направляющую кривую (может отсутствовать). \en Get additional guide curve (may be absence). + const MbCurve3D * GetCurve( size_t i ) const { return ( i < curves.size() ) ? curves[i] : nullptr; } + /// \ru Дать функцию управления сечением (радиус или дискриминант, может быть nullptr)). \en Get section control function (radius or discriminant, may be nullptr). + const MbFunction * GetFunction() const { return function; } + /// \ru Дать образующую кривую при form==cs_Shape (для других форм nullptr). \en Get forming curve for form==cs_Shape (nullptr on other case). + const MbPolyCurve * GetPattern() const { return pattern; } + /// \ru Дать форму сечения поверхности при фиксированном втором параметре. \en Get the surface cross-section shape with the second parameter fixed. + MbeSectionShape GetForm() const { return form; } + /// \ru Дать параметры опорной кривой, для которых направляющие терпят излом. \en Get parameters of the reference curve for which the guides have a break. + void GetBreakVParams( std::vector & vParams ) const; - /// \ru Вычисление параметров направляющих кривых по второму параметру поверхности. \en Calculating the parameters of guide curves by the second surface parameter. - bool GuideParams( double v, double & t1, double & t2 ) const; - /// \ru Вычисление параметра вершинной кривой по второму параметру поверхности. \en Calculating the parameter of apex curve by the second surface parameter. - bool ApexParam( double v, double & t0 ) const; - /// \ru Вычисление точки поверхности по параметру направляющей кривой. \en Calculating the surface point by the parameter of first the guide curves. - bool ParamByGuide1( double t1, MbCartPoint & p ) const; - /// \ru Вычисление точки поверхности по параметру направляющей кривой. \en Calculating the surface point by the parameter of the second guide curves. - bool ParamByGuide2( double t2, MbCartPoint & p ) const; - /// \ru Вычисление второго параметра поверхности по параметру вершинной кривой. \en Calculating the second surface parameter by the parameter of the apex curve. - bool ParamByApex( double t0, double & v ) const; - /// \ru Вычисление точек поверхности по параметрам первой направляющей кривой. \en Calculating surface points by the first guide curve. - bool PointsByGuide1( std::vector & points ) const; - /// \ru Вычисление точек поверхности по параметрам второй направляющей кривой. \en Calculating surface points by the second guide curve. - bool PointsByGuide2( std::vector & points ) const; - /// \ru Вычисление точек пересечения направляющих кривых и кривой вершин с плоскостью сечения, заданной вторым параметром поверхности. \en Calculating the intersection points of guide curves and apex curve with the section plane specified by the second surface parameter. - bool PhantomPoints( double v, MbCartPoint3D & guideP1, MbCartPoint3D & guideP2, MbCartPoint3D & apex, double & discrim ) const; + /// \ru Вычисление параметров направляющих кривых по второму параметру поверхности. \en Calculating the parameters of guide curves by the second surface parameter. + bool GuideParams( double v, double & t1, double & t2 ) const; + /// \ru Вычисление параметра вершинной кривой по второму параметру поверхности. \en Calculating the parameter of apex curve by the second surface parameter. + bool ApexParam( double v, double & t0 ) const; + /// \ru Вычисление точки поверхности по параметру направляющей кривой. \en Calculating the surface point by the parameter of first the guide curves. + bool ParamByGuide1( double t1, MbCartPoint & p ) const; + /// \ru Вычисление точки поверхности по параметру направляющей кривой. \en Calculating the surface point by the parameter of the second guide curves. + bool ParamByGuide2( double t2, MbCartPoint & p ) const; + /// \ru Вычисление второго параметра поверхности по параметру вершинной кривой. \en Calculating the second surface parameter by the parameter of the apex curve. + bool ParamByApex( double t0, double & v ) const; + /// \ru Вычисление точек поверхности по параметрам первой направляющей кривой. \en Calculating surface points by the first guide curve. + bool PointsByGuide1( std::vector & points ) const; + /// \ru Вычисление точек поверхности по параметрам второй направляющей кривой. \en Calculating surface points by the second guide curve. + bool PointsByGuide2( std::vector & points ) const; + /// \ru Вычисление точек пересечения направляющих кривых и кривой вершин с плоскостью сечения, заданной вторым параметром поверхности. \en Calculating the intersection points of guide curves and apex curve with the section plane specified by the second surface parameter. + bool PhantomPoints( double v, MbCartPoint3D & guideP1, MbCartPoint3D & guideP2, MbCartPoint3D & apex, double & discrim ) const; /** \} */ 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 CacheInit(); // \ru Инициализация вспомогательных данных. \en Auxiliary data init. + 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 CacheInit(); // \ru Инициализация вспомогательных данных. \en Auxiliary data init. // \ru Проверить и изменить при необходимости параметры поверхности. \en Check and correct parameters of the surface. - void CheckParams( double & u, double & v, bool ext ) const; + 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, const double & v, MbPlacement3D & place, - MbCartPoint & xy0, double & t0, - MbCartPoint & xy1, MbVector & vec1, double & t1, - MbCartPoint & xy2, MbVector & vec2, double & t2 ) const; + 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; // \ru Расчет двумерных точек и их производных на плоском сечении поверхности. \en Calculation of two-dimension points and their derivatives on the surface plane section. - void Round( const double & u, const double & v, - const MbCartPoint & xy1, const MbVector & xy1V, const MbVector & xy1VV, const MbVector & xy1VVV, - const MbCartPoint & xy0, const MbVector & xy0V, const MbVector & xy0VV, const MbVector & xy0VVV, - MbCartPoint & p, MbVector & pU, MbVector & pV, MbVector * pUU, MbVector * pUV, MbVector * pVV, - MbVector * pUUU, MbVector * pUUV, MbVector * pUVV, MbVector * pVVV ) const; - void Linea( const double & u, - const MbCartPoint & xy1, const MbVector & xy1V, const MbVector & xy1VV, const MbVector & xy1VVV, - const MbCartPoint & xy2, const MbVector & xy2V, const MbVector & xy2VV, const MbVector & xy2VVV, - MbCartPoint & p, MbVector & pU, MbVector & pV, MbVector * pUU, MbVector * pUV, MbVector * pVV, - MbVector * pUUU, MbVector * pUUV, MbVector * pUVV, MbVector * pVVV ) const; - void Conic( const double & u, const double & v, - const MbCartPoint & xy1, const MbVector & xy1V, const MbVector & xy1VV, const MbVector & xy1VVV, - const MbCartPoint & xy2, const MbVector & xy2V, const MbVector & xy2VV, const MbVector & xy2VVV, - const MbCartPoint & xy0, const MbVector & xy0V, const MbVector & xy0VV, const MbVector & xy0VVV, - MbCartPoint & p, MbVector & pU, MbVector & pV, MbVector * pUU, MbVector * pUV, MbVector * pVV, - MbVector * pUUU, MbVector * pUUV, MbVector * pUVV, MbVector * pVVV ) const; - void Cubic( const double & u, const double & v, std::vector & bSplines, - const std::vector & xy, const std::vector & xyV, - const std::vector & xyVV, const std::vector & xyVVV, - MbCartPoint & p, MbVector & pU, MbVector & pV, MbVector * pUU, MbVector * pUV, MbVector * pVV, - MbVector * pUUU, MbVector * pUUV, MbVector * pUVV, MbVector * pVVV ) const; - void Shape( const double & u, const double & v, - const MbCartPoint & xy1, const MbVector & xy1V, const MbVector & xy1VV, const MbVector & xy1VVV, - const MbCartPoint & xy2, const MbVector & xy2V, const MbVector & xy2VV, const MbVector & xy2VVV, - const MbCartPoint & xy0, const MbVector & xy0V, const MbVector & xy0VV, const MbVector & xy0VVV, - MbCartPoint & p, MbVector & pU, MbVector & pV, MbVector * pUU, MbVector * pUV, MbVector * pVV, - MbVector * pUUU, MbVector * pUUV, MbVector * pUVV, MbVector * pVVV ) const; - ptrdiff_t B_Splanes( double & u, std::vector & bSplanes ) const; // \ru Вычисление B-сплайнов.\en B_splines calculation. - // \ru Вычисление радиуса-вектора точки его производных поверхности. \en The surface radius-vector and it derivatives calculation. - void Section ( const double & u, const double & v, MbCartPoint3D & pnt, - MbVector3D * uDer, MbVector3D * vDer, - MbVector3D * uuDer, MbVector3D * uvDer, MbVector3D * vvDer, - MbVector3D * uuuDer, MbVector3D * uuvDer, MbVector3D * uvvDer, MbVector3D * vvvDer ) const; - void PointOn ( double & v, double & u, bool ext, MbCartPoint3D & p ) const; // \ru Вычисления точки поверхности. \en Calculate surface point. - void DeriveU ( double & u, double & v, bool ext, MbVector3D & ) const; // \ru Первая производная по u. \en The first derivative with respect to u. - void DeriveV ( double & u, double & v, bool ext, MbVector3D & ) const; // \ru Первая производная по v. \en The first derivative with respect to v. - void DeriveUU ( double & u, double & v, bool ext, MbVector3D & ) const; // \ru Вторая производная по u. \en The second derivative with respect to u. - void DeriveUV ( double & u, double & v, bool ext, MbVector3D & ) const; // \ru Вторая производная по uv. \en The second derivative with respect to uv. - void DeriveVV ( double & u, double & v, bool ext, MbVector3D & ) const; // \ru Вторая производная по v. \en The second derivative with respect to v. - void DeriveUUU( double & u, double & v, bool ext, MbVector3D & ) const; // \ru Третья производная по uuu. \en The third derivative with respect to uuu. - void DeriveUUV( double & u, double & v, bool ext, MbVector3D & ) const; // \ru Третья производная по uuv. \en The third derivative with respect to uuv. - void DeriveUVV( double & u, double & v, bool ext, MbVector3D & ) const; // \ru Третья производная по uvv. \en The third derivative with respect to uvv. - void DeriveVVV( double & u, double & v, bool ext, MbVector3D & ) const; // \ru Третья производная по vvv. \en The third derivative with respect to vvv. - void Normal ( double & u, double & v, bool ext, MbVector3D & ) const; // \ru Нормаль. \en The normal. - void Normal ( const MbVector3D & uDer, const MbVector3D & vDer, double u, double v, bool ext, MbVector3D & nor ) const; - // \ru Вычисление точек для создания NURBS копии кривых поверхности. \en Points calculation for NURBS copy surface. - bool CollectNurbsPoints( double vin, double vax, size_t pCount, double angle, - SArray & params, - SArray & points1, - SArray & points2, - SArray & points_0, - SArray & points_1, - SArray & points_2, - SArray & points_3, - SArray & points_4 ) const; + void Round( const double & u, const double & v, + const MbCartPoint & xy1, const MbVector & xy1V, const MbVector & xy1VV, const MbVector & xy1VVV, + const MbCartPoint & xy0, const MbVector & xy0V, const MbVector & xy0VV, const MbVector & xy0VVV, + MbCartPoint & p, MbVector & pU, MbVector & pV, MbVector * pUU, MbVector * pUV, MbVector * pVV, + MbVector * pUUU, MbVector * pUUV, MbVector * pUVV, MbVector * pVVV ) const; + void Linea( const double & u, + const MbCartPoint & xy1, const MbVector & xy1V, const MbVector & xy1VV, const MbVector & xy1VVV, + const MbCartPoint & xy2, const MbVector & xy2V, const MbVector & xy2VV, const MbVector & xy2VVV, + MbCartPoint & p, MbVector & pU, MbVector & pV, MbVector * pUU, MbVector * pUV, MbVector * pVV, + MbVector * pUUU, MbVector * pUUV, MbVector * pUVV, MbVector * pVVV ) const; + void Conic( const double & u, const double & v, + const MbCartPoint & xy1, const MbVector & xy1V, const MbVector & xy1VV, const MbVector & xy1VVV, + const MbCartPoint & xy2, const MbVector & xy2V, const MbVector & xy2VV, const MbVector & xy2VVV, + const MbCartPoint & xy0, const MbVector & xy0V, const MbVector & xy0VV, const MbVector & xy0VVV, + MbCartPoint & p, MbVector & pU, MbVector & pV, MbVector * pUU, MbVector * pUV, MbVector * pVV, + MbVector * pUUU, MbVector * pUUV, MbVector * pUVV, MbVector * pVVV ) const; + void Cubic( const double & u, const double & v, std::vector & bSplines, + const std::vector & xy, const std::vector & xyV, + const std::vector & xyVV, const std::vector & xyVVV, + MbCartPoint & p, MbVector & pU, MbVector & pV, MbVector * pUU, MbVector * pUV, MbVector * pVV, + MbVector * pUUU, MbVector * pUUV, MbVector * pUVV, MbVector * pVVV ) const; + void Shape( const double & u, const double & v, + const MbCartPoint & xy1, const MbVector & xy1V, const MbVector & xy1VV, const MbVector & xy1VVV, + const MbCartPoint & xy2, const MbVector & xy2V, const MbVector & xy2VV, const MbVector & xy2VVV, + const MbCartPoint & xy0, const MbVector & xy0V, const MbVector & xy0VV, const MbVector & xy0VVV, + MbCartPoint & p, MbVector & pU, MbVector & pV, MbVector * pUU, MbVector * pUV, MbVector * pVV, + MbVector * pUUU, MbVector * pUUV, MbVector * pUVV, MbVector * pVVV ) const; + ptrdiff_t B_Splanes( double & u, std::vector & bSplanes ) const; // \ru Вычисление B-сплайнов.\en B_splines calculation. + // \ru Вычисление радиуса-вектора точки его производных поверхности. \en The surface radius-vector and it derivatives calculation. + void Section ( const double & u, const double & v, MbCartPoint3D & pnt, + MbVector3D * uDer, MbVector3D * vDer, + MbVector3D * uuDer, MbVector3D * uvDer, MbVector3D * vvDer, + MbVector3D * uuuDer, MbVector3D * uuvDer, MbVector3D * uvvDer, MbVector3D * vvvDer ) const; + void PointOn ( double & v, double & u, bool ext, MbCartPoint3D & p ) const; // \ru Вычисления точки поверхности. \en Calculate surface point. + void DeriveU ( double & u, double & v, bool ext, MbVector3D & ) const; // \ru Первая производная по u. \en The first derivative with respect to u. + void DeriveV ( double & u, double & v, bool ext, MbVector3D & ) const; // \ru Первая производная по v. \en The first derivative with respect to v. + void DeriveUU ( double & u, double & v, bool ext, MbVector3D & ) const; // \ru Вторая производная по u. \en The second derivative with respect to u. + void DeriveUV ( double & u, double & v, bool ext, MbVector3D & ) const; // \ru Вторая производная по uv. \en The second derivative with respect to uv. + void DeriveVV ( double & u, double & v, bool ext, MbVector3D & ) const; // \ru Вторая производная по v. \en The second derivative with respect to v. + void DeriveUUU( double & u, double & v, bool ext, MbVector3D & ) const; // \ru Третья производная по uuu. \en The third derivative with respect to uuu. + void DeriveUUV( double & u, double & v, bool ext, MbVector3D & ) const; // \ru Третья производная по uuv. \en The third derivative with respect to uuv. + void DeriveUVV( double & u, double & v, bool ext, MbVector3D & ) const; // \ru Третья производная по uvv. \en The third derivative with respect to uvv. + void DeriveVVV( double & u, double & v, bool ext, MbVector3D & ) const; // \ru Третья производная по vvv. \en The third derivative with respect to vvv. + void Normal ( double & u, double & v, bool ext, MbVector3D & ) const; // \ru Нормаль. \en The normal. + void Normal ( const MbVector3D & uDer, const MbVector3D & vDer, double u, double v, bool ext, MbVector3D & nor ) const; + // \ru Вычисление точек для создания NURBS копии кривых поверхности. \en Points calculation for NURBS copy surface. + bool CollectNurbsPoints( double vin, double vax, size_t pCount, double angle, + SArray & params, + SArray & points1, + SArray & points2, + SArray & points_0, + SArray & points_1, + SArray & points_2, + SArray & points_3, + SArray & points_4 ) const; private: - void operator = ( const MbSectionSurface & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbSectionSurface & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbSectionSurface ) }; diff --git a/C3d/Include/surf_sector_surface.h b/C3d/Include/surf_sector_surface.h index 06cce71..3501735 100644 --- a/C3d/Include/surf_sector_surface.h +++ b/C3d/Include/surf_sector_surface.h @@ -129,8 +129,8 @@ public: \en \name Functions for get of the group of data inside and outside the surface's domain of parameters. \{ */ void Explore( double & u, double & v, bool ext, - MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, - MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; + MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, + MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; /** \} */ /** \ru \name Функции движения по поверхности \en \name Functions of moving over the surface @@ -166,9 +166,9 @@ public: bool CreateNormalPlacements ( const MbVector3D & axisZ, double angle, SArray & places, VERSION version = Math::DefaultMathVersion() ) const override; bool CreateTangentPlacements( const MbVector3D & axisZ, SArray & places ) const override; // \ru Определение разбивки параметрической области поверхности вертикалями и горизонталями. \en Determine a splitting of parametric region of a surface by verticals and horizontals. - virtual void GetTesselation( const MbStepData & stepData, - double u1, double u2, double v1, double v2, - SArray & uu, SArray & vv ) const override; + void GetTesselation( const MbStepData & stepData, + double u1, double u2, double v1, double v2, + SArray & uu, SArray & vv ) const override; // \ru Существует ли полюс на границе параметрической области. \en Whether a pole exists on parametric region boundary. bool GetPoleVMax() const override; bool IsPole( double u, double v, double paramPrecision = PARAM_PRECISION ) const override; @@ -178,22 +178,23 @@ public: /** \ru \name Функции секториальной поверхности \en \name Functions of sectorial surface. \{ */ - /// \ru Изменить точку. \en Change point. - void SetOrigin( MbCartPoint3D & p ) { origin = p; } - /// \ru Дать точку. \en Get point. - void GetOrigin( MbCartPoint3D & p ) const { p = origin; } - /// \ru Дать точку. \en Get point. - const MbCartPoint3D & GetOrigin() const { return origin; } + /// \ru Изменить точку. \en Change point. + void SetOrigin( MbCartPoint3D & p ) { origin = p; } + /// \ru Дать точку. \en Get point. + void GetOrigin( MbCartPoint3D & p ) const { p = origin; } + /// \ru Дать точку. \en Get point. + const MbCartPoint3D & GetOrigin() const { return origin; } /** \} */ private: inline void CheckParam( double & u, double & v ) const; // \ru Проверить параметры. \en Check parameters. - void operator = ( const MbSectorSurface & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbSectorSurface & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbSectorSurface ) }; IMPL_PERSISTENT_OPS( MbSectorSurface ) + //------------------------------------------------------------------------------ // \ru Проверить параметры \en Check parameters // --- diff --git a/C3d/Include/surf_smooth_surface.h b/C3d/Include/surf_smooth_surface.h index eb454db..a8aefe6 100644 --- a/C3d/Include/surf_smooth_surface.h +++ b/C3d/Include/surf_smooth_surface.h @@ -180,7 +180,7 @@ public: \{ */ // \ru Определениe точки пересечения поверхности и кривой. \en Determination of a point of intersection between a surface and a curve. MbeNewtonResult CurveIntersectNewton( const MbCurve3D &, double funcEpsilon, size_t iterLimit, - double &u0, double &v0, double &t1, bool ext0, bool ext1 ) const override; + double &u0, double &v0, double &t1, bool ext0, bool ext1 ) const override; // \ru Дать максимальное приращение параметра. \en Get the maximum increment of parameter. double GetParamDelta() const override; // \ru Дать мимнимально различимую величину параметра. \en Get the minimum distinguishable value of parameter. @@ -195,7 +195,7 @@ public: /// \ru Копия с теми же опорными поверхностям. \en A copy with the same support surfaces. virtual MbSmoothSurface & CurvesDuplicate() const = 0; /// \ru Сделать полное копирование поверхности. \en Perform a full copying of a surface. - MbSurface & TotalDuplicate() const; + MbSurface & TotalDuplicate() const; /// \ru Дать радиус. \en Get radius. virtual double GetSmoothRadius() const = 0; /// \ru Дать радиусы со знаком. \en Get radii with a sign. @@ -234,103 +234,103 @@ public: /// \ru Дать опорную кривую на второй поверхности для изменения. \en Get the support curve on the second surface for changing. MbSurfaceCurve & SetCurve2() const { return *curve2; } - /** \brief \ru Построить граничную кривую вдоль поверхности (V = const). - \en Construct boundary curve along a surface (V = const). \~ - \details \ru Построить граничную кривую вдоль поверхности (V = const). - \en Construct boundary curve along a surface (V = const). \~ - \param[in] s - \ru Если true, то вдоль минимального значения V,\n - если false, то вдоль максимального значения V - \en If it equals true then construct along the minimal value of V,\n - otherwise construct along the maximal value of V \~ - */ - MbCurve * CreateBound( bool s ) const; + /** \brief \ru Построить граничную кривую вдоль поверхности (V = const). + \en Construct boundary curve along a surface (V = const). \~ + \details \ru Построить граничную кривую вдоль поверхности (V = const). + \en Construct boundary curve along a surface (V = const). \~ + \param[in] s - \ru Если true, то вдоль минимального значения V,\n + если false, то вдоль максимального значения V + \en If it equals true then construct along the minimal value of V,\n + otherwise construct along the maximal value of V \~ + */ + MbCurve * CreateBound( bool s ) const; - /** \brief \ru Вид опорных кривых. - \en Type of support curves. \~ - \details \ru Вид опорных кривых. - \en Type of support curves. \~ - \return \ru cbt_Specific если кривые построены по отдельным точкам\n - cbt_Ordinary если кривые аналитические - \en Cbt_Specific if the curves have been constructed by the separate points\n - cbt_Ordinary if the curves are analytical \~ - */ - MbeCurveBuildType GetBuildType() const; + /** \brief \ru Вид опорных кривых. + \en Type of support curves. \~ + \details \ru Вид опорных кривых. + \en Type of support curves. \~ + \return \ru cbt_Specific если кривые построены по отдельным точкам\n + cbt_Ordinary если кривые аналитические + \en Cbt_Specific if the curves have been constructed by the separate points\n + cbt_Ordinary if the curves are analytical \~ + */ + MbeCurveBuildType GetBuildType() const; - /** \brief \ru Форма поверхности. - \en Form of a surface. \~ - \details \ru Форма поверхности. - \en Form of a surface. \~ - \return \ru 0 в случае поверхности скругления\n - 1 в случае поверхности фаски - \en 0 in a case of fillet\n - 1 in a case of chamfer \~ - */ - MbeSmoothForm Form() const { return form; } + /** \brief \ru Форма поверхности. + \en Form of a surface. \~ + \details \ru Форма поверхности. + \en Form of a surface. \~ + \return \ru 0 в случае поверхности скругления\n + 1 в случае поверхности фаски + \en 0 in a case of fillet\n + 1 in a case of chamfer \~ + */ + MbeSmoothForm Form() const { return form; } - /** \brief \ru Добавить точку в опорные кривые границы. - \en Add a point to the support curves of the boundary. \~ - \details \ru Добавить точку в опорные кривые границы.\n - Точка будет добавлена в кривую, если она имеет тип pt_LineSegment, pt_CubicSpline или pt_Hermit. - \en Add a point to the support curves of the boundary.\n - A point will be added into a curve if it has a type pt_LineSegment, pt_CubicSpline or pt_Hermit. \~ - \param[out] t1 - \ru Параметр точки на первой кривой (если add1 = true) - \en Parameter of a point on the first curve (if add1 equals true) \~ - \param[in] p1 - \ru Точка на первой кривой - \en Point on the first curve \~ - \param[in] add1 - \ru Нужно ли добавлять точку в первую кривую - \en Whether to add a point to the first curve \~ - \param[out] t2 - \ru Параметр точки на второй кривой (если add2 = true) - \en Parameter of a point on the second curve (if add2 equals true) \~ - \param[in] p2 - \ru Точка на второй кривой - \en Point on the second curve \~ - \param[in] add2 - \ru Нужно ли добавлять точку во вторую кривую - \en Whether to add a point to the second curve \~ - */ + /** \brief \ru Добавить точку в опорные кривые границы. + \en Add a point to the support curves of the boundary. \~ + \details \ru Добавить точку в опорные кривые границы.\n + Точка будет добавлена в кривую, если она имеет тип pt_LineSegment, pt_CubicSpline или pt_Hermit. + \en Add a point to the support curves of the boundary.\n + A point will be added into a curve if it has a type pt_LineSegment, pt_CubicSpline or pt_Hermit. \~ + \param[out] t1 - \ru Параметр точки на первой кривой (если add1 = true) + \en Parameter of a point on the first curve (if add1 equals true) \~ + \param[in] p1 - \ru Точка на первой кривой + \en Point on the first curve \~ + \param[in] add1 - \ru Нужно ли добавлять точку в первую кривую + \en Whether to add a point to the first curve \~ + \param[out] t2 - \ru Параметр точки на второй кривой (если add2 = true) + \en Parameter of a point on the second curve (if add2 equals true) \~ + \param[in] p2 - \ru Точка на второй кривой + \en Point on the second curve \~ + \param[in] add2 - \ru Нужно ли добавлять точку во вторую кривую + \en Whether to add a point to the second curve \~ + */ virtual bool InsertPoints( double & t1, const MbCartPoint & p1, bool add1, double & t2, const MbCartPoint & p2, bool add2 ); - /** \brief \ru Продлить поверхность. - \en Prolong surface. \~ - \details \ru Построить и добавить точки в опорные кривые до или после границы, удлиннив поверхность.\n - Точки будут построены и добавлены в кривые, если они имеют тип pt_Hermit. - \en Build and add points to the support curves of the boundary.\n - A points will be builded and added into curves if they have a type pt_Hermit. \~ - \param[in] t - \ru Первый параметр поверхности - \en First parameter of surface \~ - \param[in] p1 - \ru Точка на первой кривой - \en Point on the first curve \~ - \param[in] p2 - \ru Точка на второй кривой - \en Point on the second curve \~ - \param[in] anyCase - \ru Штатная работа со значением false (true исключение). - \en Regular work with the value false (true exception). \~ - */ - bool ProlongSurface( double u, const MbCartPoint & p1, const MbCartPoint & p2, bool anyCase ); + /** \brief \ru Продлить поверхность. + \en Prolong surface. \~ + \details \ru Построить и добавить точки в опорные кривые до или после границы, удлиннив поверхность.\n + Точки будут построены и добавлены в кривые, если они имеют тип pt_Hermit. + \en Build and add points to the support curves of the boundary.\n + A points will be builded and added into curves if they have a type pt_Hermit. \~ + \param[in] t - \ru Первый параметр поверхности + \en First parameter of surface \~ + \param[in] p1 - \ru Точка на первой кривой + \en Point on the first curve \~ + \param[in] p2 - \ru Точка на второй кривой + \en Point on the second curve \~ + \param[in] anyCase - \ru Штатная работа со значением false (true исключение). + \en Regular work with the value false (true exception). \~ + */ + bool ProlongSurface( double u, const MbCartPoint & p1, const MbCartPoint & p2, bool anyCase ); - /** \brief \ru Скорректировать кривые. - \en Correct curves. \~ - \details \ru Скорректировать опорные кривые после вставки точек.\n - Кривая будет скорректирована, если поверхность имеет полюс на краю, опорная кривая имеет тип pt_Hermit и содержит опорную точку с заданным параметром. - Корректируется опорная точка кривой, ближайшая к точке с заданным параметром со стороны полюса поверхности. - \en Correct the support curves after inserting of the points.\n - A curve will be corrected if the surface has a pole on the boundary, a support curve has the type pt_Hermit and contains the support point with the given parameter. - The curve support point which is the nearest to the point with the given parameter from the side of the surface pole is corrected. \~ - \param[in] t1 - \ru Параметр точки на первой опорной кривой. - \en Parameter of a point on the first support curve. \~ - \param[in] t2 - \ru Параметр точки на второй опорной кривой. - \en Parameter of a point on the second support curve. \~ - */ - bool CurveStraighten( double t1, double t2 ); - /// \ru Дать свойства объекта. \en Get the object properties. - void AddProperties( MbProperties &properties ); + /** \brief \ru Скорректировать кривые. + \en Correct curves. \~ + \details \ru Скорректировать опорные кривые после вставки точек.\n + Кривая будет скорректирована, если поверхность имеет полюс на краю, опорная кривая имеет тип pt_Hermit и содержит опорную точку с заданным параметром. + Корректируется опорная точка кривой, ближайшая к точке с заданным параметром со стороны полюса поверхности. + \en Correct the support curves after inserting of the points.\n + A curve will be corrected if the surface has a pole on the boundary, a support curve has the type pt_Hermit and contains the support point with the given parameter. + The curve support point which is the nearest to the point with the given parameter from the side of the surface pole is corrected. \~ + \param[in] t1 - \ru Параметр точки на первой опорной кривой. + \en Parameter of a point on the first support curve. \~ + \param[in] t2 - \ru Параметр точки на второй опорной кривой. + \en Parameter of a point on the second support curve. \~ + */ + bool CurveStraighten( double t1, double t2 ); + /// \ru Дать свойства объекта. \en Get the object properties. + void AddProperties( MbProperties &properties ); /// \ru Проверить полюса. \en Check poles. - void SetPole(); + void SetPole(); /** \} */ protected: /// \ru Корректировка параметров. \en Correction of parameters. inline void CheckParam ( double &u, double &v ) const; - void InitSmoothSurface ( const MbSmoothSurface & ); - void Init ( const MbSmoothSurface & ); + void InitSmoothSurface ( const MbSmoothSurface & ); + void Init ( const MbSmoothSurface & ); private: // \ru Определениe точки пересечения края поверхности и кривой на смежной поверхности. \en Determination of intersection point between the surface boundary and the adjacent surface. @@ -338,15 +338,16 @@ private: size_t iterLimit, double &u, double &v, double &t, bool ext0, bool ext1 ) const; MbeNewtonResult CurveTangentIntersection( const MbCurve3D &, double funcEpsilon, size_t iterLimit, double &u, double &v, double &t, bool ext0, bool ext1 ) const; - bool IsSameSurface( const MbCurve3D &, double &u, double &v, double &t ) const; // \ru Идентификация кривой. \en Identification of a curve. + bool IsSameSurface( const MbCurve3D &, double &u, double &v, double &t ) const; // \ru Идентификация кривой. \en Identification of a curve. - void operator = ( const MbSmoothSurface & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbSmoothSurface & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS( MbSmoothSurface ) }; IMPL_PERSISTENT_OPS( MbSmoothSurface ) + //------------------------------------------------------------------------------ // \ru Корректировка параметров \en Correction of parameters // --- diff --git a/C3d/Include/surf_sphere_surface.h b/C3d/Include/surf_sphere_surface.h index bb59a1c..babf1b9 100644 --- a/C3d/Include/surf_sphere_surface.h +++ b/C3d/Include/surf_sphere_surface.h @@ -103,7 +103,7 @@ public: \en \name Initialization functions \{ */ /// \ru Инициализация по сферической поверхности. \en Initialization by spherical surface. - void Init( const MbSphereSurface & ); + void Init( const MbSphereSurface & ); /** \} */ /** \ru \name Общие функции геометрического объекта \en \name Common functions of a geometric object @@ -179,12 +179,12 @@ public: \en \name Functions for get of the group of data inside and outside the surface's domain of parameters. \{ */ void Explore( double & u, double & v, bool ext, - MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, - MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; - virtual void _PointNormal( double u, double v, - MbCartPoint3D & pnt, MbVector3D & deru, MbVector3D & derv, - MbVector3D & norm, MbVector3D & noru, MbVector3D & norv, - MbVector3D & deruu, MbVector3D & dervv, MbVector3D & deruv ) const override; // \ru Значения производных в точке. \en Values of derivatives at point. + MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, + MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; + void _PointNormal( double u, double v, + MbCartPoint3D & pnt, MbVector3D & deru, MbVector3D & derv, + MbVector3D & norm, MbVector3D & noru, MbVector3D & norv, + MbVector3D & deruu, MbVector3D & dervv, MbVector3D & deruv ) const override; // \ru Значения производных в точке. \en Values of derivatives at point. /** \} */ /** \ru \name Функции движения по поверхности \en \name Functions of moving on surface @@ -205,10 +205,10 @@ public: double CurvatureV ( double u, double v ) const override; // \ru Kривизна вдоль v. \en Curvature in v direction. // \ru Определение точки касания поверхностей с одним неподвижным параметром. \en Determination of tangency point of surfaces with one fixed parameter. MbeNewtonResult SurfaceTangentNewton( const MbSurface & surf1, MbeParamDir switchPar, double funcEpsilon, size_t iterLimit, - double & u0, double & v0, double & u1, double & v1, bool ext0, bool ext1 ) const override; + double & u0, double & v0, double & u1, double & v1, bool ext0, bool ext1 ) const override; // \ru Определение точки касания поверхности и кривой. \en Determination of tangency point between a surface and a curve. MbeNewtonResult CurveTangentNewton( const MbCurve3D & curv, double funcEpsilon, size_t iterLimit, - double & u, double & v, double & t, bool ext0, bool ext1 ) const override; + double & u, double & v, double & t, bool ext0, bool ext1 ) const override; MbSplineSurface * NurbsSurface( double, double, double, double, bool bmatch = false ) const override; // \ru NURBS копия поверхности. \en NURBS copy of surface. MbSurface * NurbsSurface( const MbNurbsParameters & uParam, const MbNurbsParameters & vParam ) const override; @@ -236,9 +236,9 @@ public: MbeParamDir GetFilletDirection() const override; // \ru Направление поверхности скругления. \en Direction of fillet surface. ThreeStates Salient() const override; // \ru Выпуклая ли поверхность. \en Whether a surface is convex. // \ru Определение разбивки параметрической области поверхности вертикалями и горизонталями. \en Determine a splitting of parametric region of a surface by verticals and horizontals. - virtual void GetTesselation( const MbStepData & stepData, - double u1, double u2, double v1, double v2, - SArray & uu, SArray & vv ) const override; + void GetTesselation( const MbStepData & stepData, + double u1, double u2, double v1, double v2, + SArray & uu, SArray & vv ) const override; void CalculateGabarit( MbCube & ) const override; // \ru Выдать габарит. \en Get bounding box. void CalculateLocalGabarit( const MbMatrix3D &, MbCube & ) const override; // \ru Рассчитать габарит относительно л.с.к. \en Calculate bounding box relative to the local coordinate system. @@ -274,28 +274,30 @@ public: /** \ru \name Функции конической поверхности \en \name Functions of conical surface \{ */ - /// \ru Дать внутренний радиус. \en Get inner radius. - double GetR() const { return radius; } - /// \ru Выдать радиус параллели, соответствующей 'V'. \en Get the radius of parallel corresponding to 'V'. - double GetR( double v ) const { return radius * ::cos(v); } - /// \ru Изменение внутреннего радиуса. \en Changing of inner radius. - void SetR( double r ) { radius = r; SetDirtyGabarit(); } - /// \ru Являются ли сферы пространственно идентичными. \en Whether surfaces are spatially identical. - bool IsSpaceSame( const MbSpaceItem &, double eps ) const; + + /// \ru Дать внутренний радиус. \en Get inner radius. + double GetR() const { return radius; } + /// \ru Выдать радиус параллели, соответствующей 'V'. \en Get the radius of parallel corresponding to 'V'. + double GetR( double v ) const { return radius * ::cos(v); } + /// \ru Изменение внутреннего радиуса. \en Changing of inner radius. + void SetR( double r ) { radius = r; SetDirtyGabarit(); } + /// \ru Являются ли сферы пространственно идентичными. \en Whether surfaces are spatially identical. + bool IsSpaceSame( const MbSpaceItem &, double eps ) const; /** \} */ private: inline void CheckParam( double &u, double &v ) const; // \ru Проверка параметров \en Check parameters inline void CheckParam( double &v ) const; // \ru Пересечение с прямолинейной кривой \en Intersection with rectilinear curve - bool StraightIntersection( const MbCurve3D & curv, SArray & uv, SArray & tt, bool ext0, bool ext ) const; - void operator = ( const MbSphereSurface & ); // \ru Не реализовано. \en Not implemented. + bool StraightIntersection( const MbCurve3D & curv, SArray & uv, SArray & tt, bool ext0, bool ext ) const; + void operator = ( const MbSphereSurface & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbSphereSurface ) }; IMPL_PERSISTENT_OPS( MbSphereSurface ) + //------------------------------------------------------------------------------ // \ru Проверить параметры \en Check parameters // --- diff --git a/C3d/Include/surf_spiral_surface.h b/C3d/Include/surf_spiral_surface.h index 9fe76c9..7457cae 100644 --- a/C3d/Include/surf_spiral_surface.h +++ b/C3d/Include/surf_spiral_surface.h @@ -160,8 +160,8 @@ public: \en \name Functions for get of the group of data inside and outside the surface's domain of parameters. \{ */ void Explore( double & u, double & v, bool ext, - MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, - MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; + MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, + MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; /** \} */ /** \ru \name Функции движения по поверхности \en \name Functions of moving on surface @@ -201,9 +201,9 @@ public: bool GetMatrixToSurface( const MbSurface & surf, MbMatrix & matr, VERSION version, double precision = METRIC_PRECISION ) const override; // \ru Определение разбивки параметрической области поверхности вертикалями и горизонталями. \en Determine a splitting of parametric region of a surface by verticals and horizontals. - virtual void GetTesselation( const MbStepData & stepData, - double u1, double u2, double v1, double v2, - SArray & uu, SArray & vv ) const override; + void GetTesselation( const MbStepData & stepData, + double u1, double u2, double v1, double v2, + SArray & uu, SArray & vv ) const override; size_t GetUMeshCount() const override; // \ru Выдать количество полигонов по u. \en Get the number of polygons in u-direction. size_t GetVMeshCount() const override; // \ru Выдать количество полигонов по v. \en Get the number of polygons in v-direction. @@ -214,54 +214,54 @@ public: \en \name Functions of spiral surface \{ */ - /** \brief \ru Определение матрицы переноса для образующей. - \en Determination of a transfer matrix for generatrix. \~ - \details \ru Определение матрицы при переносе образующей - из параметра vmin в параметр v. - \en Determination of matrix when transferring the generatrix - from the parameter vmin to the parameter v. \~ - \param[in] v - \ru Новый параметр на спирали - \en A new parameter on the spiral \~ - \param[out] matr - \ru Матрица-резцультат - \en A matrix - the result \~ - */ - void TransformMatrix( double v, MbMatrix3D & matr ) const; + /** \brief \ru Определение матрицы переноса для образующей. + \en Determination of a transfer matrix for generatrix. \~ + \details \ru Определение матрицы при переносе образующей + из параметра vmin в параметр v. + \en Determination of matrix when transferring the generatrix + from the parameter vmin to the parameter v. \~ + \param[in] v - \ru Новый параметр на спирали + \en A new parameter on the spiral \~ + \param[out] matr - \ru Матрица-резцультат + \en A matrix - the result \~ + */ + void TransformMatrix( double v, MbMatrix3D & matr ) const; - /// \ru Внутренний радиус витков. \en Internal radius of coils. - double GetSpiralR() const { return radius; } - /// \ru Внутренний шаг витков. \en Internal pitch of coils. - double GetStep() const { return step; } + /// \ru Внутренний радиус витков. \en Internal radius of coils. + double GetSpiralR() const { return radius; } + /// \ru Внутренний шаг витков. \en Internal pitch of coils. + double GetStep() const { return step; } - /// \ru Физический радиус витков. \en Physical radius of coils. - double GetSpiralRadius() const; - /// \ru Физический шаг витков. \en Physical pitch of coils. - double GetSpiralStep() const; + /// \ru Физический радиус витков. \en Physical radius of coils. + double GetSpiralRadius() const; + /// \ru Физический шаг витков. \en Physical pitch of coils. + double GetSpiralStep() const; /// \ru Местная система координат (ось position.axisZ - ось спирали). \en Local coordinate system ('position.axisZ' is axis of spiral). const MbPlacement3D & GetPlacement() const { return position; } /// \ru Центр тяжести образующей. \en Center of gravity of generatrix. const MbCartPoint3D & GetOrigin() const { return origin; } - /// \ru Построить спираль. \en Construct a spiral. - MbConeSpiral * CreateSpiral() const { return MbConeSpiral::Create( radius, step, position, vmin, vmax ); } + /// \ru Построить спираль. \en Construct a spiral. + MbConeSpiral * CreateSpiral() const { return MbConeSpiral::Create( radius, step, position, vmin, vmax ); } - /// \ru Является ли локальная система координат поверхности ортонормированной. \en Whether the local coordinate system of a surface is orthonormalized. - bool IsPositionNormal() const { return ( position.IsNormal() ); } - /// \ru Является ли локальная система координат поверхности ортогональной с равными по длине осями X,Y. \en Whether the local coordinate system of a surface is orthogonal with X and Y axes equal by length. - bool IsPositionCircular() const { return ( position.IsCircular() ); } - /// \ru Является ли локальная система координат поверхности ортогональной и изотропной по осям. \en Whether the local coordinate system of a surface is orthogonal and isotropic by the axes. - bool IsPositionIsotropic() const { return ( position.IsIsotropic() ); } - /// \ru Является ли образующая кривая окружностью. \en Whether a generatrix is a circle. - bool IsCircleType() const; + /// \ru Является ли локальная система координат поверхности ортонормированной. \en Whether the local coordinate system of a surface is orthonormalized. + bool IsPositionNormal() const { return ( position.IsNormal() ); } + /// \ru Является ли локальная система координат поверхности ортогональной с равными по длине осями X,Y. \en Whether the local coordinate system of a surface is orthogonal with X and Y axes equal by length. + bool IsPositionCircular() const { return ( position.IsCircular() ); } + /// \ru Является ли локальная система координат поверхности ортогональной и изотропной по осям. \en Whether the local coordinate system of a surface is orthogonal and isotropic by the axes. + bool IsPositionIsotropic() const { return ( position.IsIsotropic() ); } + /// \ru Является ли образующая кривая окружностью. \en Whether a generatrix is a circle. + bool IsCircleType() const; - /// \ru Оценить рабочий диапазон для проецирования. \en Estimate the projection range along V. - bool GetProjectionRange( const MbCartPoint3D & pnt, bool ext, const MbRect2D * userRange, MbRect2D & resRange ) const; - /// \ru Скорректировать разбивку для проецирования точки. \en Correct the number of splittings by v-parameter for point projection. - bool CorrectVCount( double vbeg, double vend, size_t & cntv ) const; + /// \ru Оценить рабочий диапазон для проецирования. \en Estimate the projection range along V. + bool GetProjectionRange( const MbCartPoint3D & pnt, bool ext, const MbRect2D * userRange, MbRect2D & resRange ) const; + /// \ru Скорректировать разбивку для проецирования точки. \en Correct the number of splittings by v-parameter for point projection. + bool CorrectVCount( double vbeg, double vend, size_t & cntv ) const; /** \} */ private: - void Init(); // \ru Инициализация. \en Initialization. + void Init(); // \ru Инициализация. \en Initialization. inline void CheckParam ( double & v ) const; inline void RotateVector ( const double & sin_V, const double & cos_V, MbVector3D & ) const; inline void RotateDeriveV ( const double & sin_V, const double & cos_V, MbVector3D & ) const; @@ -272,13 +272,14 @@ private: inline void DirectrixDeriveVV ( const double & sinV, const double & cosV, MbVector3D & ) const; inline void DirectrixDeriveVVV( const double & sinV, const double & cosV, MbVector3D & ) const; - void operator = ( const MbSpiralSurface & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbSpiralSurface & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbSpiralSurface ) }; IMPL_PERSISTENT_OPS( MbSpiralSurface ) + //------------------------------------------------------------------------------ // \ru Проверить параметр \en Check parameter // --- diff --git a/C3d/Include/surf_spline_surface.h b/C3d/Include/surf_spline_surface.h index 4123991..cf6204c 100644 --- a/C3d/Include/surf_spline_surface.h +++ b/C3d/Include/surf_spline_surface.h @@ -182,9 +182,9 @@ public: \en A knot vector by V. \~ */ MbSplineSurface( size_t uDeg, - size_t vDeg, - bool uCls, - bool vCls, + size_t vDeg, + bool uCls, + bool vCls, const Array2 & initPoints, const SArray & initUKnots, const SArray & initVKnots ); @@ -254,97 +254,97 @@ public: public: - /// \ru Инициализация по другой поверхности. \en The initialization by another surface. - void Init( const MbSplineSurface & ); + /// \ru Инициализация по другой поверхности. \en The initialization by another surface. + void Init( const MbSplineSurface & ); - /** \brief \ru Инициализация заполненной поверхности. - \en Initialization of filled surface. \~ - \details \ru Инициализация заполненной поверхности.\n - \en Initialization of filled surface.\n \~ - \param[in] cPoints - \ru Матрица контрольных точек. - \en A matrix of control points. \~ - \param[in] pWeights - \ru Матрица весов точек. - \en Matrix of point weights. \~ - */ - bool Init( const Array2 & cPoints, - const Array2 & pWeights ); - /** \brief \ru Инициализация заполненной поверхности. - \en Initialization of filled surface. \~ - \details \ru Инициализация заполненной поверхности.\n - \en Initialization of filled surface.\n \~ - \param[in] iDegreeU - \ru Новая степень сплайнов по u. - \en New degree of splines by u. \~ - \param[in] iDegreeV - \ru Новая степень сплайнов по v. - \en New degree of splines by v. \~ - \param[in] iClosedU - \ru Замкнутость поверхности по u. - \en Closedness of a surface in u direction. \~ - \param[in] iClosedV - \ru Замкнутость поверхности по v. - \en Closedness of a surface in v direction. \~ - */ - bool Init( size_t iDegreeU, size_t iDegreeV, bool iClosedU, bool iClosedV ); - /** \brief \ru Заполнить сплайновую поверхность по данным parasolid. - \en Fill spline surface by parasolid data. \~ - \details \ru Заполнить сплайновую поверхность по данным parasolid.\n - \en Fill spline surface by parasolid data.\n \~ - \param[in] uCls - \ru Замкнутость поверхности по u. - \en Closedness of a surface in u direction. \~ - \param[in] vCls - \ru Замкнутость поверхности по v. - \en Closedness of a surface in v direction. \~ - \param[in] brational - \ru Является ли поверхность рациональной. true - строится NURBS поверхность, false - поверхность Безье. - \en Whether a surface is rational. true - NURBS surface is constructed, false - Bezier surface. \~ - \param[in] uDgr - \ru Степень сплайнов по u. - \en Splines degree by U. \~ - \param[in] vDgr - \ru Степень сплайнов по v. - \en Splines degree by V. \~ - \param[in] uCnt - \ru Количество точек по u. - \en A number of points by U direction. \~ - \param[in] vCnt - \ru Количество точек по v. - \en A number of points by V direction. \~ - \param[in] vcs - \ru Множество координат точек. Если сплайн рациональный, четвертая координата - вес точки. - \en A set of points coordinates.. If spline is rational, then the fourth coordinate is the weight of a point. \~ - \param[in] vcsCnt - \ru Количество элементов в массиве vcs. - \en Count of elements in the array vcs. \~ - \param[in] uKMul - \ru Множество с данными о кратности каждого узла по u. - \en A set with the data about the multiplicity of each knot by u. \~ - \param[in] uKMulCnt - \ru Количество элементов в массиве uKMul. - \en Count of elements in the array uKMul. \~ - \param[in] vKMul - \ru Множество с данными о кратности каждого узла по v. - \en A set with the data about the multiplicity of each knot by v. \~ - \param[in] vKMulCnt - \ru Количество элементов в массиве vKMul. - \en Count of elements in the array vKMul. \~ - \param[in] uKnt - \ru Множество со значениями узлов по u. Каждое значение представлено один раз. - Информация о кратности узла лежит в элементе массива uKMul с тем же номером. - \en A set with values of knots by u. Each value is represented once. - Information about knot multiplicity is in the element of 'uKMul' array with the same index. \~ - \param[in] uKntCnt - \ru Количество элементов в массиве uKnt. - \en Count of elements in the array uKnt. \~ - \param[in] vKnt - \ru Множество со значениями узлов по v. Каждое значение представлено один раз. - Информация о кратности узла лежит в элементе массива vKMul с тем же номером. - \en A set with values of knots by v. Each value is represented once. - Information about knot multiplicity is in the element of 'vKMul ' array with the same index. \~ - \param[in] vKntCnt - \ru Количество элементов в массиве vKnt. - \en Count of elements in the array vKnt. \~ - \param[in] scl - \ru Коэффициент масштабирования. - \en Scale factor. \~ - */ - bool InitParasolid( bool uCls, - bool vCls, - bool brational, - size_t uDgr, - size_t vDgr, - ptrdiff_t uCnt, - ptrdiff_t vCnt, - const CcArray & vcs, - ptrdiff_t vcsCnt, - const CcArray & uKMul, - ptrdiff_t uKMulCnt, - const CcArray & vKMul, - ptrdiff_t vKMulCnt, - const CcArray & uKnt, - ptrdiff_t uKntCnt, - const CcArray & vKnt, - ptrdiff_t vKntCnt, - double scl ); + /** \brief \ru Инициализация заполненной поверхности. + \en Initialization of filled surface. \~ + \details \ru Инициализация заполненной поверхности.\n + \en Initialization of filled surface.\n \~ + \param[in] cPoints - \ru Матрица контрольных точек. + \en A matrix of control points. \~ + \param[in] pWeights - \ru Матрица весов точек. + \en Matrix of point weights. \~ + */ + bool Init( const Array2 & cPoints, + const Array2 & pWeights ); + /** \brief \ru Инициализация заполненной поверхности. + \en Initialization of filled surface. \~ + \details \ru Инициализация заполненной поверхности.\n + \en Initialization of filled surface.\n \~ + \param[in] iDegreeU - \ru Новая степень сплайнов по u. + \en New degree of splines by u. \~ + \param[in] iDegreeV - \ru Новая степень сплайнов по v. + \en New degree of splines by v. \~ + \param[in] iClosedU - \ru Замкнутость поверхности по u. + \en Closedness of a surface in u direction. \~ + \param[in] iClosedV - \ru Замкнутость поверхности по v. + \en Closedness of a surface in v direction. \~ + */ + bool Init( size_t iDegreeU, size_t iDegreeV, bool iClosedU, bool iClosedV ); + /** \brief \ru Заполнить сплайновую поверхность по данным parasolid. + \en Fill spline surface by parasolid data. \~ + \details \ru Заполнить сплайновую поверхность по данным parasolid.\n + \en Fill spline surface by parasolid data.\n \~ + \param[in] uCls - \ru Замкнутость поверхности по u. + \en Closedness of a surface in u direction. \~ + \param[in] vCls - \ru Замкнутость поверхности по v. + \en Closedness of a surface in v direction. \~ + \param[in] brational - \ru Является ли поверхность рациональной. true - строится NURBS поверхность, false - поверхность Безье. + \en Whether a surface is rational. true - NURBS surface is constructed, false - Bezier surface. \~ + \param[in] uDgr - \ru Степень сплайнов по u. + \en Splines degree by U. \~ + \param[in] vDgr - \ru Степень сплайнов по v. + \en Splines degree by V. \~ + \param[in] uCnt - \ru Количество точек по u. + \en A number of points by U direction. \~ + \param[in] vCnt - \ru Количество точек по v. + \en A number of points by V direction. \~ + \param[in] vcs - \ru Множество координат точек. Если сплайн рациональный, четвертая координата - вес точки. + \en A set of points coordinates.. If spline is rational, then the fourth coordinate is the weight of a point. \~ + \param[in] vcsCnt - \ru Количество элементов в массиве vcs. + \en Count of elements in the array vcs. \~ + \param[in] uKMul - \ru Множество с данными о кратности каждого узла по u. + \en A set with the data about the multiplicity of each knot by u. \~ + \param[in] uKMulCnt - \ru Количество элементов в массиве uKMul. + \en Count of elements in the array uKMul. \~ + \param[in] vKMul - \ru Множество с данными о кратности каждого узла по v. + \en A set with the data about the multiplicity of each knot by v. \~ + \param[in] vKMulCnt - \ru Количество элементов в массиве vKMul. + \en Count of elements in the array vKMul. \~ + \param[in] uKnt - \ru Множество со значениями узлов по u. Каждое значение представлено один раз. + Информация о кратности узла лежит в элементе массива uKMul с тем же номером. + \en A set with values of knots by u. Each value is represented once. + Information about knot multiplicity is in the element of 'uKMul' array with the same index. \~ + \param[in] uKntCnt - \ru Количество элементов в массиве uKnt. + \en Count of elements in the array uKnt. \~ + \param[in] vKnt - \ru Множество со значениями узлов по v. Каждое значение представлено один раз. + Информация о кратности узла лежит в элементе массива vKMul с тем же номером. + \en A set with values of knots by v. Each value is represented once. + Information about knot multiplicity is in the element of 'vKMul ' array with the same index. \~ + \param[in] vKntCnt - \ru Количество элементов в массиве vKnt. + \en Count of elements in the array vKnt. \~ + \param[in] scl - \ru Коэффициент масштабирования. + \en Scale factor. \~ + */ + bool InitParasolid( bool uCls, + bool vCls, + bool brational, + size_t uDgr, + size_t vDgr, + ptrdiff_t uCnt, + ptrdiff_t vCnt, + const CcArray & vcs, + ptrdiff_t vcsCnt, + const CcArray & uKMul, + ptrdiff_t uKMulCnt, + const CcArray & vKMul, + ptrdiff_t vKMulCnt, + const CcArray & uKnt, + ptrdiff_t uKntCnt, + const CcArray & vKnt, + ptrdiff_t vKntCnt, + double scl ); /** \ru \name Общие функции геометрического объекта. \en \name Common functions of geometric object. @@ -464,9 +464,9 @@ public: void Rebuild() override; // \ru Инициализация поверхности. \en Initialization of surface. // \ru Определение разбивки параметрической области поверхности вертикалями и горизонталями. \en Determine a splitting of parametric region of a surface by verticals and horizontals. - virtual void GetTesselation( const MbStepData & stepData, - double u1, double u2, double v1, double v2, - SArray & uu, SArray & vv ) const override; + void GetTesselation( const MbStepData & stepData, + double u1, double u2, double v1, double v2, + SArray & uu, SArray & vv ) const override; void SetLimit( double u1, double v1, double u2, double v2 ) override; @@ -505,145 +505,145 @@ public: void DirectPointProjection( const MbCartPoint3D & pnt, const MbVector3D & vect, SArray & uv, bool ext, MbRect2D * uvRange = nullptr ) const override; // \ru Являются ли узловые векторы равными? \en Are knotVectos equal? - bool IsKnotsTheSame( const MbSplineSurface & e, bool sameDir, double precision ) const; + bool IsKnotsTheSame( const MbSplineSurface & e, bool sameDir, double precision ) const; // \ru Являются ли точки и веса равными? \en Are points and weights equal? - bool IsPointsTheSame( const MbSplineSurface & e, bool sameDir, bool uBeg, bool vBeg, double precision ) const; + bool IsPointsTheSame( const MbSplineSurface & e, bool sameDir, bool uBeg, bool vBeg, double precision ) const; // \ru Определить, подобны ли поверхности для объединения. \en Define whether the surfaces are similar for merge. bool IsSimilarToSurface( const MbSurface & surf, VERSION version, double precision = METRIC_PRECISION ) const override; bool IsSpecialSimilarToSurface( const MbSurface & surf, VERSION version, double precision = METRIC_PRECISION ) const override; // \ru Дать двумерную матрицу преобразования из своей параметрической области в параметрическую область surf. \en Get two-dimensional matrix of transformation from its parametric region to the parametric region of 'surf'. bool GetMatrixToSurface( const MbSurface & surf, MbMatrix & matr, VERSION version, double precision = METRIC_PRECISION ) const override; - /** \brief \ru Изменение веса одной вершины. - \en Changing of one point weight \~ - \details \ru Изменение веса одной вершины.\n - \en Changing of one point weight \n \~ - \param[in] i - \ru Номер строки. - \en Row index. \~ - \param[in] j - \ru Номер столбца. - \en Column index. \~ - \param[in] w - \ru Новое значение веса. - \en New value of weight. \~ - */ - void ChangeWeight ( ptrdiff_t i, ptrdiff_t j, double w ); - /// \ru Преобразовать NURBS поверхность в поверхность у которой число контрольных точек равно порядку поверхности по первой координате. \en Transform NURBS surface into surface whose number of control points is equal to the order of the surface in the first coordinate. - bool UDecompose(); - /// \ru Преобразовать NURBS поверхность в поверхность у которой число контрольных точек равно порядку поверхности по второй координате. \en Transform NURBS surface into surface whose number of control points is equal to the order of the surface in the second coordinate. - bool VDecompose(); - /** \brief \ru Увеличить порядок поверхности по первой координате, не изменяя ее геометрическую форму и параметризацию. - \en Increase order of surface by first coordinate without changing its geometric shape and parametrization. \~ - \details \ru Увеличить порядок поверхности по первой координате, не изменяя ее геометрическую форму и параметризацию. \n - \en Increase order of surface by first coordinate without changing its geometric shape and parametrization. \n \~ - \param[in] newDegree - \ru Новый порядок поверхности по первой координате. - \en New order of surface by first coordinate. \~ - \param[in] relEps - \ru Допустимая погрешность изменения формы. - \en Permissible shape error. \~ - \return \ru Возвращает true, если порядок поверхности был изменен. - \en Returns true if the order of the surface was changed. \~ - */ - bool RaiseUDegree( size_t newDegree, - double relEps ); - /** \brief \ru Увеличить порядок поверхности по второй координате, не изменяя ее геометрическую форму и параметризацию. - \en Increase order of surface by second coordinate without changing its geometric shape and parametrization. \~ - \details \ru Увеличить порядок поверхности по второй координате, не изменяя ее геометрическую форму и параметризацию. \n - \en Increase order of surface by second coordinate without changing its geometric shape and parametrization. \n \~ - \param[in] newDegree - \ru Новый порядок поверхности по второй координате. - \en New order of surface by second coordinate. \~ - \param[in] relEps - \ru Допустимая погрешность изменения формы. - \en Permissible shape error. \~ - \return \ru Возвращает true, если порядок поверхности был изменен. - \en Returns true if the order of the surface was changed. \~ - */ - bool RaiseVDegree( size_t newDegree, - double relEps ); - /** \brief \ru Изменение порядка поверхности. - \en Changing of surface order. \~ - \details \ru Изменение порядка поверхности.\n - \en Changing of surface order.\n \~ - \param[in] isU - \ru Определяет, по какой координате надо изменить порядок: true - по u, false - по v. - \en Determines a coordinate of the order changing: true - u, false - v. \~ - \param[in] order - \ru Новый порядок поверхности. - \en A new surface order. \~ - */ - void SetDegree ( bool isU, ptrdiff_t order ); - /** \brief \ru Установить область изменения параметров. - \en Set the range of parameters. \~ - \details \ru Установить область изменения параметров.\n - \en Set the range of parameters.\n \~ - \param[in] pmin - \ru Минимальное значение по u. - \en The minimal parameter value by U. \~ - \param[in] pmax - \ru Максимальное значение по u. - \en The maximal parameter value by U. \~ - \param[in] qmin - \ru Минимальное значение по v. - \en The minimal parameter value by V. \~ - \param[in] qmax - \ru Максимальное значение по v. - \en The maximal parameter value by V. \~ - */ - MbMatrix SetLimitParam( double pmin, double pmax, double qmin, double qmax ); + /** \brief \ru Изменение веса одной вершины. + \en Changing of one point weight \~ + \details \ru Изменение веса одной вершины.\n + \en Changing of one point weight \n \~ + \param[in] i - \ru Номер строки. + \en Row index. \~ + \param[in] j - \ru Номер столбца. + \en Column index. \~ + \param[in] w - \ru Новое значение веса. + \en New value of weight. \~ + */ + void ChangeWeight ( ptrdiff_t i, ptrdiff_t j, double w ); + /// \ru Преобразовать NURBS поверхность в поверхность у которой число контрольных точек равно порядку поверхности по первой координате. \en Transform NURBS surface into surface whose number of control points is equal to the order of the surface in the first coordinate. + bool UDecompose(); + /// \ru Преобразовать NURBS поверхность в поверхность у которой число контрольных точек равно порядку поверхности по второй координате. \en Transform NURBS surface into surface whose number of control points is equal to the order of the surface in the second coordinate. + bool VDecompose(); + /** \brief \ru Увеличить порядок поверхности по первой координате, не изменяя ее геометрическую форму и параметризацию. + \en Increase order of surface by first coordinate without changing its geometric shape and parametrization. \~ + \details \ru Увеличить порядок поверхности по первой координате, не изменяя ее геометрическую форму и параметризацию. \n + \en Increase order of surface by first coordinate without changing its geometric shape and parametrization. \n \~ + \param[in] newDegree - \ru Новый порядок поверхности по первой координате. + \en New order of surface by first coordinate. \~ + \param[in] relEps - \ru Допустимая погрешность изменения формы. + \en Permissible shape error. \~ + \return \ru Возвращает true, если порядок поверхности был изменен. + \en Returns true if the order of the surface was changed. \~ + */ + bool RaiseUDegree( size_t newDegree, + double relEps ); + /** \brief \ru Увеличить порядок поверхности по второй координате, не изменяя ее геометрическую форму и параметризацию. + \en Increase order of surface by second coordinate without changing its geometric shape and parametrization. \~ + \details \ru Увеличить порядок поверхности по второй координате, не изменяя ее геометрическую форму и параметризацию. \n + \en Increase order of surface by second coordinate without changing its geometric shape and parametrization. \n \~ + \param[in] newDegree - \ru Новый порядок поверхности по второй координате. + \en New order of surface by second coordinate. \~ + \param[in] relEps - \ru Допустимая погрешность изменения формы. + \en Permissible shape error. \~ + \return \ru Возвращает true, если порядок поверхности был изменен. + \en Returns true if the order of the surface was changed. \~ + */ + bool RaiseVDegree( size_t newDegree, + double relEps ); + /** \brief \ru Изменение порядка поверхности. + \en Changing of surface order. \~ + \details \ru Изменение порядка поверхности.\n + \en Changing of surface order.\n \~ + \param[in] isU - \ru Определяет, по какой координате надо изменить порядок: true - по u, false - по v. + \en Determines a coordinate of the order changing: true - u, false - v. \~ + \param[in] order - \ru Новый порядок поверхности. + \en A new surface order. \~ + */ + void SetDegree ( bool isU, ptrdiff_t order ); + /** \brief \ru Установить область изменения параметров. + \en Set the range of parameters. \~ + \details \ru Установить область изменения параметров.\n + \en Set the range of parameters.\n \~ + \param[in] pmin - \ru Минимальное значение по u. + \en The minimal parameter value by U. \~ + \param[in] pmax - \ru Максимальное значение по u. + \en The maximal parameter value by U. \~ + \param[in] qmin - \ru Минимальное значение по v. + \en The minimal parameter value by V. \~ + \param[in] qmax - \ru Максимальное значение по v. + \en The maximal parameter value by V. \~ + */ + MbMatrix SetLimitParam( double pmin, double pmax, double qmin, double qmax ); - /// \ru Получить порядок В-сплайна по u. \en Get the order of B-spline by u. - size_t GetUDegree () const { return udegree; } - /// \ru Получить порядок В-сплайна по v. \en Get the order of B-spline by v. - size_t GetVDegree () const { return vdegree; } - /// \ru Получить количество строк в матрице весов. \en Get rows count in weights matrix. - size_t GetWeightsLines() const { return weights.Lines(); } - /// \ru Получить количество столбцов в матрице весов. \en Get columns count in weights matrix. - size_t GetWeightsColumns() const { return weights.Columns(); } - /** \brief \ru Получить вес вершины. - \en Get vertex weight. \~ - \details \ru Получить вес вершины.\n - \en Get vertex weight.\n \~ - \param[in] i - \ru Номер строки. - \en Row index. \~ - \param[in] j - \ru Номер столбца. - \en Column index. \~ - \return \ru Значение веса. - \en A value of weight. \~ - */ - double GetWeight( ptrdiff_t i, ptrdiff_t j ) const { return weights.GetWeight( i, j ); } + /// \ru Получить порядок В-сплайна по u. \en Get the order of B-spline by u. + size_t GetUDegree () const { return udegree; } + /// \ru Получить порядок В-сплайна по v. \en Get the order of B-spline by v. + size_t GetVDegree () const { return vdegree; } + /// \ru Получить количество строк в матрице весов. \en Get rows count in weights matrix. + size_t GetWeightsLines() const { return weights.Lines(); } + /// \ru Получить количество столбцов в матрице весов. \en Get columns count in weights matrix. + size_t GetWeightsColumns() const { return weights.Columns(); } + /** \brief \ru Получить вес вершины. + \en Get vertex weight. \~ + \details \ru Получить вес вершины.\n + \en Get vertex weight.\n \~ + \param[in] i - \ru Номер строки. + \en Row index. \~ + \param[in] j - \ru Номер столбца. + \en Column index. \~ + \return \ru Значение веса. + \en A value of weight. \~ + */ + double GetWeight( ptrdiff_t i, ptrdiff_t j ) const { return weights.GetWeight( i, j ); } // \ru Получить матрицу весов вершин. \en Get the matrix of vertices weights. void GetWeights( Array2 & wts ) const override { weights.GetWeights( wts ); } - /** \brief \ru Получить количество элементов в узловом векторе. - \en Get the number of elements in a knot vector. \~ - \details \ru Получить количество элементов в узловом векторе.\n - \en Get the number of elements in a knot vector.\n \~ - \param[in] isU - \ru Определяет, по какой координате запрашивается узловой вектор: true - по u, false - по v. - \en Determines the requested coordinate of a knot vector: true - u, false - v. \~ - \return \ru Количество элементов в узловом векторе. - \en The number of elements in a knot vector. \~ - */ - size_t GetKnotsCount( bool isU ) const { return (isU ? uknots.Count() : vknots.Count()); } + /** \brief \ru Получить количество элементов в узловом векторе. + \en Get the number of elements in a knot vector. \~ + \details \ru Получить количество элементов в узловом векторе.\n + \en Get the number of elements in a knot vector.\n \~ + \param[in] isU - \ru Определяет, по какой координате запрашивается узловой вектор: true - по u, false - по v. + \en Determines the requested coordinate of a knot vector: true - u, false - v. \~ + \return \ru Количество элементов в узловом векторе. + \en The number of elements in a knot vector. \~ + */ + size_t GetKnotsCount( bool isU ) const { return (isU ? uknots.Count() : vknots.Count()); } // \ru Получить узловой вектор по выбранному параметру. \en Get a knots vector by the chosen parameter. void GetKnots( bool isU, SArray & knots ) const override { knots = (isU ? uknots : vknots); } - /** \brief \ru Получить значение одного узла. - \en Get the value of one knot. \~ - \details \ru Получить значение одного узла.\n - \en Get the value of one knot.\n \~ - \param[in] isU - \ru Определяет, по какой координате запрашивается узловой вектор: true - по u, false - по v. - \en Determines the requested coordinate of a knot vector: true - u, false - v. \~ - \param[in] i - \ru Номер элемента в узловом векторе. - \en The index of an element in a knot vector. \~ - \return \ru Значение узла. - \en A value of knot. \~ - */ - double GetKnot( bool isU, size_t i ) const; + /** \brief \ru Получить значение одного узла. + \en Get the value of one knot. \~ + \details \ru Получить значение одного узла.\n + \en Get the value of one knot.\n \~ + \param[in] isU - \ru Определяет, по какой координате запрашивается узловой вектор: true - по u, false - по v. + \en Determines the requested coordinate of a knot vector: true - u, false - v. \~ + \param[in] i - \ru Номер элемента в узловом векторе. + \en The index of an element in a knot vector. \~ + \return \ru Значение узла. + \en A value of knot. \~ + */ + double GetKnot( bool isU, size_t i ) const; // \ru Вставка ряда после ряда с номером idBegin без изменения поверхности по u. \en Insertion of a row after the row with the index idBegin without changing of a surface by u. void InsertUKnotsInRegion( ptrdiff_t idBegin, ptrdiff_t num = 1 ) override; - /** \brief \ru Вставка ряда со значением узла newKnot без изменения поверхности по u. - \en Insertion of a row with the value of the knot newKnot without changing of a surface by u. \~ - \details \ru Вставка ряда со значением узла newKnot без изменения поверхности по u.\n - \en Insertion of a row with the value of the knot newKnot without changing of a surface by u.\n \~ - \param[in] newKnot - \ru Значение узла. - \en A value of knot. \~ - \param[in] multiplicity - \ru Количество вставляемых рядов. - \en Count of inserted rows. \~ - */ - void InsertUKnots( double & newKnot, ptrdiff_t multiplicity ); // + /** \brief \ru Вставка ряда со значением узла newKnot без изменения поверхности по u. + \en Insertion of a row with the value of the knot newKnot without changing of a surface by u. \~ + \details \ru Вставка ряда со значением узла newKnot без изменения поверхности по u.\n + \en Insertion of a row with the value of the knot newKnot without changing of a surface by u.\n \~ + \param[in] newKnot - \ru Значение узла. + \en A value of knot. \~ + \param[in] multiplicity - \ru Количество вставляемых рядов. + \en Count of inserted rows. \~ + */ + void InsertUKnots( double & newKnot, ptrdiff_t multiplicity ); // // \ru Вставка ряда после ряда с номером idBegin без изменения поверхности по v. \en Insertion of a row after the row with the index idBegin without changing of a surface by v. void InsertVKnotsInRegion( ptrdiff_t idBegin, ptrdiff_t num = 1 ) override; @@ -657,7 +657,7 @@ public: \param[in] multiplicity - \ru Количество вставляемых рядов. \en Count of inserted rows. \~ */ - void InsertVKnots( double & newKnot, ptrdiff_t multiplicity ); // + void InsertVKnots( double & newKnot, ptrdiff_t multiplicity ); // // \ru Вычисление точек на поверхности, соответствующих узлам. \en Calculation of points on surface corresponding to knots. void CalculateUVParameters( Array2 & params ) const override; @@ -666,26 +666,26 @@ public: // \ru Вычисление доли смещения узлов при перемещении со сглаживанием. \en Calculation of a shift part of knots during the translation with blending. bool CalculatePartsForSpecMove( const Array2 & movedPoints, - size_t uIndex, size_t vIndex, - const MbVector3D & moveVector, - MbeDirectSmoothType smoothType, - double smoothDegree, - Array2 & partsPoints ) const override; + size_t uIndex, size_t vIndex, + const MbVector3D & moveVector, + MbeDirectSmoothType smoothType, + double smoothDegree, + Array2 & partsPoints ) const override; // \ru Вычисление фиксированных контрольных точек. \en Calculation of fixed control points. bool CalculateFixedPoints( const RPArray & curves, Array2 & fixedPoints ) const override; - bool CalculateFixedLimits( const MbSurfaceCurve & curve, ptrdiff_t & u1, ptrdiff_t & u2, ptrdiff_t & v1, ptrdiff_t & v2 ) const; + bool CalculateFixedLimits( const MbSurfaceCurve & curve, ptrdiff_t & u1, ptrdiff_t & u2, ptrdiff_t & v1, ptrdiff_t & v2 ) const; // \ru Удаление столбца контрольных точек без аппроксимации поверхности. \en Deletion of a column of control points without approximation of a surface. - ptrdiff_t RemoveUKnotsWithoutApprox( ptrdiff_t id, - ptrdiff_t num, - double relEps = Math::paramEpsilon, - double absEps = Math::lengthEpsilon ); + ptrdiff_t RemoveUKnotsWithoutApprox( ptrdiff_t id, + ptrdiff_t num, + double relEps = Math::paramEpsilon, + double absEps = Math::lengthEpsilon ); // \ru Удаление строки контрольных точек без аппроксимации поверхности. \en Deletion of a line of control points without approximation of a surface. - ptrdiff_t RemoveVKnotsWithoutApprox( ptrdiff_t id, - ptrdiff_t num, - double relEps = Math::paramEpsilon, - double absEps = Math::lengthEpsilon ); + ptrdiff_t RemoveVKnotsWithoutApprox( ptrdiff_t id, + ptrdiff_t num, + double relEps = Math::paramEpsilon, + double absEps = Math::lengthEpsilon ); // \ru Удаление столбца контрольных точек без изменения поверхности. \en Deletion of a column of control points without changing of a surface. size_t RemoveUKnots( ptrdiff_t & rowId, ptrdiff_t num = 1, double absEps = Math::lengthEpsilon ) override; // \ru Удаление узла в u \en Deletion of knot in u direction // \ru Удаление строки контрольных точек без изменения поверхности. \en Deletion of a row of control points without changing of a surface. @@ -696,88 +696,88 @@ public: bool ChangeVDegreeApprox ( size_t newDegree ) override; // \ru Изменить порядок и количество узлов nurbs путем перестроения поверхности с помощью функции NurbsSurface. \en Change an order and a number of knots of NURBS by construction of a surface by the function NurbsSurface. bool ChangeParametersApprox ( size_t nUDegree, size_t nVDegree, ptrdiff_t nUCount, ptrdiff_t nVCount ) override; - /** \brief \ru Перестроить поверхность с помощью функции NurbsSurface без кратных узлов. - \en Rebuild a surface by the function NurbsSurface without multiple knots. \~ - \details \ru Перестроить поверхность с помощью функции NurbsSurface без кратных узлов.\n - \en Rebuild a surface by the function NurbsSurface without multiple knots.\n \~ - \return \ru true, если аппроксимация выполнена успешно. - \en True if approximation is succeeded. \~ - */ - bool ApproxSurfWithoutMultKnots (); + /** \brief \ru Перестроить поверхность с помощью функции NurbsSurface без кратных узлов. + \en Rebuild a surface by the function NurbsSurface without multiple knots. \~ + \details \ru Перестроить поверхность с помощью функции NurbsSurface без кратных узлов.\n + \en Rebuild a surface by the function NurbsSurface without multiple knots.\n \~ + \return \ru true, если аппроксимация выполнена успешно. + \en True if approximation is succeeded. \~ + */ + bool ApproxSurfWithoutMultKnots (); // \ru Вернуть массив узловых точек и их видимость для операции редактирования как сплайна. \en Return an array of knot points and their visibility for the operation of editing as spline. void GetPointsWithVisible ( Array2 & params ) const override; - /** \brief \ru Модифицировать массив узловых точек с учетом перемещения невидимых точек. - \en Modify an array of knot points considering the moving of invisible points. \~ - \details \ru Модифицировать массив узловых точек с учетом перемещения невидимых точек.\n - \en Modify an array of knot points considering the moving of invisible points.\n \~ - \param[in] oldPoints - \ru Матрица контрольных точек. - \en A matrix of control points. \~ - \param[in,out] newPoints - \ru Матрица контрольных точек после корректирования положения невидимых точек. - \en A matrix of control points after the correction of invisible points location. \~ - */ - void ModifyPointsWithVisible ( const Array2 & oldPoints, Array2 & newPoints ) const; + /** \brief \ru Модифицировать массив узловых точек с учетом перемещения невидимых точек. + \en Modify an array of knot points considering the moving of invisible points. \~ + \details \ru Модифицировать массив узловых точек с учетом перемещения невидимых точек.\n + \en Modify an array of knot points considering the moving of invisible points.\n \~ + \param[in] oldPoints - \ru Матрица контрольных точек. + \en A matrix of control points. \~ + \param[in,out] newPoints - \ru Матрица контрольных точек после корректирования положения невидимых точек. + \en A matrix of control points after the correction of invisible points location. \~ + */ + void ModifyPointsWithVisible ( const Array2 & oldPoints, Array2 & newPoints ) const; - /** \brief \ru Зажать или разжать узловой вектор. - \en Whether to clamp a knot vector. \~ - \details \ru Преобразовать узловой вектор по u в зажатый, если поверхность замкнута по u и clm = false. - Если не замкнута и clm = true - преобразовать узловой вектор в разжатый. - \en Make a knot vector by u clamped if a surface is closed in u direction and clm = false. - If it is not closed and clm = true then make knot vector unclamped. \~ - \param[in] clm - \ru Зажать или разжать узловой вектор. - \en Whether to clamp a knot vector. \~ - */ - bool UnClampedU( bool clm ); - /** \brief \ru Зажать или разжать узловой вектор. - \en Whether to clamp a knot vector. \~ - \details \ru Преобразовать узловой вектор по v в зажатый, если поверхность замкнута по v и clm = false. - Если не замкнута и clm = true - преобразовать узловой вектор в разжатый. - \en Make a knot vector by v clamped if a surface is closed in v direction and clm = false. - If it is not closed and clm = true then make knot vector unclamped. \~ - \param[in] clm - \ru Зажать или разжать узловой вектор. - \en Whether to clamp a knot vector. \~ - */ - bool UnClampedV( bool clm ); + /** \brief \ru Зажать или разжать узловой вектор. + \en Whether to clamp a knot vector. \~ + \details \ru Преобразовать узловой вектор по u в зажатый, если поверхность замкнута по u и clm = false. + Если не замкнута и clm = true - преобразовать узловой вектор в разжатый. + \en Make a knot vector by u clamped if a surface is closed in u direction and clm = false. + If it is not closed and clm = true then make knot vector unclamped. \~ + \param[in] clm - \ru Зажать или разжать узловой вектор. + \en Whether to clamp a knot vector. \~ + */ + bool UnClampedU( bool clm ); + /** \brief \ru Зажать или разжать узловой вектор. + \en Whether to clamp a knot vector. \~ + \details \ru Преобразовать узловой вектор по v в зажатый, если поверхность замкнута по v и clm = false. + Если не замкнута и clm = true - преобразовать узловой вектор в разжатый. + \en Make a knot vector by v clamped if a surface is closed in v direction and clm = false. + If it is not closed and clm = true then make knot vector unclamped. \~ + \param[in] clm - \ru Зажать или разжать узловой вектор. + \en Whether to clamp a knot vector. \~ + */ + bool UnClampedV( bool clm ); - /// \ru Делаем зажатый узловой вектор. \en Make a clumped knot vector. - void SetClampedU(); - /// \ru Делаем зажатый узловой вектор. \en Make a clumped knot vector. - void SetClampedV(); + /// \ru Делаем зажатый узловой вектор. \en Make a clumped knot vector. + void SetClampedU(); + /// \ru Делаем зажатый узловой вектор. \en Make a clumped knot vector. + void SetClampedV(); - /** \brief \ru Установить типы границ поверхности. - \en Set types of surfaces boundaries. \~ - \details \ru Установить типы границ поверхности. Используется в конвертерах. - \en Set types of surfaces boundaries. This is used in converters. \~ - \param[in] cuMin - \ru Тип поверхности при u - минимальном. - \en A type of surface when u is minimal. \~ - \param[in] cuMax - \ru Тип поверхности при u - максимальном. - \en A type of surface when u is maximal. \~ - \param[in] cvMin - \ru Тип поверхности при v - минимальном. - \en A type of surface when v is minimal. \~ - \param[in] cvMax - \ru Тип поверхности при v - максимальном. - \en A type of surface when v is maximal. \~ - */ - void SetBordersTypes( bool cuMin, bool cuMax, bool cvMin, bool cvMax ); + /** \brief \ru Установить типы границ поверхности. + \en Set types of surfaces boundaries. \~ + \details \ru Установить типы границ поверхности. Используется в конвертерах. + \en Set types of surfaces boundaries. This is used in converters. \~ + \param[in] cuMin - \ru Тип поверхности при u - минимальном. + \en A type of surface when u is minimal. \~ + \param[in] cuMax - \ru Тип поверхности при u - максимальном. + \en A type of surface when u is maximal. \~ + \param[in] cvMin - \ru Тип поверхности при v - минимальном. + \en A type of surface when v is minimal. \~ + \param[in] cvMax - \ru Тип поверхности при v - максимальном. + \en A type of surface when v is maximal. \~ + */ + void SetBordersTypes( bool cuMin, bool cuMax, bool cvMin, bool cvMax ); - /** \brief \ru Проверить является ли точка полюсной и убрать разрыв в первой производной. - \en Check whether a point is a pole and remove discontinuity of the first derivative. \~ - \details \ru Проверить является ли точка полюсной и убрать разрыв в первой производной.\n - \en Check whether a point is a pole and remove discontinuity of the first derivative.\n \~ - \param[in] pnt - \ru Точка, в которой производится проверка. - \en A point where the check is performed. \~ - \param[in] absEps - \ru Точность. - \en Tolerance. \~ - \param[in] bSet - \ru Замещать ли контрольные точки, соответствующие полюсу и - совпадающие с указанной точностью с точкой pnt, точкой pnt. - \en Whether to replace control points corresponding to the pole and - coincident with the given tolerance with the point pnt. \~ - */ - bool CheckPolePoint( const MbCartPoint3D & pnt, double absEps, bool bSet ); + /** \brief \ru Проверить является ли точка полюсной и убрать разрыв в первой производной. + \en Check whether a point is a pole and remove discontinuity of the first derivative. \~ + \details \ru Проверить является ли точка полюсной и убрать разрыв в первой производной.\n + \en Check whether a point is a pole and remove discontinuity of the first derivative.\n \~ + \param[in] pnt - \ru Точка, в которой производится проверка. + \en A point where the check is performed. \~ + \param[in] absEps - \ru Точность. + \en Tolerance. \~ + \param[in] bSet - \ru Замещать ли контрольные точки, соответствующие полюсу и + совпадающие с указанной точностью с точкой pnt, точкой pnt. + \en Whether to replace control points corresponding to the pole and + coincident with the given tolerance with the point pnt. \~ + */ + bool CheckPolePoint( const MbCartPoint3D & pnt, double absEps, bool bSet ); - /// \ru Если поверхность касается по U - убрать разрыв в первой производной. \en If surface is touched by U then remove the discontinuity of the first derivative. - void SoftUTouch(); - /// \ru Если поверхность касается по V - убрать разрыв в первой производной. \en If surface is touched by V then remove the discontinuity of the first derivative. - void SoftVTouch(); + /// \ru Если поверхность касается по U - убрать разрыв в первой производной. \en If surface is touched by U then remove the discontinuity of the first derivative. + void SoftUTouch(); + /// \ru Если поверхность касается по V - убрать разрыв в первой производной. \en If surface is touched by V then remove the discontinuity of the first derivative. + void SoftVTouch(); bool IsLineU() const override; // \ru Если true, то все производные по U выше первой равны нулю. \en If it equals true, then all derivatives with respect to u which have more than first order are equal to null. bool IsLineV() const override; // \ru Если true, то все производные по V выше первой равны нулю. \en If it equals true, then all derivatives with respect to v which have more than first order are equal to null. @@ -794,129 +794,128 @@ public: size_t GetUMeshCount() const override; // \ru Выдать количество полигонов по u. \en Get the number of polygons in u-direction. size_t GetVMeshCount() const override; // \ru Выдать количество полигонов по v. \en Get the number of polygons in v-direction. - /// \ru Проверить, является ли поверхность рациональной, но не регулярной. \en Check whether a surface is rational but not regular. - bool IsRational() const; + /// \ru Проверить, является ли поверхность рациональной, но не регулярной. \en Check whether a surface is rational but not regular. + bool IsRational() const; - /// \ru Удалить временную структуру данных - разбивку поверхности. \en Delete the temporary data structure - surface tesselation. - void DeleteTesselation() const; + /// \ru Удалить временную структуру данных - разбивку поверхности. \en Delete the temporary data structure - surface tesselation. + void DeleteTesselation() const; - /** \brief \ru Создать двумерную кривую, если пространственная кривая является границей поверхности. - \en Create a two-dimensional curve if a space curve is a surface boundary. \~ - \details \ru Создать двумерную кривую, если пространственная кривая является границей поверхности.\n - \en Create a two-dimensional curve if a space curve is a surface boundary.\n \~ - \param[in] curve - \ru Заданная пространственная кривая. - \en A given space curve. \~ - \return \ru Ссылка на двумерную кривую на поверхности или nullptr, если построить ее не удалось. - \en A reference to the two-dimensional curve on a surface or nullptr if the construction of it is failed. \~ - */ - MbCurve * IsSplineBorder( const MbCurve3D & curve ) const; + /** \brief \ru Создать двумерную кривую, если пространственная кривая является границей поверхности. + \en Create a two-dimensional curve if a space curve is a surface boundary. \~ + \details \ru Создать двумерную кривую, если пространственная кривая является границей поверхности.\n + \en Create a two-dimensional curve if a space curve is a surface boundary.\n \~ + \param[in] curve - \ru Заданная пространственная кривая. + \en A given space curve. \~ + \return \ru Ссылка на двумерную кривую на поверхности или nullptr, если построить ее не удалось. + \en A reference to the two-dimensional curve on a surface or nullptr if the construction of it is failed. \~ + */ + MbCurve * IsSplineBorder( const MbCurve3D & curve ) const; - /** \brief \ru Области поверхности, параллельные направлению. - \en Regions of a surface parallel to the direction. \~ - \details \ru Области поверхности, наборы точек в которой параллельны заданному направлению. - \en Regions of a surface the point sets of which are parallel to the given direction. \~ - \param[in] direction - \ru Направление. - \en Direction. \~ - \param[out] collinearRects - \ru Найденные области внутри области определения поверхности. - \en Found regions inside the domain of a surface. \~ - \warning \ru В разработке. - \en Under development. \~ - */ - void DirectParallelRects( const MbVector3D & direction, std::vector & parallelRects ) const; + /** \brief \ru Области поверхности, параллельные направлению. + \en Regions of a surface parallel to the direction. \~ + \details \ru Области поверхности, наборы точек в которой параллельны заданному направлению. + \en Regions of a surface the point sets of which are parallel to the given direction. \~ + \param[in] direction - \ru Направление. + \en Direction. \~ + \param[out] collinearRects - \ru Найденные области внутри области определения поверхности. + \en Found regions inside the domain of a surface. \~ + \warning \ru В разработке. + \en Under development. \~ + */ + void DirectParallelRects( const MbVector3D & direction, std::vector & parallelRects ) const; - /// \ru Может ли быть поверхность замкнутой по первому параметру? \en Can the surface be closed by the first parameter? - bool CheckUTouch( double precision ) const; - /// \ru Может ли быть поверхность замкнутой по второму параметру? \en Can the surface be closed by the second parameter? - bool CheckVTouch( double precision ) const; + /// \ru Может ли быть поверхность замкнутой по первому параметру? \en Can the surface be closed by the first parameter? + bool CheckUTouch( double precision ) const; + /// \ru Может ли быть поверхность замкнутой по второму параметру? \en Can the surface be closed by the second parameter? + bool CheckVTouch( double precision ) const; private: - void SetClosed( bool isU, bool cls ); // \ru Установить признак замкнутости. \en Set attribute of closedness. + void SetClosed( bool isU, bool cls ); // \ru Установить признак замкнутости. \en Set attribute of closedness. - void SetKnots ( size_t degree, ptrdiff_t count, bool close, SArray & knots ); // \ru Установка значений узлового вектора \en Setting of knot vector values. - void OpenKnotsVector ( size_t degree, ptrdiff_t count, SArray & knots ); // \ru Переопределение базисного узлового вектора из Close в Open. \en Redetermination of the basis knot vector from Close to Open. - void CloseKnotsVector ( size_t degree, ptrdiff_t count, SArray & knots, double ); // \ru Переопределение базисного узлового вектора из Open в Close. \en Redetermination of the basis knot vector from Open to Close. + void SetKnots ( size_t degree, ptrdiff_t count, bool close, SArray & knots ); // \ru Установка значений узлового вектора \en Setting of knot vector values. + void OpenKnotsVector ( size_t degree, ptrdiff_t count, SArray & knots ); // \ru Переопределение базисного узлового вектора из Close в Open. \en Redetermination of the basis knot vector from Close to Open. + void CloseKnotsVector ( size_t degree, ptrdiff_t count, SArray & knots, double ); // \ru Переопределение базисного узлового вектора из Open в Close. \en Redetermination of the basis knot vector from Open to Close. - void ResetCache(); + void ResetCache(); - void operator = ( const MbSplineSurface & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbSplineSurface & ); // \ru Не реализовано. \en Not implemented. - double GetMeanParam( bool isU, double, double ) const; // \ru Получить среднее расстояние между band-ами. \en Get the middle distance between 'band'-s. - double GetKoef( bool isU ) const; // \ru Получить коэффициент пересчета из длины в параметры. \en Get a coefficient of recalculation of the length to the parameters. - bool IsShiftSplineSurfaces( const MbSplineSurface & srf, bool alongU, double precision, double & paramShift ) const; // \ru Являются ли две nurbs-поверхности сдвинутыми относительно друг друга вдоль u или v. \en Are two nurbs-surfaces shifted relative to each other along u or v. + double GetMeanParam( bool isU, double, double ) const; // \ru Получить среднее расстояние между band-ами. \en Get the middle distance between 'band'-s. + double GetKoef( bool isU ) const; // \ru Получить коэффициент пересчета из длины в параметры. \en Get a coefficient of recalculation of the length to the parameters. + bool IsShiftSplineSurfaces( const MbSplineSurface & srf, bool alongU, double precision, double & paramShift ) const; // \ru Являются ли две nurbs-поверхности сдвинутыми относительно друг друга вдоль u или v. \en Are two nurbs-surfaces shifted relative to each other along u or v. - //--- - // \ru Служебные функции, которые используют заданный кэш (должен быть != nullptr). \en Service functions that use a given cache (must != nullptr). - bool CheckPoles( MbSplineSurfaceAuxiliaryData * ) const; // \ru Проверить наличие полюсов. \en Check poles existence. + // \ru Служебные функции, которые используют заданный кэш (должен быть != nullptr). \en Service functions that use a given cache (must != nullptr). + bool CheckPoles( MbSplineSurfaceAuxiliaryData * ) const; // \ru Проверить наличие полюсов. \en Check poles existence. - bool CatchMemory( MbSplineSurfaceAuxiliaryData * ) const; - void FreeMemory ( MbSplineSurfaceAuxiliaryData * ) const; + bool CatchMemory( MbSplineSurfaceAuxiliaryData * ) const; + void FreeMemory ( MbSplineSurfaceAuxiliaryData * ) const; - bool InitPatch ( MbSplineSurfaceAuxiliaryData * ) const; - void CalculatePatch ( double & u, double & v, MbSplineSurfaceAuxiliaryData * ) const; - void CalculateSpline ( int, MbSplineSurfaceAuxiliaryData * ) const; // \ru Расчет вектора точки и его первых, вторых и третьих производных. \en Calculation of the point vector and its first, second and third derivatives - void CalculateSplineWeight( int, MbSplineSurfaceAuxiliaryData * ) const; + bool InitPatch ( MbSplineSurfaceAuxiliaryData * ) const; + void CalculatePatch ( double & u, double & v, MbSplineSurfaceAuxiliaryData * ) const; + void CalculateSpline ( int, MbSplineSurfaceAuxiliaryData * ) const; // \ru Расчет вектора точки и его первых, вторых и третьих производных. \en Calculation of the point vector and its first, second and third derivatives + void CalculateSplineWeight( int, MbSplineSurfaceAuxiliaryData * ) const; - void DeriveU ( double & u, double & v, MbVector3D &, MbSplineSurfaceAuxiliaryData *, bool calcPatch = true ) const; // \ru Первая производная по u. \en First derivative with respect to u. - void DeriveV ( double & u, double & v, MbVector3D &, MbSplineSurfaceAuxiliaryData *, bool calcPatch = true ) const; // \ru Первая производная по v. \en First derivative with respect to v. - void DeriveUU ( double & u, double & v, MbVector3D &, MbSplineSurfaceAuxiliaryData *, bool calcPatch = true ) const; // \ru Вторая производная по u. \en Second derivative with respect to u. - void DeriveVV ( double & u, double & v, MbVector3D &, MbSplineSurfaceAuxiliaryData *, bool calcPatch = true ) const; // \ru Вторая производная по v. \en Second derivative with respect to v. - void DeriveUV ( double & u, double & v, MbVector3D &, MbSplineSurfaceAuxiliaryData *, bool calcPatch = true ) const; // \ru Вторая производная по uv. \en Second derivative with respect to u and v. - void DeriveUUU ( double & u, double & v, MbVector3D &, MbSplineSurfaceAuxiliaryData *, bool calcPatch = true ) const; // \ru Третья производная по u. \en Second derivative with respect to u. - void DeriveVVV ( double & u, double & v, MbVector3D &, MbSplineSurfaceAuxiliaryData *, bool calcPatch = true ) const; // \ru Третья производная по v. \en Third derivative with respect to v. - void DeriveUUV ( double & u, double & v, MbVector3D &, MbSplineSurfaceAuxiliaryData *, bool calcPatch = true ) const; // \ru Третья производная по uuv. \en Third derivative with respect to uuv. - void DeriveUVV ( double & u, double & v, MbVector3D &, MbSplineSurfaceAuxiliaryData *, bool calcPatch = true ) const; // \ru Третья производная по uvv. \en Third derivative with respect to uvv. - bool IsRational ( MbSplineSurfaceAuxiliaryData * ) const; // \ru Проверить, является ли поверхность рациональной, но не регулярной. \en Check whether a surface is rational but not regular. - size_t GetUCount ( MbSplineSurfaceAuxiliaryData * ) const; - size_t GetVCount ( MbSplineSurfaceAuxiliaryData * ) const; - double DeviationStepV ( double u, double v, double sag, MbSplineSurfaceAuxiliaryData * ) const; // \ru Вычисление шага по v при пересечении поверхностей. \en Calculation of a step in direction of v for surfaces intersection. - double DeviationStepU ( double u, double v, double sag, MbSplineSurfaceAuxiliaryData * ) const; // \ru Вычисление шага по u при пересечении поверхностей. \en Calculation of a step in direction of u for surfaces intersection. - void CheckSurfParams ( double & u, double & v, MbSplineSurfaceAuxiliaryData * ) const; // \ru Проверить параметры. \en Check parameters. - void _DeriveU ( double u, double v, MbVector3D &, MbSplineSurfaceAuxiliaryData * ) const; // \ru Первая производная по u. \en First derivative with respect to u. - void _DeriveV ( double u, double v, MbVector3D &, MbSplineSurfaceAuxiliaryData * ) const; // \ru Первая производная по v. \en First derivative with respect to v. - void _DeriveUV ( double u, double v, MbVector3D &, MbSplineSurfaceAuxiliaryData * ) const; // \ru Вторая производная по uv. \en Second derivative with respect to u and v. - void _DeriveUUV ( double u, double v, MbVector3D &, MbSplineSurfaceAuxiliaryData * ) const; // \ru Третья производная по uuv. \en Third derivative with respect to uuv. - void _DeriveUVV ( double u, double v, MbVector3D &, MbSplineSurfaceAuxiliaryData * ) const; // \ru Третья производная по uvv. \en Third derivative with respect to uvv. - bool GetPoleUMin ( MbSplineSurfaceAuxiliaryData * ) const; - bool GetPoleUMax ( MbSplineSurfaceAuxiliaryData * ) const; - bool GetPoleVMin ( MbSplineSurfaceAuxiliaryData * ) const; - bool GetPoleVMax ( MbSplineSurfaceAuxiliaryData * ) const; - bool IsPole ( double u, double v, double paramPrecision, MbSplineSurfaceAuxiliaryData * ) const; // \ru Является ли точка особенной. \en Whether the point is singular. + void DeriveU ( double & u, double & v, MbVector3D &, MbSplineSurfaceAuxiliaryData *, bool calcPatch = true ) const; // \ru Первая производная по u. \en First derivative with respect to u. + void DeriveV ( double & u, double & v, MbVector3D &, MbSplineSurfaceAuxiliaryData *, bool calcPatch = true ) const; // \ru Первая производная по v. \en First derivative with respect to v. + void DeriveUU ( double & u, double & v, MbVector3D &, MbSplineSurfaceAuxiliaryData *, bool calcPatch = true ) const; // \ru Вторая производная по u. \en Second derivative with respect to u. + void DeriveVV ( double & u, double & v, MbVector3D &, MbSplineSurfaceAuxiliaryData *, bool calcPatch = true ) const; // \ru Вторая производная по v. \en Second derivative with respect to v. + void DeriveUV ( double & u, double & v, MbVector3D &, MbSplineSurfaceAuxiliaryData *, bool calcPatch = true ) const; // \ru Вторая производная по uv. \en Second derivative with respect to u and v. + void DeriveUUU ( double & u, double & v, MbVector3D &, MbSplineSurfaceAuxiliaryData *, bool calcPatch = true ) const; // \ru Третья производная по u. \en Second derivative with respect to u. + void DeriveVVV ( double & u, double & v, MbVector3D &, MbSplineSurfaceAuxiliaryData *, bool calcPatch = true ) const; // \ru Третья производная по v. \en Third derivative with respect to v. + void DeriveUUV ( double & u, double & v, MbVector3D &, MbSplineSurfaceAuxiliaryData *, bool calcPatch = true ) const; // \ru Третья производная по uuv. \en Third derivative with respect to uuv. + void DeriveUVV ( double & u, double & v, MbVector3D &, MbSplineSurfaceAuxiliaryData *, bool calcPatch = true ) const; // \ru Третья производная по uvv. \en Third derivative with respect to uvv. + bool IsRational ( MbSplineSurfaceAuxiliaryData * ) const; // \ru Проверить, является ли поверхность рациональной, но не регулярной. \en Check whether a surface is rational but not regular. + size_t GetUCount ( MbSplineSurfaceAuxiliaryData * ) const; + size_t GetVCount ( MbSplineSurfaceAuxiliaryData * ) const; + double DeviationStepV ( double u, double v, double sag, MbSplineSurfaceAuxiliaryData * ) const; // \ru Вычисление шага по v при пересечении поверхностей. \en Calculation of a step in direction of v for surfaces intersection. + double DeviationStepU ( double u, double v, double sag, MbSplineSurfaceAuxiliaryData * ) const; // \ru Вычисление шага по u при пересечении поверхностей. \en Calculation of a step in direction of u for surfaces intersection. + void CheckSurfParams ( double & u, double & v, MbSplineSurfaceAuxiliaryData * ) const; // \ru Проверить параметры. \en Check parameters. + void _DeriveU ( double u, double v, MbVector3D &, MbSplineSurfaceAuxiliaryData * ) const; // \ru Первая производная по u. \en First derivative with respect to u. + void _DeriveV ( double u, double v, MbVector3D &, MbSplineSurfaceAuxiliaryData * ) const; // \ru Первая производная по v. \en First derivative with respect to v. + void _DeriveUV ( double u, double v, MbVector3D &, MbSplineSurfaceAuxiliaryData * ) const; // \ru Вторая производная по uv. \en Second derivative with respect to u and v. + void _DeriveUUV ( double u, double v, MbVector3D &, MbSplineSurfaceAuxiliaryData * ) const; // \ru Третья производная по uuv. \en Third derivative with respect to uuv. + void _DeriveUVV ( double u, double v, MbVector3D &, MbSplineSurfaceAuxiliaryData * ) const; // \ru Третья производная по uvv. \en Third derivative with respect to uvv. + bool GetPoleUMin ( MbSplineSurfaceAuxiliaryData * ) const; + bool GetPoleUMax ( MbSplineSurfaceAuxiliaryData * ) const; + bool GetPoleVMin ( MbSplineSurfaceAuxiliaryData * ) const; + bool GetPoleVMax ( MbSplineSurfaceAuxiliaryData * ) const; + bool IsPole ( double u, double v, double paramPrecision, MbSplineSurfaceAuxiliaryData * ) const; // \ru Является ли точка особенной. \en Whether the point is singular. - double StepD ( bool isU, double u, double v, double sag, bool checkAngle, double angle, MbSplineSurfaceAuxiliaryData * ) const; - double StepDPlus ( bool isU, double u, double v, double sag, bool checkAngle, double angle, MbSplineSurfaceAuxiliaryData * ) const; - double DeviationStep ( bool isU, double u, double v, double angle, MbSplineSurfaceAuxiliaryData * ) const; - double DeviationStepPlus ( bool isU, double u, double v, double angle, MbSplineSurfaceAuxiliaryData * ) const; - void TypedStepPlus ( double u, double v, bool alongU, const MbStepData & stepData, double & step, MbSplineSurfaceAuxiliaryData * ) const; + double StepD ( bool isU, double u, double v, double sag, bool checkAngle, double angle, MbSplineSurfaceAuxiliaryData * ) const; + double StepDPlus ( bool isU, double u, double v, double sag, bool checkAngle, double angle, MbSplineSurfaceAuxiliaryData * ) const; + double DeviationStep ( bool isU, double u, double v, double angle, MbSplineSurfaceAuxiliaryData * ) const; + double DeviationStepPlus ( bool isU, double u, double v, double angle, MbSplineSurfaceAuxiliaryData * ) const; + void TypedStepPlus ( double u, double v, bool alongU, const MbStepData & stepData, double & step, MbSplineSurfaceAuxiliaryData * ) const; - void PoleDerive( double u, double v, MbVector3D & vDerU, MbVector3D & vDerV, MbSplineSurfaceAuxiliaryData * ) const; + void PoleDerive( double u, double v, MbVector3D & vDerU, MbVector3D & vDerV, MbSplineSurfaceAuxiliaryData * ) const; - void CalculateDerivativesAlong( double & u, double & v, bool isU, MbVector3D & tDer, MbVector3D & ttDer, - MbSplineSurfaceAuxiliaryData * ) const; - void CalculateDerivativesAlong( double & u, double & v, bool isU, MbVector3D & tDer, MbVector3D & ttDer, MbVector3D & tttDer, - MbSplineSurfaceAuxiliaryData * ) const; - //--- + void CalculateDerivativesAlong( double & u, double & v, bool isU, MbVector3D & tDer, MbVector3D & ttDer, + MbSplineSurfaceAuxiliaryData * ) const; + void CalculateDerivativesAlong( double & u, double & v, bool isU, MbVector3D & tDer, MbVector3D & ttDer, MbVector3D & tttDer, + MbSplineSurfaceAuxiliaryData * ) const; - double GetMinStep ( bool isU, const double * pRng = nullptr ) const; + double GetMinStep ( bool isU, const double * pRng = nullptr ) const; - bool ApproxAsPlane() const; // \ru Можно ли аппроксимировать поверхность как плоскость. \en Whether a surface can be approximated by a plane. - // \ru Вычислить аппроксимацию поверхности, считая, что ее можно аппроксимировать как плоскость. \en Calculate an approximation of surface assuming that it can be approximated by a plane. - MbSplineSurface * CalcApproxAsPlane( size_t nUDegree, size_t nVDegree, ptrdiff_t nUCount, ptrdiff_t nVCount ) const; - bool UseMultiplKnots() const; + bool ApproxAsPlane() const; // \ru Можно ли аппроксимировать поверхность как плоскость. \en Whether a surface can be approximated by a plane. + // \ru Вычислить аппроксимацию поверхности, считая, что ее можно аппроксимировать как плоскость. \en Calculate an approximation of surface assuming that it can be approximated by a plane. + MbSplineSurface * CalcApproxAsPlane( size_t nUDegree, size_t nVDegree, ptrdiff_t nUCount, ptrdiff_t nVCount ) const; + bool UseMultiplKnots() const; inline void CheckParam( const SArray & knots, const ptrdiff_t & degree, const bool & closed, double & t ) const; - // \ru Создать двумерную кривую, если пространственная кривая является границей поверхности. \en Create a two-dimensional curve if a space curve is surface boundary. - MbCurve * IsFullSplineBorder( const MbCurve3D & curve ) const; - MbCurve * IsPartSplineBorder( const MbCurve3D & curve ) const; + // \ru Создать двумерную кривую, если пространственная кривая является границей поверхности. \en Create a two-dimensional curve if a space curve is surface boundary. + MbCurve * IsFullSplineBorder( const MbCurve3D & curve ) const; + MbCurve * IsPartSplineBorder( const MbCurve3D & curve ) const; - void GetVertecisRects( const MbVector3D & direction, bool u, - std::vector & vertecesRects ) const; + void GetVertecisRects( const MbVector3D & direction, bool u, + std::vector & vertecesRects ) const; DECLARE_PERSISTENT_CLASS_NEW_DEL( MbSplineSurface ) }; IMPL_PERSISTENT_OPS( MbSplineSurface ) + //------------------------------------------------------------------------------ // \ru Проверка нахождения параметра в области определения и корректировка. \en Check that parameter is within the domain and correction. // --- @@ -1020,7 +1019,7 @@ MATH_FUNC (bool) DefineThroughPointsParams( ptrdiff_t degree, bool closed, const // \ru Расчет точки поверхности. \en Calculation of surface point. // --- MATH_FUNC (bool) NurbsSurfacePoint( ptrdiff_t uDeg, const SArray & uKnots, bool uCls, double uCur, SArray & uSplines, - ptrdiff_t vDeg, const SArray & vKnots, bool vCls, double vCur, SArray & vSplines, + ptrdiff_t vDeg, const SArray & vKnots, bool vCls, double vCur, SArray & vSplines, const Array2 & points, const Array2 * weights, MbCartPoint3D & nsPnt ); diff --git a/C3d/Include/surf_swept_surface.h b/C3d/Include/surf_swept_surface.h index ef6e69a..eb01dad 100644 --- a/C3d/Include/surf_swept_surface.h +++ b/C3d/Include/surf_swept_surface.h @@ -124,18 +124,19 @@ public: protected: /// \ru Инициализация по поверхности движения. \en Initialization by swept surface. - void InitSwept( const MbSweptSurface & ); + void InitSwept( const MbSweptSurface & ); /// \ru Проверить по граничным точкам, может ли поверхность оказаться плоской. \en Check by boundary points, whether a surface may be planar. - bool CheckPlaneByLimitPoints() const; + bool CheckPlaneByLimitPoints() const; private: - void operator = ( const MbSweptSurface & ); // \ru Не реализовано. \en Not implemented. + void operator = ( const MbSweptSurface & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS( MbSweptSurface ) }; IMPL_PERSISTENT_OPS( MbSweptSurface ) + //------------------------------------------------------------------------------ // \ru Получить исходную кривую, возвращает true для прямолинейной направляющей \en Get initial curve, it returns true for the rectilinear guide curve. // --- diff --git a/C3d/Include/surf_tessellation.h b/C3d/Include/surf_tessellation.h index 67dfb40..154a22c 100644 --- a/C3d/Include/surf_tessellation.h +++ b/C3d/Include/surf_tessellation.h @@ -169,6 +169,7 @@ private: MbSurfaceWorkingData & operator = ( const MbSurfaceWorkingData & ); // \ru Присвоить значение. \en Assign a value. }; + //------------------------------------------------------------------------------ // \ru Конструктор по умолчанию \en Default constructor // --- @@ -357,8 +358,8 @@ inline bool MbSurfaceWorkingData::_SetDerivative( size_t k, const MbVector3D & d // \ru Получить данные. \en Get data. // --- inline bool MbSurfaceWorkingData::Explore( double u0, double v0, bool ext0, double & u, double & v, - MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, - MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const + MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, + MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const { bool res = false; @@ -410,6 +411,7 @@ inline bool MbSurfaceWorkingData::Explore( double u0, double v0, bool ext0, doub return res; } + //------------------------------------------------------------------------------ /** \brief \ru Дополнительные (сопутствующие) данные о поверхности. \en Additional (related) surface data. \~ diff --git a/C3d/Include/surf_torus_surface.h b/C3d/Include/surf_torus_surface.h index 98102a5..6bb7704 100644 --- a/C3d/Include/surf_torus_surface.h +++ b/C3d/Include/surf_torus_surface.h @@ -126,7 +126,7 @@ public: \en \name Initialization functions \{ */ /// \ru Инициализация по тороидальной поверхности. \en The initialization by toroidal surface. - void Init( const MbTorusSurface & ); + void Init( const MbTorusSurface & ); /** \} */ /** \ru \name Общие функции геометрического объекта \en \name Common functions of a geometric object @@ -201,12 +201,12 @@ public: \en \name Functions for get of the group of data inside and outside the surface's domain of parameters. \{ */ void Explore( double & u, double & v, bool ext, - MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, - MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; - virtual void _PointNormal( double u, double v, - MbCartPoint3D & pnt, MbVector3D & deru, MbVector3D & derv, - MbVector3D & norm, MbVector3D & noru, MbVector3D & norv, - MbVector3D & deruu, MbVector3D & dervv, MbVector3D & deruv ) const override; // \ru Значения производных в точке. \en Values of derivatives at point. + MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, + MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const override; + void _PointNormal( double u, double v, + MbCartPoint3D & pnt, MbVector3D & deru, MbVector3D & derv, + MbVector3D & norm, MbVector3D & noru, MbVector3D & norv, + MbVector3D & deruu, MbVector3D & dervv, MbVector3D & deruv ) const override; // \ru Значения производных в точке. \en Values of derivatives at point. /** \} */ /** \ru \name Функции движения по поверхности \en \name Functions of moving on surface @@ -236,14 +236,14 @@ public: void DirectPointProjection( const MbCartPoint3D & p, const MbVector3D & vect, SArray & uv, bool ext, MbRect2D * uvRange = nullptr ) const override; // \ru Пересечение с кривой. \en Intersection with a curve. void CurveIntersection( const MbCurve3D & curv, SArray & uv, SArray & tt, - bool ext0, bool ext, bool touchInclude = false ) const override; + bool ext0, bool ext, bool touchInclude = false ) const override; // \ru Определение точки касания поверхностей с одним неподвижным параметром. \en Determination of tangency point of surfaces with one fixed parameter. MbeNewtonResult SurfaceTangentNewton( const MbSurface & surf1, MbeParamDir switchPar, double funcEpsilon, size_t iterLimit, - double & u0, double & v0, double & u1, double & v1, bool ext0, bool ext1 ) const override; + double & u0, double & v0, double & u1, double & v1, bool ext0, bool ext1 ) const override; // \ru Определениe точки касания поверхности и кривой. \en Determination of tangency point between a surface and a curve. MbeNewtonResult CurveTangentNewton( const MbCurve3D & curv, double funcEpsilon, size_t iterLimit, - double & u, double & v, double & t, bool ext0, bool ext1 ) const override; + double & u, double & v, double & t, bool ext0, bool ext1 ) const override; bool GetCylinderAxis( MbAxis3D & axis ) const override; // \ru Дать ось вращения для поверхности. \en Get rotation axis of a surface. bool GetCenterLines( std::vector & clCurves ) const override; // \ru Дать осевые (центральные) линии для поверхности. \en Get center lines of a surface. @@ -255,9 +255,9 @@ public: double GetFilletRadius( const MbCartPoint3D & p ) const override; // \ru Является ли поверхность скруглением. \en Whether a surface is fillet. ThreeStates Salient() const override; // \ru Выпуклая ли поверхность. \en Whether a surface is convex. // \ru Определение разбивки параметрической области поверхности вертикалями и горизонталями. \en Determine a splitting of parametric region of a surface by verticals and horizontals. - virtual void GetTesselation( const MbStepData & stepData, - double u1, double u2, double v1, double v2, - SArray & uu, SArray & vv ) const override; + void GetTesselation( const MbStepData & stepData, + double u1, double u2, double v1, double v2, + SArray & uu, SArray & vv ) const override; void SetLimit( double u1, double v1, double u2, double v2 ) override; void SetExtendedParamRegion( double u1, double v1, double u2, double v2 ) override; @@ -289,52 +289,53 @@ public: /** \ru \name Функции тороидальной поверхности \en \name Functions of toroidal surface \{ */ - /// \ru Дать физический главный радиус центров. \en Get physical major radius. - double GetMajorRadius() const; - /// \ru Дать физический меньший радиус. \en Get physical minor radius. - double GetMinorRadius() const; + /// \ru Дать физический главный радиус центров. \en Get physical major radius. + double GetMajorRadius() const; + /// \ru Дать физический меньший радиус. \en Get physical minor radius. + double GetMinorRadius() const; - /// \ru Изменение главного радиуса. \en Changing of major radius. - void SetMajorR( double r ) { majorRadius = r; CheckTorusRadii(); CalculateAngle(); SetDirtyGabarit(); } - /// \ru Изменение меньшего радиуса. \en Changing of minor radius. - void SetMinorR( double r ) { minorRadius = r; CheckTorusRadii(); CalculateAngle(); SetDirtyGabarit(); } - /// \ru Главный радиус. \en Major radius. - double GetMajorR() const { return majorRadius; } - /// \ru Меньший радиус. \en Minor radius. - double GetMinorR() const { return minorRadius; } - /// \ru Радиус v-параллели. \en Radius of v-parallel. - double GetR( double v ) const { return majorRadius + minorRadius * ::cos(v); } + /// \ru Изменение главного радиуса. \en Changing of major radius. + void SetMajorR( double r ) { majorRadius = r; CheckTorusRadii(); CalculateAngle(); SetDirtyGabarit(); } + /// \ru Изменение меньшего радиуса. \en Changing of minor radius. + void SetMinorR( double r ) { minorRadius = r; CheckTorusRadii(); CalculateAngle(); SetDirtyGabarit(); } + /// \ru Главный радиус. \en Major radius. + double GetMajorR() const { return majorRadius; } + /// \ru Меньший радиус. \en Minor radius. + double GetMinorR() const { return minorRadius; } + /// \ru Радиус v-параллели. \en Radius of v-parallel. + double GetR( double v ) const { return majorRadius + minorRadius * ::cos(v); } - /// \ru Дать центр u-линии тора. \en Get center of torus u-line. - void GetMinorCentre( double u, MbCartPoint3D & c ) const; - /// \ru Дать проекцию точки на линию центров малого радиуса. \en Get projection of the point to the line of centers of minor radius. - double MinorCentreProjection( MbCartPoint3D & p ) const; + /// \ru Дать центр u-линии тора. \en Get center of torus u-line. + void GetMinorCentre( double u, MbCartPoint3D & c ) const; + /// \ru Дать проекцию точки на линию центров малого радиуса. \en Get projection of the point to the line of centers of minor radius. + double MinorCentreProjection( MbCartPoint3D & p ) const; - /** \brief \ru Определить положение полюсов. - \en Define position of the poles. \~ - \details \ru Определить положение полюсов. - \en Define position of the poles. \~ - \param[out] poleVMin, poleVMax - \ru Значения полюсов. - \en Values of the poles. \~ - \return \ru true, если полюса найдены. - \en True if the poles are found. \~ - */ - bool GetVPoles( double & poleVMin, double & poleVMax ) const; + /** \brief \ru Определить положение полюсов. + \en Define position of the poles. \~ + \details \ru Определить положение полюсов. + \en Define position of the poles. \~ + \param[out] poleVMin, poleVMax - \ru Значения полюсов. + \en Values of the poles. \~ + \return \ru true, если полюса найдены. + \en True if the poles are found. \~ + */ + bool GetVPoles( double & poleVMin, double & poleVMax ) const; private: - void CheckTorusRadii(); + void CheckTorusRadii(); inline void CheckParam( double & u, double & v ) const; // \ru Проверка параметров \en Check parameters bool _CheckParamV( double & v ) const; // \ru Проверить параметр \en Check parameter // \ru Пересечение с прямолинейной кривой \en Intersection with rectilinear curve - bool StraightIntersection( const MbCurve3D & curv, SArray & uv, SArray & tt, bool ext0, bool ext ) const; - void CalculateAngle(); // \ru Вычислить угол \en Evaluate the angle - void operator = ( const MbTorusSurface & ); // \ru Не реализовано. \en Not implemented. + bool StraightIntersection( const MbCurve3D & curv, SArray & uv, SArray & tt, bool ext0, bool ext ) const; + void CalculateAngle(); // \ru Вычислить угол \en Evaluate the angle + void operator = ( const MbTorusSurface & ); // \ru Не реализовано. \en Not implemented. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbTorusSurface ) }; IMPL_PERSISTENT_OPS( MbTorusSurface ) + //------------------------------------------------------------------------------ // \ru Проверка параметров \en Check parameters // --- diff --git a/C3d/Include/surface.h b/C3d/Include/surface.h index 458dc22..3cd0e98 100644 --- a/C3d/Include/surface.h +++ b/C3d/Include/surface.h @@ -246,7 +246,7 @@ public: /// \ru Является ли точка полюсом. \en Whether the point is a pole. virtual bool IsPole( double u, double v, double paramPrecision = PARAM_PRECISION ) const; /// \ru Является ли точка полюсом. \en Whether the point is a pole. - bool IsPole( const MbCartPoint & uv, double paramPrecision = PARAM_PRECISION ) const { return IsPole( uv.x, uv.y, paramPrecision ); } + bool IsPole( const MbCartPoint & uv, double paramPrecision = PARAM_PRECISION ) const { return IsPole( uv.x, uv.y, paramPrecision ); } /** \} */ @@ -608,7 +608,7 @@ public: \en A sag value by parameter at given point. \~ \ingroup Surfaces */ - double SurfaceStep( const double & u, const double & v, bool alongU, const MbStepData & stepData ) const; + double SurfaceStep( const double & u, const double & v, bool alongU, const MbStepData & stepData ) const; /// \ru Количество разбиений по параметру u для проверки событий. \en The number of splittings by u-parameter for a check of events. virtual size_t GetUCount() const; @@ -723,7 +723,7 @@ public: \return \ru Кривизна. \en Curvature. \~ */ - double NormalCurvatureU( double u, double v ) const; // \ru Нормальная кривизна поверхности вдоль линии u. \en A normal curvature of surface along the direction of u. + double NormalCurvatureU( double u, double v ) const; // \ru Нормальная кривизна поверхности вдоль линии u. \en A normal curvature of surface along the direction of u. /** \brief \ru Вычислить нормальную кривизну линии вдоль v. \en Calculate a normal curvature of line along the direction of v. \~ @@ -736,7 +736,7 @@ public: \return \ru Кривизна. \en Curvature. \~ */ - double NormalCurvatureV( double u, double v ) const; // \ru Нормальная кривизна поверхности вдоль линии v. \en A normal curvature of surface along the direction of v. + double NormalCurvatureV( double u, double v ) const; // \ru Нормальная кривизна поверхности вдоль линии v. \en A normal curvature of surface along the direction of v. /** \brief \ru Вычислить нормальную кривизну поверхности. \en Calculate a normal curvature of surface. \~ @@ -753,7 +753,7 @@ public: \return \ru Кривизна. \en Curvature. \~ */ - double NormalCurvature ( double u, double v, double du, double dv ) const; // \ru Нормальная кривизна поверхности. \en Normal curvature of surface. + double NormalCurvature ( double u, double v, double du, double dv ) const; // \ru Нормальная кривизна поверхности. \en Normal curvature of surface. /** \brief \ru Вычислить Среднюю и Гауссову кривизну. \en Calculate the mean and the Gaussian curvature. \~ @@ -770,7 +770,7 @@ public: \return \ru true в случае успеха операции \n false в противном случае \en True if the operation succeeded \n otherwise false. \~ */ - bool MeanGaussCurvature( double u, double v, double & mean, double & gauss ) const; + bool MeanGaussCurvature( double u, double v, double & mean, double & gauss ) const; /** \brief \ru Вычислить главные кривизны и главные направления кривизн. \en Calculate the mean and the Gaussian curvature. \~ @@ -791,7 +791,7 @@ public: \return \ru true в случае успеха вычисления \n false в противном случае. \en True if the calculation succeeded \n otherwise false. \~ */ - bool MainCurvatures( double u, double v, double & c1, double & c2, double & du, double & dv ) const; + bool MainCurvatures( double u, double v, double & c1, double & c2, double & du, double & dv ) const; /// \ru Является ли базовая поверхность копией базовой поверхности данного объекта. \en Whether a base surface is a copy of the base surface of the given object. virtual bool IsSameBase( const MbSurface & ) const; @@ -855,7 +855,7 @@ public: \param[in] bmatch - \ru true, если при преобразовании нужно сохранить однозначное сответствие параметрических областей \en true, if it is required to keep one-to-one correspondence of parametric regions in mapping. \~ */ - MbSplineSurface * NurbsSurface( bool bmatch = false ) const; + MbSplineSurface * NurbsSurface( bool bmatch = false ) const; /** \brief \ru Построить NURBS копию усеченной поверхности. \en Construct a NURBS copy of trimmed surface. \~ @@ -880,7 +880,6 @@ public: */ virtual MbSplineSurface * NurbsSurface( double u1, double u2, double v1, double v2, bool bmatch = false ) const; - // \ru Построить NURBS-копию поверхности. \en Construct a NURBS copy of a surface. /** \brief \ru Построить NURBS копию поверхности. \en Construct a NURBS copy of a surface. \~ \details \ru Строит NURBS поверхность, аппроксимирующую исходную с заданными параметрами по каждому направлению. @@ -925,8 +924,8 @@ public: \return \ru true, если операция прошла успешно. \en True if the operation succeeded. \~ */ - bool NurbsParam( const MbNurbsParameters & tParam, bool uParam, double op1, double op2, - bool & isClosedNurbs, double & epsilon, SArray & params ) const; + bool NurbsParam( const MbNurbsParameters & tParam, bool uParam, double op1, double op2, + bool & isClosedNurbs, double & epsilon, SArray & params ) const; /** \brief \ru Выбрать точки для аппроксимации вдоль параметра. \en Chose points for approximation along the parameter. \~ @@ -959,8 +958,8 @@ public: \param[in,out] aKnots - \ru Узловой вектор NURBS-поверхности. \en A knot vector of NURBS surface. \~ */ - void CheckApproxPointParamsOpen( bool isU, double par, size_t degree, size_t pCount, - SArray & tList, SArray & aKnots ) const; + void CheckApproxPointParamsOpen( bool isU, double par, size_t degree, size_t pCount, + SArray & tList, SArray & aKnots ) const; /** \brief \ru Выбрать точки для аппроксимации вдоль параметра. \en Chose points for approximation along the parameter. \~ @@ -993,8 +992,8 @@ public: \param[in,out] aKnots - \ru Узловой вектор NURBS-поверхности. \en A knot vector of NURBS surface. \~ */ - void CheckApproxPointParamsClosed( bool isU, double par, size_t degree, size_t pCount, - SArray & tList, SArray & aKnots ) const; + void CheckApproxPointParamsClosed( bool isU, double par, size_t degree, size_t pCount, + SArray & tList, SArray & aKnots ) const; // \ru Построить эквидистантую поверхность. \en Create an offset surface. /** \brief \ru Построить эквидистантую поверхность. @@ -1158,7 +1157,7 @@ public: \return \ru Количество пересечений. \en The number of intersections. \~ */ - size_t SurfaceBorderIntersection( const MbCurve & curve, SArray & tcurv, SArray & dir ) const; + size_t SurfaceBorderIntersection( const MbCurve & curve, SArray & tcurv, SArray & dir ) const; /// \ru Нахождение проекции точки на поверхность. Для внутреннего использования. \en Finding of point projection on surface. For internal use only. virtual MbeNewtonResult PointProjectionNewton( const MbCartPoint3D & p, size_t iterLimit, double & u, double & v, bool ext ) const; @@ -1329,7 +1328,7 @@ public: \result \ru true - если операция прошла успешно. \en True - if the operation succeeded. \~ */ - bool ProjectCurveOnSimilarSurface( const MbCurve3D & spaceCurve, const MbCurve & curve, const MbSurface & surfNew, SPtr & curveNew ) const; + bool ProjectCurveOnSimilarSurface( const MbCurve3D & spaceCurve, const MbCurve & curve, const MbSurface & surfNew, SPtr & curveNew ) const; /** \brief \ru Дать двумерную матрицу преобразования из своей параметрической области в параметрическую область surf. \en Get two-dimensional matrix of transformation from its parametric region to the parametric region of 'surf'. \~ @@ -1404,9 +1403,9 @@ public: /// \ru Построить касательные плейсменты конструктивных плоскостей. Для внутреннего использования. \en Construct tangent placements of constructive planes. For internal use only. MbeNewtonResult PlacementNewton( const MbVector3D & vec, double angle, MbeParamDir switchPar, size_t iterLimit, double & u, double & v ) const; /// \ru Построить нормальные или касательные плейсменты на v-линиях. \en Construct the normal or tangent placements on v-lines. - bool CreateVconstPlacements ( const MbVector3D & axisZ, double angle, bool normalPlace, SArray & places ) const; + bool CreateVconstPlacements ( const MbVector3D & axisZ, double angle, bool normalPlace, SArray & places ) const; /// \ru Построить нормальные или касательные плейсменты на u-линиях. \en Construct the normal or tangent placements on u-lines. - bool CreateUconstPlacements ( const MbVector3D & axisZ, double angle, bool normalPlace, SArray & places ) const; + bool CreateUconstPlacements ( const MbVector3D & axisZ, double angle, bool normalPlace, SArray & places ) const; /// \ru Вычислить площадь области определения параметров. \en Calculate the area of parameters domain. @@ -1442,8 +1441,8 @@ public: */ virtual size_t GetVPairs( double u, SArray & v ) const; - /// \ru Определение параметров точки изоклины поверхности. Для внутреннего использования. \en Determination of parameters of a surface isocline point. For internal use only. - MbeNewtonResult IsoclinalNewton( const MbVector3D & dir, size_t iterLimit, double & u, double & v ) const; + /// \ru Определение параметров точки изоклины поверхности. Для внутреннего использования. \en Determination of parameters of a surface isocline point. For internal use only. + MbeNewtonResult IsoclinalNewton( const MbVector3D & dir, size_t iterLimit, double & u, double & v ) const; /** \brief \ru Найти все изоклины поверхности. \en Find all isoclines of a surface. \~ @@ -1468,7 +1467,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 { cube.SetEmpty(); } /** \brief \ru Скопировать габаритный куб из копии. \en Copy the bounding box from the copy. \~ @@ -1479,9 +1478,9 @@ public: \param[in] s - \ru Поверхность-копия. \en A surface-copy. \~ */ - void CopyGabarit( const MbSurface & s, const MbVector3D * to = nullptr ) { cube = s.cube; if ( (to != nullptr) && !cube.IsEmpty() ) { cube.Move( *to ); } } + void CopyGabarit( const MbSurface & s, const MbVector3D * to = nullptr ) { cube = s.cube; if ( (to != nullptr) && !cube.IsEmpty() ) { cube.Move( *to ); } } /// \ru Вычислить диагональ габаритного куба. \en Calculate the diagonal of the bounding box. - double GetGabDiagonal() const { if ( cube.IsEmpty() ) { MbCube tmp; CalculateGabarit( tmp ); } return cube.GetDiagonal(); } + double GetGabDiagonal() const { if ( cube.IsEmpty() ) { MbCube tmp; CalculateGabarit( tmp ); } return cube.GetDiagonal(); } /** \brief \ru Вычислить прямоугольный габарит поверхности в заданной плоскости. \en Calculate the rectangular bounding box of a surface in the given plane. \~ @@ -1492,7 +1491,7 @@ public: \param[out] rect - \ru Вычисленный прямоугольник. \en Calculated rectangle. \~ */ - void CalculateRect( const MbPlacement3D & place, MbRect & rect ) const; + void CalculateRect( const MbPlacement3D & place, MbRect & rect ) const; /** \brief \ru Вернуть граничный двумерный контур. \en Return the bounding two-dimensional contour. \~ @@ -1545,12 +1544,12 @@ public: \result \ru Граничная кривая. \en A boundary curve. \~ */ - MbCurve & MakeCurve( size_t number1, size_t number2 ) const; + MbCurve & MakeCurve( size_t number1, size_t number2 ) const; /// \ru Установить пределы поверхности. Для внутреннего использования. \en Set surface limits. For internal use only. virtual void SetLimit( double u1, double v1, double u2, double v2 ); /// \ru Установить пределы поверхности. Для внутреннего использования. \en Set surface limits. For internal use only. - void SetLimit( const MbRect & ); + void SetLimit( const MbRect & ); /// \ru Установить расширенные пределы поверхности. Для внутреннего использования. \en Set extended limits of surface. For internal use only. virtual void SetExtendedParamRegion( double u1, double v1, double u2, double v2 ); @@ -1558,9 +1557,9 @@ public: virtual void IncludePoint( double u, double v ); /// \ru Дать максимальное приращение параметра U. \en Get the maximum increment of U-parameter. - double GetMaxParamDeltaU() const { return GetURange() / c3d::COUNT_DELTA; } + double GetMaxParamDeltaU() const { return GetURange() / c3d::COUNT_DELTA; } /// \ru Дать максимальное приращение параметра V. \en Get the maximum increment of V-parameter. - double GetMaxParamDeltaV() const { return GetVRange() / c3d::COUNT_DELTA; } + double GetMaxParamDeltaV() const { return GetVRange() / c3d::COUNT_DELTA; } /// \ru Дать максимальное приращение параметра. \en Get the maximum increment of parameter. virtual double GetParamDelta() const; /// \ru Дать минимально различимую величину параметра. \en Get the minimum distinguishable value of parameter. @@ -1575,29 +1574,29 @@ public: /// \ru Дать приращение параметра v, соответствующее единичной длине в пространстве. \en Get increment of v-parameter, corresponding to the unit length in space. virtual double GetVParamToUnit( double u, double v ) const; /// \ru Дать приращение параметра u, соответствующее единичной длине в пространстве. \en Get increment of u-parameter, corresponding to the unit length in space. - double GetUParamToUnit( const MbCartPoint & uv ) const { return GetUParamToUnit( uv.x, uv.y ); } + double GetUParamToUnit( const MbCartPoint & uv ) const { return GetUParamToUnit( uv.x, uv.y ); } /// \ru Дать приращение параметра v, соответствующее единичной длине в пространстве. \en Get increment of v-parameter, corresponding to the unit length in space. - double GetVParamToUnit( const MbCartPoint & uv ) const { return GetVParamToUnit( uv.x, uv.y ); } + double GetVParamToUnit( const MbCartPoint & uv ) const { return GetVParamToUnit( uv.x, uv.y ); } /// \ru Дать приращение параметра u и параметра v, соответствующее единичной длине в пространстве. \en Get increment of parameters, corresponding to the unit length in space. virtual void GetParamsToUnit( double u, double v, double & uParam, double & vParam ) const; /// \ru Дать минимально различимую величину параметра U. Соответствует длине в пространстве = Math::metricEpsilon. \en Get the minimum distinguishable value of u-parameter. It corresponds to the length Math::metricEpsilon in space. - double GetUEpsilon() const; + double GetUEpsilon() const; /// \ru Дать минимально различимую величину параметра V. Соответствует длине в пространстве = Math::metricEpsilon. \en Get the minimum distinguishable value of v-parameter. It corresponds to the length Math::metricEpsilon in space. - double GetVEpsilon() const; + double GetVEpsilon() const; /// \ru Дать минимально различимую величину параметра U. Соответствует длине в пространстве = Math::metricEpsilon. \en Get the minimum distinguishable value of u-parameter. It corresponds to the length Math::metricEpsilon in space. - double GetUEpsilon( double u, double v ) const; + double GetUEpsilon( double u, double v ) const; /// \ru Дать минимально различимую величину параметра V. Соответствует длине в пространстве = Math::metricEpsilon. \en Get the minimum distinguishable value of v-parameter. It corresponds to the length Math::metricEpsilon in space. - double GetVEpsilon( double u, double v ) const; + double GetVEpsilon( double u, double v ) const; /// \ru Дать минимально различимую величину параметра U. Соответствует длине в пространстве = Math::metricRegion. \en Get the minimum distinguishable value of u-parameter. It corresponds to the length Math::metricRegion in space. - double GetURegion() const; + double GetURegion() const; /// \ru Дать минимально различимую величину параметра V. Соответствует длине в пространстве = Math::metricRegion. \en Get the minimum distinguishable value of v-parameter. It corresponds to the length Math::metricRegion in space. - double GetVRegion() const; + double GetVRegion() const; /// \ru Дать минимально различимую величину параметра U. Соответствует длине в пространстве = Math::metricRegion. \en Get the minimum distinguishable value of u-parameter. It corresponds to the length Math::metricRegion in space. - double GetURegion( double u, double v ) const; + double GetURegion( double u, double v ) const; /// \ru Дать минимально различимую величину параметра V. Соответствует длине в пространстве = Math::metricRegion. \en Get the minimum distinguishable value of v-parameter. It corresponds to the length Math::metricRegion in space. - double GetVRegion( double u, double v ) const; + double GetVRegion( double u, double v ) const; /// \ru Выдать количество разбиений по u. \en The the number of splittings in u-direction. virtual size_t GetUMeshCount() const; @@ -1627,8 +1626,8 @@ public: \param[out] polygon - \ru Насчитанный полигон. \en Calculated polygon. \~ */ - void CalculatePolygon( double minPar, double maxPar, double constPar, MbeParamDir dir, - const MbStepData & stepData, MbPolygon3D & polygon ) const; + void CalculatePolygon( double minPar, double maxPar, double constPar, MbeParamDir dir, + const MbStepData & stepData, MbPolygon3D & polygon ) const; /** \brief \ru Рассчитать сетку. \en Calculate mesh. \~ @@ -1702,9 +1701,9 @@ public: \param[out] vv - \ru Множество параметров разбиения по v. \en A set of parameters of splitting by v. \~ */ - void AddTesselation( const MbStepData & stepData, MbeParamDir dir, - double u1, double u2, double v1, double v2, - SArray & uu, SArray & vv ) const; + void AddTesselation( const MbStepData & stepData, MbeParamDir dir, + double u1, double u2, double v1, double v2, + SArray & uu, SArray & vv ) const; /** \brief \ru Аппроксимировать поверхность треугольными пластинами. \en Approximate a surface by triangular plates. \~ @@ -1752,9 +1751,9 @@ public: virtual void CheckSurfParams( double & u, double & v ) const; /// \ru Дать локальную систему координат плоской поверхности (или только возможность ее выдачи). \en Get a local coordinate system of planar surface (or only a possibility of getting it). - bool GetPlacement ( MbPlacement3D * place, bool exact = false ) const; + bool GetPlacement ( MbPlacement3D * place, bool exact = false ) const; /// \ru Дать локальную систему координат, если поверхность является плоскостью. \en Get a local coordinate system if a surface is a plane. - bool GetPlanePlacement( MbPlacement3D & place ) const; + bool GetPlanePlacement( MbPlacement3D & place ) const; /** \brief \ru Построить локальную систему координат с началом в средней точке параметрических пределов базовой поверхности. \en Construct a local coordinate system of a surface with origin at the middle point of base surface parametric limits. \~ \details \ru Построить локальную систему координат с началом в средней точке параметрических пределов поверхности. @@ -1766,17 +1765,17 @@ public: \result \ru true - Если получилось построить. \en True - if construction has been successfully. \~ */ - bool GetControlPlacement( MbPlacement3D & place, bool sameSense = true ) const; + bool GetControlPlacement( MbPlacement3D & place, bool sameSense = true ) const; /// \ru Сориентировать ось Х плейсмента вдоль линии его пересечения с поверхностью. \en Orient an axis X of a placement along the line of its intersection with surface. - bool OrientPlacement ( MbPlacement3D & place, bool normalSense = true ) const; + bool OrientPlacement ( MbPlacement3D & place, bool normalSense = true ) const; /// \ru Определить, лежит ли точка на поверхности. \en Determine whether a point is located on a surface or not. - bool IsPointOn ( const MbCartPoint3D &, double eps = METRIC_PRECISION ) const; + bool IsPointOn ( const MbCartPoint3D &, double eps = METRIC_PRECISION ) const; /// \ru Вычислить точку на поверхности в области определения поверхности. \en Calculate the point on a surface inside the domain of surface. - void PointOn ( MbCartPoint & uv, MbCartPoint3D & p ) const; + void PointOn ( MbCartPoint & uv, MbCartPoint3D & p ) const; /// \ru Вычислить точку на продолженной поверхности. \en Calculate a point on a surface extension. void _PointOn ( const MbCartPoint & uv, MbCartPoint3D & p ) const; /// \ru Вычислить нормаль к поверхности в области определения поверхности. \en Calculate the normal vector to a surface inside the domain of surface. - void Normal ( MbCartPoint & uv, MbVector3D & v ) const; + void Normal ( MbCartPoint & uv, MbVector3D & v ) const; /** \brief \ru Найти матрицу преобразования для кривых на поверхности при изменении параметризации. \en Find a matrix of transformation for the curves on a surface when the parameterization is changed. \~ @@ -1797,37 +1796,37 @@ public: \param[in] matr - \ru Матрица преобразования. \en A transformation matrix. \~ */ - bool GetMatrix( double xMin, double xMax, double yMin, double yMax, MbMatrix & matr ) const; + bool GetMatrix( double xMin, double xMax, double yMin, double yMax, MbMatrix & matr ) const; /// \ru Среднее значение параметра u. \en The middle value of u. - double GetUMid() const { return ((GetUMin() + GetUMax()) * 0.5); } + double GetUMid() const { return ((GetUMin() + GetUMax()) * 0.5); } /// \ru Среднее значение параметра v. \en The middle value of v. - double GetVMid() const { return ((GetVMin() + GetVMax()) * 0.5); } + double GetVMid() const { return ((GetVMin() + GetVMax()) * 0.5); } /// \ru Параметрическая длина по u. \en Parametric length by u. - double GetURange() const { return (GetUMax() - GetUMin()); } + double GetURange() const { return (GetUMax() - GetUMin()); } /// \ru Параметрическая длина по v. \en Parametric length by v. - double GetVRange() const { return (GetVMax() - GetVMin()); } + double GetVRange() const { return (GetVMax() - GetVMin()); } /// \ru Получить параметрические границы поверхности. \en Get parametric bounding box. - void GetRect( MbRect & r ) const { r.Set( GetUMin(), GetVMin(), GetUMax(), GetVMax() ); } + void GetRect( MbRect & r ) const { r.Set( GetUMin(), GetVMin(), GetUMax(), GetVMax() ); } /// \ru Получить параметрические границы поверхности. \en Get parametric bounding box. - void GetRect( MbRect2D & r ) const { r.Init( GetUMin(), GetVMin(), GetUMax(), GetVMax() ); } + void GetRect( MbRect2D & r ) const { r.Init( GetUMin(), GetVMin(), GetUMax(), GetVMax() ); } /** \} */ // \ru Функции унификации объекта и вектора объектов в шаблонных функциях. \en Functions for compatibility of a object and a vector of objects in template functions. - size_t size() const { return 1; } ///< \ru Количество объектов при трактовке объекта как вектора объектов. \en Number of objects if object is interpreted as vector of objects. + size_t size() const { return 1; } ///< \ru Количество объектов при трактовке объекта как вектора объектов. \en Number of objects if object is interpreted as vector of objects. const MbSurface * operator [] ( size_t ) const { return this; } ///< \ru Оператор доступа. \en An access operator. protected: /// \ru Сдвинуть габарит. \en Move bounding box. - void MoveGabarit( const MbVector3D & v ) { if ( !cube.IsEmpty() ) cube.Move( v ) ; } + void MoveGabarit( const MbVector3D & v ) { if ( !cube.IsEmpty() ) cube.Move( v ) ; } /// \ru Вычислить нормаль по известным производным uDer и vDer в точке с параметрами u, v. \en Normal calculation by derivatives uDer and vDer on point with parameters u, v. - void NormalCalculation( const MbVector3D & uDer, const MbVector3D & vDer, double u, double v, bool ext, MbVector3D & nor ) const; + void NormalCalculation( const MbVector3D & uDer, const MbVector3D & vDer, double u, double v, bool ext, MbVector3D & nor ) const; /// \ru Вычислить шаг по параметру для заданного прогиба. \en Step calculation by sag. - double StepAlong( double u, double v, double sag, bool alongU, double stepMinCoeff, + double StepAlong( double u, double v, double sag, bool alongU, double stepMinCoeff, const MbVector3D & der, const MbVector3D & sec ) const; /// \ru Вычислить шаг по параметру для заданного углового отклонения нормали. \en Step calculation by normal deviation. - double DeviationStepAlong( double u, double v, double angle, bool alongU, + double DeviationStepAlong( double u, double v, double angle, bool alongU, const MbVector3D & der, const MbVector3D & sec ) const; private: @@ -1836,11 +1835,11 @@ private: /// \ru Найти аппроксимационную поверхность с помощью метода наименьших квадратов. \en Find an approximation surface using the method of least squares. MbSplineSurface * NurbsSurfaceThroughPoints( MbNurbsParameters & paramU, MbNurbsParameters & paramV, size_t uCount, size_t vCount ) const; /// \ru Подготовить параметры для преобразования в NURBS поверхность при заданном узловом векторе для интерполяции. \en Prepare parameters for the transformation to NURBS surface with the given knot vector for the interpolation. - bool NurbsParamForKnots( const MbNurbsParameters & tParam, const SArray & knots, bool uParam, double op1, double op2, + bool NurbsParamForKnots( const MbNurbsParameters & tParam, const SArray & knots, bool uParam, double op1, double op2, bool & isClosedNurbs, double & epsilon, SArray & params ) const; // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию \en Declaration without implementation of the assignment operator to prevent an assignment by default - void operator = ( const MbSurface & ); + void operator = ( const MbSurface & ); DECLARE_PERSISTENT_CLASS( MbSurface ) }; diff --git a/C3d/Include/topology.h b/C3d/Include/topology.h index 3dca6a9..7beac58 100644 --- a/C3d/Include/topology.h +++ b/C3d/Include/topology.h @@ -878,10 +878,12 @@ public : \en The angular deviation step of the motion along the curve in the general case. \~ \param[in] version - \ru Версия операции. \en Version of operation. \~ + \param[in] eps - \ru Точность построений. + - \en Build precision. \~ \return \ru Возвращает true, если продление выполнено, false - в противном случае. \en Returns true if the edge was prolonged, otherwise returns false. \~ */ - bool ProlongEdge ( double & t, bool begin, double deviateAngle, const VERSION version ); + bool ProlongEdge ( double & t, bool begin, double deviateAngle, const VERSION version, double eps = Math::paramNear ); /** \brief \ru Объединение двух стыкующихся ребер. \en Merging of two connected edges. \~ @@ -902,7 +904,8 @@ public : \return \ru Возвращает поглощенное ребро edge2, которое можно удалять. \en Returns absorbed edge (edge2), which can be removed. \~ */ - MbCurveEdge * MergeEdges( MbCurveEdge & edge2, bool begin1, bool begin2, const MbSNameMaker & snMaker ); + MbCurveEdge * MergeEdges( MbCurveEdge & edge2, bool begin1, bool begin2, + const MbSNameMaker & snMaker, double tolerance = Math::paramNear ); /// \ru Собрать все ребра, стыкующиеся с заданным ребром в его начале begin==true (конце begin==false). \en Collect all edges which are connected with the given edge at its start vertex (begin==true) or at its end vertex (begin==false). void GetConnectedEdges( bool begin, RPArray & edges, SArray & orients ) const; diff --git a/C3d/Include/topology_faceset.h b/C3d/Include/topology_faceset.h index b1a357e..11f2cd1 100644 --- a/C3d/Include/topology_faceset.h +++ b/C3d/Include/topology_faceset.h @@ -28,7 +28,7 @@ class MATH_CLASS MbShellHistory; class MATH_CLASS MbPntLoc; class MATH_CLASS MbFaceSetTemp; struct MATH_CLASS MbEdgeFunction; -struct MATH_CLASS MbCheckTopologyParams; +class MATH_CLASS MbCheckTopologyParams; class MATH_CLASS MbFaceShell; class MATH_CLASS MbShellsDistanceData; struct MATH_CLASS MbUnitInfo; @@ -1423,7 +1423,7 @@ bool MbFaceShell::FindIndexByVertices( const ConstVertexPointers & init, ItemInd \ingroup Data_Structures */ //--- -struct MATH_CLASS MbCheckTopologyParams { +class MATH_CLASS MbCheckTopologyParams : public MbPrecision { protected: bool mergeEdges; ///< \ru Флаг слияния ребер. \en Merge flag for edges. SPtr nameMaker; ///< \ru Именователь с версией операции. \en Names maker with operation version. @@ -1432,18 +1432,24 @@ protected: c3d::ConstEdgesVector boundaryEdges; ///< \ru Исходные краевые ребра (до операции). \en Initial boundary edges (before an operation). public: explicit MbCheckTopologyParams( bool doMergingEdges, - const MbSNameMaker & nMaker ) - : mergeEdges ( doMergingEdges ) + const MbSNameMaker & nMaker, + double tolerance = Math::paramAccuracy ) + : MbPrecision() + , mergeEdges ( doMergingEdges ) , nameMaker ( &nMaker.Duplicate() ) , lastMainName ( c3d::SIMPLENAME_MAX ) // \ru Неизвестно. \en Unknown. , controlFaces ( ) , boundaryEdges( ) - {} + { + SetTolerance( tolerance ); + } template explicit MbCheckTopologyParams( bool doMergingEdges, const MbSNameMaker & nMaker, - const Faces & faces ) - : mergeEdges ( doMergingEdges ) + const Faces & faces, + double tolerance = Math::paramAccuracy ) + : MbPrecision() + , mergeEdges ( doMergingEdges ) , nameMaker ( &nMaker.Duplicate() ) , lastMainName ( c3d::SIMPLENAME_MAX ) // \ru Неизвестно. \en Unknown. , controlFaces ( ) @@ -1456,13 +1462,16 @@ public: controlFaces.push_back( faces[k] ); std::sort( controlFaces.begin(), controlFaces.end() ); } + SetTolerance( tolerance ); } template - explicit MbCheckTopologyParams( bool doMergingEdges, - const MbSNameMaker & nMaker, - const Faces & faces, - const c3d::ConstEdgesVector & edges ) - : mergeEdges ( doMergingEdges ) + explicit MbCheckTopologyParams( bool doMergingEdges, + const MbSNameMaker & nMaker, + const Faces & faces, + const c3d::ConstEdgesVector & edges, + double tolerance = Math::paramAccuracy ) + : MbPrecision() + , mergeEdges ( doMergingEdges ) , nameMaker ( &nMaker.Duplicate() ) , lastMainName ( c3d::SIMPLENAME_MAX ) // \ru Неизвестно. \en Unknown. , controlFaces ( ) @@ -1476,6 +1485,7 @@ public: std::sort( controlFaces.begin(), controlFaces.end() ); } std::sort( boundaryEdges.begin(), boundaryEdges.end() ); + SetTolerance( tolerance ); } ~MbCheckTopologyParams() {} public: diff --git a/C3d/Lib/x32/Debug/c3d.lib b/C3d/Lib/x32/Debug/c3d.lib index a5216c0..68868b1 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 9034727..eaaa1ac 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 4cb45af..b6a9b20 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 fc9bfce..303ecc3 100644 Binary files a/C3d/Lib/x64/Release/c3d.lib and b/C3d/Lib/x64/Release/c3d.lib differ