diff --git a/C3d/Include/action.h b/C3d/Include/action.h index 3efbb30..2672396 100644 --- a/C3d/Include/action.h +++ b/C3d/Include/action.h @@ -1205,6 +1205,7 @@ MATH_FUNC (MbResultType) CreateMerging( MbSolid & solid, c3d::FacesVector & faces, const MbNurbsParameters & uParam, const MbNurbsParameters & vParam, + double tolerance, const MbSNameMaker & names, bool prolong, MbSolid *& result ); @@ -1306,6 +1307,24 @@ MATH_FUNC (MbResultType) TouchedSolidsMerging( MbSolid & solid1, MATH_FUNC (MbResultType) SolidRepairing( MbSolid & solid, double accuracy ); +//------------------------------------------------------------------------------ +/** \brief \ru Найти грани скругления и фаски. \~ + \en Find fillet and chamfer faces. \~ + \details \ru Найти грани скругления и фаски среди присланных граней и добавить в присланный контейнер. \~ + \en Find fillet and chamfer faces and add them into container. \~ + \param[in] faces - \ru Грани для поиска. + \en Faces for check. \~ + \param[in] accuracy - \ru Точность для поиска. + \en The accuracy for finding. \~ + \param[in] filletFaces - \ru Найденные грани скругления и фаски. + \en Found fillet and chamfer faces. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (void) FindFilletFaces( const RPArray & faces, + double accuracy, + RPArray & filletFaces ); + //------------------------------------------------------------------------------ /** \brief \ru Получить трансформированную копию тела. \~ \en Get transformed copy of a solid. \~ diff --git a/C3d/Include/action_analysis.h b/C3d/Include/action_analysis.h index 856c287..ec649fc 100644 --- a/C3d/Include/action_analysis.h +++ b/C3d/Include/action_analysis.h @@ -12,6 +12,7 @@ #include +#include #include @@ -375,10 +376,199 @@ MATH_FUNC( void ) CurveMinMaxCurvature( const MbCurve3D & curve, \en Point of calculation. \~ \param[out] dir - \ru Рассчитываемое направление. \en The calculated direction. \~ - \ingroup Algorithms_3D + \ingroup Algorithms_3D */ MATH_FUNC( void ) SurfaceMaxCurvatureDirection( const MbSurface & surf, const MbCartPoint & pnt, MbVector & dir ); + +//------------------------------------------------------------------------------ +/** \brief \ru Входные параметры функции поиска минимальных и максимальных углов между нормалями поверхностей кривой пересечения. + \en Input parameters of the function of finding the minimum and maximum angles between surfaces normals of the intersection curve. \~ + \details \ru Входные параметры функции поиска минимальных и максимальных углов между нормалями поверхностей кривой пересечения. \n + \en Input parameters of the function of finding the minimum and maximum angles between surfaces normals of the intersection curve. \n \~ + \warning \ru В разработке. + \en Under development. \~ + \ingroup Algorithms_3D +*/ // --- +class MATH_CLASS MbNormalsMinMaxAnglesParams { +public: + enum OperationMode + { + om_FuncDerCos2 = 0, // минимизация производной функции квадрата косинуса угла между нормалями + }; +protected: + c3d::ConstIntersectionCurveSPtr intCurve; ///< \ru Кривая пересечения. \en Surfaces intersection curve. + bool sameSense1; ///< \ru Совпадение направления нормали первой поверхности и грани на ее основе. \en Coincidence of direction of the normal of the first surface and the face on its basis. + bool sameSense2; ///< \ru Совпадение направления нормали второй поверхности и грани на ее основе. \en Coincidence of direction of the normal of the second surface and the face on its basis. + ThreeStates dirMatch; ///< \ru Прямое, неопределенное или обратное соответствие поверхность-грань. \en Direct, undefined, or inverse surface-to-face match. + OperationMode calcMode; ///< \ru Режим расчета. \en Operation mode. +private: + const MbSNameMaker & snMaker; ///< \ru Именователь с версией операции. \en Names maker with operation version. +public: + /** \brief \ru Конструктор. + \en Constructor. \~ + \details \ru Конструктор по параметрам. + \en Constructor by parameters. \~ + \param[in] intCrv - \ru Кривая пересечения поверхностей. + \en Surfaces intersection curve. \~ + */ + MbNormalsMinMaxAnglesParams( const MbSurfaceIntersectionCurve & intCrv, const MbSNameMaker & nm ) + : intCurve ( &intCrv ) + , sameSense1( true ) + , sameSense2( true ) + , dirMatch ( ts_neutral ) + , calcMode ( om_FuncDerCos2 ) + , snMaker ( nm ) + {} + /** \brief \ru Конструктор. + \en Constructor. \~ + \details \ru Конструктор по параметрам. + \en Constructor by parameters. \~ + \param[in] intCrv - \ru Кривая пересечения поверхностей. + \en Surfaces intersection curve. \~ + */ + MbNormalsMinMaxAnglesParams( const MbCurveEdge & edge, const MbSNameMaker & nm ) + : intCurve ( &edge.GetIntersectionCurve() ) + , sameSense1( true ) + , sameSense2( true ) + , dirMatch ( ts_neutral ) + , calcMode ( om_FuncDerCos2 ) + , snMaker ( nm ) + { + const MbSurface & surface1 = intCurve->GetCurveOneSurface().GetSurface(); + const MbSurface & surface2 = intCurve->GetCurveTwoSurface().GetSurface(); + const MbFace * fp = edge.GetFacePlus(); + const MbFace * fm = edge.GetFaceMinus(); + + if ( fp != c3d_null && fm != c3d_null ) { + const MbSurface & sp = fp->GetSurface().GetSurface(); + const MbSurface & sm = fm->GetSurface().GetSurface(); + + if ( &sp == &surface1 && &sm == &surface2 ) { + sameSense1 = fp->IsSameSense(); + sameSense2 = fm->IsSameSense(); + dirMatch = ts_positive; + } + else if ( &sp == &surface2 && &sm == &surface1 ) { + sameSense1 = fm->IsSameSense(); + sameSense2 = fp->IsSameSense(); + dirMatch = ts_negative; + } + else { + intCurve = c3d_null; // parameter error + } + } + else if ( (fp != c3d_null) || (fm != c3d_null) ) { + const MbFace * f = (fp != c3d_null) ? fp : fm; + const MbSurface & s = f->GetSurface().GetSurface(); + + if ( &s == &surface1 && &s == &surface2 ) { + sameSense1 = f->IsSameSense(); + sameSense2 = sameSense1; + dirMatch = ts_positive; + } + else if ( &s == &surface1 ) { + const MbCurve & pCurve1 = intCurve->GetCurveOneCurve(); + intCurve = new MbSurfaceIntersectionCurve( surface1, pCurve1, surface1, pCurve1, cbt_Boundary, true, true ); + sameSense1 = f->IsSameSense(); + sameSense2 = sameSense1; + dirMatch = ts_positive; + } + else if ( &s == &surface2 ) { + const MbCurve & pCurve2 = intCurve->GetCurveOneCurve(); + intCurve = new MbSurfaceIntersectionCurve( surface2, pCurve2, surface2, pCurve2, cbt_Boundary, true, true ); + sameSense1 = f->IsSameSense(); + sameSense2 = sameSense1; + dirMatch = ts_negative; + } + else { + intCurve = c3d_null; // parameter error + } + } + } +public: + /// \ru Есть ли кривая пересечения? \en Does an intersection curve exist? + bool IsCurve() const { return (intCurve != c3d_null); } + /// \ru Получить кривую пересечения? \en Get intersection curve. + c3d::ConstIntersectionCurveSPtr GetCurve() const { return intCurve; } + /// \ru Признак совпадения нормали первой поверхности и грани. \en The flag of the coincidence of the normal of the first surface and the corresponding face . + bool IsSameSense1() const { return sameSense1; } + /// \ru Признак совпадения нормали второй поверхности и грани. \en The flag of the coincidence of the normal of the second surface and the corresponding face . + bool IsSameSense2() const { return sameSense2; } + /// \ru Получит режим работы. \en Get operation mode. + OperationMode GetOperationMode() const { return calcMode; } + /// \ru Получить ссылку на именователь. \en Get names maker reference. + const MbSNameMaker & GetNameMaker() const { return snMaker; } + +OBVIOUS_PRIVATE_COPY( MbNormalsMinMaxAnglesParams) +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Выходные параметры функции поиска минимальных и максимальных углов между нормалями поверхностей кривой пересечения. + \en Output parameters of the function of finding the minimum and maximum angles between surfaces normals of the intersection curve. \~ + \details \ru Выходные параметры функции поиска минимальных и максимальных углов между нормалями поверхностей кривой пересечения. \n + \en Output parameters of the function of finding the minimum and maximum angles between surfaces normals of the intersection curve. \n \~ + \warning \ru В разработке. + \en Under development. \~ + \ingroup Algorithms_3D +*/ // --- +class MATH_CLASS MbNormalsMinMaxAnglesResults { +public: + /// \ru Локальные выходные параметры. \en Output local parameters. + struct Data { + double t; ///< \ru Параметр кривой. \en Intersection curve parameter. + double f; ///< \ru Значение целевой функции (f = 1.0 - (cos(a)*cos(a)). \en Objective function value (f = 1.0 - (cos(a)*cos(a)). + double a; ///< \ru Угол между нормалями поверхностей в кривой пересечения. \en Angle between surfaces normals in the intersection curve. + ThreeStates isMin; ///< \ru Локальный минимум, максимум или неопределенное состояние. \en Local minimum, maximum or undefined state. + public: + Data() : t( UNDEFINED_DBL ), f( UNDEFINED_DBL ), a( UNDEFINED_DBL ), isMin( ts_neutral ) {} + Data( double f0 ) : t( UNDEFINED_DBL ), f( f0 ), a( UNDEFINED_DBL ), isMin( ts_neutral ) {} + Data( double t0, double f0 ) : t( t0 ), f( f0 ), a( UNDEFINED_DBL ), isMin( ts_neutral ) {} + Data( double t0, double f0, double a0 ) : t( t0 ), f( f0 ), a( a0 ), isMin( ts_neutral ) {} + Data( double t0, double f0, double a0, ThreeStates s ) : t( t0 ), f( f0 ), a( a0 ), isMin( s ) {} + Data( const Data & d ) : t( d.t ), f( d.f ), a( d.a ), isMin( d.isMin ) {} + public: + const Data & operator = ( const Data & d ) { t = d.t; f = d.f; a = d.a; isMin = d.isMin; return *this; } + public: + void Reset() { t = f = a = UNDEFINED_DBL; isMin = ts_neutral; } + }; +public: + std::vector allParamValues; ///< \ru Все найденные экстремальные углы. \en All found extrema angles. + std::vector minParamValues; ///< \ru Все найденные локальные минимумы углов. \en All found local minimum angles. + std::vector maxParamValues; ///< \ru Все найденные локальные максимумы углов. \en All found local maximum angles. + Data minParamValue; ///< \ru Глобальный минимальный угол. \en Global minimum angle. + Data maxParamValue; ///< \ru Глобальный максимальный угол. \en Global maximum angle. + MbResultType resType; ///< \ru Код результата операции. \en Operation result code. + +public: + /// \ru Конструктор. \en Constructor. + MbNormalsMinMaxAnglesResults() : allParamValues(), minParamValues(), maxParamValues(), minParamValue( MB_MAXDOUBLE ), maxParamValue( -MB_MAXDOUBLE ) {} +public: + /// \ru Очистка данных. \en Data cleaning. + void Clear() { allParamValues.clear(); minParamValues.clear(); maxParamValues.clear(); minParamValue.Reset(); maxParamValue.Reset(); } + +OBVIOUS_PRIVATE_COPY( MbNormalsMinMaxAnglesResults ) +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Функция поиска минимальных и максимальных углов между нормалями поверхностей кривой пересечения. + \en The function of finding the minimum and maximum angles between surfaces normals of the intersection curve. \~ + \details \ru Функция поиска минимальных и максимальных углов между нормалями поверхностей кривой пересечения. \n + \en The function of finding the minimum and maximum angles between surfaces normals of the intersection curve. \n \~ + \param[in] params - \ru Входные параметры. + \en Input parameters. \~ + \param[out] results - \ru Выходные параметры. + \en Output parameters. \~ + \warning \ru В разработке. + \en Under development. \~ + \ingroup Algorithms_3D +*/ // --- +MATH_FUNC( bool ) SurfacesNormalsMinMaxAngles( const MbNormalsMinMaxAnglesParams & params, + MbNormalsMinMaxAnglesResults & results ); + + #endif // __ACTION_CURVATURE_ANALYSIS_H diff --git a/C3d/Include/action_curve.h b/C3d/Include/action_curve.h index 3976d69..605bfd1 100644 --- a/C3d/Include/action_curve.h +++ b/C3d/Include/action_curve.h @@ -143,7 +143,6 @@ MATH_FUNC (MbResultType) Segment( const MbCartPoint & point1, MbCurve *& result ); - //------------------------------------------------------------------------------ /** \brief \ru Создать эллипс (окружность) или его дугу указанным способом. \en Create an ellipse (circle) or an elliptical (circular) arc in the specified way. \~ @@ -170,7 +169,6 @@ MATH_FUNC (MbResultType) Segment( const MbCartPoint & point1, \ingroup Curve_Modeling */ //--- - MATH_FUNC( MbResultType ) Arc( MbeArcCreateWay createWay, const MbCartPoint & center, const c3d::ParamPointsVector & points, @@ -183,10 +181,13 @@ MATH_FUNC( MbResultType ) Arc( MbeArcCreateWay createWay, //------------------------------------------------------------------------------ /**\attention \ru Функция устарела. Вместо неё применять #Arc. \en The function is deprecated. Use #Arc instead. \~ + \deprecated \ru Метод устарел. + \en The method is deprecated. \~ \ingroup Curve_Modeling */ // 2018 //--- +DEPRECATE_DECLARE MATH_FUNC( MbResultType ) Arc( const MbCartPoint & centre, const SArray & points, bool curveClosed, @@ -407,14 +408,16 @@ MATH_FUNC (MbResultType) CreateContour( MbCurve & curve, \en Create a copy of a curve. \~ \details \ru Создать копию кривой с заменой некоторых кривых. \n \en Create a copy of a curve with substitution of some curves. \n \~ - \param[in] curve - \ru Исходная кривая. - \en The initial curve. \~ + \param[in] curve - \ru Исходная кривая. + \en The initial curve. \~ + \param[in] version - \ru Версия исполнения. + \en The version. \~ \return \ru Возвращает модифицированную копию кривой, если получилось ее создать. \en Returns a modified copy of the curve if it has been successfully created. \~ \ingroup Curve_Modeling */ // --- -MATH_FUNC (MbCurve *) DuplicateCurve( const MbCurve & curve ); +MATH_FUNC (MbCurve *) DuplicateCurve( const MbCurve & curve, VERSION version = Math::DefaultMathVersion() ); //------------------------------------------------------------------------------ @@ -430,6 +433,34 @@ MATH_FUNC (MbCurve *) DuplicateCurve( const MbCurve & curve ); \en The flag determines whether segments can be replaced or merged. \~ \param[in] names - \ru Именователь, синхронизированный с контуром. \en An object defining the names synchronized with contour. \~ + \deprecated \ru Метод устарел. + \en The method is deprecated. \~ + \return \ru Возвращает модифицированнную копию контура, если получилось его создать. + \en Returns a modified copy of the contour if it has been successfully created. \~ + \ingroup Curve_Modeling +*/ +// --- +DEPRECATE_DECLARE +MATH_FUNC (MbContour *) DuplicateContour( const MbContour & cntr, + bool modifySegments, + MbSNameMaker * names = c3d_null ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать копию контура. + \en Create a copy of a contour. \~ + \details \ru Создать копию контура с заменой некоторых кривых и его модификацией по флагу. + Модификация - слияние подобных кривых и удаление вырожденных. \n + \en Create a copy of a contour with substitution of some curves and its modification according to the flag. + Modification is a merging of similar curves and deleting of degenerate ones. \n \~ + \param[in] cntr - \ru Исходный контур. + \en The initial contour. \~ + \param[in] modifySegments - \ru Флаг разрешения замены и слияния сегментов. + \en The flag determines whether segments can be replaced or merged. \~ + \param[in] version - \ru Версия исполнения. + \en The version. \~ + \param[in] names - \ru Именователь, синхронизированный с контуром. + \en An object defining the names synchronized with contour. \~ \return \ru Возвращает модифицированнную копию контура, если получилось его создать. \en Returns a modified copy of the contour if it has been successfully created. \~ \ingroup Curve_Modeling @@ -437,6 +468,7 @@ MATH_FUNC (MbCurve *) DuplicateCurve( const MbCurve & curve ); // --- MATH_FUNC (MbContour *) DuplicateContour( const MbContour & cntr, bool modifySegments, + VERSION version, MbSNameMaker * names = c3d_null ); @@ -760,6 +792,31 @@ MATH_FUNC (bool) IsLikeStraightLine( const MbCurve & curve, double eps ); \en The flag determines whether segments can be replaced. \~ \param[in] names - \ru Именователь, синхронизированный с контуром. \en An object defining the names synchronized with contour. \~ + \deprecated \ru Метод устарел. + \en The method is deprecated. \~ + \return \ru Возвращает модифицированнную копию контура, если получилось его создать. + \en Returns a modified copy of the contour if it has been successfully created. \~ + \ingroup Curve_Modeling +*/ +// --- +DEPRECATE_DECLARE +MATH_FUNC( MbContour * ) DeleteDegenerateSegments( const MbContour & cntr, + bool modifySegments, + MbSNameMaker * names = c3d_null ); + +//------------------------------------------------------------------------------ +/** \brief \ru Удалить вырожденные сегменты из контура. + \en Delete degenerate segments from contour. \~ + \details \ru Удалить вырожденные сегменты из контура с заменой некоторых кривых и модификацией по флагу. \n + \en Delete degenerate segments from contour with substitution of some curves and its modification according to the flag. \n \~ + \param[in] cntr - \ru Исходный контур. + \en The initial contour. \~ + \param[in] modifySegments - \ru Флаг разрешения замены сегментов. + \en The flag determines whether segments can be replaced. \~ + \param[in] version - \ru Версия исполнения. + \en The version. \~ + \param[in] names - \ru Именователь, синхронизированный с контуром. + \en An object defining the names synchronized with contour. \~ \return \ru Возвращает модифицированнную копию контура, если получилось его создать. \en Returns a modified copy of the contour if it has been successfully created. \~ \ingroup Curve_Modeling @@ -767,6 +824,7 @@ MATH_FUNC (bool) IsLikeStraightLine( const MbCurve & curve, double eps ); // --- MATH_FUNC( MbContour * ) DeleteDegenerateSegments( const MbContour & cntr, bool modifySegments, + VERSION verison, MbSNameMaker * names = c3d_null ); diff --git a/C3d/Include/action_mesh.h b/C3d/Include/action_mesh.h index f35afad..d141364 100644 --- a/C3d/Include/action_mesh.h +++ b/C3d/Include/action_mesh.h @@ -283,7 +283,7 @@ MATH_FUNC (MbResultType) MeshCutting( MbMesh & mesh, \en The source polygonal object. \~ \param[in] place - \ru Секущая плоскость. \en A cutting plane. \~ - \param[out] polylines - \ru Построенные ломагные контура сечения объекта. + \param[out] polylines - \ru Построенные ломаные контура сечения объекта. \en The resultant contours. \~ \return \ru Возвращает код результата операции. \en Returns operation result code. \~ @@ -295,6 +295,28 @@ MATH_FUNC (MbResultType) MeshSection( const MbMesh & mesh, RPArray & polylines ); + +//------------------------------------------------------------------------------ +/** \brief \ru Построить контур пересечения двух полигональных объектов. + \en Create an intersection contour of two polygon objects. \~ + \details \ru Построить контур пересечения двух полигональных объектов. \n + \en Create an intersection contour of two polygon objects. \n + \param[in] mesh1 - \ru Исходный полигональный объект. + \en The source polygonal object. \~ + \param[in] mesh1 - \ru Исходный полигональный объект. + \en The source polygonal object. \~ + \param[out] polylines - \ru Построенные ломаные контура пересечения полигональных объектов. + \en The result contours. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Polygonal_Objects +*/ +// --- +MATH_FUNC( MbResultType ) MeshMeshIntersection( const MbMesh & mesh1, + const MbMesh & mesh2, + std::vector< SPtr > & polylines ); + + //------------------------------------------------------------------------------ /** \brief \ru Построить триангуляцию по облаку точек на основе алгоритма поворотного шара. \en Build a triangulation by point cloud with Ball Pivoting algorithm. \~ @@ -319,5 +341,4 @@ MATH_FUNC (MbResultType) CalculateBallPivotingGrid( const MbCollection & collect double angle, MbMesh *& result ); - #endif // __ACTION_MESH_H diff --git a/C3d/Include/action_phantom.h b/C3d/Include/action_phantom.h index b5cc68b..176d456 100644 --- a/C3d/Include/action_phantom.h +++ b/C3d/Include/action_phantom.h @@ -317,4 +317,55 @@ MATH_FUNC (MbFunction *) CreateFunction( const MbCurve3D & curve, size_t coordinate ); +//------------------------------------------------------------------------------ +/** \brief \ru Вычисление данных фантома для торцев поверхности переменного сечения. + \en Calculation of the phantom data for the ends of the mutable section surface. \~ + \details \ru Вычисление плоскости сечения, точек направляющих, сторон охватывающего треугольника и вершины на торце поверхности. \n + \en Calculating the section plane, guide points, sides of the enclosing triangle, and apex at the ends of the surface. \n + \param[in] sectionData - \ru Параметры поверхности переменного сечения. + \en The parameters of the mutable section surface. \~ + \param[out] begPlace - \ru XY плоскость локальной системы координат в начале поверхности. + \en The XY plane of the local coordinate system is the plane at the beginning of the surface. \~ + \param[out] begGuideP1 - \ru Точка первой направляющей в начале поверхности. + \en The point of the first guide at the beginning of the surface. \~ + \param[out] begGuideP2 - \ru Точка второй направляющей в начале поверхности. + \en The point of the second guide at the beginning of the surface. \~ + \param[out] begVector1 - \ru Вектор направления от первой направляющей (сторона охватывающего треугольника) в начале поверхности. + \en The direction vector from the first guide (the side of the enclosing triangle) at the beginning of the surface. \~ + \param[out] begVector2 - \ru Вектор направления от второй направляющей (сторона охватывающего треугольника) в начале поверхности. + \en The direction vector from the second guide (the side of the enclosing triangle) at the beginning of the surface. \~ + \param[out] begApex - \ru Точка вершинной кривой в начале поверхности (может быть в бесконечности). + \en The point of the apex curve at the beginning of the surface (maybe in infinity). \~ + \param[out] endPlace - \ru XY плоскость локальной системы координат в конце поверхности. + \en The XY plane of the local coordinate system is the plane at the end of the surface. \~ + \param[out] endGuideP1 - \ru Точка первой направляющей в конце поверхности. + \en The point of the first guide at the end of the surface. \~ + \param[out] endGuideP2 - \ru Точка второй направляющей в конце поверхности. + \en The point of the second guide at the end of the surface. \~ + \param[out] endVector1 - \ru Вектор направления от первой направляющей (сторона охватывающего треугольника) в конце поверхности. + \en The direction vector from the first guide (the side of the enclosing triangle) at the end of the surface. \~ + \param[out] endVector2 - \ru Вектор направления от второй направляющей (сторона охватывающего треугольника) в конце поверхности. + \en The direction vector from the second guide (the side of the enclosing triangle) at the end of the surface. \~ + \param[out] endApex - \ru Точка вершинной кривой в конце поверхности (может быть в бесконечности). + \en The point of the apex curve at the end of the surface (maybe in infinity). \~ + \return \ru Возвращает код результата построения. + \en Returns the creation result code. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (MbResultType) SectionPhantom( const MbSectionData & sectionData, + MbPlacement3D & begPlace, + MbCartPoint3D & begGuideP1, + MbCartPoint3D & begGuideP2, + MbVector3D & begVector1, + MbVector3D & begVector2, + MbCartPoint3D & begApex, + MbPlacement3D & endPlace, + MbCartPoint3D & endGuideP1, + MbCartPoint3D & endGuideP2, + MbVector3D & endVector1, + MbVector3D & endVector2, + MbCartPoint3D & endApex ); + + #endif // __ACTION_PHANTOM_H diff --git a/C3d/Include/action_sheet.h b/C3d/Include/action_sheet.h index d277aee..f0d60a6 100644 --- a/C3d/Include/action_sheet.h +++ b/C3d/Include/action_sheet.h @@ -16,6 +16,7 @@ #include #include #include +#include #include #include @@ -26,6 +27,7 @@ class MbLine3D; class MbSolid; + //------------------------------------------------------------------------------ /** \brief \ru Способ сегментации эскиза. \en The method of contour segmentation. \~ @@ -365,13 +367,47 @@ private: */ // --- class MATH_CLASS MbCloseCornerGapHotPointCalc { +private: + /// \ru Тип ребра замыкания. \en A corner edge type. + enum MbCornerEdgeType { + cet_BendEdge = 0, ///< \ru Торцевое ребро сгиба листового тела. \en Butt edge of sheet solid bend. + cet_RipEdge = 1 ///< \ru Ребро разъема нелистового тела(для операции преобразования в листовое тело). \en Rip edge of non sheet solid (for operation of converting to sheet solid). + }; + +private: + const MbCornerEdgeType edgeType; ///< \ru Тип ребра. \en The type of edge. const MbCurveEdge & curveEdge; ///< \ru Ребро. \en The edge. const MbClosedCornerValues & parameters; ///< \ru Параметры замыкания сгиба. \en The bend closure parameters. + const double thickness; ///< \ru Толщина листового тела. \en The thickness of sheet solid. + const bool sheetSense; ///< \ru Направление придания толщины. \en The sense of thickness of sheet solid. + const VERSION version; ///< \ru Версия математики. \en Math version. public: /// \ru Конструктор. \en Constructor. - MbCloseCornerGapHotPointCalc( const MbCurveEdge & edge, const MbClosedCornerValues & params ) - : curveEdge( edge ), parameters( params ) {} + MbCloseCornerGapHotPointCalc( const MbCurveEdge & edge, + const MbClosedCornerValues & params, + const VERSION mathVersion = Math::DefaultMathVersion() ) + : edgeType ( cet_BendEdge ) + , curveEdge ( edge ) + , parameters( params ) + , thickness ( edge.GetMetricLength() ) + , sheetSense( false ) + , version ( mathVersion ) + {} + /// \ru Конструктор расчетчика хот-точки для операции распознавания в листовое тело. \en Constructor for case of operation of converting to sheet solid. + MbCloseCornerGapHotPointCalc( const bool sense, + const double sheetThickness, + const MbCurveEdge & ripEdge, + const MbClosedCornerValues & params, + const VERSION mathVersion = Math::DefaultMathVersion() ) + : edgeType ( cet_RipEdge ) + , sheetSense( sense ) + , curveEdge ( ripEdge ) + , parameters( params ) + , thickness ( sheetThickness ) + , version ( mathVersion ) + {} + /// \ru Рассчитать положение "хот"-точки. \en Calculate the hot point location. bool CalcHotPoint( MbCartPoint3D & point ) const; @@ -389,6 +425,7 @@ private: const bool begin, MbLine3D & line1, MbLine3D & line2 ); + bool CalcByRipEdge ( MbCartPoint3D & pnt ) const; MbCloseCornerGapHotPointCalc( const MbCloseCornerGapHotPointCalc & ); // \ru Не реализовано \en Not implemented MbCloseCornerGapHotPointCalc & operator = ( const MbCloseCornerGapHotPointCalc & ); // \ru Не реализовано \en Not implemented @@ -965,8 +1002,8 @@ MATH_FUNC (MbResultType) CreateStampParts( const MbPlacement3D & placement, Штамповка подрезается границами листовой грани, которую пересекает тело.\n \en The stamping is created based on a tool body and a flat sheet face. The stamping is trimmed by the boundary of the sheet face which contains the sketch.\n \~ - \param[in] solid - \ru Исходное листовое тело. - \en The source sheet solid. \~ + \param[in] solid - \ru Листовое тело со штамповкой. + \en The sheet solid with stamp. \~ \param[in] sameShell - \ru Флаг удаления оболочки исходного тела. \en Whether to delete the shell of the source solid. \~ \param[in] targetFace - \ru Грань штамповки. @@ -977,6 +1014,8 @@ MATH_FUNC (MbResultType) CreateStampParts( const MbPlacement3D & placement, \en Whether to delete the shell of the tool solid. \~ \param[in] punch - \ru Является тело-инструмент пуансоном или матрицей. \en Is tool body a punch or a die. \~ + \param[in] removeOriginalStamp - \ru Удалить исходную штамповку. + \en Remove the original stamping. \~ \param[in] pierceFaces - \ru Вскрываемые для вырубки грани инструмента, \en Pierce faces of tool body. \~ \param[in] params - \ru Параметры штамповки. @@ -990,17 +1029,18 @@ MATH_FUNC (MbResultType) CreateStampParts( const MbPlacement3D & placement, \ingroup Sheet_Metal_Modeling */ // --- -MATH_FUNC(MbResultType) CreateStampWithToolSolidParts( MbSolid & solid, - MbeCopyMode sameShell, - const MbFace & targetFace, - MbSolid & toolSolid, - MbeCopyMode sameShellTool, - bool punch, - const RPArray& pierceFaces, - const MbToolStampingValues & params, - const MbSNameMaker & nameMaker, - MbSolid * & partsToAdd, - MbSolid * & partsToSubtract ); +MATH_FUNC(MbResultType) CreateStampWithToolSolidParts( MbSolid & solid, + MbeCopyMode sameShell, + const MbFace & targetFace, + MbSolid & toolSolid, + MbeCopyMode sameShellTool, + bool punch, + bool removeOriginalStamp, + const RPArray & pierceFaces, + const MbToolStampingValues & params, + const MbSNameMaker & nameMaker, + MbSolid * & partsToAdd, + MbSolid * & partsToSubtract ); //------------------------------------------------------------------------------ @@ -1219,7 +1259,7 @@ MATH_FUNC (MbResultType) CreateBeadParts( const MbFace * face, //------------------------------------------------------------------------------ -// устаревшая +/// \deprecated \ru Метод устарел. \en The method is deprecated. // --- DEPRECATE_DECLARE MATH_FUNC (MbResultType) CreateBeadParts( const MbPlacement3D & placement, @@ -1275,7 +1315,7 @@ MATH_FUNC (MbResultType) CreateBead( MbSolid & solid, MbSolid *& result ); -// устаревшая +/// \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE MATH_FUNC (MbResultType) CreateBead( MbSolid & solid, MbeCopyMode sameShell, @@ -1326,7 +1366,7 @@ MATH_FUNC (MbResultType) CreateJalousieParts( const MbFace * fac //------------------------------------------------------------------------------ -// устаревшая +/// \deprecated \ru Метод устарел. \en The method is deprecated. // --- DEPRECATE_DECLARE MATH_FUNC (MbResultType) CreateJalousieParts( const MbPlacement3D & placement, @@ -1933,14 +1973,14 @@ MATH_FUNC (double) CalculateSegmentationParameter( const MbCurve & c //------------------------------------------------------------------------------ -/** \brief \ru Аппроксимировать кривую (дугу) ломаной. - \en Split a curve (an arc) into segments. \~ - \details \ru Аппроксимировать кривую (дугу) ломаной.\n - \en Split a curve (an arc) into segments.\n \~ - \param[in] contour - \ru Кривая (дуга). - \en Curve (arc).\~ - \param[in] segmNumber - \ru Количество сегментов аппроксимации. - \en Number of segments after splitting.\~ +/** \brief \ru Аппроксимировать дуги контура ломаной. + \en Split every arc of the contour into segments. \~ + \details \ru Аппроксимировать дуги контура ломаной.\n + \en Split every arc of the contour into segments.\n \~ + \param[in] contour - \ru Кривая или контур. + \en A curve or a contour.\~ + \param[in] segmNumber - \ru Количество сегментов аппроксимации каждой дуги контура. + \en Number of segments for splitting every arc in the contour.\~ \param[out] resultContour - \ru Аппроксимированный отрезками контур. \en Segmented contour. \~ \result \ru - Код результата операции. @@ -1949,7 +1989,7 @@ MATH_FUNC (double) CalculateSegmentationParameter( const MbCurve & c */ // --- MATH_FUNC (MbResultType) SplitContourIntoSegments( const MbCurve & curve, - const size_t segmNumb, + const size_t segmNumber, MbContour *& resultContour ); @@ -2395,9 +2435,9 @@ MATH_FUNC (MbResultType) SimplifyFlatPattern( MbSolid & //------------------------------------------------------------------------------ -/** \brief \ru Удалить из тела результат операции с главным именем mainName. - \en Remove the result of the operation with main name "mainName" from the solid. \~ - \details \ru Операция удаляет грани с главным именем mainName и потом заделывает образовавшиеся дыры.\n +/** \brief \ru Удалить из тела результат операции с именем removeName . + \en Remove the result operation with name "removeName". \~ + \details \ru Операция удаляет грани с главным именем removeName и потом заделывает образовавшиеся дыры.\n \en The operation deletes the faces that have main name equal to "mainName" and then closes up the holes that remain after the first stage of the operation.\n \~ \param[in] solid - \ru Исходное тело. \en The source solid. \~ @@ -2405,6 +2445,8 @@ MATH_FUNC (MbResultType) SimplifyFlatPattern( MbSolid & \en Whether to delete the shell of the source solid. \~ \param[in] removeName - \ru Главное имя удаляемой операции. \en Main name of the operation to delete. \~ + \param[in] opType - \ru Тип листовой операции. + \en Type of sheet metal operations. \~ \param[in] nameMaker - \ru Именователь. \en An object for naming the new objects. \~ \param[out] result - \ru Результирующее тело. @@ -2414,6 +2456,16 @@ MATH_FUNC (MbResultType) SimplifyFlatPattern( MbSolid & \ingroup Sheet_Metal_Modeling */ // --- +MATH_FUNC (MbResultType) RemoveOperationResult( MbSolid & solid, + const MbeCopyMode sameShell, + const SimpleName removeName, + MbeSheetOperationName opType, + const MbSNameMaker & nameMaker, + MbSolid *& result ); + + +/// \deprecated \ru Метод устарел. \en The method is deprecated. +DEPRECATE_DECLARE MATH_FUNC (MbResultType) RemoveOperationResult( MbSolid & solid, const MbeCopyMode sameShell, const SimpleName removeName, @@ -2421,7 +2473,6 @@ MATH_FUNC (MbResultType) RemoveOperationResult( MbSolid & solid, MbSolid *& result ); - //------------------------------------------------------------------------------ /** \brief \ru Преобразовать тело в листовой металл. \en Construct sheet metal solid based on an arbitary solid. \~ diff --git a/C3d/Include/action_shell.h b/C3d/Include/action_shell.h index 524385f..a400ea2 100644 --- a/C3d/Include/action_shell.h +++ b/C3d/Include/action_shell.h @@ -682,6 +682,7 @@ MATH_FUNC (MbResultType) CutShellSilhouetteContour( MbSolid & \en Stitch faces of several solids into single solid. \~ \details \ru Сшить стыкующиеся друг с другом грани нескольких тел в одно тело. Ориентация граней может быть изменена. \n \en Stitch faces of several solids with coincident edges into single solid. The faces orientation can be changed. \n \~ + \deprecated \ru Метод устарел. \en The method is deprecated. \~ \param[in] initialSolids - \ru Множество тел для сшивки. \en An array of solids for stitching. \~ \param[in] operNames - \ru Именователь операции. diff --git a/C3d/Include/action_solid.h b/C3d/Include/action_solid.h index 99e2a4a..efb10aa 100644 --- a/C3d/Include/action_solid.h +++ b/C3d/Include/action_solid.h @@ -205,6 +205,31 @@ MATH_FUNC (MbResultType) GridSolid( const MbGrid & grid, IProgressIndicator * prog = c3d_null ); +//------------------------------------------------------------------------------ +/** \brief \ru Создать тело на основе триангуляции. + \en Create a solid on the basis of a triangulation. \~ + \details \ru Создать тело #MbSolid на основе триангуляции #MbGrid. \n + \en Create a solid #MbSolid on the basis of a triangulation #MbGrid. \n \~ + \param[in] grid - \ru Полигональная модель. + \en The polygonal geometric object. \~ + \param[in] params - \ru Параметры операции. + \en Operation parameters. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Построенное тело. + \en The resultant solid. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) GridSolid( const MbGrid & grid, + const GridsToShellValues & params, + const MbSNameMaker & names, + MbSolid *& result, + IProgressIndicator * prog = c3d_null ); + + //------------------------------------------------------------------------------ /** \brief \ru Создать тело на основе коллекции элементов. \en Create a solid on the basis of elements. \~ @@ -1246,7 +1271,8 @@ MATH_FUNC (MbResultType) SolidCutting( MbSolid & solid, /** \brief \ru Разрезать тело поверхностью. \en Cut a solid off by a surface. \~ \details \ru Разрезать тело поверхностью с построением всех отрезанных частей. \n - \en Cut a solid off by a surface, keep all parts of the solid. \n + \en Cut a solid off by a surface, keep all parts of the solid. \n \~ + \deprecated \ru Метод устарел. \en The method is deprecated. \~ \param[in] solid - \ru Исходное тело. \en The source solid. \~ \param[in] sameShell - \ru Режим копирования исходного тела. При sameShell != cm_Copy построенные тела нельзя перемещать относительно друг друга. @@ -1280,7 +1306,8 @@ MATH_FUNC (MbResultType) SolidCutting( MbSolid & solid, /** \brief \ru Разрезать тело выдавленным плоским контуром. \en Cut a solid off with an extruded planar contour. \~ \details \ru Разрезать тело оболочкой, полученной выдавливанием плоского контура, с построением всех отрезанных частей. \n - \en Cut a solid by a shell of planar contour extrusion, keep all parts of the solid. \n + \en Cut a solid by a shell of planar contour extrusion, keep all parts of the solid. \n \~ + \deprecated \ru Метод устарел. \en The method is deprecated. \~ \param[in] solid - \ru Исходное тело. \en The source solid. \~ \param[in] sameShell - \ru Режим копирования исходного тела. При sameShell != cm_Copy построенные тела нельзя перемещать относительно друг друга. diff --git a/C3d/Include/action_surface.h b/C3d/Include/action_surface.h index 16a41f1..e7b8249 100644 --- a/C3d/Include/action_surface.h +++ b/C3d/Include/action_surface.h @@ -16,18 +16,16 @@ #include #include -#include +#include +#include #include #include class MATH_CLASS MbCurve; class MATH_CLASS MbCurve3D; -class MATH_CLASS MbSurface; -class MATH_CLASS MbFace; class MATH_CLASS MbSolid; class MATH_CLASS MbSurfaceCurve; -class MATH_CLASS MbCurveEdge; class MATH_CLASS MbFunction; class MATH_CLASS MbGrid; class MATH_CLASS MbRegion; @@ -66,8 +64,8 @@ class MATH_CLASS MbRegion; MATH_FUNC (MbResultType) ElementarySurface( const MbCartPoint3D & point0, const MbCartPoint3D & point1, const MbCartPoint3D & point2, - MbeSpaceType surfaceType, - MbSurface *& result ); + MbeSpaceType surfaceType, + MbSurface *& result ); //------------------------------------------------------------------------------ @@ -102,9 +100,11 @@ MATH_FUNC (MbResultType) SplineSurface( const MbCartPoint3D & pUMinVMin, const MbCartPoint3D & pUMaxVMin, const MbCartPoint3D & pUMaxVMax, const MbCartPoint3D & pUMinVMax, - size_t uCount, size_t vCount, - size_t uDegree, size_t vDegree, - MbSurface *& result ); + size_t uCount, + size_t vCount, + size_t uDegree, + size_t vDegree, + MbSurface *& result ); //------------------------------------------------------------------------------ @@ -146,11 +146,16 @@ MATH_FUNC (MbResultType) SplineSurface( const MbCartPoint3D & pUMinVMin, */ // --- MATH_FUNC (MbResultType) SplineSurface( const SArray & pointList, - const SArray & weightList, - size_t uCount, size_t vCount, - size_t uDegree, const SArray & uKnotList, bool uClosed, - size_t vDegree, const SArray & vKnotList, bool vClosed, - MbSurface *& result ); + const SArray & weightList, + size_t uCount, + size_t vCount, + size_t uDegree, + const SArray & uKnotList, + bool uClosed, + size_t vDegree, + const SArray & vKnotList, + bool vClosed, + MbSurface *& result ); //------------------------------------------------------------------------------ @@ -171,9 +176,9 @@ MATH_FUNC (MbResultType) SplineSurface( const SArray & pointList, \ingroup Surface_Modeling */ // --- -MATH_FUNC (MbResultType) ExtrusionSurface( MbCurve3D & curve, +MATH_FUNC (MbResultType) ExtrusionSurface( const MbCurve3D & curve, const MbVector3D & direction, - bool simplify, + bool simplify, MbSurface *& result ); @@ -199,12 +204,12 @@ MATH_FUNC (MbResultType) ExtrusionSurface( MbCurve3D & curve, \ingroup Surface_Modeling */ // --- -MATH_FUNC (MbResultType) RevolutionSurface( MbCurve3D & curve, +MATH_FUNC (MbResultType) RevolutionSurface( const MbCurve3D & curve, const MbCartPoint3D & origin, - const MbVector3D & axis, - double angle, - bool simplify, - MbSurface *& result ); + const MbVector3D & axis, + double angle, + bool simplify, + MbSurface *& result ); //------------------------------------------------------------------------------ @@ -223,9 +228,10 @@ MATH_FUNC (MbResultType) RevolutionSurface( MbCurve3D & curve, \ingroup Surface_Modeling */ // --- -MATH_FUNC (MbResultType) ExpansionSurface( MbCurve3D & curve, MbCurve3D & spine, - MbCurve3D * curve1, - MbSurface *& result ); +MATH_FUNC (MbResultType) ExpansionSurface( const MbCurve3D & curve, + const MbCurve3D & spine, + const MbCurve3D * curve1, + MbSurface *& result ); //------------------------------------------------------------------------------ @@ -325,9 +331,9 @@ MATH_FUNC (MbResultType) SectorSurface( const MbCurve3D & curve, \ingroup Surface_Modeling */ // --- -MATH_FUNC (MbResultType) RuledSurface( MbCurve3D & curve1, - MbCurve3D & curve2, - bool simplify, +MATH_FUNC (MbResultType) RuledSurface( MbCurve3D & curve1, + MbCurve3D & curve2, + bool simplify, MbSurface *& result ); @@ -349,9 +355,9 @@ MATH_FUNC (MbResultType) RuledSurface( MbCurve3D & curve1, \ingroup Surface_Modeling */ // --- -MATH_FUNC (MbResultType) CornerSurface( MbCurve3D & curve1, - MbCurve3D & curve2, - MbCurve3D & curve3, +MATH_FUNC (MbResultType) CornerSurface( MbCurve3D & curve1, + MbCurve3D & curve2, + MbCurve3D & curve3, MbSurface *& result ); @@ -375,10 +381,10 @@ MATH_FUNC (MbResultType) CornerSurface( MbCurve3D & curve1, \ingroup Surface_Modeling */ // --- -MATH_FUNC (MbResultType) CoverSurface( MbCurve3D & curve1, - MbCurve3D & curve2, - MbCurve3D & curve3, - MbCurve3D & curve4, +MATH_FUNC (MbResultType) CoverSurface( MbCurve3D & curve1, + MbCurve3D & curve2, + MbCurve3D & curve3, + MbCurve3D & curve4, MbSurface *& result ); @@ -406,9 +412,11 @@ MATH_FUNC (MbResultType) CoverSurface( MbCurve3D & curve1, \ingroup Surface_Modeling */ // --- -MATH_FUNC (MbResultType) LoftedSurface( const RPArray & curveList, bool closed, - const MbVector3D & begDirection, const MbVector3D & endDirection, - MbSurface *& result ); +MATH_FUNC (MbResultType) LoftedSurface( const RPArray & curveList, + bool closed, + const MbVector3D & begDirection, + const MbVector3D & endDirection, + MbSurface *& result ); //------------------------------------------------------------------------------ @@ -428,9 +436,9 @@ MATH_FUNC (MbResultType) LoftedSurface( const RPArray & curveList, bo */ // --- MATH_FUNC (MbResultType) LoftedSurface( const RPArray & curveList, - MbCurve3D & spine, - MbSurface *& result, - bool isSimToEvol = true ); + MbCurve3D & spine, + MbSurface *& result, + bool isSimToEvol = true ); //------------------------------------------------------------------------------ @@ -451,7 +459,7 @@ MATH_FUNC (MbResultType) LoftedSurface( const RPArray & curveList, // --- MATH_FUNC (MbResultType) MeshSurface( const RPArray & uCurveList, const RPArray & vCurveList, - MbSurface *& result ); + MbSurface *& result ); //------------------------------------------------------------------------------ @@ -470,9 +478,9 @@ MATH_FUNC (MbResultType) MeshSurface( const RPArray & uCurveList, \ingroup Surface_Modeling */ // --- -MATH_FUNC (MbResultType) OffsetSurface( MbSurface & surface, - double distance, - MbSurface *& result ); +MATH_FUNC (MbResultType) OffsetSurface( const MbSurface & surface, + double distance, + MbSurface *& result ); //------------------------------------------------------------------------------ @@ -499,13 +507,13 @@ MATH_FUNC (MbResultType) OffsetSurface( MbSurface & surface, \ingroup Surface_Modeling */ // --- -MATH_FUNC (MbResultType) OffsetSurface( MbSurface & surface, - double offsetUminVmin, - double offsetUmaxVmin, - double offsetUminVmax, - double offsetUmaxVmax, - MbeOffsetType type, - MbSurface *& result ); +MATH_FUNC (MbResultType) OffsetSurface( const MbSurface & surface, + double offsetUminVmin, + double offsetUmaxVmin, + double offsetUminVmax, + double offsetUmaxVmax, + MbeOffsetType type, + MbSurface *& result ); //------------------------------------------------------------------------------ @@ -562,11 +570,13 @@ MATH_FUNC (MbResultType) ExtendedSurface( MbSurface & surface, \ingroup Surface_Modeling */ // --- -MATH_FUNC (MbResultType) DeformedSurface( MbSurface & surface, - size_t uCount, size_t vCount, - size_t uDegree, size_t vDegree, - double dist, - MbSurface *& result ); +MATH_FUNC (MbResultType) DeformedSurface( const MbSurface & surface, + size_t uCount, + size_t vCount, + size_t uDegree, + size_t vDegree, + double dist, + MbSurface *& result ); //------------------------------------------------------------------------------ @@ -587,9 +597,9 @@ MATH_FUNC (MbResultType) DeformedSurface( MbSurface & surface, \ingroup Surface_Modeling */ // --- -MATH_FUNC (MbResultType) BoundedSurface( MbSurface & surface, +MATH_FUNC (MbResultType) BoundedSurface( MbSurface & surface, const RPArray & boundList, - MbSurface *& result ); + MbSurface *& result ); //------------------------------------------------------------------------------ /** \brief \ru Создать поверхность с заданной границей. @@ -608,8 +618,8 @@ MATH_FUNC (MbResultType) BoundedSurface( MbSurface & surface, */ // --- MATH_FUNC (MbResultType) BoundedSurface( const MbPlacement3D & place, - const MbRegion & region, - MbSurface *& result ); + const MbRegion & region, + MbSurface *& result ); //------------------------------------------------------------------------------ @@ -630,8 +640,8 @@ MATH_FUNC (MbResultType) BoundedSurface( const MbPlacement3D & place, \ingroup Surface_Modeling */ // --- -MATH_FUNC (MbResultType) NurbsSurface( const MbSurface & surf, - VERSION version, +MATH_FUNC (MbResultType) NurbsSurface( const MbSurface & surf, + VERSION version, MbSurface *& result ); @@ -649,7 +659,7 @@ MATH_FUNC (MbResultType) NurbsSurface( const MbSurface & surf, \ingroup Surface_Modeling */ // --- -MATH_FUNC (MbResultType) SimplexSplineSurface( SArray & pList, MbSurface *& resSurface ); +MATH_FUNC (MbResultType) SimplexSplineSurface( const SArray & pList, MbSurface *& resSurface ); //------------------------------------------------------------------------------ @@ -672,8 +682,11 @@ MATH_FUNC (MbResultType) SimplexSplineSurface( SArray & pList, Mb \ingroup Surface_Modeling */ // --- -MATH_FUNC (MbResultType) TriBezierSurface( ptrdiff_t k, MbCartPoint3D & p1, MbCartPoint3D & p2, MbCartPoint3D & p3, - MbSurface *& resSurface ); +MATH_FUNC (MbResultType) TriBezierSurface( ptrdiff_t k, + const MbCartPoint3D & p1, + const MbCartPoint3D & p2, + const MbCartPoint3D & p3, + MbSurface *& resSurface ); //------------------------------------------------------------------------------ @@ -700,8 +713,9 @@ MATH_FUNC (MbResultType) TriSplineSurface( const MbCartPoint3D & p0, const MbCartPoint3D & p1, const MbCartPoint3D & p2, const MbCartPoint3D & p3, - ptrdiff_t d, ptrdiff_t count, - MbSurface *& resSurface ); + ptrdiff_t d, + ptrdiff_t count, + MbSurface *& resSurface ); //------------------------------------------------------------------------------ @@ -722,7 +736,7 @@ MATH_FUNC (MbResultType) TriSplineSurface( const MbCartPoint3D & p0, \ingroup Algorithms_3D */ // --- -MATH_FUNC (bool) GetLineSegmentNURBSSurface( MbSurface & surf, RPArray & segments ); +MATH_FUNC (bool) GetLineSegmentNURBSSurface( const MbSurface & surf, RPArray & segments ); //------------------------------------------------------------------------------ @@ -741,7 +755,7 @@ MATH_FUNC (bool) GetLineSegmentNURBSSurface( MbSurface & surf, RPArray & edges, - std::vector & result ); +MATH_FUNC (MbResultType) CreateSplinePatch( const c3d::ConstEdgesVector & edges, + c3d::SurfacesVector & result ); #endif // __ACTION_SURFACE_H diff --git a/C3d/Include/action_surface_curve.h b/C3d/Include/action_surface_curve.h index 7ad3f83..a5536b8 100644 --- a/C3d/Include/action_surface_curve.h +++ b/C3d/Include/action_surface_curve.h @@ -113,6 +113,7 @@ MATH_FUNC (MbResultType) OffsetPlaneCurve( const MbCurve3D & curve, \en Create an offset curve in space. \~ \details \ru Создать эквидистантную кривую в пространстве по трехмерной кривой и вектору направления. \n \en Create an offset curve in space from a three-dimensional curve and a direction vector. \n \~ + \deprecated \ru Метод устарел. \en The method is deprecated. \~ \param[in] initCurve - \ru Пространственная кривая, к которой строится эквидистантная. \en A space curve for which to construct the offset curve. \~ \param[in] offsetVect - \ru Вектор, задающий смещение в точке кривой. @@ -171,6 +172,7 @@ MATH_FUNC (MbResultType) OffsetCurve( const MbCurve3D & initCur \en Create an offset curve on a surface. \~ \details \ru Создать эквидистантную кривую на поверхности по поверхностной кривой и значению смещения. \n \en Create an offset curve on a surface from a curve on the surface and a shift value. \n \~ + \deprecated \ru Метод устарел. \en The method is deprecated. \~ \param[in] curve - \ru Кривая на поверхности грани face. \en A curve on face 'face' surface. \~ \param[in] face - \ru Грань, на которой строится эквидистанта. @@ -251,6 +253,39 @@ MATH_FUNC (MbResultType) CurveProjection( const MbSurface & surface, VERSION version = Math::DefaultMathVersion() ); +//------------------------------------------------------------------------------ +/** \brief \ru Создать проекцию кривой на поверхность. + \en Create a curve projection onto the surface. \~ + \details \ru Создать проекцию кривой curve на поверхность surface (направление проецирования direction может быть c3d_null). \n + \en Create the projection of a curve onto surface 'surface' (the projection direction 'direction' can be c3d_null). \n \~ + \param[in] surface - \ru Поверхность для проецирования. + \en The surface to project onto. \~ + \param[in] curve - \ru Проецируемая кривая. + \en The curve to project. \~ + \param[in] direction - \ru Направление проецирования (если не указано то проецирование по нормали). + \en The projection direction (if not specified, the projection along the normal). \~ + \param[in] createExact - \ru Создавать проекционную кривую при необходимости. + \en Create a projection curve if necessary. \~ + \param[in] truncateByBounds - \ru Усекать границами поверхности. + \en Truncate by the surface bounds. \~ + \param[in] version - \ru Версия исполнения. + \en The version. \~ + \param[out] result - \ru Множество кривых на поверхности. + \en An array of curves on the surface. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC (MbResultType) CurveProjection( const MbSurface & surface, + const MbCurve3D & curve, + MbVector3D * direction, + bool createExact, + bool truncateByBounds, + c3d::SpaceCurvesSPtrVector & result, + VERSION version = Math::DefaultMathVersion() ); + + //------------------------------------------------------------------------------ /** \brief \ru Создать пространственную кривую по двум плоским проекциям. \en Create a space curve from two planar projections. \~ @@ -495,6 +530,8 @@ MATH_FUNC (MbResultType) SilhouetteCurve( const MbFace & face, \en Create the intersection curves of two surfaces. \~ \details \ru Создать кривые пересечения двух поверхностей. Результат - массив кривых пересечения поверхностей. \n \en Create the intersection curves of two surfaces. The result is an array of intersection curves of surfaces. \n \~ + \deprecated \ru Метод устарел. Вместо него используйте аналогичную функцию с параметрами #MbIntCurveParams. + \en The method is deprecated. Instead use the function IntersectionCurve with parameters #MbIntCurveParams. \~ \param[in] surface1 - \ru Первая поверхность. \en The first surface. \~ \param[in] surface2 - \ru Вторая поверхность. @@ -514,36 +551,92 @@ MATH_FUNC (MbResultType) SilhouetteCurve( const MbFace & face, But the surface bounds in faces are exact since they are stored in the form of intersection curves, not in the form of two-dimensional curves. \n \~ \ingroup Curve3D_Modeling -*/ -// --- +*/ // --- +DEPRECATE_DECLARE MATH_FUNC (MbResultType) IntersectionCurve( const MbSurface & surface1, const MbSurface & surface2, const MbSNameMaker & snMaker, MbWireFrame *& result ); +//------------------------------------------------------------------------------ +/** \brief \ru Создать кривые пересечения двух поверхностей. + \en Create the intersection curves of two surfaces. \~ + \details \ru Создать кривые пересечения двух поверхностей. Результат - массив кривых пересечения поверхностей. \n + \en Create the intersection curves of two surfaces. The result is an array of intersection curves of surfaces. \n \~ + \param[in] surface1 - \ru Первая поверхность. + \en The first surface. \~ + \param[in] surface2 - \ru Вторая поверхность. + \en The second surface. \~ + \param[in] params - \ru Параметры. + \en Parameters. \~ + \param[out] result - \ru Каркас с построенными кривыми. + \en The frame with the constructed curves. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \warning \ru Лучше использовать IntersectionCurve на гранях, т.к. границы поверхностей могут бы неточные, \n + что приведет к неточному положению концов кривых пересечения в результате операции. \n + В гранях же границы поверхности точные, т.к. хранятся в виде кривых пересечения, + а не виде двумерных кривых. \n + \en It is better to use IntersectionCurve on faces since the surfaces bounds can be inexact, \n + and it will result in inexact position of intersection curves ends. \n + But the surface bounds in faces are exact since they are stored in the form of intersection curves, + not in the form of two-dimensional curves. \n \~ + \ingroup Curve3D_Modeling +*/ // --- +MATH_FUNC (MbResultType) IntersectionCurve( const MbSurface & surface1, + const MbSurface & surface2, + const MbIntCurveParams & params, + MbWireFrame *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать кривые пересечения двух граней. + \en Create intersection curves of two faces. \~ + \details \ru Создать кривые пересечения двух граней. Результат - массив кривых пересечения поверхностей. \n + \en Create intersection curves of two faces. The result is an array of intersection curves of surfaces. \n \~ + \deprecated \ru Метод устарел. Вместо него используйте аналогичную функцию с параметрами #MbIntCurveParams. + \en The method is deprecated. Instead use the function IntersectionCurve with parameters #MbIntCurveParams. \~ + \param[in] face1 - \ru Первая грань оболочки. + \en The first face of the shell. \~ + \param[in] face2 - \ru Вторая грани оболочки. + \en The second face of the shell. \~ + \param[in] snMaker - \ru Именователь кривых каркаса. + \en An object defining the frame curves names. \~ + \param[out] result - \ru Каркас с построенными кривыми. + \en The frame with the constructed curves. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling +*/ // --- +DEPRECATE_DECLARE +MATH_FUNC (MbResultType) IntersectionCurve( MbFace & face1, + MbFace & face2, + const MbSNameMaker & snMaker, + MbWireFrame *& result ); + + //------------------------------------------------------------------------------ /** \brief \ru Создать кривые пересечения двух граней. \en Create intersection curves of two faces. \~ \details \ru Создать кривые пересечения двух граней. Результат - массив кривых пересечения поверхностей. \n \en Create intersection curves of two faces. The result is an array of intersection curves of surfaces. \n \~ - \param[in] face1 - \ru Первая грань оболочки. - \en The first face of the shell. \~ - \param[in] face2 - \ru Вторая грани оболочки. - \en The second face of the shell. \~ - \param[in] snMaker - \ru Именователь кривых каркаса. - \en An object defining the frame curves names. \~ + \param[in] face1 - \ru Первая грань оболочки. + \en The first face of the shell. \~ + \param[in] face2 - \ru Вторая грани оболочки. + \en The second face of the shell. \~ + \param[in] params - \ru Параметры. + \en Parameters. \~ \param[out] result - \ru Каркас с построенными кривыми. \en The frame with the constructed curves. \~ \return \ru Возвращает код результата операции. \en Returns operation result code. \~ \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC (MbResultType) IntersectionCurve( MbFace & face1, - MbFace & face2, - const MbSNameMaker & snMaker, - MbWireFrame *& result ); +*/ // --- +MATH_FUNC (MbResultType) IntersectionCurve( MbFace & face1, + MbFace & face2, + const MbIntCurveParams & params, + MbWireFrame *& result ); //------------------------------------------------------------------------------ @@ -551,27 +644,31 @@ MATH_FUNC (MbResultType) IntersectionCurve( MbFace & face1, \en Create intersection curves of two shells faces. \~ \details \ru Создать кривые пересечения граней двух оболочек. Результат - массив кривых пересечения поверхностей. \n \en Create intersection curves of two shells faces. The result is an array of intersection curves of surfaces. \n \~ - \param[in] solid1 - \ru Первая оболочка. - \en The first shell. \~ + \deprecated \ru Метод устарел. Вместо него используйте аналогичную функцию с параметрами #MbIntCurveParams. + \en The method is deprecated. Instead use the function IntersectionCurve with parameters #MbIntCurveParams. \~ + \param[in] solid1 - \ru Первая оболочка. + \en The first shell. \~ \param[in] faceIndices1 - \ru Номера граней в первой оболочке. \en The numbers of faces in the first shell. \~ - \param[in] solid2 - \ru Вторая оболочка. - \en The second shell. \~ + \param[in] solid2 - \ru Вторая оболочка. + \en The second shell. \~ \param[in] faceIndices2 - \ru Номера граней во второй оболочке. \en The numbers of faces in the second shell. \~ - \param[in] snMaker - \ru Именователь кривых каркаса. - \en An object defining the frame curves names. \~ - \param[out] result - \ru Каркас с построенными кривыми. - \en The frame with the constructed curves. \~ + \param[in] snMaker - \ru Именователь кривых каркаса. + \en An object defining the frame curves names. \~ + \param[out] result - \ru Каркас с построенными кривыми. + \en The frame with the constructed curves. \~ \return \ru Возвращает код результата операции. \en Returns operation result code. \~ \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC (MbResultType) IntersectionCurve( const MbSolid & solid1, const SArray & faceIndices1, - const MbSolid & solid2, const SArray & faceIndices2, - const MbSNameMaker & snMaker, - MbWireFrame *& result ); +*/ // --- +DEPRECATE_DECLARE +MATH_FUNC (MbResultType) IntersectionCurve( const MbSolid & solid1, + const SArray & faceIndices1, + const MbSolid & solid2, + const SArray & faceIndices2, + const MbSNameMaker & snMaker, + MbWireFrame *& result ); //------------------------------------------------------------------------------ @@ -579,30 +676,101 @@ MATH_FUNC (MbResultType) IntersectionCurve( const MbSolid & solid1, const SArray \en Create intersection curves of two shells faces. \~ \details \ru Создать кривые пересечения граней двух оболочек. Результат - массив кривых пересечения поверхностей. \n \en Create intersection curves of two shells faces. The result is an array of intersection curves of surfaces. \n \~ - \param[in] solid1 - \ru Первая оболочка. - \en The first shell. \~ + \param[in] solid1 - \ru Первая оболочка. + \en The first shell. \~ \param[in] faceIndices1 - \ru Номера граней в первой оболочке. \en The numbers of faces in the first shell. \~ - \param[in] same1 - \ru Использовать ли тот же журнал построителей первого тела или сделать копию. - \en Flag whether to use the same creators of the first body or make a copy. \~ - \param[in] solid2 - \ru Вторая оболочка. - \en The second shell. \~ + \param[in] solid2 - \ru Вторая оболочка. + \en The second shell. \~ \param[in] faceIndices2 - \ru Номера граней во второй оболочке. \en The numbers of faces in the second shell. \~ - \param[in] same2 - \ru Использовать ли тот же самый журнал построителей второго тела или сделать копию. - \en Flag whether to use the same creators of the second body or make a copy. \~ - \param[in] snMaker - \ru Именователь кривых каркаса. - \en An object defining the frame curves names. \~ - \param[out] result - \ru Каркас с построенными кривыми. - \en The frame with the constructed curves. \~ + \param[in] params - \ru Параметры. + \en Parameters. \~ + \param[out] result - \ru Каркас с построенными кривыми. + \en The frame with the constructed curves. \~ \return \ru Возвращает код результата операции. \en Returns operation result code. \~ \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC (MbResultType) IntersectionCurve( const MbSolid & solid1, const SArray & faceIndices1, const bool same1, - const MbSolid & solid2, const SArray & faceIndices2, const bool same2, - const MbSNameMaker & snMaker, MbWireFrame *& result ); +*/ // --- +MATH_FUNC (MbResultType) IntersectionCurve( const MbSolid & solid1, + const c3d::IndicesVector & faceIndices1, + const MbSolid & solid2, + const c3d::IndicesVector & faceIndices2, + const MbIntCurveParams & params, + MbWireFrame *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать кривые пересечения граней двух оболочек. + \en Create intersection curves of two shells faces. \~ + \details \ru Создать кривые пересечения граней двух оболочек. Результат - массив кривых пересечения поверхностей. \n + \en Create intersection curves of two shells faces. The result is an array of intersection curves of surfaces. \n \~ + \deprecated \ru Метод устарел. Вместо него используйте аналогичную функцию с параметрами #MbIntCurveParams. + \en The method is deprecated. Instead use the function IntersectionCurve with parameters #MbIntCurveParams. \~ + \param[in] solid1 - \ru Первая оболочка. + \en The first shell. \~ + \param[in] faceIndices1 - \ru Номера граней в первой оболочке. + \en The numbers of faces in the first shell. \~ + \param[in] same1 - \ru Использовать ли тот же журнал построителей первого тела или сделать копию. + \en Flag whether to use the same creators of the first body or make a copy. \~ + \param[in] solid2 - \ru Вторая оболочка. + \en The second shell. \~ + \param[in] faceIndices2 - \ru Номера граней во второй оболочке. + \en The numbers of faces in the second shell. \~ + \param[in] same2 - \ru Использовать ли тот же самый журнал построителей второго тела или сделать копию. + \en Flag whether to use the same creators of the second body or make a copy. \~ + \param[in] snMaker - \ru Именователь кривых каркаса. + \en An object defining the frame curves names. \~ + \param[out] result - \ru Каркас с построенными кривыми. + \en The frame with the constructed curves. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling +*/ // --- +DEPRECATE_DECLARE +MATH_FUNC (MbResultType) IntersectionCurve( const MbSolid & solid1, + const SArray & faceIndices1, + const bool same1, + const MbSolid & solid2, + const SArray & faceIndices2, + const bool same2, + const MbSNameMaker & snMaker, + MbWireFrame *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать кривые пересечения граней двух оболочек. + \en Create intersection curves of two shells faces. \~ + \details \ru Создать кривые пересечения граней двух оболочек. Результат - массив кривых пересечения поверхностей. \n + \en Create intersection curves of two shells faces. The result is an array of intersection curves of surfaces. \n \~ + \param[in] solid1 - \ru Первая оболочка. + \en The first shell. \~ + \param[in] faceIndices1 - \ru Номера граней в первой оболочке. + \en The numbers of faces in the first shell. \~ + \param[in] same1 - \ru Использовать ли тот же журнал построителей первого тела или сделать копию. + \en Flag whether to use the same creators of the first body or make a copy. \~ + \param[in] solid2 - \ru Вторая оболочка. + \en The second shell. \~ + \param[in] faceIndices2 - \ru Номера граней во второй оболочке. + \en The numbers of faces in the second shell. \~ + \param[in] same2 - \ru Использовать ли тот же самый журнал построителей второго тела или сделать копию. + \en Flag whether to use the same creators of the second body or make a copy. \~ + \param[in] params - \ru Параметры. + \en Parameters. \~ + \param[out] result - \ru Каркас с построенными кривыми. + \en The frame with the constructed curves. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling +*/ // --- +MATH_FUNC (MbResultType) IntersectionCurve( const MbSolid & solid1, + const c3d::IndicesVector & faceIndices1, + bool same1, + const MbSolid & solid2, + const c3d::IndicesVector & faceIndices2, + bool same2, + const MbIntCurveParams & params, + MbWireFrame *& result ); //------------------------------------------------------------------------------ @@ -639,16 +807,18 @@ MATH_FUNC (MbResultType) IntersectionCurve( const MbSolid & solid1, const SArray \ingroup Curve3D_Modeling */ // --- -MATH_FUNC (MbResultType) IntersectionCurve( const MbSurface & surface1, bool ext1, - const MbCartPoint & uv1beg, - const MbCartPoint & uv1end, - const MbSurface & surface2, bool ext2, - const MbCartPoint & uv2beg, - const MbCartPoint & uv2end, - const MbVector3D & dir, - MbCurve *& result1, - MbCurve *& result2, - MbeCurveBuildType & label ); +MATH_FUNC (MbResultType) IntersectionCurve( const MbSurface & surface1, + bool ext1, + const MbCartPoint & uv1beg, + const MbCartPoint & uv1end, + const MbSurface & surface2, + bool ext2, + const MbCartPoint & uv2beg, + const MbCartPoint & uv2end, + const MbVector3D & dir, + MbCurve *& result1, + MbCurve *& result2, + MbeCurveBuildType & label ); //------------------------------------------------------------------------------ @@ -690,18 +860,20 @@ MATH_FUNC (MbResultType) IntersectionCurve( const MbSurface & surface1, bool ext \ingroup Curve3D_Modeling */ // --- -MATH_FUNC( MbResultType ) IntersectionCurve( const MbSurface & surf1, bool ext1, - const MbCartPoint & uv1beg, - const MbCartPoint & uv1end, - const MbSurface & surf2, bool ext2, - const MbCartPoint & uv2beg, - const MbCartPoint & uv2end, - const MbCurve3D * guideCurve, - bool useRedetermination, - bool checkPoles, - MbCurve *& pCurve1, - MbCurve *& pCurve2, - MbeCurveBuildType & label ); +MATH_FUNC( MbResultType ) IntersectionCurve( const MbSurface & surf1, + bool ext1, + const MbCartPoint & uv1beg, + const MbCartPoint & uv1end, + const MbSurface & surf2, + bool ext2, + const MbCartPoint & uv2beg, + const MbCartPoint & uv2end, + const MbCurve3D * guideCurve, + bool useRedetermination, + bool checkPoles, + MbCurve *& pCurve1, + MbCurve *& pCurve2, + MbeCurveBuildType & label ); //------------------------------------------------------------------------------ @@ -854,9 +1026,11 @@ MATH_FUNC (MbResultType) SurfaceSpline( const MbSurface & su \ingroup Curve3D_Modeling */ //--- -MATH_FUNC (MbResultType) IsoparametricCurve( const MbSurface & surface, - double x, bool isU, const MbRect1D * yRange, - MbCurve3D *& result ); +MATH_FUNC (MbResultType) IsoparametricCurve( const MbSurface & surface, + double x, + bool isU, + const MbRect1D * yRange, + MbCurve3D *& result ); //------------------------------------------------------------------------------ diff --git a/C3d/Include/alg_base.h b/C3d/Include/alg_base.h index 39b329e..4555a73 100644 --- a/C3d/Include/alg_base.h +++ b/C3d/Include/alg_base.h @@ -151,10 +151,10 @@ void AngleToParam( double dir, bool left, double & t ) //------------------------------------------------------------------------------ -/** \brief \ru Вычислить угол между двумя векторами. - \en Calculate the angle between two vectors. \~ - \details \ru Шаблонная функция. Применима для любых векторов. - \en Template function. Applicable for any vectors. \~ +/** \brief \ru Вычислить угол между двумерными векторами. + \en Calculate the angle between two-dimensional vectors. \~ + \details \ru Вычислить угол между двумерными векторами. \n + \en Calculate the angle between two-dimensional vectors. \n \~ \param[in] v1 - \ru Вектор 1. \en The first vector. \~ \param[in] v2 - \ru Вектор 2. diff --git a/C3d/Include/alg_max_distance.h b/C3d/Include/alg_max_distance.h index 8c0dcfb..c5d204b 100644 --- a/C3d/Include/alg_max_distance.h +++ b/C3d/Include/alg_max_distance.h @@ -42,11 +42,11 @@ class MATH_CLASS MbSurface; \return \ru true, если максимальное расстояние было найдено. \en true if the maximal distance has been found. \~ \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (bool) MaxDistance( const MbCartPoint3D & pnt, const MbCurve3D & curv, - double & t, - double & distance ); +*/ // --- +MATH_FUNC (bool) MaxDistance( const MbCartPoint3D & pnt, + const MbCurve3D & curv, + double & t, + double & distance ); //------------------------------------------------------------------------------ @@ -63,11 +63,12 @@ MATH_FUNC (bool) MaxDistance( const MbCartPoint3D & pnt, const MbCurve3D & curv, \return \ru true, если максимальное расстояние было найдено. \en true if the maximal distance has been found. \~ \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (bool) MaxDistance( const MbCurve3D & curv1, const MbCurve3D & curv2, - double & t1, double & t2, - double & distance ); +*/ // --- +MATH_FUNC (bool) MaxDistance( const MbCurve3D & curv1, + const MbCurve3D & curv2, + double & t1, + double & t2, + double & distance ); //------------------------------------------------------------------------------ @@ -86,11 +87,11 @@ MATH_FUNC (bool) MaxDistance( const MbCurve3D & curv1, const MbCurve3D & curv2, \return \ru true, если максимальное расстояние было найдено. \en true if the maximal distance has been found. \~ \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (bool) MaxDistance( const MbCartPoint3D & pnt, const MbSurface & surf, - MbCartPoint & uv, - double & distance ); +*/ // --- +MATH_FUNC (bool) MaxDistance( const MbCartPoint3D & pnt, + const MbSurface & surf, + MbCartPoint & uv, + double & distance ); //------------------------------------------------------------------------------ @@ -111,11 +112,12 @@ MATH_FUNC (bool) MaxDistance( const MbCartPoint3D & pnt, const MbSurface & surf, \return \ru true, если максимальное расстояние было найдено. \en true if the maximal distance has been found. \~ \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (bool) MaxDistance( const MbCurve3D & curv, const MbSurface & surf, - double & t, MbCartPoint & uv, - double & distance ); +*/ // --- +MATH_FUNC (bool) MaxDistance( const MbCurve3D & curv, + const MbSurface & surf, + double & t, + MbCartPoint & uv, + double & distance ); //------------------------------------------------------------------------------ @@ -132,11 +134,12 @@ MATH_FUNC (bool) MaxDistance( const MbCurve3D & curv, const MbSurface & surf, \return \ru true, если максимальное расстояние было найдено. \en true if the maximal distance has been found. \~ \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (bool) MaxDistance( const MbSurface & surf1, const MbSurface & surf2, - MbCartPoint & uv1, MbCartPoint & uv2, - double & distance ); +*/ // --- +MATH_FUNC (bool) MaxDistance( const MbSurface & surf1, + const MbSurface & surf2, + MbCartPoint & uv1, + MbCartPoint & uv2, + double & distance ); //------------------------------------------------------------------------------ @@ -155,11 +158,11 @@ MATH_FUNC (bool) MaxDistance( const MbSurface & surf1, const MbSurface & surf2, \return \ru true, если максимальное расстояние было найдено. \en true if the maximal distance has been found. \~ \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (bool) MaxDistance( const MbAxis3D & axis, const MbCurve3D & curve, - double & param, - double & distance ); +*/ // --- +MATH_FUNC (bool) MaxDistance( const MbAxis3D & axis, + const MbCurve3D & curve, + double & param, + double & distance ); #endif // __ALG_MAX_DISTANCE_H diff --git a/C3d/Include/attr_dencity.h b/C3d/Include/attr_dencity.h index 06efd72..2f4e8ed 100644 --- a/C3d/Include/attr_dencity.h +++ b/C3d/Include/attr_dencity.h @@ -160,4 +160,50 @@ private: IMPL_PERSISTENT_OPS( MbStrains ) +//------------------------------------------------------------------------------ +/** \brief \ru Толщина. + \en Thickness. \~ + \details \ru Толщина. \n + \en Thickness. \n \~ + \ingroup Model_Attributes +*/ +// --- +class MATH_CLASS MbThickness : public MbElementaryAttribute { +protected : + double thickness; ///< \ru Толщина. \en Thickness. + +protected : + /// \ru Конструктор копирования. \en Copy constructor. + MbThickness( const MbThickness & init ); +public : + /// \ru Конструктор по параметрам. \en Constructor by parameters. + MbThickness( double init ); + /// \ru Деструктор. \en Destructor. + virtual ~MbThickness(); + + // \ru Общие функции объекта \en Common functions of object. + + virtual MbeAttributeType AttributeType() const; // \ru Дать подтип атрибута. \en Get subtype of an attribute. + virtual MbAttribute & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual bool IsSame( const MbAttribute &, double accuracy ) const; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. + virtual bool Init( const MbAttribute & ); // \ru Инициализировать данные по присланным. \en Initialize data. + + /// \ru Установить толщину. \en Set a thickness. + void Init( double init ) { thickness = init; } + /// \ru Дать толщину. \en Get a thickness. + double Thickness() const { return thickness; } + + virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. + virtual size_t SetProperties( const MbProperties & ); // \ru Установить свойства объекта. \en Set properties of object. + virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта. \en Get a name of object property. + +private: + void operator = ( const MbThickness & ); // \ru Не реализовано \en Not implemented + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbThickness ) + +}; // MbDencity + +IMPL_PERSISTENT_OPS( MbThickness ) + #endif // __ATTR_DENCITY_H diff --git a/C3d/Include/attr_product.h b/C3d/Include/attr_product.h index 5dad842..51a1213 100644 --- a/C3d/Include/attr_product.h +++ b/C3d/Include/attr_product.h @@ -180,14 +180,15 @@ public : /// \ru Получить роли автора. \en Get person's roles. void GetPersonRoles( std::vector& ) const; - /// \ru Получить роли автора. \en Get person's roles. + /// \ru Получить роли автора. \en Get person's roles. \~ \deprecated \ru Метод устарел. \en The method is deprecated. template< typename T > DEPRECATE_DECLARE void GetRoles( T dest ) const { std::copy( roles.begin(), roles.end(), dest ); } - /// \ru Добавить роли к приёмнику. \en Add person's roles to destination. + /// \ru Добавить роли к приёмнику. \en Add person's roles to destination. \~ \deprecated \ru Метод устарел. \en The method is deprecated. template< typename T > DEPRECATE_DECLARE void AddRolesTo( T dest ) const; /** \brief \ru Задать данные лица. \en Set person's data. \~ + \deprecated \ru Метод устарел. \en The method is deprecated. \~ \param[in] oPersonId - \ru Идентификатор лица. \en Identifier of the person. \~ \param[in] oLast - \ru Фамилия. \en Last name. \~ \param[in] oFirst - \ru Имя. \en First name. \~ @@ -206,6 +207,7 @@ public : /** \brief \ru Получить данные. \en Get data. \~ + \deprecated \ru Метод устарел. \en The method is deprecated. \~ \param[out] oPersonId - \ru Идентификатор лица. \en Identifier of the person. \~ \param[out] oLast - \ru Фамилия. \en Last name. \~ \param[out] oFirst - \ru Имя. \en First name. \~ @@ -223,6 +225,7 @@ public : /** \brief \ru Задать данные лица. \en Set person's data. \~ + \deprecated \ru Метод устарел. \en The method is deprecated. \~ \param[in] oPersonId - \ru Идентификатор лица. \en Identifier of the person. \~ \param[in] oLast - \ru Фамилия. \en Last name. \~ \param[in] oFirst - \ru Имя. \en First name. \~ @@ -242,6 +245,7 @@ public : /** \brief \ru Получить данные. \en Get data. \~ + \deprecated \ru Метод устарел. \en The method is deprecated. \~ \param[out] oPersonId - \ru Идентификатор лица. \en Identifier of the person. \~ \param[out] oLast - \ru Фамилия. \en Last name. \~ \param[out] oFirst - \ru Имя. \en First name. \~ @@ -260,6 +264,7 @@ public : /** \brief \ru Получить данные организации. \en Get organization data. \~ + \deprecated \ru Метод устарел. \en The method is deprecated. \~ \param[out] oOrgId - \ru Идентификатор организации. \en Identifier of the organization. \~ \param[out] oOrgLabel - \ru Название организации. \en Label of the organization. \~ \param[out] oOrgDesc - \ru Описание организации. \en Description of the organization. \~ @@ -269,6 +274,7 @@ public : /** \brief \ru Задать данные организации. \en Set organization's data. \~ + \deprecated \ru Метод устарел. \en The method is deprecated. \~ \param[in] oOrgId - \ru Идентификатор организации. \en Identifier of the organization. \~ \param[in] oOrgLabel - \ru Название организации. \en Label of the organization. \~ \param[in] oOrgDesc - \ru Описание организации. \en Description of the organization. \~ @@ -278,6 +284,7 @@ public : /** \brief \ru Задать данные лица и организации в упрощенной форме. \en Set person's and organization's simplified data. \~ + \deprecated \ru Метод устарел. \en The method is deprecated. \~ \param[in] person - \ru Фамилия автора. \en Author's second name. \~ \param[in] organization - \ru Название организации. \en Label of the organization. \~ */ @@ -337,7 +344,7 @@ public : /// \ru Получить данные. \en Get data. void GetData( c3d::string_t & oId, c3d::string_t & oName, c3d::string_t & oDesc ) const; - /// \ru Получить данные. \en Get data. + /// \ru Получить данные. \en Get data. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE void GetDataStd( std::string & oId, std::string & oName, std::string & oDesc ) const; /// \ru Задать название. \en Set the name of the product. diff --git a/C3d/Include/attribute.h b/C3d/Include/attribute.h index 3f50a18..ac239ed 100644 --- a/C3d/Include/attribute.h +++ b/C3d/Include/attribute.h @@ -70,6 +70,7 @@ enum MbeAttributeType at_Embodiment = 114, ///< \ru Признак исполнения (варианта реализации модели). \en Indication of embodiment (variant of model implementation). at_Elasticity = 115, ///< \ru Механические характеристики: модуль Юнга и коэффициент Пуассана. \en Mechanical properties: Young's modulus and Poisson's ratio. at_Strains = 116, ///< \ru Деформации. \en The strains. + at_Thickness = 117, ///< \ru Толщина оболочки. \en The shell thickness. at_ElementaryLast = 200, ///< \ru Простые атрибуты вставлять перед этим значением. \en Elementary attributes should be inserted before this value. \n // \ru Типы обобщенных атрибутов. \en Types of common attributes. diff --git a/C3d/Include/attribute_container.h b/C3d/Include/attribute_container.h index cc07b16..c451f1a 100644 --- a/C3d/Include/attribute_container.h +++ b/C3d/Include/attribute_container.h @@ -128,7 +128,7 @@ public: /// \ru Выдать атрибуты заданного типа. \en Get attributes of a given type. void GetAttributes( c3d::AttrVector &, MbeAttributeType aType ) const; /// \ru Выдать атрибуты по строке описания. \en Get attributes using sample of description string. - void GetCommonAttributes( c3d::AttrVector &, const c3d::string_t & samplePrompt, MbeAttributeType subType = at_Undefined ) const; + void GetCommonAttributes( c3d::AttrVector &, const c3d::string_t & samplePrompt, MbeAttributeType subType = at_Undefined, bool firstFound = false ) const; /// \ru Выдать строковые атрибуты по строке содержания. \en Get string attributes using sample of contents of the string. void GetStringAttributes( c3d::AttrVector &, const c3d::string_t & sampleContent ) const; diff --git a/C3d/Include/check_geometry.h b/C3d/Include/check_geometry.h index a09bb28..de1557d 100644 --- a/C3d/Include/check_geometry.h +++ b/C3d/Include/check_geometry.h @@ -801,6 +801,7 @@ MATH_FUNC( bool ) RepairEdges( MbFaceShell & shell, bool updateFacesBounds = tru Функция устарела и будет удалена. Замените вызовы на RemoveCommonSurfaceSubstrates. \n \en Find and eliminate common underlying surfaces of a shell faces. \n The function is deprecated and will be removed. Replace calls with RemoveCommonSurfaceSubstrates. \~ + \deprecated \ru Метод устарел. \en The method is deprecated. \~ \param[in] shell - \ru Модифицируемая оболочка. \en A shell to be modified. \~ \return \ru Возвращает true, если была выполнена модификация оболочки. diff --git a/C3d/Include/contour_combine.h b/C3d/Include/contour_combine.h index 8885813..6996ba2 100644 --- a/C3d/Include/contour_combine.h +++ b/C3d/Include/contour_combine.h @@ -38,6 +38,7 @@ enum MbeIntLoopsResult { \en Calculate two curves intersection. \~ \details \ru Найти пересечение областей двух замкнутых кривых. \en Calculate two closed curves' regions intersection. \~ + \deprecated \ru Метод устарел. \en The method is deprecated. \~ \param[in] iCheck - \ru Признак проверки кривых на касание вершин. \en Attribute of check of curves for vertices tangency. \~ \param[in] loop1 - \ru Первая замкнутая кривая. @@ -58,8 +59,8 @@ enum MbeIntLoopsResult { false - exterior is the curve's region. \~ \param[out] intLoops - \ru Массив кривых пересечения. \en Intersection curve array. \~ - \attention \ru Устаревшая функция. - \en An obsolete function. \~ + \deprecated \ru Метод устарел. + \en The method is deprecated. \~ \return \ru Код результата пересечения. \en Intersection result code. \~ \ingroup Algorithms_2D diff --git a/C3d/Include/conv_annotation_item.h b/C3d/Include/conv_annotation_item.h index 98c5565..a537d27 100644 --- a/C3d/Include/conv_annotation_item.h +++ b/C3d/Include/conv_annotation_item.h @@ -193,17 +193,17 @@ enum MbeDefinedDimensionSymbol { \en Type of tip. \~ */ enum MbeDefinedTerminatorSymbol { - dts_BlankedArrow, ///< \ru Незакрашенная стрелка. \en Blank arrow. - dts_BlankedBox, ///< \ru Незакрашенный квадрат. \en Blank square. - dts_BlankedDot, ///< \ru Незакрашенная точка. \en Blank point. - dts_DimensionOrigin, ///< \ru Базовsq объект. \en Base object. - dts_FilledArrow, ///< \ru Закрашенная стрелка. \en Filled arrow. - dts_FilledBox, ///< \ru Закрашенный квадрат. \en Filled square. - dts_FilledDot, ///< \ru Закрашенная точка. \en Filled point. - dts_IntegralSymbol, ///< \ru Знак интеграла. \en Integral symbol. - dts_OpenArrow, ///< \ru Открытая стрелка. \en Open arrow. - dts_Slash, ///< \ru Косая черта. \en Slash. - dts_UnfilledArrow ///< \ru Стрелка без заполнения. \en Unfilled arrow. + dts_BlankedArrow, ///< \ru Незакрашенная стрелка. \en Blank arrow. + dts_BlankedBox, ///< \ru Незакрашенный квадрат. \en Blank square. + dts_BlankedDot, ///< \ru Незакрашенная точка. \en Blank point. + dts_DimensionOrigin, ///< \ru Базовый объект. \en Base object. + dts_FilledArrow, ///< \ru Закрашенная стрелка. \en Filled arrow. + dts_FilledBox, ///< \ru Закрашенный квадрат. \en Filled square. + dts_FilledDot, ///< \ru Закрашенная точка. \en Filled point. + dts_IntegralSymbol, ///< \ru Знак интеграла. \en Integral symbol. + dts_OpenArrow, ///< \ru Открытая стрелка. \en Open arrow. + dts_Slash, ///< \ru Косая черта. \en Slash. + dts_UnfilledArrow ///< \ru Стрелка без заполнения. \en Unfilled arrow. }; @@ -379,7 +379,7 @@ public: */ struct MaTerminatorSymbol { MbeDefinedTerminatorSymbol type; ///< \ru Тип символа \en Symbol type - double parameter; ///< \ru Значенеи параметра на размерной кривой. Если не указан, должен быть равен UNDEFINED_DBL. \en Parameter value on the dimensional curve. If not known, must be equal UNDEFINED_DBL. + double parameter; ///< \ru Значение параметра на размерной кривой. Если не указан, должен быть равен UNDEFINED_DBL. \en Parameter value on the dimensional curve. If not known, must be equal UNDEFINED_DBL. double sizeX; ///< \ru Размер по x. \en Size by x. double sizeY; ///< \ru Размер по у. \en Size by y. /// \ru Признак сонаправленности с касательной к кривой в точке размещения. В случае неопределённого значения параметра - признак направленности внутрь. diff --git a/C3d/Include/conv_exchange_settings.h b/C3d/Include/conv_exchange_settings.h index 23c7f6c..c89f24e 100644 --- a/C3d/Include/conv_exchange_settings.h +++ b/C3d/Include/conv_exchange_settings.h @@ -8,8 +8,8 @@ */ //////////////////////////////////////////////////////////////////////////////// -#ifndef __CONV_MODEL_PROPERTIES_H -#define __CONV_MODEL_PROPERTIES_H +#ifndef __CONV_EXCHANGE_SETTINGS_H +#define __CONV_EXCHANGE_SETTINGS_H #include #include @@ -36,18 +36,6 @@ class MbProductInfo; #define LENGTH_UNIT_INCH 25.4 -//------------------------------------------------------------------------------ -/** \brief \ru Прикладной протокол. -\en Applied protocol.\~ -\ingroup Data_Interface -*/ -// --- -enum MbeImpExpFormat { - ief_STEP203, ///< \ru STEP прикладной протокол 203 ( Проектирование с управляемой конфигурацией ). \en STEP applied protocol STEP 203 (Configuration controlled design). - ief_STEP214, ///< \ru STEP прикладной протокол 214 ( Проектирование автомобилей ). \en STEP applied protocol STEP 214 (Automotive design). - ief_STEP242, ///< \ru STEP прикладной протокол 242 ( Проектирование автомобилей ). \en STEP applied protocol STEP 242 (Automotive design). -}; - #define EXPORT_DEFAULT -1 ///< \ru По умолчанию для заданного формата. \en Default for specified format. #define EXPORT_STEP_203 203 ///< \ru STEP прикладной протокол 203 ( Проектирование с управляемой конфигурацией ). \en STEP applied protocol STEP 203 (Configuration controlled design). @@ -323,8 +311,6 @@ public: virtual bool IsFileAscii () const = 0; /// \ru Получить версию формата при экспорте. \en Get the version of format for export. virtual long int GetFormatVersion () const { return EXPORT_DEFAULT; }; - /// \ru Задать формат для экспорта \en Set format for export - DEPRECATE_DECLARE virtual MbeImpExpFormat GetFormat () const { return ief_STEP203; } /// \ru Следует ли экспортировать только поверхности ( введено для работы конвертера IGES ). \en Whether to export only surfaces (introduced for work with converter IGES ). virtual bool IsOutOnlySurfaces() const = 0; /// \ru Является ли экспортируемый документ сборкой. \en Whether the document for export is an assembly. @@ -341,7 +327,11 @@ public: virtual void SetPropertyString ( MbeConverterStrings nString, const std::string & propertyString ) = 0; /// \ru Представление текста в аннотационных объектах. \en Text representation in annotation objects. virtual eTextForm GetAnnotationTextRepresentation () const { return exf_TextOnly; } - /// \ru Следует ли компоненты экспортировать в разные файлы (если позволяет формат). \en Export components into separate files ( if provided in format). + /** \brief \ru Следует ли компоненты экспортировать в разные файлы (если позволяет формат). + \en Export components into separate files ( if provided in format). \~ + \note \ru ЭКСПЕРИМЕНТАЛЬНАЯ. + \en EXPEREIMENTAL \~. + */ virtual bool ExportComponentsSeparately() const { return false; } /// \ru Получить ЛСК, относительно которой позиционирована модель. \en Get the location, the model is placed in. virtual MbPlacement3D GetOriginLocation() const = 0; @@ -405,8 +395,6 @@ public: virtual MbStepData LOD0TesselationParameters() const { return TesselationParameters(); } /// \ru Флаг сохранения совпадающих точек швов. (для конвертера STL и VRML). \en Whether to keep coincident points of seams (for STL, VRML only). virtual bool DualSeams() const { return true; } - /// \ru Флаг сохранения совпадающих точек швов. (для конвертера STL и VRML). \en Whether to keep coincident points of seams (for STL, VRML only). - virtual void DualSeams( bool ) {} /// \ru Выполнять ли слияние подобных граней. \en Whether to join similar faces. virtual bool JoinSimilarFaces() const { return true; } /// \ru Добавлять ли удаленные грани в качестве оболочек. \en Whether to add removed faces as shells. @@ -414,7 +402,12 @@ public: /// \ru Получить генератор однострочного идентификтора изделия. \en Get generator of one-line product identifier. virtual SPtr ProductIdentifierGenerator() const { return SPtr(); } - /// \ru Проводить ли аудит траснляции. \en Whether to audit the translation. + /** \brief \ru Проводить ли аудит траснляции. + \en Whether to audit the translation. \~ + \note \ru ТОЛЬКО ДЛЯ РАЗРАБОТЧИКОВ. + \en DEVELOPERS ONLY \~. + + */ virtual bool TotalAudit() const { return false; } /// \ru Следует ли формировать атрибут на основе идентификатора элемнта в файле. \en Whether to attatch the element's id in file as attribute. virtual bool AttatchIdAttributes() const { return true; } @@ -498,7 +491,7 @@ public: /// \ru Получить значение разрешения на импорт экспорт объектов определенного типа. \en Get the value of permission for import-export of objects of a certain type. virtual bool GetIoPermission( MbeIOPermiss nPermission ) const; /// \ru Получить значения разрешений на импорт экспорт объектов определенных типов. \en Get values of permission for import-export of objects of certain types. - virtual void GetIoPermissions( std::vector& ioPermissions ) const; + virtual void GetIoPermissions( std::vector& ioPermissions ) const; /// \ru Установить разрешение на импорт экспорт объектов определенного типа. \en Set permission for import-export of objects of a certain type. virtual void SetIoPermission( MbeIOPermiss nPermission, bool isSet ); /// \ru Получить значение специфичной строки для конвертера. \en Get the value of a certain string for the converter. @@ -507,7 +500,12 @@ public: virtual void SetPropertyString ( MbeConverterStrings nString, const std::string & propertyString ); /// \ru Представление текста в аннотационных объектах. \en Text representation in annotation objects. virtual eTextForm GetAnnotationTextRepresentation () const; - /// \ru Следует ли компоненты экспортировать в разные файлы (если позволяет формат). \en Export components into separate files ( if provided in format). + /** \brief \ru Следует ли компоненты экспортировать в разные файлы (если позволяет формат). + \en Export components into separate files ( if provided in format). \~ + \note \ru ЭКСПЕРИМЕНТАЛЬНАЯ. + \en EXPEREIMENTAL \~. + + */ virtual bool ExportComponentsSeparately() const; /// \ru Получить ЛСК, относительно которой позиционирована модель. \en Get the location, the model is placed in. virtual MbPlacement3D GetOriginLocation() const; @@ -574,4 +572,4 @@ public: -#endif // __CONV_MODEL_PROPERTIES_H +#endif // __CONV_EXCHANGE_SETTINGS_H diff --git a/C3d/Include/conv_model_document.h b/C3d/Include/conv_model_document.h index bf5307b..d002f27 100644 --- a/C3d/Include/conv_model_document.h +++ b/C3d/Include/conv_model_document.h @@ -142,7 +142,9 @@ public: //------------------------------------------------------------------------------ /** \brief \ru Формирователь геометрического представления текста. -\en Generator of text element's geometry shape. \~ + \en Generator of text element's geometry shape. \~ + \note \ru ДЛЯ РАЗРАБОТЧИКОВ. + \en DEVELOPERS ONLY. \~ \ingroup Exchange_Interface */ // --- @@ -157,7 +159,10 @@ public: //------------------------------------------------------------------------------ /** \brief \ru Формирователь геометрического представления PMI. -\en Generator of PMI's geometry shape. \~ + \en Generator of PMI's geometry shape. \~ + \note \ru ДЛЯ РАЗРАБОТЧИКОВ. + \en DEVELOPERS ONLY. \~ + \ingroup Exchange_Interface */ // --- @@ -165,7 +170,9 @@ class CONV_CLASS C3DPmiToItem : public MbRefItem { SPtr symToItem; public: C3DPmiToItem( SPtr = SPtr() ); + virtual SPtr operator() ( const MaAnnotationItem* ) const; + virtual SPtr operator() ( const MbItem* ) const; virtual ~C3DPmiToItem(); }; @@ -216,7 +223,7 @@ public: virtual void OpenDocument(); /// \ru Включены ли PMI в элемент модели. \en If PMI is included into model item. - SPtrPmiInContent() const; + SPtr PmiInContent() const; /// \ru Зарегистрировать элемент аннотации. \en Register annotation object. void RegisterAnnotation( c3d::ItemSPtr component, const AnnotationSptrVector& annotation, const AnnotationSptrVector& requirements ); @@ -256,56 +263,56 @@ public: /// \ru Наименование. \en Name. - /// \ru Задать имя документа. \en Set document's name. + /// \ru Задать имя документа. \en Set document's name. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE virtual bool SetName( const std::string& /*name*/ ) { return false; }; - /// \ru Получить имя документа. \en Get document's name. + /// \ru Получить имя документа. \en Get document's name. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE virtual std::string Name() const { return std::string(); }; /// \ru Обозначение. \en Marking. - /// \ru Задать обозначение документа. \en Set document marking. + /// \ru Задать обозначение документа. \en Set document marking. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE virtual bool SetMarking( const std::string& /*name*/ ) { return false; }; - /// \ru Получить обозначение документа. \en Get document marking. + /// \ru Получить обозначение документа. \en Get document marking. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE virtual std::string Marking() const { return std::string(); }; /// \ru Автор. \en Author. - /// \ru Задать имя автора. \en Set author's name. + /// \ru Задать имя автора. \en Set author's name. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE virtual bool SetAuthor( const std::string& /*name*/ ) { return false; }; - /// \ru Получить имя автора. \en Get author's name. + /// \ru Получить имя автора. \en Get author's name. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE virtual std::string Author() const { return std::string(); }; /// \ru Организация. \en Organization. - /// \ru Задать имя автора. \en Set author's name. + /// \ru Задать имя автора. \en Set author's name. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE virtual bool SetOrganization( const std::string& /*name*/ ) { return false; }; - /// \ru Получить имя автора. \en Get author's name. + /// \ru Получить имя автора. \en Get author's name. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE virtual std::string Organization() const { return std::string(); }; /// \ru Комментарий. \en Comment. - /// \ru Задать комментарии. \en Set the comments. + /// \ru Задать комментарии. \en Set the comments. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE virtual bool SetComments( const std::vector< std::string > & /*comments*/ ) { return false; }; - /// \ru Получить следующий комментарий. \en Get the next comment. + /// \ru Получить следующий комментарий. \en Get the next comment. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE virtual std::vector< std::string > GetComments( ) const { return std::vector< std::string >(); }; /// \ru Цвет сборки, детали или вставки. \en Color of an assembly, a part or an instance. - /// \ru Задать цветовые свойства. \en Set color properties. + /// \ru Задать цветовые свойства. \en Set color properties. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE virtual bool SetColor( const MbAttributeContainer & ) { return false; }; - /// \ru Получить цветовые свойства. \en Get color properties. + /// \ru Получить цветовые свойства. \en Get color properties. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE virtual bool GetColor( MbAttributeContainer & ) const { return false; }; /// \ru Цвет тела. \en Solid color. - /// \ru Задать цветовые свойства оболочки. \en Set color properties of a shell. + /// \ru Задать цветовые свойства оболочки. \en Set color properties of a shell. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE virtual bool SetColor( const MbAttributeContainer &, size_t ) { return false; }; /// \ru Цвет грани. \en Face color. - /// \ru Задать цветовые свойства грани \en Set color properties of a face. + /// \ru Задать цветовые свойства грани \en Set color properties of a face. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE virtual bool SetColor( const MbAttributeContainer &, const MbName & ) { return false; }; - /// \ru Получить цветовые свойства грани. \en Get color properties of a face. + /// \ru Получить цветовые свойства грани. \en Get color properties of a face. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE virtual bool GetColor( MbAttributeContainer &, const MbName & ) const { return false; }; }; diff --git a/C3d/Include/conv_model_exchange.h b/C3d/Include/conv_model_exchange.h index 1b9a8ef..8b6d16e 100644 --- a/C3d/Include/conv_model_exchange.h +++ b/C3d/Include/conv_model_exchange.h @@ -12,8 +12,8 @@ */ //////////////////////////////////////////////////////////////////////////////// -#ifndef __CONV_I_CONVERTER_H -#define __CONV_I_CONVERTER_H +#ifndef __CONV_MODEL_EXCHANGE_H +#define __CONV_MODEL_EXCHANGE_H #include #include @@ -22,9 +22,10 @@ #include class IProgressIndicator; -struct IScaleRequestor; +class IScaleRequestor; class ItModelDocument; class IConvertorProperty3D; +class IConfigurationSelector; /** \addtogroup Exchange_Interface @@ -46,9 +47,10 @@ enum MbeModelExchangeFormat { mxf_STEP, ///< \ru Интерпретировать содержимое как STEP (.stp или .step). \en Read data from buffer as STEP (.stp or .step). mxf_STL, ///< \ru Интерпретировать содержимое как STL (.stl). \en Read data from buffer as STL (.stl). mxf_VRML, ///< \ru Интерпретировать содержимое как VRML (.wrl). \en Read data from buffer as VRML (.wrl). + mxf_OBJ, ///< \ru Интерпретировать содержимое как OBJ (.obj). \en Read data from buffer as OBJ (.obj). mxf_GRDECL, ///< \ru Интерпретировать содержимое как GRDECL (.grdecl). \en Read data from buffer as GRDECL (.grdecl). mxf_ASCIIPoint, ///< \ru Интерпретировать содержимое как облако точек в ASCII (.txt, .asc или .xyz). \en Read data from buffer as ASCII point cloud (.txt, .asc or .xyz). - mxf_C3D, ///< \ru Интерпретировать содержимое как C3D (.c3d). \en Read data from buffer as C3D (.c3d). + mxf_C3D ///< \ru Интерпретировать содержимое как C3D (.c3d). \en Read data from buffer as C3D (.c3d). }; @@ -311,6 +313,27 @@ namespace c3d { IConvertorProperty3D* prop = c3d_null, IProgressIndicator* indicator = c3d_null ); + /** \brief \ru Экспортировать модельный документ в буфер. + \en Export model document into buffer. \~ + \param[in] mDoc - \ru Экспортируемый модельный документ. + \en The exported model document. \~ + \param[in] modelFormat - \ru Формат модели. + \en Model format. \~ + \param[out] buffer - \ru Буфер. + \en Buffer. \~ + \param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ + \param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup Exchange_Interface + */ + CONV_FUNC( MbeConvResType ) ExportIntoBuffer( ItModelDocument& item, + MbeModelExchangeFormat modelFormat, + C3DExchangeBuffer& buffer, + IConvertorProperty3D* prop = c3d_null, + IProgressIndicator* indicator = c3d_null ); //------------------------------------------------------------------------------ /** \brief \ru Буфер для обмена. @@ -619,6 +642,22 @@ public: */ virtual MbeConvResType STLWrite( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0, MbRefItem* qeuryStitch = 0 ) = 0; + /** \brief \ru Прочитать файл формата OBJ. + \en Read a file of OBJ format. \~ + \param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ + \param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ + \param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ + \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей (не используется). + \en Dialog of request for stitching the surfaces (not used). \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup VRML_Exchange + */ + virtual MbeConvResType OBJRead( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0 ) = 0; + /** \brief \ru Прочитать файл формата VRML. \en Read a file of VRML format. \~ \param[in] prop - \ru Реализация интерфейса свойств конвертера. @@ -717,20 +756,6 @@ public: */ virtual MbeConvResType ASCIIPointCloudWrite( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0, MbRefItem* qeuryStitch = 0 ) = 0; - - /** \brief \ru Загрузить плагин получения данных для построения модели. - \en Load plugin for getting information necessary to build model. \~ - \note \ru Экспериментальное API. \en Expereimental API. \~ - \param[in] pluginName - \ru Имя подключаемого файла. - \en Name of the file to link. \~ - \param[in] thirdPartyLocation - \ru Расположение стороннего компонента, который подключается с помощью плагина. - \en Location of the third-party component linked by plugin. \~ - \return \ru Код завершения операции. - \en Code of the operation termination. \~ - \ingroup ASCII_Exchange - */ - virtual MbeConvResType LoadForeignReader( const c3d::path_string& pluginName, const c3d::path_string& thirdPartyLocation = c3d::path_string() ) = 0; - /** \brief \ru Загрузить плагин получения данных для построения модели. \en Load plugin for getting information necessary to build model. \~ \details \ru Описание специфичных для плагина настроек следует получить у поставщика комопонента. @@ -742,9 +767,11 @@ public: \en Plugin-specific settings. \~ \return \ru Код завершения операции. \en Code of the operation termination. \~ + \note \ru ЭКСПЕРИМЕНТАЛЬНАЯ. + \en EXPEREIMENTAL \~. \ingroup ASCII_Exchange */ - virtual MbeConvResType LoadForeignReader( const c3d::path_string& pluginName, const c3d::optionNameValuePairs_t& pluginSpecificSettings ) = 0; + virtual MbeConvResType LoadForeignReader( const c3d::path_string& pluginName, const c3d::optionNameValuePairs_t& pluginSpecificSettings, IConfigurationSelector * configSelector = 0 ) = 0; /** \brief \ru Отключить загруженный плагин получения данных для построения модели. @@ -765,6 +792,8 @@ public: \en Implementation of converter's properties interface. \~ \param[in] indicator - \ru Индикатор хода процесса. \en The process progress indicator. \~ + \note \ru ЭКСПЕРИМЕНТАЛЬНАЯ. + \en EXPEREIMENTAL \~. \return \ru Код завершения операции. \en Code of the operation termination. \~ \ingroup ASCII_Exchange @@ -963,6 +992,20 @@ CONV_FUNC( MbeConvResType ) STLRead( IConvertorProperty3D& prop, ItModelDocument */ CONV_FUNC( MbeConvResType ) STLWrite( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0 ); +/** \brief \ru Прочитать файл формата OBJ. + \en Read a file of OBJ format. \~ +\param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ +\param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ +\param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ +\return \ru Код завершения операции. + \en Code of the operation termination. \~ +\ingroup VRML_Exchange +*/ +CONV_FUNC( MbeConvResType ) OBJRead( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0 ); + /** \brief \ru Прочитать файл формата VRML. \en Read a file of VRML format. \~ \param[in] prop - \ru Реализация интерфейса свойств конвертера. @@ -1054,6 +1097,7 @@ namespace c3d { /** \brief \ru Импортировать данные из буфера в модель. \en Import data from buffer into model. \~ + \deprecated \ru Метод устарел. \en The method is deprecated. \~ \param[out] model - \ru Модель. \en The model. \~ \param[in] data - \ru Буфер. @@ -1079,6 +1123,7 @@ namespace c3d { /** \brief \ru Импортировать данные из буфера в модель. \en Import data from buffer into model. \~ + \deprecated \ru Метод устарел. \en The method is deprecated. \~ \param[out] item - \ru Замещаемый элемент. \en The item to replace. \~ \param[in] data - \ru Буфер. @@ -1103,6 +1148,7 @@ namespace c3d { /** \brief \ru Экспортировать модель в буфер. \en Export model into buffer. \~ + \deprecated \ru Метод устарел. \en The method is deprecated. \~ \param[in] model - \ru Модель. \en The model. \~ \param[in] modelFormat - \ru Формат модели. @@ -1129,6 +1175,7 @@ namespace c3d { /** \brief \ru Экспортировать модель в буфер. \en Export model into buffer. \~ + \deprecated \ru Метод устарел. \en The method is deprecated. \~ \param[in] item - \ru Экспортируемый элемент. \en The item to export. \~ \param[in] modelFormat - \ru Формат модели. @@ -1156,4 +1203,4 @@ namespace c3d { /** \} */ -#endif // __CONV_I_CONVERTER_H +#endif // __CONV_MODEL_EXCHANGE_H diff --git a/C3d/Include/conv_plugin_import.h b/C3d/Include/conv_plugin_import.h index c3045ff..462807e 100644 --- a/C3d/Include/conv_plugin_import.h +++ b/C3d/Include/conv_plugin_import.h @@ -21,6 +21,25 @@ topology and geomentry transmission.\~ // //////////////////////////////////////////////////////////////////////////////// + +//------------------------------------------------------------------------------ +/** \brief \ru Путь, по которому расположен интегратор для интеграционного пакета + со сторонним модулем. + \en Path where integration kit for external module is located.\~ + + \details \ru Путь должен содержать завершающий. + \en Path where integration kit for external module is located.\~ + +\ingroup Data_Interface +*/ +// --- +#ifdef _UNICODE +#define C3D_PATH_TO_PLUGIN L"C3D_PATH_TO_PLUGIN" +#else +#define C3D_PATH_TO_PLUGIN "C3D_PATH_TO_PLUGIN" +#endif + + //------------------------------------------------------------------------------ /** \brief \ru Имена функций инициализации и завершения работы плагина. \en Initialize and release functions of plugin.\~ @@ -30,6 +49,7 @@ topology and geomentry transmission.\~ #define C3D_PLUGIN_INIT_SOURCE InitSource #define C3D_PLUGIN_C_SET_PLUGIN_OPTION CSetPluginOption #define C3D_PLUGIN_W_SET_PLUGIN_OPTION WSetPluginOption +#define C3D_PLUGIN_W_SET_MODEL_CONFIGURATION_SELECT WSetModelConfigurationSelect #define C3D_PLUGIN_RELEASE_SOURCE ReleaseSource //------------------------------------------------------------------------------ @@ -41,11 +61,12 @@ topology and geomentry transmission.\~ #define C3D_PLUGIN_INIT_SOURCE_NAME "InitSource" #define C3D_PLUGIN_C_SET_PLUGIN_OPTION_NAME "CSetPluginOption" #define C3D_PLUGIN_W_SET_PLUGIN_OPTION_NAME "WSetPluginOption" +#define C3D_PLUGIN_W_SET_MODEL_CONFIGURATION_SELECT_NAME "WSetModelConfigurationSelect" #define C3D_PLUGIN_RELEASE_SOURCE_NAME "ReleaseSource" struct ObModelSource; - +struct IWSelectConfigurationCallback; //------------------------------------------------------------------------------ /** \brief \ru Объявление функций инициализации и завершения работы плагина. @@ -54,14 +75,16 @@ struct ObModelSource; */ // --- #ifdef WIN32 -#define C3D_PLUGIN_INIT_EXPORT_DECLARE extern "C" __declspec( dllexport ) ObModelSource* _cdecl C3D_PLUGIN_INIT_SOURCE ( const char*, const char* ); +#define C3D_PLUGIN_INIT_EXPORT_DECLARE extern "C" __declspec( dllexport ) ObModelSource* _cdecl C3D_PLUGIN_INIT_SOURCE ( const char*, const char* ); #define C3D_PLUGIN_C_SET_PLUGIN_OPTION_DECLARE extern "C" __declspec( dllexport ) void _cdecl C3D_PLUGIN_C_SET_PLUGIN_OPTION ( const char*, const char* ); #define C3D_PLUGIN_W_SET_PLUGIN_OPTION_DECLARE extern "C" __declspec( dllexport ) void _cdecl C3D_PLUGIN_W_SET_PLUGIN_OPTION ( const wchar_t*, const wchar_t* ); +#define C3D_PLUGIN_W_SET_MODEL_CONFIGURATION_SELECT_DECLARE extern "C" __declspec( dllexport ) void _cdecl C3D_PLUGIN_W_SET_MODEL_CONFIGURATION_SELECT ( IWSelectConfigurationCallback* ); #define C3D_PLUGIN_RELEASE_EXPORT_DECLARE extern "C" __declspec( dllexport ) void _cdecl C3D_PLUGIN_RELEASE_SOURCE ( ObModelSource* ); #else #define C3D_PLUGIN_INIT_EXPORT_DECLARE ObModelSource* C3D_PLUGIN_INIT_SOURCE ( const char*, const char* ); #define C3D_PLUGIN_C_SET_PLUGIN_OPTION_DECLARE void C3D_PLUGIN_C_SET_PLUGIN_OPTION ( const char*, const char* ); #define C3D_PLUGIN_W_SET_PLUGIN_OPTION_DECLARE void C3D_PLUGIN_W_SET_PLUGIN_OPTION ( const wchar_t*, const wchar_t* ); +#define C3D_PLUGIN_W_SET_MODEL_CONFIGURATION_SELECT_DECLARE void C3D_PLUGIN_W_SET_MODEL_CONFIGURATION_SELECT ( IWSelectConfigurationCallback* ); #define C3D_PLUGIN_RELEASE_EXPORT_DECLARE void C3D_PLUGIN_RELEASE_SOURCE ( ObModelSource* ); #endif // WIN32 @@ -76,11 +99,13 @@ struct ObModelSource; typedef ObModelSource* ( _cdecl* C3D_PLUGIN_INIT_SOURCE_CALL ) ( const char*, const char* ); typedef void ( _cdecl* C3D_PLUGIN_C_SET_OPTION_CALL ) ( const char*, const char* ); typedef void ( _cdecl* C3D_PLUGIN_W_SET_OPTION_CALL ) ( const wchar_t*, const wchar_t* ); +typedef void ( _cdecl* C3D_PLUGIN_W_SET_MODEL_CONFIGURATION_SELECT_CALL ) ( IWSelectConfigurationCallback* ); typedef void ( _cdecl* C3D_PLUGIN_RELEASE_SOURCE_CALL )( ObModelSource* ); #else typedef ObModelSource* ( * C3D_PLUGIN_INIT_SOURCE_CALL ) ( const char*, const char* ); typedef void ( * C3D_PLUGIN_C_SET_OPTION_CALL ) ( const char*, const char* ); typedef void ( * C3D_PLUGIN_W_SET_OPTION_CALL ) ( const wchar_t*, const wchar_t* ); +typedef void ( * C3D_PLUGIN_W_SET_MODEL_CONFIGURATION_SELECT_CALL ) ( IWSelectConfigurationCallback* ); typedef void ( * C3D_PLUGIN_RELEASE_SOURCE_CALL ) ( ObModelSource* ); #endif // WIN32 @@ -823,5 +848,12 @@ struct ObModelSource { }; +struct IWSelectConfigurationCallback { + virtual void AddConfiguration( const wchar_t* ) = 0; + virtual void SetActiveConfiguration( int ) = 0; + virtual int SelectConfiguration() const = 0; +}; + + #endif // __CONV_PUGIN_IMPORT_H diff --git a/C3d/Include/conv_predefined.h b/C3d/Include/conv_predefined.h index f218121..3b1a56c 100644 --- a/C3d/Include/conv_predefined.h +++ b/C3d/Include/conv_predefined.h @@ -10,8 +10,8 @@ */ //////////////////////////////////////////////////////////////////////////////// -#ifndef __CONV_ERROR_RESULT_H -#define __CONV_ERROR_RESULT_H +#ifndef __CONV_PREDEFINED_H +#define __CONV_PREDEFINED_H #include @@ -148,4 +148,4 @@ enum MbeProgBarId_MassInertiaProperties { }; -#endif // __CONV_ERROR_RESULT_H \ No newline at end of file +#endif // __CONV_PREDEFINED_H \ No newline at end of file diff --git a/C3d/Include/conv_requestor.h b/C3d/Include/conv_requestor.h index 61057ac..fbc324e 100644 --- a/C3d/Include/conv_requestor.h +++ b/C3d/Include/conv_requestor.h @@ -12,22 +12,59 @@ #include +#include //------------------------------------------------------------------------------ -/// \ru Интерфейс запроса масштаба. \en Interface of scale request. +/** +\brief \ru Интерфейс выбора конфигурации. + \en Interface of configuration selection. \~ +\details \ru Вызывается при импорте однократно, если импортируемоя модель содержит более одной конфигурации. + \en Called on import once if the model contains contains more than one configurations. \~ + \note \ru ЭКСПЕРИМЕНТАЛЬНАЯ. + \en EXPEREIMENTAL. \~ +*/ // --- -struct IScaleRequestor : public MbRefItem +class IConfigurationSelector : public MbRefItem { +public: + virtual void AddConfiguration ( const c3d::string_t& configurationName ) = 0; + virtual void SetActiveConfiguration ( const size_t index ) = 0; + virtual size_t GetConfiguration () const = 0; +}; + + +//------------------------------------------------------------------------------ +/// +/** +\brief \ru Интерфейс запроса масштаба. + \en Interface of scale request. \~ +\details \ru Рекомендуется использовать методы интерфейса IConvertorProperty3D. + \en Using methods of the IConvertorProperty3D interface recommended. \~ + \note \ru Рекомендуется использовать методы интерфейса IConvertorProperty3D. + \en Using methods of the IConvertorProperty3D interface recommended. \~ +*/ +// --- +class IScaleRequestor : public MbRefItem +{ +public: virtual double ScaleRequest() = 0; }; //------------------------------------------------------------------------------ -/// \ru Интерфейс запроса сшивки. \en Interface of stitching request. +/** +\brief \ru Интерфейс запроса сшивки. + \en Interface of stitching request \~ +\details \ru Рекомендуется использовать методы интерфейса IConvertorProperty3D. + \en Using methods of the IConvertorProperty3D interface recommended. \~ + \note \ru Рекомендуется использовать методы интерфейса IConvertorProperty3D. + \en Using methods of the IConvertorProperty3D interface recommended. \~ +*/ // --- -struct IStitchRequestor : public MbRefItem +class IStitchRequestor : public MbRefItem { +public: virtual bool StitchRequest() = 0; }; diff --git a/C3d/Include/cr_connecting_curve.h b/C3d/Include/cr_connecting_curve.h index 657a176..78d432c 100644 --- a/C3d/Include/cr_connecting_curve.h +++ b/C3d/Include/cr_connecting_curve.h @@ -45,11 +45,14 @@ private: MbeConnectingType type; ///< \ru Тип скругления (обычное или на поверхности) \en Connection type (ordinary or on a surface) protected: - MbConnectingCurveCreator( const MbConnectingCurveCreator & , MbRegDuplicate * iReg ); // \ru Конструктор копирования \en Copy-constructor + /// \ru Конструктор копирования. \en Copy-constructor. + MbConnectingCurveCreator( const MbConnectingCurveCreator & , MbRegDuplicate * iReg ); +private: MbConnectingCurveCreator( const MbConnectingCurveCreator & ); // \ru Не реализовано \en Not implemented MbConnectingCurveCreator(); // \ru Не реализовано \en Not implemented public: + /// \ru Конструктор по параметрам. \en Constructor by parameters. MbConnectingCurveCreator( const MbSNameMaker & n, const MbCurve3D & c1, double t1, double p1, double r1, bool s1, MbeMatingType m1, const MbCurve3D & c2, double t2, double p2, double r2, bool s2, MbeMatingType m2, MbeConnectingType t ); @@ -85,11 +88,12 @@ private: // \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 ) +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbConnectingCurveCreator ) }; IMPL_PERSISTENT_OPS( MbConnectingCurveCreator ) + //------------------------------------------------------------------------------ /** \brief \ru Создание строителя скругления двух кривых. \en Create two curves fillet constructor. \~ diff --git a/C3d/Include/cr_cutting_solid.h b/C3d/Include/cr_cutting_solid.h index af52814..02af35a 100644 --- a/C3d/Include/cr_cutting_solid.h +++ b/C3d/Include/cr_cutting_solid.h @@ -52,10 +52,10 @@ public : MbCuttingSolid( const MbShellCuttingParams & cuttingParams, bool sameCutterObject ); DEPRECATE_DECLARE MbCuttingSolid( const MbSurface & surface, bool sameSurface, int part, - bool closed, const MbMergingFlags & flags, const MbSNameMaker & n ); + bool closed, const MbMergingFlags & flags, const MbSNameMaker & n ); ///< \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE MbCuttingSolid( const MbPlacement3D & place, const MbContour & contour, const MbVector3D & direction, int part, - bool closed, const MbMergingFlags & flags, const MbSNameMaker & n ); + bool closed, const MbMergingFlags & flags, const MbSNameMaker & n ); ///< \deprecated \ru Метод устарел. \en The method is deprecated. private : MbCuttingSolid( const MbCuttingSolid &, MbRegDuplicate * ireg ); // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. diff --git a/C3d/Include/cr_displace_creator.h b/C3d/Include/cr_displace_creator.h index 0159523..ad4cf1f 100644 --- a/C3d/Include/cr_displace_creator.h +++ b/C3d/Include/cr_displace_creator.h @@ -27,11 +27,13 @@ class MATH_CLASS MbMotionMaker : public MbCreator { protected: MbVector3D vector; ///< \ru Вектор перемещения. \en The displacement vector. -public: // \ru Конструктор по параметрам. \en Constructor by parameters. +public: + /// \ru Конструктор по параметрам. \en Constructor by parameters. MbMotionMaker( const MbVector3D & ); -private: // \ru Конструктор дублирующий. \en Duplication constructor. +private: + /// \ru Конструктор дублирующий. \en Duplication constructor. MbMotionMaker( const MbMotionMaker &, MbRegDuplicate * ireg ); - // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. + /// \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. MbMotionMaker( const MbMotionMaker & ); public: // \ru Деструктор \en Destructor @@ -74,7 +76,7 @@ private: // \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 ) }; IMPL_PERSISTENT_OPS( MbMotionMaker ) @@ -93,11 +95,13 @@ protected: MbAxis3D axis; ///< \ru Ось вращения. \en The axis. double angle; ///< \ru Угол поворота. \en The angle of rotatation. -public: // \ru Конструктор по параметрам. \en Constructor by parameters. +public: + /// \ru Конструктор по параметрам. \en Constructor by parameters. MbRotationMaker( const MbAxis3D & ax, double an ); -private: // \ru Конструктор дублирующий. \en Duplication constructor. +private: + /// \ru Конструктор дублирующий. \en Duplication constructor. MbRotationMaker( const MbRotationMaker &, MbRegDuplicate * ireg ); - // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. + /// \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. MbRotationMaker( const MbRotationMaker & ); public: // \ru Деструктор \en Destructor @@ -140,7 +144,7 @@ private: // \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 ) +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbRotationMaker ) }; IMPL_PERSISTENT_OPS( MbRotationMaker ) @@ -158,11 +162,13 @@ class MATH_CLASS MbTransformationMaker : public MbCreator { protected: MbMatrix3D matrix; ///< \ru Матрица преобразования. \en The transform matrix. -public: // \ru Конструктор по параметрам. \en Constructor by parameters. +public: + /// \ru Конструктор по параметрам. \en Constructor by parameters. MbTransformationMaker( const MbMatrix3D & ); -private: // \ru Конструктор дублирующий. \en Duplication constructor. +private: + /// \ru Конструктор дублирующий. \en Duplication constructor. MbTransformationMaker( const MbTransformationMaker &, MbRegDuplicate * ireg ); - // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. + /// \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. MbTransformationMaker( const MbTransformationMaker & ); public: // \ru Деструктор \en Destructor @@ -205,7 +211,7 @@ private: // \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 ) +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbTransformationMaker ) }; IMPL_PERSISTENT_OPS( MbTransformationMaker ) diff --git a/C3d/Include/cr_intersection_curve.h b/C3d/Include/cr_intersection_curve.h index eec1a5b..ca58b4b 100644 --- a/C3d/Include/cr_intersection_curve.h +++ b/C3d/Include/cr_intersection_curve.h @@ -23,16 +23,22 @@ // --- class MATH_CLASS MbIntCurveCreator : public MbCreator { private: - RPArray creators1; // \ru Журнал построения первой оболочки. \en The first shell history tree. - RPArray creators2; // \ru Журнал построения второй оболочки. \en The second shell history tree. + RPArray creators1; ///< \ru Журнал построения первой оболочки. \en The first shell history tree. + RPArray creators2; ///< \ru Журнал построения второй оболочки. \en The second shell history tree. + bool mergeCurves; ///< \ru Объединять кривые, разрезанные швом. \en Merge curves cut by a surface seam. + bool cutCurves; ///< \ru Разрезать кривые в точках пересечения. \en Cut curves at intersection points. protected: - MbIntCurveCreator( const MbIntCurveCreator &, MbRegDuplicate * iReg ); // \ru Конструктор копирования \en Copy-constructor + /// \ru Конструктор копирования. \en Copy-constructor. + MbIntCurveCreator( const MbIntCurveCreator &, MbRegDuplicate * iReg ); +private: MbIntCurveCreator( const MbIntCurveCreator & ); // \ru Не реализовано \en Not implemented MbIntCurveCreator(); // \ru Не реализовано \en Not implemented public: + /// \ru Конструктор по параметрам. \en Constructor by parameters. MbIntCurveCreator( const RPArray & creators1, bool same1, const RPArray & creators2, bool same2, + bool mergeCurves, bool curCurves, const MbSNameMaker & snMaker ); public: virtual ~MbIntCurveCreator(); @@ -65,7 +71,7 @@ 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!!! - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbIntCurveCreator ) +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbIntCurveCreator ) }; IMPL_PERSISTENT_OPS( MbIntCurveCreator ) diff --git a/C3d/Include/cr_nurbs3d.h b/C3d/Include/cr_nurbs3d.h index 23d8e42..a217629 100644 --- a/C3d/Include/cr_nurbs3d.h +++ b/C3d/Include/cr_nurbs3d.h @@ -25,20 +25,23 @@ // --- class MATH_CLASS MbNurbs3DCreator : public MbCreator { private: - SArray points; // \ru Точки, через которые проходит сплайн \en Points which the spline passes through - SArray weights; // \ru Веса \en Weights - SArray knots; // \ru Узлы \en Knots - RPArray matingData; // \ru Данные сопряжения в точках \en Data about mating in the points - MbeSplineParamType paramType; // \ru Тип параметризации \en Parametrization type - size_t degree; // \ru Степень сплайна \en Spline degree - bool closed; // \ru Замкнутость сплайна \en Spline closedness - bool throughPnts; // \ru через точки \en Through points + SArray points; ///< \ru Точки, через которые проходит сплайн. \en Points which the spline passes through. + SArray weights; ///< \ru Веса. \en Weights. + SArray knots; ///< \ru Узлы. \en Knots. + RPArray matingData; ///< \ru Данные сопряжения в точках. \en Data about mating in the points. + MbeSplineParamType paramType; ///< \ru Тип параметризации. \en Parametrization type. + size_t degree; ///< \ru Степень сплайна. \en Spline degree. + bool closed; ///< \ru Замкнутость сплайна. \en Spline closedness. + bool throughPnts; ///< \ru через точки. \en Through points. protected: - MbNurbs3DCreator( const MbNurbs3DCreator &, MbRegDuplicate * iReg ); // \ru Конструктор копирования \en Copy-constructor - MbNurbs3DCreator( const MbNurbs3DCreator & ); // \ru Не реализовано \en Not implemented - MbNurbs3DCreator(); // \ru Не реализовано \en Not implemented + /// \ru Конструктор копирования. \en Copy-constructor. + MbNurbs3DCreator( const MbNurbs3DCreator &, MbRegDuplicate * iReg ); +private: + MbNurbs3DCreator( const MbNurbs3DCreator & ); // \ru Не реализовано. \en Not implemented. + MbNurbs3DCreator(); // \ru Не реализовано. \en Not implemented. public: + /// \ru Конструктор по параметрам. \en Constructor by parameters. MbNurbs3DCreator( const SArray & spacePnts, bool throughPnts, MbeSplineParamType paramType, size_t degree, bool closed, const SArray * weights, @@ -76,7 +79,7 @@ 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!!! - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbNurbs3DCreator ) +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbNurbs3DCreator ) }; IMPL_PERSISTENT_OPS( MbNurbs3DCreator ) diff --git a/C3d/Include/cr_offset_curve.h b/C3d/Include/cr_offset_curve.h index 5d4082f..1477a02 100644 --- a/C3d/Include/cr_offset_curve.h +++ b/C3d/Include/cr_offset_curve.h @@ -46,9 +46,12 @@ private: c3d::CreatorsSPtrVector shellCreators; ///< \ru Журнал построения оболочки. \en The shell history tree. protected: - MbOffsetCurveCreator( const MbOffsetCurveCreator &, MbRegDuplicate * iReg ); // \ru Конструктор копирования \en Copy-constructor + /// \ru Конструктор копирования \en Copy-constructor + MbOffsetCurveCreator( const MbOffsetCurveCreator &, MbRegDuplicate * iReg ); +private: MbOffsetCurveCreator( const MbOffsetCurveCreator & ); // \ru Не реализовано \en Not implemented MbOffsetCurveCreator(); // \ru Не реализовано \en Not implemented + public: /** \brief \ru Конструктор эквидистанты в пространстве. \en Constructor of offset in the space. \~ diff --git a/C3d/Include/cr_projection_curve.h b/C3d/Include/cr_projection_curve.h index 847cbd9..4a64aa1 100644 --- a/C3d/Include/cr_projection_curve.h +++ b/C3d/Include/cr_projection_curve.h @@ -31,16 +31,19 @@ private: bool truncateByBounds; // \ru Усечь границами \en Truncate by bounds protected: - MbProjCurveCreator( const MbProjCurveCreator &, MbRegDuplicate * iReg ); // \ru Конструктор копирования \en Copy-constructor + /// \ru Конструктор копирования. \en Copy-constructor. + MbProjCurveCreator( const MbProjCurveCreator &, MbRegDuplicate * iReg ); +private: MbProjCurveCreator( const MbProjCurveCreator & ); // \ru Не реализовано \en Not implemented MbProjCurveCreator(); // \ru Не реализовано \en Not implemented public: + /// \ru Конструктор по параметрам. \en Constructor by parameters. MbProjCurveCreator( const MbCurve3D & curve, const RPArray & shellCreators, bool sameCreators, const MbVector3D * dir, bool exact, bool truncate, const MbSNameMaker & snMaker ); - - MbProjCurveCreator( const MbWireFrame &wf, const bool sameWire, + /// \ru Конструктор по параметрам. \en Constructor by parameters. + MbProjCurveCreator( const MbWireFrame & wf, const bool sameWire, const RPArray & shellCreators, bool sameCreators, const MbVector3D * dir, bool exact, bool truncate, const MbSNameMaker & snMaker ); diff --git a/C3d/Include/cr_smooth_solid.h b/C3d/Include/cr_smooth_solid.h index d41ce33..3f35057 100644 --- a/C3d/Include/cr_smooth_solid.h +++ b/C3d/Include/cr_smooth_solid.h @@ -20,8 +20,7 @@ \details \ru Строитель фаски или скругления ребeр тела содержит идентификаторы обрабатываемых рёбер и параметры для выполнения операции. \n \en Constructor of solid's edges chamfer or fillet contains identifiers of edges being processed and parameters for performing operation. \n \~ \ingroup Model_Creators -*/ -// --- +*/ // --- class MATH_CLASS MbSmoothSolid : public MbCreator { protected : SArray indexes; ///< \ru Номера ребер и номера смежных (сопрягаемых) граней. \en Indices of edges and indices of adjacent (conjugated) faces. diff --git a/C3d/Include/cr_stamp_remove_solid.h b/C3d/Include/cr_stamp_remove_solid.h index d555811..00de62a 100644 --- a/C3d/Include/cr_stamp_remove_solid.h +++ b/C3d/Include/cr_stamp_remove_solid.h @@ -16,6 +16,20 @@ //#include +//------------------------------------------------------------------------------ +/** \brief \ru Типы листовых операций. + \en Sheet operation names. \~ +*/ +// --- +enum MbeSheetOperationName { + son_Unknown = 0, ///< \ru Неопределённая операция. \en Undefined operation. + son_RibStamp, ///< \ru Операция ребро усиления. \en Operation of adding an edge of reinforcement. + son_Stamp , ///< \ru Операция штамповка. \en Add stamp operation . + son_UserStamp ///< \ru Операция пользовательская штамповка. \en Add user stamp operation. + +}; + + //------------------------------------------------------------------------------ /** \brief \ru Строитель оболочки из листового материала с удалёнными элементами указанной операции. \en The constructor of a shell from sheet material without elements of the specified operation. \~ @@ -28,10 +42,12 @@ // --- class MATH_CLASS MbRemoveOperationSolid : public MbCreator { SimpleName removeName; - + MbeSheetOperationName operationType; + public : - MbRemoveOperationSolid( const SimpleName removeName, - const MbSNameMaker & names ); + MbRemoveOperationSolid( const SimpleName removeName, + MbeSheetOperationName opType, + const MbSNameMaker & names ); private: MbRemoveOperationSolid( const MbRemoveOperationSolid &, MbRegDuplicate * iReg ); // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. @@ -72,6 +88,7 @@ private: IMPL_PERSISTENT_OPS( MbRemoveOperationSolid ) + //------------------------------------------------------------------------------ /** \brief \ru Построить оболочку без указанной операции. \en Constructs a shell without the specified operation. \~ @@ -85,6 +102,8 @@ IMPL_PERSISTENT_OPS( MbRemoveOperationSolid ) \en Mode of copying the initial shell. \~ \param[in] removeName - \ru Главное имя операции которую надо удалить. \en The main name of the operation to be removed. \~ + \param[in] opType - \ru Тип листовой операции. + \en Type of the sheet operation. \~ \param[in] names - \ru Именователь граней. \en An object for naming faces. \~ \param[out] res - \ru Код результата операции. @@ -96,6 +115,17 @@ IMPL_PERSISTENT_OPS( MbRemoveOperationSolid ) \ingroup Model_Creators */ // --- +MATH_FUNC (MbCreator *) CreateRemovedOperationResult ( MbFaceShell & initialShell, + const MbeCopyMode sameShell, + const SimpleName removeName, + MbeSheetOperationName opType, + const MbSNameMaker & names, + MbResultType & res, + MbFaceShell *& shell ); + + +/// \deprecated \ru Метод устарел. \en The method is deprecated. +DEPRECATE_DECLARE MATH_FUNC (MbCreator *) CreateRemovedOperationResult( MbFaceShell & initialShell, const MbeCopyMode sameShell, const SimpleName removeName, @@ -104,7 +134,6 @@ MATH_FUNC (MbCreator *) CreateRemovedOperationResult( MbFaceShell & MbFaceShell *& shell ); - #endif // __CR_STAMP_REMOVE_SOLID_H diff --git a/C3d/Include/cr_surface_spline.h b/C3d/Include/cr_surface_spline.h index 20e3008..d984d2c 100644 --- a/C3d/Include/cr_surface_spline.h +++ b/C3d/Include/cr_surface_spline.h @@ -31,26 +31,29 @@ class MATH_CLASS MbSurface; // --- class MATH_CLASS MbSurfaceSplineCreator : public MbCreator { private: - MbSurface * surface; // \ru Поверхность \en Surface - bool throughPnts; // \ru через точки \en Through points - SArray paramPnts; // \ru Параметрические точки \en Parametric points - SArray paramWts; // \ru Веса параметрических точек \en Parametric points weights - bool paramClosed; // \ru Замкнуть параметрический сплайн \en Make the parametric spline close - RPArray spaceTransitions; // \ru Сопряжения в точках \en Tangents at the points + c3d::SurfaceSPtr surface; ///< \ru Поверхность. \en Surface. + bool throughPnts; ///< \ru через точки. \en Through points. + SArray paramPnts; ///< \ru Параметрические точки. \en Parametric points. + SArray paramWts; ///< \ru Веса параметрических точек. \en Parametric points weights. + bool paramClosed; ///< \ru Замкнуть параметрический сплайн. \en Make the parametric spline close. + RPArray spaceTransitions; ///< \ru Сопряжения в точках. \en Tangents at the points. protected: - MbSurfaceSplineCreator( const MbSurfaceSplineCreator &, MbRegDuplicate * iReg ); // \ru Конструктор копирования \en Copy-constructor + /// \ru Конструктор копирования. \en Copy-constructor. + MbSurfaceSplineCreator( const MbSurfaceSplineCreator &, MbRegDuplicate * iReg ); +private: MbSurfaceSplineCreator( const MbSurfaceSplineCreator & ); // \ru Не реализовано \en Not implemented MbSurfaceSplineCreator(); // \ru Не реализовано \en Not implemented public: + /// \ru Конструктор по параметрам. \en Constructor by parameters. MbSurfaceSplineCreator( const MbSurface & surface, bool sameSurf, bool thrPnts, const SArray & pnts, const SArray & wts, bool parCls, - RPArray & transitions, + const RPArray & transitions, const MbSNameMaker & snMaker ); public : virtual ~MbSurfaceSplineCreator(); diff --git a/C3d/Include/cur_arc.h b/C3d/Include/cur_arc.h index ca20731..b543bc4 100644 --- a/C3d/Include/cur_arc.h +++ b/C3d/Include/cur_arc.h @@ -1478,7 +1478,7 @@ inline void MbArc::ParamToAngle( double & t ) const inline void MbArc::AngleToParam( double & t ) const { double dtr = ( trim2 + trim1 - M_PI2 ) * 0.5; - t -= ::floor( (t - dtr) * Math::invPI2 ) * M_PI2; + t -= ::floor( (t - dtr) * Math::invPI2 ) * M_PI2; // SKIP_SA t = ( trim2 > trim1 ) ? ( t - trim1 ) : ( trim1 - t ); } diff --git a/C3d/Include/cur_arc3d.h b/C3d/Include/cur_arc3d.h index 3af393d..8f94db3 100644 --- a/C3d/Include/cur_arc3d.h +++ b/C3d/Include/cur_arc3d.h @@ -13,6 +13,7 @@ #include #include +#include c3d_constexpr size_t CONIC_COUNT = 32; @@ -58,6 +59,8 @@ protected : double trim1; ///< \ru Параметры начальной точки. \en The start point parameters. double trim2; ///< \ru Параметры конечной точки. \en The end point parameters. bool closed; ///< \ru Замкнутость. \en Closedness. + // \ru Временные данные. \en Temporary data. + mutable MbCube cube; ///< \ru Габаритный куб. \en Bounding box. public : /** \brief \ru Конструктор дуги эллипса. @@ -387,28 +390,30 @@ 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) virtual bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place, bool saveParams, PlanarCheckParams params = PlanarCheckParams() ) const; + virtual void AddYourGabaritTo( MbCube & ) const; // \ru Добавить габарит кривой в куб. \en Add a bounding box of a curve to a cube. virtual void CalculateGabarit( MbCube & ) const; // \ru Вычислить габарит кривой \en Calculate bounding box of curve virtual void CalculateLocalGabarit( const MbMatrix3D &, MbCube & ) const; // \ru Рассчитать габарит относительно л.с.к. \en Calculate bounding box relative to local coordinate system /// \ru Является ли объект смещением \en Whether the object is a shift virtual bool IsShift ( const MbSpaceItem &, MbVector3D &, bool & isSame, double accuracy = LENGTH_EPSILON ) const; virtual bool IsSimilarToCurve( const MbCurve3D & curve, double precision = METRIC_PRECISION ) const; // \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; } - double GetRadiusB() const { return b; } - void SetLimitPoint( ptrdiff_t number, const MbCartPoint3D & ); // \ru Заменить точку отрезка \en Replace a point of the segment - 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 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. - bool IsCircle( double eps = Math::metricRegion ) const; + 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. - inline double CheckParam( double & t ) const; - 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 + 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. @@ -418,10 +423,11 @@ public : virtual bool GetPlacement( MbPlacement3D & place, PlanarCheckParams params = PlanarCheckParams() ) const; const MbPlacement3D & GetPlacement() const { return position; } - MbPlacement3D & SetPlacement() { return position; } - void SetPlacement( const MbPlacement3D & pl ) { position = pl; } - virtual void GetCentre( MbCartPoint3D & wc ) const; - virtual void GetWeightCentre( MbCartPoint3D & wc ) const; + MbPlacement3D & SetPlacement() { return position; } + void SetPlacement( const MbPlacement3D & pl ) { position = pl; } + + virtual void GetCentre( MbCartPoint3D & ) const; + virtual void GetWeightCentre( MbCartPoint3D & ) const; bool Normalize(); ///< \ru Ортонормировать локальную систему координат. \en Orthonormalize the local coordinate system. bool IsPositionNormal() const { return ( !position.IsAffine() ); } @@ -431,7 +437,7 @@ public : 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. @@ -444,7 +450,8 @@ IMPL_PERSISTENT_OPS( MbArc3D ) //------------------------------------------------------------------------------ // \ru Установить параметр в область допустимых значений \en Set the parameter into the region of the legal values // --- -inline double MbArc3D::CheckParam( double & t ) const +inline +double MbArc3D::CheckParam( double & t ) const { double tMax = trim2 - trim1; if ( (t < 0.0) || (t > tMax) ) { @@ -468,7 +475,8 @@ inline double MbArc3D::CheckParam( double & t ) const //------------------------------------------------------------------------------ // \ru Перевод параметра кривой в угол \en Convert parameter of curve to the angle // --- -inline void MbArc3D::ParamToAngle( double & t ) const +inline +void MbArc3D::ParamToAngle( double & t ) const { if ( ::fabs(trim1) > NULL_EPSILON ) { t = trim1 + t; @@ -481,11 +489,12 @@ inline void MbArc3D::ParamToAngle( double & t ) const //------------------------------------------------------------------------------ // \ru Перевод угла кривой в параметр кривой \en Convert an angle of curve to a parameter of curve // --- -inline void MbArc3D::AngleToParam( double & t ) const +inline +void MbArc3D::AngleToParam( double & t ) const { if ( ::fabs(trim1) > NULL_EPSILON ) { double dtr = ( trim2 + trim1 - M_PI2 ) * 0.5; - t -= ::floor( (t - dtr) * Math::invPI2 ) * M_PI2; + t -= ::floor( (t - dtr) * Math::invPI2 ) * M_PI2; // SKIP_SA t = t - trim1; } } diff --git a/C3d/Include/cur_bezier.h b/C3d/Include/cur_bezier.h index 04e1d93..0620e3d 100644 --- a/C3d/Include/cur_bezier.h +++ b/C3d/Include/cur_bezier.h @@ -53,7 +53,8 @@ public : \details \ru Конструктор по массиву всех точек(полюсов и коромысел), для создания из трехмерной кривой MbBezier3D. \en Constructor by array of all points(poles and rockers), - for creation from three-dimensional curve MbBezier3D. \~ + for creation from three-dimensional curve MbBezier3D. \~ + \deprecated \ru Метод устарел. \en The method is deprecated. \~ \param[in] closed - \ru Замкнута ли кривая. \en Is curve closed? \~ \param[in] points - \ru Массив точек. @@ -70,6 +71,7 @@ public : \en Constructor by poles. \~ \details \ru Конструктор по полюсам. В массиве initList заданы только полюса. \en Constructor by poles. initList array contains only poles. \~ + \deprecated \ru Метод устарел. \en The method is deprecated. \~ \param[in] initList - \ru Массив полюсов кривой. Минимальное количество точек в массиве равно двум. \en An array of curve poles. diff --git a/C3d/Include/cur_bridge3d.h b/C3d/Include/cur_bridge3d.h index a3db18c..6b178f6 100644 --- a/C3d/Include/cur_bridge3d.h +++ b/C3d/Include/cur_bridge3d.h @@ -68,7 +68,7 @@ public: virtual MbeSpaceType IsA() const; // \ru Тип элемента \en A type of element virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента \en Create a copy of the element - virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Является ли объект копией \en Whether the object is a copy + virtual bool IsSame ( const MbSpaceItem &, double accuracy = LENGTH_EPSILON ) const; // \ru Является ли объект копией \en Whether the object is a copy virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равным \en Make equal virtual bool IsSimilar( const MbSpaceItem & init ) const; // \ru Сделать элементы равными \en Make the elements equal virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix @@ -104,7 +104,7 @@ public: virtual MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & ) const; virtual MbCurve3D * NurbsCurve( const MbNurbsParameters & ) const; // \ru Построить NURBS-копию кривой \en Create a NURBS-copy of the curve - const MbCube & GetGabarit() const; // \ru Выдать габарит кривой \en Get the bounding box of a curve + const MbCube & GetGabarit() const; ///< \ru Выдать габарит кривой. \en Get the bounding box of a curve. private: inline void CheckParam ( double & t ) const; // \ru Проверка параметра \en Check parameter @@ -118,25 +118,33 @@ private: IMPL_PERSISTENT_OPS( MbBridgeCurve3D ) + //------------------------------------------------------------------------------ /// \ru Проверка параметра. \en Check parameter. // --- -inline void MbBridgeCurve3D::CheckParam( double & t ) const { +inline +void MbBridgeCurve3D::CheckParam( double & t ) const +{ if ( t < tmin ) t = tmin; - else - if ( t > tmax ) - t = tmax; + else if ( t > tmax ) + t = tmax; } //------------------------------------------------------------------------------ /// \ru Определение необходимых локальных параметров. \en Determination of the necessary local parameters. // --- -inline void MbBridgeCurve3D::LocalParams( const double & t, double & quota1, double & quota2 ) const { - double paramW = 1 / ( tmax - tmin ); - quota1 = ( tmax - t ) * paramW; - quota2 = ( t - tmin ) * paramW; +inline +void MbBridgeCurve3D::LocalParams( const double & t, double & quota1, double & quota2 ) const +{ + double paramW = 1.0; + C3D_ASSERT( tmax > tmin ); + if ( tmax > tmin ) + paramW = 1.0 / (tmax - tmin); + + quota1 = (tmax - t) * paramW; + quota2 = (t - tmin) * paramW; } diff --git a/C3d/Include/cur_contour.h b/C3d/Include/cur_contour.h index abeef2f..76dc249 100644 --- a/C3d/Include/cur_contour.h +++ b/C3d/Include/cur_contour.h @@ -690,7 +690,7 @@ MbContour::MbContour( const Curves & initCurves, bool same ) SPtr segment; for ( size_t i = 0; i < count; ++i ) { segment = same ? &const_cast( *initCurves[i] ) : &static_cast( initCurves[i]->Duplicate() ); - SegmentsAdd( *segment ); + SegmentsAdd( *segment, false ); } CalculateGabarit( rect ); // посчитать габарит diff --git a/C3d/Include/cur_contour_on_surface.h b/C3d/Include/cur_contour_on_surface.h index bf11c49..20f35d5 100644 --- a/C3d/Include/cur_contour_on_surface.h +++ b/C3d/Include/cur_contour_on_surface.h @@ -25,6 +25,20 @@ class MbCurveIntoNurbsInfo; class MbSegmentsSearchTree; +class MATH_CLASS MbContourOnSurface; +namespace c3d // namespace C3D +{ +typedef SPtr ContourOnSurfaceSPtr; +typedef SPtr ConstContourOnSurfaceSPtr; + +typedef std::vector ContourOnSurfaceVector; +typedef std::vector ConstContourOnSurfaceVector; + +typedef std::vector ContourOnSurfaceSPtrVector; +typedef std::vector ConstContourOnSurfaceSPtrVector; +} + + //------------------------------------------------------------------------------ /** \brief \ru Контур на поверхности. \en Contour on surface. \~ @@ -182,6 +196,9 @@ public : virtual MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = c3d_null, VERSION version = Math::DefaultMathVersion(), bool * coincParams = c3d_null ) const; // \ru Дать плоскую проекцию кривой. \en Get a planar projection of curve. + /// \ru Получить границы участков кривой, которые описываются одной аналитической функцией. + /// \en Get the boundaries of the curve sections that are described by one analytical function. \~ + virtual void GetAnalyticalFunctionsBounds( std::vector & params ) const; /// \ru Найти все особые точки функции кривизны кривой. /// \en Find all the special points of the curvature function of the curve. virtual void GetCurvatureSpecialPoints( std::vector & points ) const; diff --git a/C3d/Include/cur_nurbs.h b/C3d/Include/cur_nurbs.h index 524e4e8..1070501 100644 --- a/C3d/Include/cur_nurbs.h +++ b/C3d/Include/cur_nurbs.h @@ -100,7 +100,7 @@ private: mutable CacheManager cache; public://protected: - DEPRECATE_DECLARE MbNurbs(); + DEPRECATE_DECLARE MbNurbs(); ///< \deprecated \ru Метод устарел. \en The method is deprecated. protected: /** \brief \ru Конструктор. \en Constructor. \~ @@ -1072,7 +1072,8 @@ MbNurbs::MbNurbs( size_t initDegree, bool initClosed, const PointsVector & initP //------------------------------------------------------------------------------ // \ru Добавить точку в конец массива. \en Add point to the end of the array. // --- -inline void MbNurbs::AddPoint( const MbCartPoint & pnt, double weight ) +inline +void MbNurbs::AddPoint( const MbCartPoint & pnt, double weight ) { pointList.push_back( pnt ); weights.push_back( weight ); @@ -1107,6 +1108,7 @@ bool IsStraightNurbs( const Nurbs & nurbs, double mEps = METRIC_EPSILON ) isStraight = false; std::vector pnts; pnts.reserve( nurbs.GetPointsCount() ); + nurbs.GetPointList( pnts ); if ( c3d::ArePointsOnLine( pnts, mEps ) ) isStraight = true; } diff --git a/C3d/Include/cur_plane_curve.h b/C3d/Include/cur_plane_curve.h index c5b1632..8e72100 100644 --- a/C3d/Include/cur_plane_curve.h +++ b/C3d/Include/cur_plane_curve.h @@ -14,6 +14,7 @@ #include #include #include +#include class MATH_CLASS MbContour; @@ -38,6 +39,8 @@ protected : MbPlacement3D position; ///< \ru Локальная система координат, в плоскости XY которой расположена кривая. \en The local coordinate system in XY plane of which the curve is located. MbCurve * curve; ///< \ru Двумерная кривая (не может быть c3d_null). \en A two-dimensional uv-curve (can not be c3d_null). + mutable MbCube cube; ///< \ru Габаритный куб. \en Bounding box. + public : /// \ru same = false - копировать кривую init. \en Same = false - copy the curve "init". MbPlaneCurve( const MbPlacement3D &, const MbCurve & init, bool same ); @@ -137,6 +140,7 @@ public : virtual size_t GetCount () const; virtual void GetPointsByEvenLengthDelta( size_t n, std::vector & pnts ) const; // \ru Выдать n точек кривой с равными интервалами по длине дуги \en Get n points of curves equally spaced by the arc length + virtual void AddYourGabaritTo( MbCube & ) const; // \ru Добавить габарит кривой в куб. \en Add a bounding box of a curve to a cube. virtual void CalculateGabarit( MbCube & ) const; // \ru Вычислить габарит кривой \en Calculate the bounding box of curve virtual void CalculateLocalGabarit( const MbMatrix3D &, MbCube & ) const; // \ru Рассчитать габарит относительно л.с.к. \en Calculate bounding box relative to the local coordinate system. diff --git a/C3d/Include/cur_polycurve.h b/C3d/Include/cur_polycurve.h index e267ea7..079524b 100644 --- a/C3d/Include/cur_polycurve.h +++ b/C3d/Include/cur_polycurve.h @@ -53,7 +53,7 @@ public : virtual MbePlaneType IsA() const = 0; // \ru Тип элемента \en Type of element virtual MbePlaneType Type() const; // \ru Тип элемента \en Type of element virtual bool SetEqual( const MbPlaneItem & ) = 0; // \ru Сделать элементы равными \en Make the elements equal - virtual bool IsSame( const MbPlaneItem & other, double accuracy = LENGTH_EPSILON ) const = 0; // \ru Является ли кривая curve копией данной кривой ? \en Whether curve 'curve' is a duplicate of the current curve. + virtual bool IsSame( const MbPlaneItem & other, double accuracy = LENGTH_EPSILON ) const = 0; // \ru Является ли кривая curve копией данной кривой ? \en Whether curve 'curve' is a duplicate of the current curve. virtual void Transform( const MbMatrix & matr, MbRegTransform * ireg = c3d_null, const MbSurface * newSurface = c3d_null ) = 0; // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix virtual void Move( const MbVector & to, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ) = 0; // \ru Сдвиг \en Translation virtual void Rotate( const MbCartPoint & pnt, const MbDirection & angle, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ) = 0; // \ru Поворот \en Rotation @@ -133,7 +133,7 @@ public : */ virtual void GetPoint( ptrdiff_t index, MbCartPoint & pnt ) const; // \ru Выдать точку \en Get point - virtual ptrdiff_t GetNearPointIndex( const MbCartPoint & pnt ) const; ///< \ru Выдать индекс точки, ближайшей к заданной. \en Get index of the point nearest to the given one. + virtual ptrdiff_t GetNearPointIndex( const MbCartPoint & pnt ) const; ///< \ru Выдать индекс точки, ближайшей к заданной. \en Get index of the point nearest to the given one. /** \brief \ru Вернуть интервал влияния точки кривой. \en Get the range of influence of point of the curve. \~ diff --git a/C3d/Include/cur_surface_intersection.h b/C3d/Include/cur_surface_intersection.h index 96cd261..4b4181b 100644 --- a/C3d/Include/cur_surface_intersection.h +++ b/C3d/Include/cur_surface_intersection.h @@ -650,7 +650,9 @@ public: /// \ru Вычислить точки изменения выпуклости-вогнутости кривой пересечения. \en Calculate points of changing the convexity-concavity of intersection curve. MbeNewtonResult ConvexoConcaveNewton( size_t iterLimit, double & t ) const; /// \ru Определить наличие точек изменения выпуклости-вогнутости. \en Determine existence of points of changing the convexity-concavity. - bool IsConvexoConcave( SArray & params ) const; + bool IsConvexoConcave( SArray & ) const; + /// \ru Определить наличие точек изменения выпуклости-вогнутости. \en Determine existence of points of changing the convexity-concavity. + bool IsConvexoConcave( c3d::DoubleVector & ) const; /// \ru Построить участок пространственной копии кривой. \en Construct a piece of a spatial curve copy. MbCurve3D * MakeCurve( double t1, double t2 ) const; @@ -694,13 +696,9 @@ private: MbCartPoint & pointTwo, MbVector & firstTwo, MbVector & secondTwo, MbCartPoint3D & pnt1, MbVector3D & uDer1, MbVector3D & vDer1, MbVector3D & uuDer1, MbVector3D & vvDer1, MbVector3D & uvDer1, MbVector3D & nor1, MbCartPoint3D & pnt2, MbVector3D & uDer2, MbVector3D & vDer2, MbVector3D & uuDer2, MbVector3D & vvDer2, MbVector3D & uvDer2, MbVector3D & nor2 ) const; - /// \ru Вычислить точку. \en Calculate a point. - void CalculatePointOn( double t, MbCartPoint3D & ) const; - /// \ru Вычислить первую производную. \en Calculate the first derivative. - void CalculateFirstDer( double t, MbVector3D & ) const; /// \ru Вычислить значения точки и производных. \en Calculate the point and the first derivative. - void CalculateExplore( double t, MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const; - // \ru Вычислить толерантность кривой. \en Calculate tolerance of the curve. + void SpecificExplore( double t, MbCartPoint3D & pnt, MbVector3D * fir, MbVector3D * sec, MbVector3D * thir ) const; + // \ru Вычислить толерантность кривой. \en Calculate tolerance of the curve. void CalculateTolerance() const; // \ru Создать пространственную кривую по проекционной кривой. \en Create a spatial curve from a projection curve. bool TryProjection() const; diff --git a/C3d/Include/curve3d.h b/C3d/Include/curve3d.h index e4266a0..0fadcd7 100644 --- a/C3d/Include/curve3d.h +++ b/C3d/Include/curve3d.h @@ -602,7 +602,7 @@ public : */ virtual void CalculatePolygon( const MbStepData & stepData, MbPolygon3D & polygon ) const; // \ru Рассчитать полигон. \en Calculate a polygon. - DEPRECATE_DECLARE void CalculatePolygon( double, MbPolygon3D & ) const; // The method deprecated. It will be removed at 2018. Use CalculatePolygon( MbStepData(ist_SpaceStep,sag), poligon ); \~ + DEPRECATE_DECLARE void CalculatePolygon( double, MbPolygon3D & ) const; ///< \deprecated \ru Метод устарел и будет удален в 2018г. Используйте CalculatePolygon( MbStepData(ist_SpaceStep,sag), poligon ); \en The method deprecated. It will be removed at 2018. Use CalculatePolygon( MbStepData(ist_SpaceStep,sag), poligon ); \~ /// \ru Выдать центр кривой. \en Give the curve center. virtual void GetCentre ( MbCartPoint3D & ) const; @@ -981,12 +981,69 @@ public : /// \ru Преобразовать параметр кривой в параметр подложки. \en Transform a curve parameter to the substrate parameter. virtual void CurveToSubstrate( double & ) const; - /// \ru Дать плоскую кривую и плейсмент, если пространственная кривая плоская (после использования вызывать DeleteItem на двумерную кривую). \en Get planar curve and placement if the space curve is planar (after the using call DeleteItem for two-dimensional curves) + /** \brief \ru Дать плоскую кривую и плейсмент, если пространственная кривая плоская. + \en Get planar curve and placement if the space curve is planar. \~ + \details \ru Дать плоскую кривую и плейсмент, если пространственная кривая плоская (после использования вызывать DeleteItem на двумерную кривую). + \en Get planar curve and placement if the space curve is planar (after the using call DeleteItem for two-dimensional curves). \~ + \param[out] curve2d - \ru Полученная плоская кривая. + \en The resulting flat curve. \~ + \param[out] place - \ru Система координат полученной двумерной кривой. + \en The coordinate system of the resulting 2D curve. \~ + \param[in] saveParams - \ru Параметр, задающий сохранение соответствия параметризации у двумерной кривой. + Если true - параметризация кривой curve2d должна соответствовать параметризациии исходной кривой this. + Если false - параметризации кривых могут не соответствовать. Кривая curve2d может быть найдена с больший вероятностью, чем если бы saveParams = true. + \en The parameter specifying the preservation of the correspondence of the parameterization for the two-dimensional curve. + If true - parameterization of curve2d curve must match the parameterization of the original curve this. + If false - curve parameterizations may not correspond. The curve2d is more likely to be detected than with the true flag. \~ + \param[in] params - \ru Параметры проверки. + \en Validation parameters. \~ + \return \ru true, если создана плоская кривая. + \en true if a flat curve was created. \~ + */ virtual bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place, bool saveParams, PlanarCheckParams params = PlanarCheckParams() ) const; - /// \ru Дать плоскую кривую и плейсмент, если пространственная кривая плоская (после использования вызывать DeleteItem на двумерную кривую). \en Get planar curve and placement if the space curve is planar (after the using call DeleteItem for two-dimensional curves) + + /** \brief \ru Дать плоскую кривую и плейсмент, если пространственная кривая плоская. + \en Get planar curve and placement if the space curve is planar. \~ + \details \ru Дать плоскую кривую и плейсмент, если пространственная кривая плоская (после использования вызывать DeleteItem на двумерную кривую). + \en Get planar curve and placement if the space curve is planar (after the using call DeleteItem for two-dimensional curves). \~ + \param[out] curve2d - \ru Полученная плоская кривая. + \en The resulting flat curve. \~ + \param[out] place - \ru Система координат полученной двумерной кривой. + \en The coordinate system of the resulting 2D curve. \~ + \param[in] saveParams - \ru Параметр, задающий сохранение соответствия параметризации у двумерной кривой. + Если true - параметризация кривой curve2d должна соответствовать параметризациии исходной кривой this. + Если false - параметризации кривых могут не соответствовать. Кривая curve2d может быть найдена с больший вероятностью, чем если бы saveParams = true. + \en The parameter specifying the preservation of the correspondence of the parameterization for the two-dimensional curve. + If true - parameterization of curve2d curve must match the parameterization of the original curve this. + If false - curve parameterizations may not correspond. The curve2d is more likely to be detected than with the true flag. \~ + \param[in] params - \ru Параметры проверки. + \en Validation parameters. \~ + \return \ru true, если создана плоская кривая. + \en true if a flat curve was created. \~ + */ bool GetPlaneCurve( SPtr & curve2d, MbPlacement3D & place, bool saveParams, PlanarCheckParams params = PlanarCheckParams() ) const; - /// \ru Дать плоскую кривую и плейсмент, если пространственная кривая плоская (после использования вызывать DeleteItem на двумерную кривую). \en Get planar curve and placement if the space curve is planar (after the using call DeleteItem for two-dimensional curves) + + /** \brief \ru Дать плоскую кривую и плейсмент, если пространственная кривая плоская. + \en Get planar curve and placement if the space curve is planar. \~ + \details \ru Дать плоскую кривую и плейсмент, если пространственная кривая плоская (после использования вызывать DeleteItem на двумерную кривую). + \en Get planar curve and placement if the space curve is planar (after the using call DeleteItem for two-dimensional curves). \~ + \param[out] curve2d - \ru Полученная плоская кривая. + \en The resulting flat curve. \~ + \param[out] place - \ru Система координат полученной двумерной кривой. + \en The coordinate system of the resulting 2D curve. \~ + \param[in] saveParams - \ru Параметр, задающий сохранение соответствия параметризации у двумерной кривой. + Если true - параметризация кривой curve2d должна соответствовать параметризациии исходной кривой this. + Если false - параметризации кривых могут не соответствовать. Кривая curve2d может быть найдена с больший вероятностью, чем если бы saveParams = true. + \en The parameter specifying the preservation of the correspondence of the parameterization for the two-dimensional curve. + If true - parameterization of curve2d curve must match the parameterization of the original curve this. + If false - curve parameterizations may not correspond. The curve2d is more likely to be detected than with the true flag. \~ + \param[in] params - \ru Параметры проверки. + \en Validation parameters. \~ + \return \ru true, если создана плоская кривая. + \en true if a flat curve was created. \~ + */ 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) @@ -1133,7 +1190,7 @@ MATH_FUNC (MbeNewtonResult) CurveCrossNewton( const MbCurve3D & curve1, bool ext // --- MATH_FUNC (void) CalculatePolygon( const MbCurve3D & curve, const MbStepData & stepData, std::vector< std::pair > & paramPoints ); -DEPRECATE_DECLARE MATH_FUNC (void) CalculatePolygon( const MbCurve3D &, double, std::vector< std::pair > & ); // The method deprecated. It will be removed at 2018. Use ::CalculatePolygon( curve, MbStepData(ist_SpaceStep,sag), paramPoints ); \~ +DEPRECATE_DECLARE MATH_FUNC (void) CalculatePolygon( const MbCurve3D &, double, std::vector< std::pair > & ); ///< \deprecated \ru Метод устарел и будет удален в 2018г. Используйте CalculatePolygon( MbStepData(ist_SpaceStep,sag), poligon ); \en The method deprecated. It will be removed at 2018. Use ::CalculatePolygon( curve, MbStepData(ist_SpaceStep,sag), paramPoints ); #endif // __CURVE3D_H diff --git a/C3d/Include/func_cubic_function.h b/C3d/Include/func_cubic_function.h index b71a72b..2278fba 100644 --- a/C3d/Include/func_cubic_function.h +++ b/C3d/Include/func_cubic_function.h @@ -28,9 +28,9 @@ c3d_constexpr size_t FUNC_NUMB = 4; ///< \ru Количество элемент // --- class MATH_CLASS MbCubicFunction : public MbFunction { protected: - SArray valueList; ///< \ru Характерные точки. \en The control points. + 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 curve which is modeled by a cubic spline. + SArray tList; ///< \ru Значения параметров функции, которую моделирует кубический сплайн. \en The values of parameters on a function which is modeled by a cubic spline. bool closed; ///< \ru Признак замкнутости кривой. \en An attribute of curve closedness. ptrdiff_t uppIndex; ///< \ru Количество интервалов (число точек - 1). \en The number of intervals (a number of points - 1). @@ -113,13 +113,18 @@ public: // \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 GetValuesCount() const; // \ru Выдать количество опорных точек \en Get the number of control points + 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: - bool CalculateDerivatives(); // \ru Расчет производных. \en Calculation of derivatives 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; diff --git a/C3d/Include/func_cubic_spline_function.h b/C3d/Include/func_cubic_spline_function.h index 5294a29..d66ac73 100644 --- a/C3d/Include/func_cubic_spline_function.h +++ b/C3d/Include/func_cubic_spline_function.h @@ -96,14 +96,23 @@ public: virtual MbFunction * BreakFunction( double t, bool beg ); 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 + 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 + 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 CalcSecondDerives (); // \ru Расчет вторых производных \en Calculation of second derivatives - 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 + 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 diff --git a/C3d/Include/func_power_function.h b/C3d/Include/func_power_function.h index 3018514..41a6c87 100644 --- a/C3d/Include/func_power_function.h +++ b/C3d/Include/func_power_function.h @@ -89,6 +89,13 @@ public: virtual void SetLimitValue( size_t n, double newValue ); // \ru Установить значение на конце ( 1 - в начале, 2 - в конце) \en Set the value at the end (1 - at beginning, 2 - at ending) virtual double GetLimitValue( size_t n ) const; // \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. + private: void operator = ( const MbPowerFunction & ); // \ru Не реализовано \en Not implemented diff --git a/C3d/Include/func_sinus_function.h b/C3d/Include/func_sinus_function.h index 0bb33ef..d2994f6 100644 --- a/C3d/Include/func_sinus_function.h +++ b/C3d/Include/func_sinus_function.h @@ -89,6 +89,11 @@ public: virtual void SetLimitValue( size_t n, double newValue ); // \ru Установить значение на конце ( 1 - в начале, 2 - в конце) \en Set the value at the end (1 - at beginning, 2 - at ending) virtual double GetLimitValue( size_t n ) const; // \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. + private: void operator = ( const MbSinusFunction & ); // \ru Не реализовано \en Not implemented diff --git a/C3d/Include/function.h b/C3d/Include/function.h index a92065c..942d1d7 100644 --- a/C3d/Include/function.h +++ b/C3d/Include/function.h @@ -34,17 +34,18 @@ enum MbeFunctionType { ft_Undefined = 0, ///< \ru Неизвестный объект. \en Unknown object. ft_Function = 1, ///< \ru Функция. \en A function. - ft_ConstFunction = 2, ///< \ru Постоянная функция. \en A constant function. - ft_LineFunction = 3, ///< \ru Линейная функция. \en A linear function. - ft_CubicFunction = 4, ///< \ru Кубическая функция Эрмита. \en A cubic Hermite function. - ft_CubicSplineFunction = 5, ///< \ru Кубическая сплайновая функция. \en A cubic spline function. + ft_ConstFunction = 2, ///< \ru Постоянная функция. \en Constant function. + ft_LineFunction = 3, ///< \ru Линейная функция. \en Linear function. + ft_CubicFunction = 4, ///< \ru Кубическая функция Эрмита. \en Cubic Hermite function. + ft_CubicSplineFunction = 5, ///< \ru Кубическая сплайновая функция. \en Cubic spline function. ft_PowerFunction = 6, ///< \ru Степенная функция. \en Power function. ft_SinusFunction = 7, ///< \ru Синусоидальная функция. \en Sinusoidal function. ft_ServeFunction = 8, ///< \ru Служебная функция. \en Service function. - ft_C2MonoSplineFunction= 9, ///< \ru Кубическая сплайновая функция. \en A cubic spline function. + ft_MonoSmoothFunction = 9, ///< \ru Монотонная функция. \en Monotonous function. + ft_NurbsFunction = 10, ///< \ru NURBS функция. \en NURBS function. - ft_CharacterFunction = 101, ///< \ru Символьная функция. \en A symbolic function. - ft_AnalyticalFunction = 102, ///< \ru Символьная функция на модельном выражении. \en A symbolic function in model expression. + ft_CharacterFunction = 101, ///< \ru Символьная функция. \en Symbolic function. + ft_AnalyticalFunction = 102, ///< \ru Символьная функция на модельном выражении. \en Symbolic function in model expression. ft_FreeItem = 600, ///< \ru Тип для объектов, созданных пользователем. \en Type for the user-defined objects. @@ -170,10 +171,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 ); - - /// \ru Наличие полюса функции. \en Existence of a function pole. - virtual bool IsPole( double t ) const; + bool CuttingFunction( SArray & params, bool beginSafe, double eps, RPArray & cutted ); /// \ru Сместить функцию. \en Shift a function. virtual void SetOffsetFunc( double distOld, double distNew ) = 0; /// \ru Установить область изменения параметра. \en Set the range of parameter. @@ -192,6 +190,10 @@ public: virtual void GetCharacteristicParams( std::vector & tSpecific, double t1, double t2 ); /** \} */ + + /// \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. /// \ru Вернуть середину параметрического диапазона. \en Return the middle of parametric range. double GetTMid() const { return ((GetTMin() + GetTMax()) * 0.5); } /// \ru Параметрическая длина. \en The parametric length. diff --git a/C3d/Include/gce_api.h b/C3d/Include/gce_api.h index 33d1e7a..cd06293 100644 --- a/C3d/Include/gce_api.h +++ b/C3d/Include/gce_api.h @@ -1362,9 +1362,8 @@ GCE_FUNC(constraint_item) GCE_AddPerpendicular( GCE_system gSys, geom_item g[2] lObj - \en Descriptor of the axis of symmetry. \~ \return \ru Дескриптор нового ограничения. \en Descriptor of a new constraint. \~ - - \attention \ru В настоящий момент данное ограничение применимо только для симметрии точек. - \en Currently, this restriction only applies to the symmetry of the points. \~ + \details \ru Ограничение применимо для симметрии любых геометрических объектов, определённых в типе #geom_type. + \en The constraint applies to symmetry of any geometric objects defined in #geom_type enum. \~ */ //--- GCE_FUNC(constraint_item) GCE_AddSymmetry( GCE_system gSys, geom_item g[2], geom_item lObj ); diff --git a/C3d/Include/gcm_manager.h b/C3d/Include/gcm_manager.h index a7c3f59..1d2d0d9 100644 --- a/C3d/Include/gcm_manager.h +++ b/C3d/Include/gcm_manager.h @@ -277,7 +277,7 @@ public: private: SPtr m_geom; // Geometric object of the constraint system (often, it is a rigid body) - MtGeomVariant m_refGeom; // Geometric object given in the m_geom's LCS. + MtGeomVariant m_refGeom; // Geometric object given in the vNode's LCS. }; //---------------------------------------------------------------------------------------- @@ -653,7 +653,7 @@ private: //---------------------------------------------------------------------------------------- /** \brief \ru Создать пустую систему ограничений. - \en Create a simple constraint system. \~ + \en Create an empty constraint system. \~ \details \ru Вызов создает пустую систему ограничений. Кроме того, в памяти создаются внутренние структуры данных геометрического решателя, обслуживающего систему ограничений. Функция возвращает специальный дескриптор, по которому @@ -673,6 +673,13 @@ private: //--- GCM_FUNC(GCM_system) GCM_CreateSystem( ItPositionManager * ); +//---------------------------------------------------------------------------------------- +/** \brief \ru Выдать решатель для данной системы геометрических ограничений. + \en Get the solver of the given geometric constraint system. +*/ +//--- +GCM_FUNC(SPtr) GCM_GetSolver( GCM_system gSys ); + /** \} */ //---------------------------------------------------------------------------------------- diff --git a/C3d/Include/gcm_types.h b/C3d/Include/gcm_types.h index f0ff680..893a17f 100644 --- a/C3d/Include/gcm_types.h +++ b/C3d/Include/gcm_types.h @@ -129,7 +129,6 @@ typedef enum /* (!) Do not change the constants (they are written to file permanently). */ - GCM_MIN_ALIGNMENT= -1, // Minimum value of this enum GCM_OPPOSITE = -1, ///< \ru Противонаправленные. \en Anti-align the directions. \~ GCM_CLOSEST = 0, ///< \ru Ориентация согласно ближайшего решения. \en Orientation according to the nearest solution. \~ GCM_COORIENTED = 1, ///< \ru Сонаправленные. \en Cooriented directions. \~ @@ -146,14 +145,14 @@ typedef enum GCM_REVERSE_2 = 7, GCM_REVERSE_3 = 8, /* - Additional variants of alignment (they are used for patterns and symmetry) + Additional variants of alignment (they are used for patterns and symmetry). */ GCM_ALIGNED = 1, ///< \ru ЛСК с одинаковой ориентацией. \en Axis aligned local coordinate systems. \~ GCM_ROTATED = 9, ///< Ротационное (вращательной) выравнивание элементов паттерна. GCM_ALIGN_WITH_AXIAL_GEOM = 10, ///< Выровнять с объектом, задающим ось. - GCM_MAX_ALIGNMENT, // Maximum value of this enum - + GCM_MAX_ALIGNMENT, // Maximum value of this enum + GCM_MIN_ALIGNMENT= -1, // Minimum value of this enum } GCM_alignment; //---------------------------------------------------------------------------------------- diff --git a/C3d/Include/generic_utility.h b/C3d/Include/generic_utility.h index 14b83d0..aaf410e 100644 --- a/C3d/Include/generic_utility.h +++ b/C3d/Include/generic_utility.h @@ -43,13 +43,13 @@ struct index_tag //---------------------------------------------------------------------------------------- /// \ru Цветовая маркировка (применяется для графов) \en Color marking (used for graphs) //--- -enum color_code -{ - white_color=0 - , black_color=1 - , red_color=2 - , gray_color - , green_color +enum color_code +{ + white_color = 0 + , gray_color = 1 + , green_color = 2 + , black_color = 3 + , red_color , orange_color , visited_color }; @@ -104,49 +104,6 @@ struct graph_traits typedef typename Graph::edge_iterator edge_iterator; // Итератор обхода исходящих ребер [или неориентированных ребер] }; -//---------------------------------------------------------------------------------------- -/// \ru Пара ссылок. \en A pair of references. -//--- -template -struct ref_pair -{ - _Ty1 & first; - _Ty2 & second; - - ref_pair( _Ty1 & val1, _Ty2 & val2 ) - : first(val1), second(val2) - {} - ref_pair( const ref_pair & other ) - : first(other.first), second(other.second) - {} - - template - ref_pair( const std::pair<_Other1, _Other2> & right ) - : first(right.first), second(right.second) - {} - - template - ref_pair & operator = ( const std::pair<_Other1, _Other2> & right ) - { - first = right.first; - second = right.second; - return *this; - } - -private: - ref_pair & operator = ( const ref_pair & ); // \ru не реализуемо \en not implemented -}; - -//---------------------------------------------------------------------------------------- -/// \ru Выдать ссылки одной связкой. \en Get references as one bunch. -//--- -template -inline ref_pair -tie( Type & iter1, Type & iter2 ) -{ - return ref_pair ( iter1, iter2 ); -} - //---------------------------------------------------------------------------------------- /// \ru Наибольшее из двух. \en Maximum of two. // --- @@ -386,6 +343,24 @@ public: return *this; } + /// \ru Равенство. \en Equality. + template + bool operator == ( const _Vector & vec ) const + { + if ( arrSize != vec.size() ) + { + return false; + } + for( size_t idx = 0; idx -struct _IterTraits { +struct _IterTraits +{ typedef typename Iterator::value_type value_type; }; template -struct _IterTraits { - typedef T value_type; -}; +struct _IterTraits { typedef T value_type; }; //---------------------------------------------------------------------------------------- // Диапазон итераторов @@ -1175,6 +1150,12 @@ range range_of( const _Cont & list ) range rng( list.begin(), list.end() ); return rng; } +template +range range_of( _Cont & list ) +{ + range rng( list.begin(), list.end() ); + return rng; +} //---------------------------------------------------------------------------------------- // Get a range of iterators @@ -1186,8 +1167,51 @@ range<_Iterator> make_range( _Iterator first, _Iterator last ) return rng; } +//---------------------------------------------------------------------------------------- +/// \ru Пара ссылок. \en A pair of references. +//--- +template +struct ref_pair +{ + _Ty1 & first; + _Ty2 & second; + + ref_pair( _Ty1 & val1, _Ty2 & val2 ) + : first(val1), second(val2) + {} + ref_pair( const ref_pair & other ) + : first(other.first), second(other.second) + {} + + template + ref_pair( const std::pair<_Other1, _Other2> & right ) + : first(right.first), second(right.second) + {} + + template + ref_pair & operator = ( const std::pair<_Other1, _Other2> & right ) + { + first = right.first; + second = right.second; + return *this; + } + +private: + ref_pair & operator = ( const ref_pair & ); // \ru не реализуемо \en not implemented }; +//---------------------------------------------------------------------------------------- +/// \ru Выдать ссылки одной связкой. \en Get references as one bunch. +//--- +template +inline ref_pair +tie( Type1 & iter1, Type2 & iter2 ) +{ + return ref_pair ( iter1, iter2 ); +} + +}; // namespace c3d + #endif // __GENERIC_UTILITY_H // eof diff --git a/C3d/Include/graph_algorithms.h b/C3d/Include/graph_algorithms.h index df80c0c..6e2d11d 100644 --- a/C3d/Include/graph_algorithms.h +++ b/C3d/Include/graph_algorithms.h @@ -26,7 +26,7 @@ template struct DefaultDFSVisitor { - typedef typename Graph::vertex_index vertex_index; + typedef typename Graph::vertex vertex; /// Встретили "обратное" ребро (дуга, если орграф) dfs-дерева. /** @@ -34,26 +34,26 @@ struct DefaultDFSVisitor ранее посещенной вершине. Другими словами, вершина u является предком вершине v в dfs-дереве. */ - void BackEdge( vertex_index /*v*/, vertex_index /*u*/, const Graph & /*g*/ ) {} + void BackEdge( vertex /*v*/, vertex /*u*/, const Graph & /*g*/ ) {} /// Вызывается, когда впервые проходим через исходящую дугу v->u, вершину u еще не посещали - void ExamineEdge( vertex_index /*v*/, vertex_index /*u*/, const Graph & /*g*/ ) {} + void ExamineEdge( vertex /*v*/, vertex /*u*/, const Graph & /*g*/ ) {} /// Посещение вершины: Вызывается один раз для каждой вершины, когда она впервые начинает просматриваться - void DiscoverNode( vertex_index /*v*/, const Graph & /*g*/ ) {} + void DiscoverNode( vertex /*v*/, const Graph & /*g*/ ) {} /// Вершина рассмотрена: Означает, что все исходящие ребра вершины рассмотрены - void FinishNode( vertex_index /*v*/, const Graph & /*g*/ ) {} + void FinishNode( vertex /*v*/, const Graph & /*g*/ ) {} /// Встретили "поперечное" или "прямое" ребро /** Вызывается, когда находим дугу, идущую к другому dfs-дереву, либо прямую дугу, идущую к потомку того же дерева, имеющему два и более отцов. Для поперечного ребра вызывается только для ориентированных графов. */ - void ForwardOrCrossEdge( vertex_index /*v*/, vertex_index /*u*/, const Graph & /*g*/ ) {} + void ForwardOrCrossEdge( vertex /*v*/, vertex /*u*/, const Graph & /*g*/ ) {} /// Отвечает, что вершина исключена из рассмотрения - bool Ignored( vertex_index /*v*/, const Graph & /*g*/ ) const { return false; } + bool Ignored( vertex /*v*/, const Graph & /*g*/ ) const { return false; } /// Означает, что начато рассмотрение корневой вершины будущего дерева обхода - void StartNode( vertex_index /*v*/, const Graph & /*g*/ ) {} + void StartNode( vertex /*v*/, const Graph & /*g*/ ) {} /// Ребро стало "древесным" (принадлежит dfs-дереву). Вызывается перед переходом от посещенной вершины v к еще не посещенной вершине u - void TreeEdge( vertex_index /*v*/, vertex_index /*u*/, const Graph & /*g*/ ) {} + void TreeEdge( vertex /*v*/, vertex /*u*/, const Graph & /*g*/ ) {} }; @@ -326,7 +326,7 @@ public: , m_iter() , m_last() { - tie(m_iter,m_last) = graph.AdjacentVertices( v ); + c3d::tie(m_iter,m_last) = graph.AdjacentVertices( v ); } DFSVertexInfo( const DFSVertexInfo & vi ) @@ -354,21 +354,12 @@ public: \param vis Посетитель алгоритма */ //--- - template void DepthFirstSearch( const Graph & graph, Visitor & vis ) { typedef typename Graph::vertices_size_t vertices_size_t; typedef typename Graph::vertex_index vertex_index; typedef typename Graph::adj_iterator adj_iterator; - /* - enum Color // Разметка - { - col_white // не посещалась - , col_gray // в стеке - , col_black // - }; - */ const vertices_size_t vCount = graph.NumVertices(); @@ -393,7 +384,8 @@ void DepthFirstSearch( const Graph & graph, Visitor & vis ) { colourMap[startNode] = gray_color; vis.StartNode( startNode, graph ); - vis.DiscoverNode( startNode, graph ); + + vis.DiscoverNode( startNode, graph ); stack.push_back( DFSVertexInfo(startNode,graph) ); while ( !stack.empty() ) @@ -421,7 +413,7 @@ void DepthFirstSearch( const Graph & graph, Visitor & vis ) colourMap[trgNode] = gray_color; stack.push_back( DFSVertexInfo( srcNode, vIter, vLast ) ); vis.DiscoverNode( srcNode = trgNode, graph ); - tie( vIter, vLast ) = graph.AdjacentVertices( srcNode ); + c3d::tie( vIter, vLast ) = graph.AdjacentVertices( srcNode ); break; } case gray_color: // Встетили обратное ребро @@ -445,6 +437,94 @@ void DepthFirstSearch( const Graph & graph, Visitor & vis ) } } +//---------------------------------------------------------------------------------------- +// Обход на фиксированную в глубину от стартовой вершины root с посещением вершин не однократно. +/* + DFS-функция изначально создавалась для поиска циклов, включающих до N вершин. Т.к. максимальная + глубина поиска известна, рекурсия раскрывается на этапе компиляции. + Если FinColor = white_color, то обход в глубину можно применять для выявления всех циклов + длиной до N, однако с неоднократным посещением каждой вершины. + Если FinColor = black_color, тогда получим классический обход на глубину не более N узлов + с однократным посещением узлов графа.. + +*/ +//--- +template +struct dfs_fixed_from_anode +{ + template + dfs_fixed_from_anode( const Graph & graph, Node root, ColorMap & colorMap, Visitor & vis ) + { + typename Graph::adjacency_iterator vIter, vLast; + colorMap[root] = gray_color; + vis.DiscoverNode( root, graph ); + c3d::tie( vIter, vLast ) = graph.AdjacentVertices( root ); + for ( ; vIter!=vLast; ++vIter ) + { + const color_code cVal = colorMap[*vIter]; + switch ( cVal ) + { + case white_color: + vis.ExamineEdge( root, *vIter, graph ); + dfs_fixed_from_anode( graph, *vIter, colorMap, vis ); + break; + case gray_color: + vis.BackEdge( root, *vIter, graph ); // The cycle is found. + break; + default: + break; + } + } + // black_color: set the color to avoid the visiting again. + // white_color: reset the color label to visit it again. + colorMap[root] = FinColor; + vis.FinishNode( root, graph ); + } +}; + +//---------------------------------------------------------------------------------------- +// Stop recursion +//--- +template +struct dfs_fixed_from_anode<0,FinColor> +{ + template + dfs_fixed_from_anode( const Graph &, Node, ColorMap &, Visitor & ) {} +}; + +//---------------------------------------------------------------------------------------- +// Обход всех маршрутов в графе длинной не более N (применяется для выявления циклов и не только..) +/* + В отличие от классического алгоритма DFS каждая вершина посещается не единожды. Однако мы + не ожидаем сильного замедления благодаря ограничению на глубину ветки обхода. +*/ +//--- +template +void dfs_fixed_depth( const Graph & graph, ColorMap & colorMap, Visitor & vis ) +{ + typedef typename Graph::vertex_iterator vertex_iterator; + typedef typename Graph::vertex vertex; + + vertex_iterator vIter, vLast; + // Пометить пропускаемые вершины + for ( c3d::tie(vIter,vLast) = graph.Vertices(); vIter!=vLast; ++vIter ) + { + if ( vis.Ignored(*vIter,graph) ) + { + colorMap[*vIter] = black_color; + } + } + // Обход всех циклов длиной N + for ( c3d::tie(vIter,vLast) = graph.Vertices(); vIter!=vLast; ++vIter ) + { + if ( colorMap[*vIter] == white_color ) + { + vis.StartNode( *vIter, graph ); + dfs_fixed_from_anode( graph, *vIter, colorMap, vis ); + colorMap[*vIter] = black_color; // the node is labeled as visited and will not be visited again. + } + } +} ////////////////////////////////////////////////////////////////////////////////////////// // @@ -786,12 +866,12 @@ void MtStrongComponents::operator() () vertex_iterator vIter, vLast; - for ( tie(vIter,vLast) = m_diGraph.Vertices(); vIter!=vLast; ++vIter ) + for ( c3d::tie(vIter,vLast) = m_diGraph.Vertices(); vIter!=vLast; ++vIter ) { num[*vIter] = 0; } - for ( tie(vIter,vLast) = m_diGraph.Vertices(); vIter!=vLast; ++vIter ) + for ( c3d::tie(vIter,vLast) = m_diGraph.Vertices(); vIter!=vLast; ++vIter ) { if ( num[*vIter] == 0 && !m_vis.IsFiltered(m_diGraph,*vIter) ) StrongSearch( *vIter, stack ); @@ -823,7 +903,7 @@ void MtStrongComponents::StrongSearch( vertex vx, std::vecto stack.push_back( vx ); edge_iterator eIter, eLast; // итераторы обхода инцидентных ребер - for ( tie(eIter,eLast) = m_diGraph.OutArcs(vx); eIter!=eLast; ++eIter ) + for ( c3d::tie(eIter,eLast) = m_diGraph.OutArcs(vx); eIter!=eLast; ++eIter ) { vertex w = m_diGraph.Target( *eIter ); // Выходящая вершина прямого ребра PRECONDITION( w != vx ); // Граф не ориентированный !!! @@ -884,7 +964,7 @@ struct DFS_element { typedef typename Graph::vertices_size_t vertices_size_t; typedef typename Graph::vertex vertex; - typedef typename Graph::edge_iterator edge_iterator; + typedef typename Graph::edge_iterator edge_iterator; vertex node; edge_iterator iter; @@ -901,7 +981,7 @@ struct DFS_element , iter() , last() { - tie( iter, last ) = graph.OutArcs( v ); + c3d::tie( iter, last ) = graph.OutArcs( v ); } DFS_element( const DFS_element & vi ) diff --git a/C3d/Include/hash32.h b/C3d/Include/hash32.h index fc3cfa1..085f41d 100644 --- a/C3d/Include/hash32.h +++ b/C3d/Include/hash32.h @@ -228,9 +228,9 @@ SimpleName Hash32( uint8 * k, size_t length, SimpleName _c = INIT_HASH32_VAL ) // handle most of the key while ( len >= 12 ) { - a += ((uint)k[0] + ((uint)k[1]<<8) + ((uint)k[2] <<16) + ((uint)k[3] <<24)); - b += ((uint)k[4] + ((uint)k[5]<<8) + ((uint)k[6] <<16) + ((uint)k[7] <<24)); //-V112 - c += ((uint)k[8] + ((uint)k[9]<<8) + ((uint)k[10]<<16) + ((uint)k[11]<<24)); + a += ((uint)k[0] + ((uint)k[1]<<8) + ((uint)k[2] <<16) + ((uint)k[3] <<24)); // SKIP_SA + b += ((uint)k[4] + ((uint)k[5]<<8) + ((uint)k[6] <<16) + ((uint)k[7] <<24)); // SKIP_SA + c += ((uint)k[8] + ((uint)k[9]<<8) + ((uint)k[10]<<16) + ((uint)k[11]<<24)); // SKIP_SA mix ( a, b, c ); k += 12; len -= 12; @@ -240,18 +240,18 @@ SimpleName Hash32( uint8 * k, size_t length, SimpleName _c = INIT_HASH32_VAL ) c += LoUint32( length ); // \ru Первый байт с резервируется для length \en The first byte c is reserved for 'length' switch ( len ) // \ru Случаи \en Cases { - case 11: c += ((uint)k[10]<<24); - case 10: c += ((uint)k[9] <<16); - case 9 : c += ((uint)k[8] <<8 ); + case 11: c += ((uint)k[10]<<24); // SKIP_SA + case 10: c += ((uint)k[9] <<16); // SKIP_SA + case 9 : c += ((uint)k[8] <<8 ); // SKIP_SA // \ru Первый байт с резервируется для length \en The first byte c is reserved for 'length' - case 8 : b += ((uint)k[7] <<24); - case 7 : b += ((uint)k[6] <<16); - case 6 : b += ((uint)k[5] <<8 ); - case 5 : b += ((uint)k[4]); //-V112 - case 4 : a += ((uint)k[3] <<24); - case 3 : a += ((uint)k[2] <<16); - case 2 : a += ((uint)k[1] <<8 ); - case 1 : a += ((uint)k[0]); + case 8 : b += ((uint)k[7] <<24); // SKIP_SA + case 7 : b += ((uint)k[6] <<16); // SKIP_SA + case 6 : b += ((uint)k[5] <<8 ); // SKIP_SA + case 5 : b += ((uint)k[4]); // SKIP_SA + case 4 : a += ((uint)k[3] <<24); // SKIP_SA + case 3 : a += ((uint)k[2] <<16); // SKIP_SA + case 2 : a += ((uint)k[1] <<8 ); // SKIP_SA + case 1 : a += ((uint)k[0]); // SKIP_SA // \ru case 0: Ничего не добавляем. \en case 0: Add nothing. } diff --git a/C3d/Include/io_tape.h b/C3d/Include/io_tape.h index 82dfe52..6837572 100644 --- a/C3d/Include/io_tape.h +++ b/C3d/Include/io_tape.h @@ -210,7 +210,7 @@ #include #include #include -//#include +#include #ifdef __DEBUG_MEMORY_ALLOCATE_FREE_ #include @@ -322,7 +322,11 @@ public: \ingroup Base_Tools_IO */ // --- +#ifndef ENABLE_MEMORY_LEAKS_CHECK class MATH_CLASS TapeBase { +#else +class MATH_CLASS TapeBase : virtual public c3d::MemoryLeaksVerifiable { +#endif private: mutable use_count_type m_countRegistrable; ///< \ru Счетчик ссылок регистрируемого объекта. \en Number of usages of the registrable object. @@ -590,9 +594,9 @@ public: /// \ru Деструктор. \en Destructor. virtual ~tape(); - /// \ru Получить доступ к буферу. \en Get access to the buffer. + /// \ru Получить доступ к буферу. \en Get access to the buffer. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE iobuf & buffer() const; - /// \ru Получить доступ к буферу. \en Get access to the buffer. + /// \ru Получить доступ к буферу. \en Get access to the buffer. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE iobuf & operator()() const; /// \ru Получить доступ к буферу. \en Get access to the buffer. @@ -670,7 +674,7 @@ public: void FinishProgress(); protected: - /// \ru Конструктор. \en Constructor. + /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE tape( membuf &, bool openSys, uint8 om, TapeRegistrator * , bool ownReg = false); /// \ru Конструктор. \en Constructor. @@ -701,17 +705,17 @@ protected: /// \ru Конструктор. \en Constructor. reader( iobuf_Seq & buf, bool ownbuf, bool openSys, uint16 om, TapeRegistrator * reg ); - /// \ru Конструктор. \en Constructor. + /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE reader( iobuf_Seq & buf, bool ownbuf, bool openSys, uint16 om, TapeRegistrator & reg ); - /// \ru Конструктор. \en Constructor. + /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE reader( membuf & sb, bool openSys, uint8 om, TapeRegistrator & reg ); public: - /// \ru Конструктор. \en Constructor. + /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE reader( membuf & sb, uint8 om ); - /// \ru Конструктор. \en Constructor. + /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE reader( iobuf_Seq & buf, uint16 om ); virtual ~reader() {} @@ -736,7 +740,7 @@ public: /// \ru Установить позицию чтения. \en Set reading position. virtual bool SetReadPosition ( ClusterReference & ) { return false; } // not supported - /// \ru Прочитать последовательность байт из буфера. \en Read a sequence of bytes from the buffer. + /// \ru Прочитать последовательность байт из буфера. \en Read a sequence of bytes from the buffer. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE size_t readSBytes ( void * bf, size_t len ); /// \ru Прочитать беззнаковое 64-разрядное целое \en Read unsigned 64-bit integer. @@ -824,10 +828,10 @@ protected: reader_ex( iobuf_Seq & buf, bool ownbuf, bool openSys, uint16 om ); public: - /// \ru Конструктор. \en Constructor. + /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE reader_ex( membuf & sb, uint8 om ); - /// \ru Конструктор. \en Constructor. + /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE reader_ex( iobuf_Seq & buf, uint16 om ); virtual ~reader_ex() {} @@ -891,15 +895,15 @@ public: protected: /// \ru Конструктор. \en Constructor. writer ( iobuf_Seq & buf, bool ownBuf, bool openSys, uint16 om, TapeRegistrator * reg ); - /// \ru Конструктор. \en Constructor. + /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE writer( iobuf_Seq & buf, bool ownBuf, bool openSys, uint16 om, TapeRegistrator & reg ); - /// \ru Конструктор. \en Constructor. + /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE writer ( membuf & sb, bool openSys, uint8 om, TapeRegistrator & reg ); public: - /// \ru Конструктор. \en Constructor. + /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE writer ( membuf & sb, uint8 om ); - /// \ru Конструктор. \en Constructor. + /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE writer ( iobuf_Seq & buf, uint16 om ); virtual ~writer() {} @@ -925,7 +929,7 @@ public: virtual void writeByte ( uint8 ch ); /// \ru Записать последовательность байт в буфер. \en Write the sequence of bytes to the buffer. virtual void writeBytes ( const void * bf, size_t len ); - /// \ru Записать последовательность байт в буфер. \en Write the sequence of bytes to the buffer. + /// \ru Записать последовательность байт в буфер. \en Write the sequence of bytes to the buffer. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE size_t writeSBytes( const void * bf, size_t len ); /// \ru Записать беззнаковое 64-разрядное целое. \en Write unsigned 64-bit integer. \~ \return \ru Возвращает количество записанных байт. \en Returns the number of written bytes. \~ void writeUInt64( const uint64 & val ); @@ -980,10 +984,10 @@ protected: writer_ex ( iobuf_Seq & buf, bool ownBuf, bool openSys, uint16 om ); public: - /// \ru Конструктор. \en Constructor. + /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE writer_ex ( membuf & sb, uint8 om ); - /// \ru Конструктор. \en Constructor. + /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE writer_ex ( iobuf_Seq & buf, uint16 om ); virtual ~writer_ex() {} @@ -1033,7 +1037,7 @@ class MATH_CLASS rw : public writer, public reader { public: typedef std_unique_ptr rw_ptr; public: - /// \ru Конструктор. \en Constructor. + /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE rw( membuf & sb, uint8 om ); /// \ru Создать читатель/писатель для буфера в памяти. \en Create reader/writer for membuf. @@ -1964,7 +1968,7 @@ inline uint16 hash( const char * name ) // If there are any remaining characters, // then XOR in the rest, using a mask: - if ( (i = uint16(l % sizeof(uint16))) != 0 ) + if ( (i = uint16(l % sizeof(uint16))) != 0 ) // SKIP_SA h ^= uint16(*c & 0xff); return h; diff --git a/C3d/Include/math_define.h b/C3d/Include/math_define.h index 6749456..bc49714 100644 --- a/C3d/Include/math_define.h +++ b/C3d/Include/math_define.h @@ -49,6 +49,8 @@ typedef std::pair DoubleIndicesPair; ///< \ru Чи typedef std::pair IndexBool; ///< \ru Пара номер-флаг. \en Index-double pair. typedef std::pair BoolIndex; ///< \ru Пара флаг-номер. \en Double-index pair. +typedef std::pair NumberBool; ///< \ru Пара номер-флаг. \en Index-double pair. +typedef std::pair BoolNumber; ///< \ru Пара флаг-номер. \en Double-index pair. typedef std::pair IndexDouble; ///< \ru Пара номер-число. \en Index-double pair. typedef std::pair DoubleIndex; ///< \ru Пара число-номер. \en Double-index pair. typedef std::pair FlagDouble; ///< \ru Пара флаг-число. \en Flag-double pair. @@ -95,7 +97,12 @@ typedef std::pair IndicesPairsPair; ///< \ru Па //------------------------------------------------------------------------------ -// +/** \brief \ru Проверка нулевого указателя. + \en Null pointer check . \~ + \details \ru Проверка нулевого указателя. \n + \en Null pointer check. \n \~ + \ingroup Base_Tools +*/ // --- template bool IsNullPointer( const ItemPtr * itemPtr ) { @@ -103,10 +110,15 @@ bool IsNullPointer( const ItemPtr * itemPtr ) { } //------------------------------------------------------------------------------ -// +/** \brief \ru Cортировка массива с удалением дубликатов. + \en Sorting an array with removing duplicates. \~ + \details \ru Cортировка массива с удалением дубликатов. \n + \en Sorting an array with removing duplicates. \n \~ + \ingroup Base_Tools +*/ // --- -template -void UniqueSortVector( Elements & items ) +template +void UniqueSortVector( ElementsVector & items ) { if ( items.size() > 1 ) { std::sort( items.begin(), items.end() ); @@ -114,15 +126,41 @@ void UniqueSortVector( Elements & items ) } } + //------------------------------------------------------------------------------ -// +/** \brief \ru Поиск элемента в не сортированном массиве. + \en Finding an element in a unsorted array. \~ + \details \ru Поиск элемента в не сортированном массиве. \n + \en Finding an element in a unsorted array. \n \~ + \ingroup Base_Tools +*/ // --- -template -size_t BinarySearch( Elements & items, const Element & item ) +template +size_t DirectSearch( const ElementsVector & items, const Element & item ) +{ + if ( items.size() > 0 ) { + typename ElementsVector::const_iterator it = std::find( items.begin(), items.end(), item ); + if ( it != items.end() ) + return std::distance( items.begin(), it ); + } + return SYS_MAX_T; +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Поиск элемента в сортированном массиве. + \en Finding an element in a sorted array. \~ + \details \ru Поиск элемента в сортированном массиве. \n + \en Finding an element in a sorted array. \n \~ + \ingroup Base_Tools +*/ +// --- +template +size_t BinarySearch( const ElementsVector & items, const Element & item ) { size_t ind = SYS_MAX_T; - typename Elements::iterator it = std::lower_bound( items.begin(), items.end(), item ); + typename ElementsVector::iterator it = std::lower_bound( items.begin(), items.end(), item ); if ( (it != items.end()) && !(item < *it) ) { ind = std::distance( items.begin(), it ); } @@ -206,7 +244,7 @@ size_t BinarySearch( Elements & items, const Element & item ) //------------------------------------------------------------------------------ // \ru Синтаксис дружественной шаблонной функции шаблона \en Syntax of friendly template function of a template -#if !(defined (_MSC_VER)) +#if !(defined (_MSC_VER)) || (_MSVC_PERMISSIVE_OFF) #define TEMPLATE_FRIEND friend // \ru по стандарту C++98 \en by the C++98 standard #define TEMPLATE_SUFFIX @@ -270,12 +308,13 @@ private: \ // \ru #pragma message( __TODO__ "Восстановить закрытый код" ) \en #pragma message( __TODO__ "Restore the private code" ) // \ru #pragma message( __WARN__ "Отсутствует проверка на c3d_null" ) \en #pragma message( __WARN__ "There is no check for c3d_null" ) //--- -#ifdef _MSC_VER // __TODO__ / __WARN__ - #define __ANYTOSTR__(x) #x #define __DEFTOSTR__(x) __ANYTOSTR__(x) -#define __TODO__ __FILE__ "("__DEFTOSTR__(__LINE__)") : TODO: " -#define __WARN__ __FILE__ "("__DEFTOSTR__(__LINE__)") : warning: " + +#ifdef _MSC_VER // __TODO__ / __WARN__ + +#define __TODO__ __FILE__ "(" __DEFTOSTR__(__LINE__) ") : TODO: " +#define __WARN__ __FILE__ "(" __DEFTOSTR__(__LINE__) ") : warning: " #else // _MSC_VER // For linux @@ -303,15 +342,15 @@ private: \ // --- // \ru Модуль геометрического моделирования. \en Geometric modeling module. #ifdef C3D_WINDOWS //_MSC_VER -#if defined ( _BUILDMATHDLL ) - #define MATH_CLASS __declspec( dllexport ) - #define MATH_FUNC(retType) __declspec( dllexport ) retType CALL_DECLARATION - #define MATH_FUNC_EX __declspec( dllexport ) // \ru для KNOWN_OBJECTS_RW_REF_OPERATORS_EX и KNOWN_OBJECTS_RW_PTR_OPERATORS_EX \en for KNOWN_OBJECTS_RW_REF_OPERATORS_EX and KNOWN_OBJECTS_RW_PTR_OPERATORS_EX -#else - #define MATH_CLASS __declspec( dllimport ) - #define MATH_FUNC(retType) __declspec( dllimport ) retType CALL_DECLARATION - #define MATH_FUNC_EX __declspec( dllimport ) -#endif + #if defined ( _BUILDMATHDLL ) + #define MATH_CLASS __declspec( dllexport ) + #define MATH_FUNC(retType) __declspec( dllexport ) retType CALL_DECLARATION + #define MATH_FUNC_EX __declspec( dllexport ) // \ru для KNOWN_OBJECTS_RW_REF_OPERATORS_EX и KNOWN_OBJECTS_RW_PTR_OPERATORS_EX \en for KNOWN_OBJECTS_RW_REF_OPERATORS_EX and KNOWN_OBJECTS_RW_PTR_OPERATORS_EX + #else + #define MATH_CLASS __declspec( dllimport ) + #define MATH_FUNC(retType) __declspec( dllimport ) retType CALL_DECLARATION + #define MATH_FUNC_EX __declspec( dllimport ) + #endif #else // C3D_WINDOWS #define MATH_CLASS #define MATH_FUNC(retType) retType @@ -323,6 +362,13 @@ private: \ #define GCM_CLASS MATH_CLASS #define GCE_FUNC MATH_FUNC #define GCM_FUNC MATH_FUNC +#if !defined(PROTECTION_ENABLED) + #define GCT_CLASS MATH_CLASS + #define GCT_FUNC MATH_FUNC +#else + #define GCT_CLASS + #define GCT_FUNC(retType) retType +#endif // \ru Модуль конвертеров. \en Converters module. #define CONV_CLASS MATH_CLASS diff --git a/C3d/Include/mb_data.h b/C3d/Include/mb_data.h index 39cb5da..297167d 100644 --- a/C3d/Include/mb_data.h +++ b/C3d/Include/mb_data.h @@ -624,7 +624,7 @@ public: \en Parameters for checking if the curve is planar. \~ */ // --- -struct PlanarCheckParams { +struct MATH_CLASS PlanarCheckParams { double accuracy; VERSION version; @@ -654,4 +654,112 @@ struct PlanarCheckParams { }; +//------------------------------------------------------------------------------ +/** \brief \ru Отступ от ребра пересечения. + \en Offset from the edge of the intersection. \~ + \details \ru Отступ от ребра пересечения на грани. + \en Offset from the edge of the intersection on face. \~ +*/ +// --- +class MATH_CLASS MbTraverse { + + /** + \ru Свиг от пробной точки касательно поверхности по нормали от ребра пересечения на грани. + \en The offset from the sample point touching the surface from the intersection edge on the face. \~ + */ + MbVector3D offset; + /** + \ru Нормализованный вектор нормали справа или слева от ребра пересечения на гранях. + \en The normalized normal vector to the right or left of the intersection edge on the faces. \~ + */ + MbVector3D normal; + +public: + /// \ru Конструктор по умолчанию. \en Default constructor. + MbTraverse() + : offset() + , normal() + {} + + /// \ru Конструктор. \en Constructor. + MbTraverse( const MbVector3D & offset_, const MbVector3D & normal_ ) + : offset( offset_ ) + , normal( normal_ ) + {} + + /// \ru Конструктор копирования. \en Copy-constructor. + MbTraverse( const MbTraverse & other ) + : offset( other.offset ) + , normal( other.normal ) + {} + + ~MbTraverse() {} + + /// \ru \en + void Init( const MbVector3D & offset_, const MbVector3D & normal_ ); + + const MbVector3D & GetOffset() const { return offset; } ///< \ru Выдать вектор сдвига. \en Get offset vector. + const MbVector3D & GetNormal() const { return normal; } ///< \ru Выдать вектор нормали. \en Get normal vector. + + MbVector3D & SetOffset() { return offset; } ///< \ru Выдать вектор сдвига \en Get offset vector. + MbVector3D & SetNormal() { return normal; } ///< \ru Выдать вектор нормали \en Get normal vector. + + /// \ru Поменять направление нормали. \en Change direction of normal. \~ + void InvertNormal() { normal.Invert(); } + + /// \ ru Обнулить координаты векторов. \en Set coordinates of vectors to zero. + void SetZero() { offset.SetZero(); normal.SetZero(); } + + /// \ru Присвоить отступу значения другого отступа. \en Set the offset to a different offset value. + MbTraverse & operator = ( const MbTraverse & other ) + { + offset = other.offset; + normal = other.normal; + return *this; + } +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Отступы от ребра пересечения. + \en Offsets from the edge of the intersection. \~ + \details \ru Отступы влево и вправо от ребра пересечения. + \en Offsets to the left and right from the edge. \~ +*/ +// --- +class MATH_CLASS MbTwoTraverses { + MbTraverse left; ///< \ru Отступ влево. \en Left offset. \~ + MbTraverse right; ///< \ru Отступ вправо. \en Right offset. \~ + +public: + /// \ru Конструктор по умолчанию. \en Default constructor. + MbTwoTraverses() + : left() + , right() + {} + + /// \ru Конструктор копирования. \en Copy-constructor. + MbTwoTraverses( const MbTwoTraverses & other ) + : left( other.left ) + , right( other.right ) + {} + + ~MbTwoTraverses() {} + + const MbTraverse & GetLeft() const { return left; } ///< \ru Выдать отступ слева. \en Get left offset. \~ + const MbTraverse & GetRight() const { return right; } ///< \ru Выдать отступ справа. \en Get right offset. \~ + MbTraverse & SetLeft() { return left; } ///< \ru Выдать отступ слева. \en Get left offset. \~ + MbTraverse & SetRight() { return right; } ///< \ru Выдать отступ справа. \en Get right offset. \~ + + /// \ru Поменять местами лево и право. \en Swap left and right. \~ + void Swap(); + + /// \ru Поменять направление нормалей. \en Change direction of normals. \~ + void InvertNormals() { left.InvertNormal(); right.InvertNormal(); } + + /// \ru Обнулить координаты векторов. \en Set coordinates of vectors to zero. + void SetZero() { left.SetZero(); right.SetZero(); } +}; + + #endif // __MB_DATA_H diff --git a/C3d/Include/mb_matrixnn.h b/C3d/Include/mb_matrixnn.h index 5ff3916..4e056f9 100644 --- a/C3d/Include/mb_matrixnn.h +++ b/C3d/Include/mb_matrixnn.h @@ -76,7 +76,7 @@ public: /// \ru Выдать адрес начала строки матрицы. \en Get an address of the matrix row start . const double * GetLine( size_t i ) const { C3D_ASSERT( !!parr && i < n ); return parr[i]; } /// \ru Выдать адрес начала строки матрицы. \en Get an address of the matrix row start . - double * SetLine( size_t i ) { C3D_ASSERT( !!parr && i < n ); return parr[i]; } + double * SetLine( size_t i ) { C3D_ASSERT( !!parr && i < n ); return parr[i]; } // SKIP_SA /// \ru Инициировать элемент. \en Initiate an element. void Init( size_t i, size_t j, double v ) { C3D_ASSERT( !!parr && i < n && j < n ); parr[i][j] = v; } /// \ru Установить строку. \en Set a row. @@ -190,7 +190,7 @@ MbeNewtonResult TypedGaussEquation ( MatrixNN & a, Type * b, double epsilon, Pro a.SetElem( i, k, 0.0 ); for ( j = k + 1; j < count; j++ ) a.SetElem( i, j, a(i, j) - a(k, j) * m ); - b[i] -= b[k] * m; + b[i] -= b[k] * m; // SKIP_SA } } diff --git a/C3d/Include/mb_nurbs_function.h b/C3d/Include/mb_nurbs_function.h index a9d48ca..3b45bc8 100644 --- a/C3d/Include/mb_nurbs_function.h +++ b/C3d/Include/mb_nurbs_function.h @@ -1048,13 +1048,13 @@ void CurveDeriveCpts( ptrdiff_t p, const KnotsVector & U, const Point * P, const else { if ( !useWeight && ( r1 + r ) < (ptrdiff_t)pointCount ) { for ( i = 0; i <= r; i++ ) { - DT0[i].Init( P[r1 + i].x, P[r1 + i].y, P[r1 + i].z ); + DT0[i].Init( P[r1 + i].x, P[r1 + i].y, P[r1 + i].z ); // SKIP_SA } } else { for ( i = 0; i <= r; i++ ) { k = ( ( r1 + i ) % pointCount ); - DT0[i].Init( P[k], W[k] ); + DT0[i].Init( P[k], W[k] ); // SKIP_SA if ( useWeight ) WT0[i] = W[k]; } diff --git a/C3d/Include/mb_operation_result.h b/C3d/Include/mb_operation_result.h index 701f9b2..2ed4a4f 100644 --- a/C3d/Include/mb_operation_result.h +++ b/C3d/Include/mb_operation_result.h @@ -288,7 +288,8 @@ enum MbeStitchResType { stch_OutwardOrientError, ///< \ru Не удалось установить нормали граней наружу тела. \en Can't set the normals of faces oriented outside the solid. stch_NoEdgeWasStitched, ///< \ru Не было сшито ни одного ребра. \en No edge was stitched. stch_SeparatePartsResult, ///< \ru После сшивки остались несвязанные между собой куски. \en There are separate parts after stitching. - stch_EdgeStitchError ///< \ru Ошибка сшивки ребра. \en Edge stitching error. + stch_EdgeStitchError, ///< \ru Ошибка сшивки ребра. \en Edge stitching error. + stch_InputTopologyError ///< \ru Критические ошибки топологии во входных оболочках. \en Critical topology errors in input shells. }; diff --git a/C3d/Include/mb_point_mating.h b/C3d/Include/mb_point_mating.h index aee71bd..dbd395b 100644 --- a/C3d/Include/mb_point_mating.h +++ b/C3d/Include/mb_point_mating.h @@ -470,7 +470,7 @@ bool CopyMating( const PointMatingDataPtrVector & src, PointMatingDataPtrVector copyItem = new MbPntMatingData(); isDone = copyItem->Init( *src[k] ); } - dst.Add( copyItem ); + dst.push_back( copyItem ); } if ( !isDone ) ::DeleteMatItems( dst ); @@ -724,8 +724,12 @@ class MATH_CLASS MbVector3D; namespace c3d // namespace C3D { -typedef MbPntMatingData PntMatingData2D; -typedef MbPntMatingData PntMatingData3D; + typedef MbPntMatingData PntMatingData2D; + typedef MbPntMatingData PntMatingData3D; + typedef SPtr PntMatingSPtr2D; + typedef SPtr PntMatingSPtr3D; + typedef std::vector PntMatingSPtrVector2D; + typedef std::vector PntMatingSPtrVector3D; } // namespace C3D diff --git a/C3d/Include/mb_property_title.h b/C3d/Include/mb_property_title.h index c1e9caf..15163de 100644 --- a/C3d/Include/mb_property_title.h +++ b/C3d/Include/mb_property_title.h @@ -99,6 +99,12 @@ enum MbePrompt IDS_ITEM_0115, ///< \ru Символьная функция. \en Symbolic Function. IDS_ITEM_0116, ///< \ru Степенная функция. \en Power Function. IDS_ITEM_0117, ///< \ru Синус функция. \en Sinus Function. + IDS_ITEM_0118, ///< \ru Служебная функция. \en Service function. + IDS_ITEM_0119, ///< \ru Монотонная функция. \en Monotonous function. + IDS_ITEM_0120, ///< \ru NURBS функция. \en NURBS function. + + IDS_ITEM_0191, ///< \ru Символьная функция. \en Symbolic function. + IDS_ITEM_0192, ///< \ru Символьная функция на модельном выражении. \en Symbolic function in model expression. // \ru Типы трехмерных кривы.х \en Types of three-dimensional curves. @@ -623,7 +629,7 @@ enum MbePrompt IDS_PROP_0271, ///< \ru Удаление выбранных граней. \en Remove selected faces. IDS_PROP_0272, ///< \ru Создание тела из выбранных граней. \en Solid creation by selected faces. IDS_PROP_0273, ///< \ru Перемещение выбранных граней. \en Move selected faces. - IDS_PROP_0274, ///< \ru Смещение выбранных граней по нормали. \en Offset selected faces. + IDS_PROP_0274, ///< \ru Эквидистантное смещение выбранных граней. \en Offset selected faces. IDS_PROP_0275, ///< \ru Изменение радиусов выбранных скруглений. \en Change selected fillets. IDS_PROP_0276, ///< \ru Замена выбранных граней деформируемыми. \en Replace selected faces by deformed. IDS_PROP_0277, ///< \ru Удаление выбранных скруглений. \en Remove selected features. @@ -749,11 +755,17 @@ enum MbePrompt IDS_PROP_0416, ///< \ru Сохранять радиус. \en Keep the radius. IDS_PROP_0417, ///< \ru Притуплять острый угол. \en Blunt a sharp angle. IDS_PROP_0418, ///< \ru Проверка пересечений. \en Check for intersections. - IDS_PROP_0419, ///< \ru Слияние подобных граней. \en Merging of similar faces. - IDS_PROP_0420, ///< \ru Слияние подобных ребер. \en Merging of similar edges. + IDS_PROP_0419, ///< \ru Слияние подобных граней. \en Similar faces merging. + IDS_PROP_0420, ///< \ru Слияние подобных ребер. \en Similar edges merging. IDS_PROP_0421, ///< \ru Номер соседнего объекта. \en The number of neighbour object. + IDS_PROP_0422, ///< \ru Слияние подобных кривых. \en Similar curves merging. + IDS_PROP_0423, ///< \ru Резка кривых. \en Curves cutting. + IDS_PROP_0424, ///< \ru Резка ребер. \en Edges cutting. + IDS_PROP_0425, ///< \ru Резка поверхностей. \en Surfaces cutting. + IDS_PROP_0426, ///< \ru Резка граней. \en Faces cutting. + IDS_PROP_0450, ///< \ru Начальный радиус (поверхность). \en Start radius (surface). IDS_PROP_0451, ///< \ru Конечный радиус (резьба). \en End radius (thread). IDS_PROP_0452, ///< \ru Длина резьбы. \en Thread length. diff --git a/C3d/Include/mb_variables.h b/C3d/Include/mb_variables.h index 7d4fec9..316d404 100644 --- a/C3d/Include/mb_variables.h +++ b/C3d/Include/mb_variables.h @@ -459,12 +459,12 @@ public: // \ru Временные переменные. \en Temporary variables. //--- public: - static size_t tempIndex; ///< \ru Временный коэффициент\индекс. \en Temporary coefficient\index. - static MbRefItem * selectCurve; ///< \ru Запомненный объект (для отладки). \en Stored object (for debug). - static MbRefItem * selectSurface; ///< \ru Запомненный объект (для отладки). \en Stored object (for debug). - static MbRefItem * selectEdge; ///< \ru Запомненный объект (для отладки). \en Stored object (for debug). - static MbRefItem * selectFace; ///< \ru Запомненный объект (для отладки). \en Stored object (for debug). - static MbRefItem * selectSolid; ///< \ru Запомненный объект (для отладки). \en Stored object (for debug). + static size_t tempIndex; ///< \ru Временный коэффициент\индекс. \en Temporary coefficient\index. + static const MbRefItem * selectCurve; ///< \ru Запомненный объект (для отладки). \en Stored object (for debug). + static const MbRefItem * selectSurface; ///< \ru Запомненный объект (для отладки). \en Stored object (for debug). + static const MbRefItem * selectEdge; ///< \ru Запомненный объект (для отладки). \en Stored object (for debug). + static const MbRefItem * selectFace; ///< \ru Запомненный объект (для отладки). \en Stored object (for debug). + static const MbRefItem * selectSolid; ///< \ru Запомненный объект (для отладки). \en Stored object (for debug). //------------------------------------------------------------------------------ diff --git a/C3d/Include/mesh.h b/C3d/Include/mesh.h index 9020c54..38254eb 100644 --- a/C3d/Include/mesh.h +++ b/C3d/Include/mesh.h @@ -321,12 +321,19 @@ public: /// \ru Дать тип полигонального объекта. \en Get a type of polygonal object. MbeSpaceType GetMeshType() const { return type; } - /// \ru Установить имя всем триангуляциям. \en Set the name of all triangulations. - void SetGridName( SimpleName n ); - /// \ru Установить имя всем полигонам. \en Set the name of all polygons. - void SetPolygonName( SimpleName n ); /// \ru Установить имя всем апексам. \en Set the name of all apexes. void SetApexName( SimpleName n ); + /// \ru Установить имя всем полигонам. \en Set the name of all polygons. + void SetPolygonName( SimpleName n ); + /// \ru Установить имя всем триангуляциям. \en Set the name of all triangulations. + void SetGridName( SimpleName n ); + + /// \ru Найти арекс по хешу имени. \en Find apex by name. + const MbApex3D * FindApexByName( const SimpleName h ) const; + /// \ru Найти полигон по имени. \en Find polygon by name. + const MbPolygon3D * FindPolygonByName( const SimpleName h ) const; + /// \ru Найти триангуляцию по имени. \en Find grid by name. + const MbGrid * FindGridByName( const SimpleName h ) const; /// \ru Замкнутость объекта. \en Object closedness. bool IsClosed() const { return closed; } diff --git a/C3d/Include/mesh_primitive.h b/C3d/Include/mesh_primitive.h index 31fdd9f..1fe24eb 100644 --- a/C3d/Include/mesh_primitive.h +++ b/C3d/Include/mesh_primitive.h @@ -100,7 +100,7 @@ enum MbePrimitiveType { //////////////////////////////////////////////////////////////////////////////// class MATH_CLASS MbPrimitive : public MbAttributeContainer, public MbRefItem, public MbNestSyncItem { protected: - SimpleName name; ///< \ru Имя примитива. \en Name of primitive. + SimpleName name; ///< \ru Имя примитива (хеш сложного имени). \en Name of primitive (hash of a complex name). const MbRefItem * parentItem; ///< \ru Породивший объект (не владеем). \en Begetter object (don't own). MbeRefType type; ///< \ru Тип примитива. \en Type of primitive. @@ -1004,6 +1004,8 @@ public: void SetStepData( const MbStepData & stData ) { stepData = stData; } /// \ru Вернуть габаритный куб. \en Return bounding box. const MbCube & Cube() const { return cube; } + /// \ru Вернуть габаритный куб. \en Return bounding box. + const MbCube & GetCube() const; // \ru Инициировать по другой триангуляции. \en Init by other triangulation. virtual void Init( const MbGrid & grid ) = 0; diff --git a/C3d/Include/mesh_triangle.h b/C3d/Include/mesh_triangle.h index 9dbcaab..2d2e1a0 100644 --- a/C3d/Include/mesh_triangle.h +++ b/C3d/Include/mesh_triangle.h @@ -409,9 +409,9 @@ inline bool MbElement::GetElement ( uint & i0, uint & i1, uint & i2, uint & i3, /** \brief \ru Граница триангуляции. \en Border of triangulation. \~ \details \ru Граница триангуляции используется для описания набора ребер грани оболочки. \n - Граница триангуляции содержит номера последовательности вершины. + Граница триангуляции содержит номера последовательности вершин. \en Border of triangulation is used to describe edge sequence of shell's face. \n - Border of triangulation contains indices of vertex sequence. \~ + Border of triangulation contains indices of vertices sequence. \~ \ingroup Polygonal_Objects */ // --- diff --git a/C3d/Include/name_item.h b/C3d/Include/name_item.h index f3ab337..bd1db17 100644 --- a/C3d/Include/name_item.h +++ b/C3d/Include/name_item.h @@ -722,7 +722,7 @@ bool MbName::operator < ( const MbName & n ) const if ( defNames.CountAll() == n.defNames.CountAll() ) { if ( defNames.CountAll() ) { if ( defNames.Hash() != n.defNames.Hash() ) // C3D-510 - return (::memcmp( defNames.GetAddr(), n.defNames.GetAddr(), defNames.CountAll() * sizeofSimpleName ) < 0); + return (::memcmp( defNames.GetAddr(), n.defNames.GetAddr(), defNames.CountAll() * sizeofSimpleName ) < 0); // SKIP_SA } return false; } diff --git a/C3d/Include/name_version.h b/C3d/Include/name_version.h index 7dcfc89..a4d1326 100644 --- a/C3d/Include/name_version.h +++ b/C3d/Include/name_version.h @@ -28,11 +28,11 @@ class MATH_CLASS MbNameVersion { public: /// \ru Конструктор по умолчанию. \en Default constructor. - MbNameVersion(); + MbNameVersion() : m_ver() {} /// \ru Конструктор копирования. \en Copy-constructor. - explicit MbNameVersion( const VersionContainer & vers ); + explicit MbNameVersion( const VersionContainer & ver ) : m_ver( ver ) {} /// \ru Конструктор копирования. \en Copy-constructor. - MbNameVersion( const MbNameVersion & o ); + MbNameVersion( const MbNameVersion & o ) : m_ver( o.m_ver ) {} /// \ru Установить версию имени по умолчанию. \en Set default version of a name. void SetDefault(); /// \ru Установить версию в контейнере версий по индексу. \en Set the version in container of versions by an index. @@ -45,30 +45,30 @@ public: /// \ru Оператор получения математической версии. \en Operator for obtaining a mathematical version. operator VERSION () const { return m_ver.GetMathVersion(); } /// \ru Оператор равенства. \en An equality operator. - bool operator == ( VERSION v ) const { return (v == *this); } + bool operator == ( VERSION v ) const { return (v == m_ver.GetMathVersion()); } /// \ru Оператор неравенства. \en Inequality operator. - bool operator != ( VERSION v ) const { return (v != *this); } + bool operator != ( VERSION v ) const { return (v != m_ver.GetMathVersion()); } /// \ru Оператор больше. \en "Greater than" operator. - bool operator > ( VERSION v ) const { return (v < *this); } + bool operator > ( VERSION v ) const { return (v < m_ver.GetMathVersion()); } /// \ru Оператор больше или равно. \en "Greater than or equal to" operator. - bool operator >= ( VERSION v ) const { return (v <= *this); } + bool operator >= ( VERSION v ) const { return (v <= m_ver.GetMathVersion()); } /// \ru Оператор меньше. \en "Less than" operator. - bool operator < ( VERSION v ) const { return (v > *this); } + bool operator < ( VERSION v ) const { return (v > m_ver.GetMathVersion()); } /// \ru Оператор меньше или равно. \en "Less than or equal to" operator. - bool operator <= ( VERSION v ) const { return (v >= *this); } + bool operator <= ( VERSION v ) const { return (v >= m_ver.GetMathVersion()); } /// \ru Оператор равенства. \en An equality operator. - bool operator == ( int32 v ) const { return ((VERSION)v == *this); } + bool operator == ( int32 v ) const { return ((VERSION)v == m_ver.GetMathVersion()); } /// \ru Оператор неравенства. \en Inequality operator. - bool operator != ( int32 v ) const { return ((VERSION)v != *this); } + bool operator != ( int32 v ) const { return ((VERSION)v != m_ver.GetMathVersion()); } /// \ru Оператор больше. \en "Greater than" operator. - bool operator > ( int32 v ) const { return ((VERSION)v < *this); } + bool operator > ( int32 v ) const { return ((VERSION)v < m_ver.GetMathVersion()); } /// \ru Оператор больше или равно. \en "Greater than or equal to" operator. - bool operator >= ( int32 v ) const { return ((VERSION)v <= *this); } + bool operator >= ( int32 v ) const { return ((VERSION)v <= m_ver.GetMathVersion()); } /// \ru Оператор меньше. \en "Less than" operator. - bool operator < ( int32 v ) const { return ((VERSION)v > *this); } + bool operator < ( int32 v ) const { return ((VERSION)v > m_ver.GetMathVersion()); } /// \ru Оператор меньше или равно. \en "Less than or equal to" operator. - bool operator <= ( int32 v ) const { return ((VERSION)v >= *this); } + bool operator <= ( int32 v ) const { return ((VERSION)v >= m_ver.GetMathVersion()); } /// \ru Оператор присваивания. \en An assignment operator. void operator = ( const MbNameVersion & o ) { m_ver = o.m_ver; } @@ -76,41 +76,16 @@ private: static VERSION GetIOVersion( uint8 v, VERSION ver ); static uint8 GetVersion ( VERSION iov ); - KNOWN_OBJECTS_RW_REF_OPERATORS( MbNameVersion ); +KNOWN_OBJECTS_RW_REF_OPERATORS( MbNameVersion ) }; //------------------------------------------------------------------------------ // // --- -inline MbNameVersion::MbNameVersion() +inline +reader & CALL_DECLARATION operator >> ( reader & in, MbNameVersion & ref ) { -} - - -//------------------------------------------------------------------------------ -// -// --- -inline MbNameVersion::MbNameVersion( const VersionContainer & iov ) - : m_ver ( iov ) -{ -} - - -//------------------------------------------------------------------------------ -// -// --- -inline MbNameVersion::MbNameVersion( const MbNameVersion & o ) - : m_ver ( o.m_ver ) -{ -} - - - -//------------------------------------------------------------------------------ -// -// --- -inline reader& CALL_DECLARATION operator >> ( reader& in, MbNameVersion& ref ) { VERSION version = in.MathVersion(); if ( version < 0x0590004FL ) { @@ -134,8 +109,9 @@ inline reader& CALL_DECLARATION operator >> ( reader& in, MbNameVersion& ref ) { //------------------------------------------------------------------------------ // // --- -inline writer& CALL_DECLARATION operator << ( writer& out, const MbNameVersion& ref ) { - +inline +writer & CALL_DECLARATION operator << ( writer & out, const MbNameVersion & ref ) +{ VERSION version = out.MathVersion(); if ( version < 0x07000104L ) { out << MbNameVersion::GetVersion( version ); diff --git a/C3d/Include/op_curve_parameter.h b/C3d/Include/op_curve_parameter.h index a005069..5195156 100644 --- a/C3d/Include/op_curve_parameter.h +++ b/C3d/Include/op_curve_parameter.h @@ -20,14 +20,84 @@ #include +//------------------------------------------------------------------------------ +/** \brief \ru Параметры кривой пересечения поверхностей. + \en Parameters of an surface intersection curve. \~ + \details \ru Параметры эквидистантной кривой в пространстве по трехмерной кривой и вектору направления. \n + \en Parameters of an offset curve in space from a three-dimensional curve and a direction vector. \n \~ + \ingroup Build_Parameters +*/ // --- +struct MATH_CLASS MbIntCurveParams { +public: + bool mergeCurves; ///< \ru Объединять кривые, разрезанные швом. \en Merge curves cut by a surface seam. + bool cutCurves; ///< \ru Разрезать кривые в точках пересечения. \en Cut curves at intersection points. +protected: + const MbSNameMaker & snMaker; ///< \ru Именователь с версией операции. \en Names maker with operation version. +public: + /** \brief \ru Конструктор. + \en Constructor. \~ + \details \ru Конструктор по параметрам. + \en Constructor by parameters. \~ + \param[in] _mergeCurves - \ru Объединять кривые, разрезанные швом. + \en Merge curves cut by a surface seam. \~ + \param[in] _cutCurves - \ru Разрезать кривые в точках пересечения. + \en Cut curves at intersection points. \~ + \param[in] _snMaker - \ru Именователь с версией операции. + \en Names maker with operation version. \~ + */ + MbIntCurveParams( const MbSNameMaker & _snMaker ) + : mergeCurves( true ) + , cutCurves ( false ) + , snMaker ( _snMaker ) + { + if ( _snMaker.GetMathVersion() > MATH_19_VERSION ) // KOMPAS-39273 + KOMPAS-40408 + cutCurves = true; + } + /** \brief \ru Конструктор. + \en Constructor. \~ + \details \ru Конструктор по параметрам. + \en Constructor by parameters. \~ + \param[in] _cutCurves - \ru Разрезать кривые в точках пересечения. + \en Cut curves at intersection points. \~ + \param[in] _snMaker - \ru Именователь с версией операции. + \en Names maker with operation version. \~ + */ + MbIntCurveParams( bool _cutCurves, const MbSNameMaker & _snMaker ) + : mergeCurves( true ) + , cutCurves ( _cutCurves ) + , snMaker ( _snMaker ) + {} + /** \brief \ru Конструктор. + \en Constructor. \~ + \details \ru Конструктор по параметрам. + \en Constructor by parameters. \~ + \param[in] _mergeCurves - \ru Объединять кривые, разрезанные швом. + \en Merge curves cut by a surface seam. \~ + \param[in] _cutCurves - \ru Разрезать кривые в точках пересечения. + \en Cut curves at intersection points. \~ + \param[in] _snMaker - \ru Именователь с версией операции. + \en Names maker with operation version. \~ + */ + MbIntCurveParams( bool _mergeCurves, bool _cutCurves, const MbSNameMaker & _snMaker ) + : mergeCurves( _mergeCurves ) + , cutCurves ( _cutCurves ) + , snMaker ( _snMaker ) + {} +public: + /// \ru Получить ссылку на именователь. \en Get names maker reference. + const MbSNameMaker & GetNameMaker() const { return snMaker; } + +OBVIOUS_PRIVATE_COPY( MbIntCurveParams ) +}; + + //------------------------------------------------------------------------------ /** \brief \ru Параметры эквидистантной кривой в пространстве. \en Parameters of an offset curve in space. \~ \details \ru Параметры эквидистантной кривой в пространстве по трехмерной кривой и вектору направления. \n \en Parameters of an offset curve in space from a three-dimensional curve and a direction vector. \n \~ \ingroup Build_Parameters -*/ -// --- +*/ // --- struct MATH_CLASS MbSpatialOffsetCurveParams { public: MbVector3D offsetVect; ///< \ru Вектор, задающий смещение в точке кривой. \en The displacement vector at a point of the curve. @@ -83,8 +153,7 @@ OBVIOUS_PRIVATE_COPY( MbSpatialOffsetCurveParams ) \details \ru Параметры эквидистантной кривой на поверхности по поверхностной кривой и значению смещения. \n \en Parameters of an offset curve on surface from a curve on the surface and a shift value. \n \~ \ingroup Build_Parameters -*/ -// --- +*/ // --- struct MATH_CLASS MbSurfaceOffsetCurveParams { public: c3d::ConstFaceSPtr face; ///< \ru Грань, на которой строится эквидистанта. \en The face on which to build the offset curve. diff --git a/C3d/Include/op_shell_parameter.h b/C3d/Include/op_shell_parameter.h index 52768f6..062af8b 100644 --- a/C3d/Include/op_shell_parameter.h +++ b/C3d/Include/op_shell_parameter.h @@ -45,8 +45,7 @@ class MbRegDuplicate; \details \ru Параметры скругления или фаски ребра содержат информацию, необходимую для выполнения операции. \n \en The parameter of fillet or chamfer of edge contain Information necessary to perform the operation. \n \~ \ingroup Build_Parameters -*/ -// --- +*/ // --- struct MATH_CLASS SmoothValues { public: /// \ru Способы обработки углов стыковки трёх рёбер. \en Methods of processing corners of connection by three edges. @@ -847,7 +846,7 @@ public: /// \ru Выдать тип сопряжения. \en Get the type of conjugation. virtual MbePatchMatingType GetMatingType() const = 0; - /// \ru Выдать посверхность. \en Get surface. + /// \ru Выдать поверхность. \en Get surface. virtual const MbSurface * GetSurface() const = 0; /// \ru Сопряжение для сегмента номер segInd. \en The conjugation by segment number segInd. @@ -889,6 +888,7 @@ private: bool checkSelfInt; ///< \ru Флаг проверки самопересечений (вычислительно "тяжелыми" методами). \en Flag for checking of self-intersection (computationally by "heavy" methods). bool mergeEdges; ///< \ru Сливать подобные ребра (true). \en Whether to merge similar edges (true). std::vector> curvesMatings; ///< \ru Сопряжения по кривым. Параметр используется при type == ts_byCurves. \en The conjugation by curves. + bool tolerantData; ///< \ru Построить неточную заплатку по неточным входным данным. \en Build an tolerant patch from tolerant input data. public: /** \brief \ru Конструктор по умолчанию. @@ -900,14 +900,18 @@ public: : type ( ts_none ) , checkSelfInt( false ) , mergeEdges ( true ) + , tolerantData( false ) {} + /// \ru Конструктор копирования. \en Copy-constructor. PatchValues( const PatchValues & other ) : type ( other.type ) , checkSelfInt ( other.checkSelfInt ) , mergeEdges ( other.mergeEdges ) , curvesMatings( other.curvesMatings ) + , tolerantData ( other.tolerantData ) {} + /// \ru Деструктор. \en Destructor. ~PatchValues() {} @@ -938,6 +942,19 @@ public: /// \ru Декомпозиция сопряжений контура номер cInd, segCount - число сегментов контура. \en Decomposition of cInd - contour mates, segCount - the number of contour segments. void DecomposeMates( size_t cInd, size_t segCount ); + /// \ru Удалить сопряжения. \en Remove curves matings. + void DeleteCurvesMatings(); + /// \ru Удалить сопряжение кривой номер cInd (при удалении кривой). \en Remove curve mate cInd number (when removing curve). + void DeleteCurveMating( size_t cInd ); + + /// \ru Дать поверхность для сопряжений, если она одна (поверхности одинаковые). Give a surface for fillets, if it is one (the surfaces are the same). \en . + const MbSurface * GetGeneralMatingSurface() const; + + /// \ru Выдать флаг построения неточной заплатки по неточным входным данным. \en Get the flag for building an tolerant patch from tolerant input data. + bool IsTolerantData() const { return tolerantData; } + /// \ru Установить флаг построения неточной заплатки по неточным входным данным. \en Set the flag for building an tolerant patch from tolerant input data. + void SetTolerantData( bool tolData ) { tolerantData = tolData; } + /// \ru Оператор присваивания. \en Assignment operator. void operator = ( const PatchValues & other ) { type = other.type; checkSelfInt = other.checkSelfInt; mergeEdges = other.mergeEdges; curvesMatings = other.curvesMatings; } /// \ru Являются ли объекты равными? \en Determine whether an object is equal? @@ -969,6 +986,8 @@ public: MbPatchCurve( const MbCurve3D &, const MbMatrix3D & ); /// \ru Конструктор по ребру (копирует кривую, трансформируя по матрице). \en Constructor by an edge (copies a curve, transforms by the matrix). MbPatchCurve( const MbCurveEdge &, const MbMatrix3D & ); + /// \ru Конструктор по ребру (копирует кривую, трансформируя по матрице). \en Constructor by an edge (copies a curve, transforms by the matrix). + MbPatchCurve( const MbEdge &, const MbMatrix3D & ); /// \ru Деструктор. \en Destructor. virtual ~MbPatchCurve(); @@ -1133,6 +1152,9 @@ struct MATH_CLASS ModifyValues { public: MbeModifyingType way; ///< \ru Тип модификации. \en Type of modification. MbVector3D direction; ///< \ru Перемещение при модификации. \en Moving when modifying. + MbCartPoint3D origin; ///< \ru Точка опоры при модификации. \en Fulcrum when modifying. + double value; ///< \ru Величина смещения/изменение радиуса. \en Offset value/change of radius. + double tolerance; ///< \ru Точность построения. \en Operation tolerance. public: /** \brief \ru Конструктор по умолчанию. @@ -1141,18 +1163,35 @@ public: \en Constructor of operation parameters of removing the specified faces from the solid. \~ */ ModifyValues() - : way( dmt_Remove ) + : way ( dmt_Remove ) , direction( 0.0, 0.0, 0.0 ) + , origin ( 0.0, 0.0, 0.0 ) + , value ( 0.0 ) + , tolerance( 1.0 ) {} /// \ru Конструктор по способу модификации и вектору перемещения. \en Constructor by way of modification and movement vector. ModifyValues( MbeModifyingType w, const MbVector3D & p ) : way ( w ) , direction( p ) + , origin ( 0.0, 0.0, 0.0 ) + , value ( 0.0 ) + , tolerance( 1.0 ) + {} + /// \ru Конструктор по способу модификации и скалярному параметру. \en Constructor by way of modification and the scalar value. + ModifyValues( MbeModifyingType w, double val, double eps = 1.0 ) + : way ( w ) + , direction( 0.0, 0.0, 0.0 ) + , origin ( 0.0, 0.0, 0.0 ) + , value ( val ) + , tolerance( eps ) {} /// \ru Конструктор копирования. \en Copy-constructor. ModifyValues( const ModifyValues & other ) : way ( other.way ) , direction( other.direction ) + , origin ( other.origin ) + , value ( other.value ) + , tolerance( other.tolerance ) {} /// \ru Деструктор. \en Destructor. ~ModifyValues() {} @@ -1161,11 +1200,17 @@ public: void Init( const ModifyValues & other ) { way = other.way; direction = other.direction; + origin = other.origin; + value = other.value; + tolerance = other.tolerance; } /// \ru Оператор присваивания. \en Assignment operator. ModifyValues & operator = ( const ModifyValues & other ) { way = other.way; direction = other.direction; + origin = other.origin; + value = other.value; + tolerance = other.tolerance; return *this; } /// \ru Преобразовать объект согласно матрице. \en Transform an object according to the matrix. @@ -1177,6 +1222,19 @@ public: /// \ru Являются ли объекты равными? \en Determine whether an object is equal? bool IsSame( const ModifyValues & other, double accuracy ) const; + /// \ru Перемещение при модификации. \en Moving when modifying. + const MbVector3D & GetDirection() const { return direction; } + void SetDirection( const MbVector3D & d ) { direction = d; } + /// \ru Точка опоры при модификации. \en Fulcrum when modifying. + const MbCartPoint3D & GetOrigin() const { return origin; } + void SetOrigin( const MbCartPoint3D & p ) { origin = p; } + /// \ru Величина смещения/изменение радиуса. \en Offset value/change of radius. + double GetValue() const { return value; } + void SetValue( double v ) { value = v; } + /// \ru Точность построения. \en Operation tolerance. + double GetTolerance() const { return tolerance; } + void SetTolerance( double t ) { tolerance = ::fabs( t ); } + KNOWN_OBJECTS_RW_REF_OPERATORS( ModifyValues ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. }; @@ -1677,6 +1735,8 @@ private: bool defaultDir3; ///< \ru Направление сопряжения на границе 3 по умолчанию. \en Default mate direction through the boundary 3. mutable uint8 directOrderV;///< \ru По второму семейству кривых порядок кривых совпадает. \en Order of the curves coincides by the second set of curves. bool tesselate; ///< \ru Достраивать ли дополнительные сечения. \en Whether to build additional sections. + bool g2Cont; ///< \ru Требуется ли гладкость g2 для граней оболочки. \en Is the smoothness g2 required for the faces of the shell. + private: /// \ru Конструктор копирования. \en Copy-constructor. MeshSurfaceValues( const MeshSurfaceValues &, MbRegDuplicate * ireg ); @@ -1730,6 +1790,50 @@ public: bool modify = true, bool direct0 = true, bool direct1 = true, bool direct2 = true, bool direct3 = true ); + /** \brief \ru Функция инициализации. + \en Initialization function. \~ + \details \ru Функция инициализации на оригиналах кривых и копиях поверхностей. + \en Initialization function on the original curves and copies of surfaces. \~ + \param[in] curvesU, curvesV - \ru Наборы кривых по первому и второму направлению. + \en Sets of curves along the first and second directions. \~ + \param[in] uClosed, vClosed - \ru Признак замкнутости по направлениям u и v. + \en Closedness attribute along the u and v directions. \~ + \param[in] types - \ru Типы сопряжений на границах. + \en Mates types on the boundaries. \~ + \param[in] surfaces - \ru Соответствующие сопрягаемые поверхности. Ноль, если не задано. + \en Corresponding mating surfaces. Zero if not defined.\~ + \param[in] useDefaultDir - \ru Направление поверхности на границе сопряжения. + \en The direction of the surface at the border of mating. \~ + \param[in] checkSelfInt - \ru Флаг проверки на самопересечение. + \en Flag of check for self-intersection. \~ + \param[in] tess - \ru Достраивать ли дополнительные сечения. + \en Whether to build additional sections. \~ + \param[in] smooth - \ru Требуется ли гладкость g2 для граней оболочки. + \en Is the smoothness g2 required for the faces of the shell. + \param[in] chainsU, chainsV - \ru Наборы цепочек по первому и второму направлению. Ноль, если не задано. + \en Sets of chains along the first and second directions. Zero if not defined.\~ + \param[in] point - \ru Точка на поверхности. Используется для уточнения. Ноль, если не задано. + \en Point on the surface. Used for specializing. Zero if not defined.\~ + \param[in] modify - \ru Флаг модификации кривых по сопряжениям. + \en Flag of curves modification by mates. \~ + \return \ru Статус выполнения. + \en Execution status. + */ + bool Init( const RPArray & curvesU, + const RPArray & curvesV, + bool uClosed, + bool vClosed, + MbeMatingType ( &types )[4], + const c3d::ConstSurfacesVector * ( &surfaces )[4], + bool ( &useDefaultDir )[4], + bool checkSelfInt, + bool tess, + bool smooth, + const RPArray * chainsU, + const RPArray * chainsV, + const MbPoint3D * pnt, + bool modify ); + /** \brief \ru Функция инициализации. \en Initialization function. \~ \details \ru Функция инициализации на оригиналах или копиях кривых и поверхностей. @@ -1919,6 +2023,8 @@ public: bool CheckSelfInt() const { return checkSelfInt; } ///< \ru Достраивать ли дополнительные сечения. \en Whether to build additional sections. bool IsTesselate() const { return tesselate; } + ///< \ru Требуется ли гладкость g2 для граней оболочки. \en Is the smoothness g2 required for the faces of the shell. + bool IsSmooth() const { return g2Cont; } /// \ru Получить поверхность сопряжения к граничной кривой по параметру на кривой. /// \en Get the mating surface to the border curve by the curve parameter. static const MbSurface * @@ -2511,18 +2617,18 @@ struct MATH_CLASS MedianShellValues { public: /** \brief \ru Тип расчета радиуса скругления между гранями срединной оболочки. \en Type of fillet radius calculation between faces of median shell. \~ - \details \ru Флаг можно установить через вызов MedianShellValues::SetFilletType(). - \en The flag can be set by calling MedianShellValues::SetFilletType(). \~ + \details \ru Флаг можно установить через вызов MedianShellValues::SetType(). + \en The flag can be set by calling MedianShellValues::SetType(). \~ */ enum FilletType { tf_none, ///< \ru Не определено. \en Undefined. - tf_internal, ///< \ru По внутренней грани скругления. \en Along the tangent. - tf_external, ///< \ru По внешней грани скругления. \en Along the normal. - tf_average ///< \ru По среднему значению. \en Plane patch. + tf_internal, ///< \ru По внутренней грани скругления. \en By internal fillet face. + tf_external, ///< \ru По внешней грани скругления. \en By external fillet face. + tf_average ///< \ru По среднему значению. \en By average value. }; public: - FilletType filletType; + FilletType filletType; ///< \ru Флаг обработки скруглений. \en Fillet proccessing flag. double position; ///< \ru Параметр смещения срединной оболочки относительно первой грани из пары. По умолчанию равен 50% расстояния между гранями. \en Parameter of shift the median surface from first face in faces pair. By default is 50% from distance between faces in pair. double dmin; ///< \ru Минимальный параметр эквидистантности. \en Minimal equidistation value. double dmax; ///< \ru Максимальный параметр эквидистантности. \en Maximal equidistation value. @@ -2567,9 +2673,9 @@ public: return false; } - /// \ru Выдать тип заплатки. \en Get type of patch. + /// \ru Выдать тип скругления. \en Get type of fillet. FilletType GetType() const { return filletType; } - /// \ru Выдать тип заплатки для изменения. \en Get type of patch for changing. + /// \ru Выдать тип скругления для изменения. \en Get type of fillet for changing. FilletType & SetType() { return filletType; } public: diff --git a/C3d/Include/reference_item.h b/C3d/Include/reference_item.h index a6c4401..64a0216 100644 --- a/C3d/Include/reference_item.h +++ b/C3d/Include/reference_item.h @@ -18,7 +18,7 @@ #include #include #include -//#include +#include #include @@ -89,7 +89,11 @@ typedef std::vector ConstRefItemsSPtrVector; \ingroup Geometric_Items */ // --- +#ifndef ENABLE_MEMORY_LEAKS_CHECK class MATH_CLASS MbRefItem { +#else +class MATH_CLASS MbRefItem: virtual public c3d::MemoryLeaksVerifiable { +#endif private: mutable use_count_type useCount; ///< \ru Счетчик ссылок на объект, изменяемый владельцами объекта. \en A counter of references to an object modifiable by owners of object. public: @@ -290,9 +294,9 @@ void ReleaseItem( Type *& item ) { if ( item != c3d_null ) { item->Release(); - item = c3d_null; + item = c3d_null; // SKIP_SA } -} +} // SKIP_SA //------------------------------------------------------------------------------ /// \ru Захватить объект. \en Catch an object. diff --git a/C3d/Include/sheet_metal_param.h b/C3d/Include/sheet_metal_param.h index 8475292..781a4d2 100644 --- a/C3d/Include/sheet_metal_param.h +++ b/C3d/Include/sheet_metal_param.h @@ -1335,7 +1335,7 @@ struct MATH_CLASS MbRuledSolidValues { }; MbPlacement3D placement1; ///< \ru Локальная система координат первого контура. \en The local coordinate system of the first contour. - MbContour contour1; ///< \ru Первый контур. \en The first contour. + SPtr contour1; ///< \ru Первый контур. \en The first contour. DPtr< SArray > breaks1; ///< \ru Параметры разбивки первого контура. \en The fragmentation parameters of the first contour. DPtr placement2; ///< \ru Локальная система координат второго контура. \en The local coordinate system of the second contour. SPtr contour2; ///< \ru Второй контур. \en The second contour. @@ -1357,31 +1357,31 @@ struct MATH_CLASS MbRuledSolidValues { /// \ru Конструктор по умолчанию. \en Default constructor. MbRuledSolidValues() - : placement1 ( ), - contour1 ( ), - breaks1 ( c3d_null ), - placement2 ( c3d_null ), - contour2 ( c3d_null ), - breaks2 ( c3d_null ), - thickness ( 0.0 ), - radius ( 0.0 ), - slopeAngle ( 0.0 ), - height ( 0.0 ), - gapValue ( 0.0 ), - gapAngle ( 0.0 ), - gapShift ( 0.0 ), - shiftType ( gsAngle ), - guideSidesByNorm( false ), - generSidesByNorm( false ), - cylindricBends ( false ), - joinByVertices ( true ), - surfDistance ( 0.0 ), - surface ( c3d_null ) { + : placement1 ( ), + contour1 ( c3d_null ), + breaks1 ( c3d_null ), + placement2 ( c3d_null ), + contour2 ( c3d_null ), + breaks2 ( c3d_null ), + thickness ( 0.0 ), + radius ( 0.0 ), + slopeAngle ( 0.0 ), + height ( 0.0 ), + gapValue ( 0.0 ), + gapAngle ( 0.0 ), + gapShift ( 0.0 ), + shiftType ( gsAngle ), + guideSidesByNorm( false ), + generSidesByNorm( false ), + cylindricBends ( false ), + joinByVertices ( true ), + surfDistance ( 0.0 ), + surface ( c3d_null ) { } /// \ru Конструктор копирования. \en Copy-constructor. MbRuledSolidValues( const MbRuledSolidValues & other ) : placement1 ( other.placement1 ), - contour1 (), + contour1 ( (other.contour1 != c3d_null) ? new MbContour() : c3d_null ), breaks1 ( (other.breaks1 != c3d_null) ? new SArray(*other.breaks1) : c3d_null ), placement2 ( (other.placement2 != c3d_null) ? new MbPlacement3D(*other.placement2) : c3d_null ), contour2 ( (other.contour2 != c3d_null) ? new MbContour() : c3d_null ), @@ -1400,7 +1400,8 @@ struct MATH_CLASS MbRuledSolidValues { joinByVertices ( other.joinByVertices ), surfDistance ( other.surfDistance ), surface ( (other.surface != c3d_null) ? static_cast(&other.surface->Duplicate()) : c3d_null ) { - contour1.Init( other.contour1 ); + if ( contour1 != c3d_null && other.contour1 != c3d_null ) + contour1->Init( *other.contour1 ); if ( contour2 != c3d_null && other.contour2 != c3d_null ) contour2->Init( *other.contour2 ); } @@ -1412,7 +1413,7 @@ struct MATH_CLASS MbRuledSolidValues { const bool guideByNorm, const bool generByNorm, const bool cylBends, const bool joinByVert, const double surfDist, const MbSurface * surf ) : placement1( place1 ), - contour1(), + contour1( new MbContour() ), breaks1( (brks1 != c3d_null) ? new SArray(*brks1) : c3d_null ), placement2( (place2 != c3d_null) ? new MbPlacement3D(*place2) : c3d_null ), contour2( (cntr2 != c3d_null) ? new MbContour() : c3d_null ), @@ -1431,7 +1432,7 @@ struct MATH_CLASS MbRuledSolidValues { joinByVertices( joinByVert ), surfDistance( surfDist ), surface( (surf != c3d_null) ? static_cast(&surf->Duplicate()) : c3d_null ) { - contour1.Init( cntr1 ); + contour1->Init( cntr1 ); if ( (contour2 != c3d_null) && (cntr2 != c3d_null) ) contour2->Init( *cntr2 ); } @@ -1439,7 +1440,14 @@ struct MATH_CLASS MbRuledSolidValues { /// \ru Инициализировать по другому объекту. \en Initialize by another object. void Init( const MbRuledSolidValues & other ) { placement1.Init( other.placement1 ); - contour1.Init( other.contour1 ); + if ( other.contour1 != c3d_null ) { + if ( contour1 == c3d_null ) + contour1 = new MbContour(); + contour1->Init( *other.contour1 ); + } + else + contour1 = c3d_null; + if ( other.breaks1 != c3d_null ) { if ( breaks1 != c3d_null ) @@ -1500,7 +1508,9 @@ struct MATH_CLASS MbRuledSolidValues { void Init( const MbPlacement3D & place1, const MbContour & cntr1, const SArray * brks1, const MbPlacement3D * place2, const MbContour * cntr2, const SArray * brks2 ) { placement1.Init( place1 ); - contour1.Init( cntr1 ); + if ( contour1 == c3d_null ) + contour1 = new MbContour(); + contour1->Init( cntr1 ); if ( brks1 != c3d_null ) { if ( breaks1 != c3d_null ) @@ -1555,7 +1565,6 @@ struct MATH_CLASS MbRuledSolidValues { cylindricBends == other.cylindricBends && joinByVertices == other.joinByVertices && placement1.IsSame( other.placement1, accuracy ) && - contour1.IsSame( other.contour1, accuracy ) && ::fabs( thickness - other.thickness ) < accuracy && ::fabs( radius - other.radius ) < accuracy && ::fabs( slopeAngle - other.slopeAngle ) < accuracy && @@ -1565,6 +1574,8 @@ struct MATH_CLASS MbRuledSolidValues { ::fabs( gapShift - other.gapShift ) < accuracy && ::fabs( surfDistance - other.surfDistance ) < accuracy ) { + bool isContour1 = contour1 != c3d_null; + bool isOtherContour1 = other.contour1 != c3d_null; bool isBreaks1 = breaks1 != c3d_null; bool isOtherBreaks1 = other.breaks1 != c3d_null; bool isPlacement2 = placement2 != c3d_null; @@ -1576,12 +1587,16 @@ struct MATH_CLASS MbRuledSolidValues { bool isSurf = surface != c3d_null; bool isOtherSurf = other.surface != c3d_null; - if ( isBreaks1 == isOtherBreaks1 && + if ( isContour1 == isOtherContour1 && + isBreaks1 == isOtherBreaks1 && isPlacement2 == isOtherPlacement2 && isContour2 == isOtherContour2 && isBreaks2 == isOtherBreaks2 && isSurf == isOtherSurf ) { isSame = true; + if ( isContour1 && isOtherContour1 && !contour1->IsSame( *other.contour1, accuracy ) ) + isSame = false; + if ( isSame && isBreaks1 && isOtherBreaks1 ) { if ( breaks1->Count() != other.breaks1->Count() ) isSame = false; @@ -1909,41 +1924,54 @@ private: //------------------------------------------------------------------------------ /** \brief \ru Параметры штамповки телом-инструментом. \en The parameters of stamping by a tool solid. \~ - \details \ru Параметры шатмповки телом-инструментом определяют толщину формованной части и радиусы скругления основания.\n + \details \ru Параметры штамповки телом-инструментом определяют толщину формованной части и радиусы скругления основания.\n \en The parameters of stamping by a tool solid is specified a thickness of a stamped part and fillet radiuses of stamping base.\n \~ \ingroup Build_Parameters */ // --- struct MATH_CLASS MbToolStampingValues { - double punchFilletRadius; ///< \ru Радиус скругления основания со стороны пуансона (отрицательное значение запрещает скругление). \en Punch fillet radius of base (negative value prohibits fillet). - double dieFilletRadius; ///< \ru Радиус скругления основания со стороны матрицы (отрицательное значение запрещает скругление). \en Die fillet radius of base (negative value prohibits fillet). - double toolFilletRadius; ///< \ru Радиус скругления негладких ребер инструмента (отрицательное значение запрещает скругление). \en Fillet radius of sharp edges of tool (negative value prohibits fillet). - double stampThickness; ///< \ru Толщина формованной части. \en Thickness of a stamped part. - bool filletToolEdges; ///< \ru Флаг скругления острых ребер инструмента. \en Flag of fillet sharp edges of tool solid. + /** \brief \ru Cпособ обработки кромок вырубки. + \en Type of pierce edge processing. \~ + \ingroup Build_Parameters + */ + enum MbePierceEdgeType { + petCutted = 0, ///< \ru Обрезка гранью вырубки. \en Pierce face cutting. + petNormal = 1, ///< \ru По нормали к листовым граням. \en By normal to sheet faces. + }; + + double punchFilletRadius; ///< \ru Радиус скругления основания со стороны пуансона (отрицательное значение запрещает скругление). \en Punch fillet radius of base (negative value prohibits fillet). + double dieFilletRadius; ///< \ru Радиус скругления основания со стороны матрицы (отрицательное значение запрещает скругление). \en Die fillet radius of base (negative value prohibits fillet). + double toolFilletRadius; ///< \ru Радиус скругления негладких ребер инструмента (отрицательное значение запрещает скругление). \en Fillet radius of sharp edges of tool (negative value prohibits fillet). + double stampThickness; ///< \ru Толщина формованной части. \en Thickness of a stamped part. + bool filletToolEdges; ///< \ru Флаг скругления острых ребер инструмента. \en Flag of fillet sharp edges of tool solid. + MbePierceEdgeType pierceEdgeType; ///< \ru Способ обработки кромок вырубки. /// \ru Конструктор по умолчанию. \en Default constructor. - MbToolStampingValues() : - punchFilletRadius( 0.0 ), - dieFilletRadius ( 0.0 ), - toolFilletRadius ( 0.0 ), - stampThickness ( 0.0 ), - filletToolEdges ( true ) + MbToolStampingValues() + : punchFilletRadius( 0.0 ) + , dieFilletRadius ( 0.0 ) + , toolFilletRadius ( 0.0 ) + , stampThickness ( 0.0 ) + , filletToolEdges ( true ) + , pierceEdgeType ( petCutted ) {} /// \ru Конструктор копирования. \en Copy-constructor. - MbToolStampingValues( const MbToolStampingValues & other ) : - punchFilletRadius( other.punchFilletRadius ), - dieFilletRadius ( other.dieFilletRadius ), - toolFilletRadius ( other.toolFilletRadius ), - stampThickness ( other.stampThickness ), - filletToolEdges ( other.filletToolEdges ) + MbToolStampingValues( const MbToolStampingValues & other ) + : punchFilletRadius( other.punchFilletRadius ) + , dieFilletRadius ( other.dieFilletRadius ) + , toolFilletRadius ( other.toolFilletRadius ) + , stampThickness ( other.stampThickness ) + , filletToolEdges ( other.filletToolEdges ) + , pierceEdgeType ( other.pierceEdgeType ) {} /// \ru Конструктор по конкретным параметрам. \en Constructor by specific parameters. - MbToolStampingValues( double punchRad, double dieRad, double toolRad, double thick, bool filletTool ) : - punchFilletRadius( punchRad ), - dieFilletRadius ( dieRad ), - toolFilletRadius ( toolRad ), - stampThickness ( thick ), - filletToolEdges ( filletTool ) + MbToolStampingValues( double punchRad, double dieRad, double toolRad, double thick, bool filletTool, MbePierceEdgeType edgeType = MbePierceEdgeType::petCutted ) + : punchFilletRadius( punchRad ) + , dieFilletRadius ( dieRad ) + , toolFilletRadius ( toolRad ) + , stampThickness ( thick ) + , filletToolEdges ( filletTool ) + , pierceEdgeType ( edgeType ) {} /// \ru Оператор присваивания. \en Assignment operator. @@ -1955,17 +1983,18 @@ struct MATH_CLASS MbToolStampingValues { toolFilletRadius = other.toolFilletRadius; stampThickness = other.stampThickness; filletToolEdges = other.filletToolEdges; + pierceEdgeType = other.pierceEdgeType; } ///\ru Являются ли объекты равными? \en Determine whether an object is equal? bool IsSame( const MbToolStampingValues & other, double accuracy ) const { bool isSame = false; - if ( ::fabs(punchFilletRadius - other.punchFilletRadius) < accuracy && ::fabs(dieFilletRadius - other.dieFilletRadius) < accuracy && ::fabs(toolFilletRadius - other.toolFilletRadius) < accuracy && ::fabs(stampThickness - other.stampThickness) < accuracy && - filletToolEdges == other.filletToolEdges ) + filletToolEdges == other.filletToolEdges && + pierceEdgeType == other.petCutted ) isSame = true; return isSame; diff --git a/C3d/Include/solid.h b/C3d/Include/solid.h index f27368a..2575849 100644 --- a/C3d/Include/solid.h +++ b/C3d/Include/solid.h @@ -404,6 +404,13 @@ public : /// \ru Найти грань по имени. \en Find face by name. MbFace * FindFaceByName ( const MbName & ); + /// \ru Найти вершину по хешу имени. \en Find vertex by hash of a name. + const MbVertex * FindVertexByHash( const SimpleName h ) const; + /// \ru Найти ребро по хешу имени. \en Find edge by hash of a name. + const MbCurveEdge * FindEdgeByHash ( const SimpleName h ) const; + /// \ru Найти грань по хешу имени. \en Find face by hash of a name. + const MbFace * FindFaceByHash ( const SimpleName h ) const; + /// \ru Создать именователь тела. \en Create name-maker of solid. SPtr GetYourNameMaker() const; diff --git a/C3d/Include/surf_cone_surface.h b/C3d/Include/surf_cone_surface.h index 197e6b0..0fe05f6 100644 --- a/C3d/Include/surf_cone_surface.h +++ b/C3d/Include/surf_cone_surface.h @@ -315,10 +315,10 @@ public: virtual void SetExtendedParamRegion( double u1, double v1, double u2, double v2 ); virtual void IncludePoint( double u, double v ); // \ru Включить точку в область определения. \en Include point into domain. - // \ru Существует ли полюс на границе параметрической области сплайновой кривой. \en Whether there is pole on boundary of parametric region of spline curve. + // \ru Существует ли полюс на границе параметрической области. \en Whether there is pole on boundary of parametric region. virtual bool GetPoleVMin() const; virtual bool GetPoleVMax() const; - virtual bool IsPole( double u, double v ) const; // \ru Является ли точка особенной. \en Whether the point is special. + virtual bool IsPole( double u, double v, double paramPrecision = PARAM_PRECISION ) const; // \ru Является ли точка особенной. \en Whether the point is special. virtual size_t GetUMeshCount() const; // \ru Выдать количество полигонов по u. \en Get the count of polygons by u. virtual size_t GetVMeshCount() const; // \ru Выдать количество полигонов по v. \en Get the count of polygons by v. diff --git a/C3d/Include/surf_coons_surface.h b/C3d/Include/surf_coons_surface.h index eb30cc0..77c39fc 100644 --- a/C3d/Include/surf_coons_surface.h +++ b/C3d/Include/surf_coons_surface.h @@ -223,7 +223,7 @@ public: virtual bool GetPoleUMax() const; virtual bool GetPoleVMin() const; virtual bool GetPoleVMax() const; - virtual bool IsPole( double u, double v ) const; // \ru Является ли точка особенной \en Whether the point is special + virtual bool IsPole( double u, double v, double paramPrecision = PARAM_PRECISION ) const; // \ru Является ли точка особенной \en Whether the point is special virtual void Refresh(); // \ru Сбросить все временные данные \en Flush all the temporary data /** \} */ diff --git a/C3d/Include/surf_corner_surface.h b/C3d/Include/surf_corner_surface.h index 002424e..ccadc19 100644 --- a/C3d/Include/surf_corner_surface.h +++ b/C3d/Include/surf_corner_surface.h @@ -121,7 +121,7 @@ public: virtual bool GetPoleUMax() const; virtual bool GetPoleVMin() const; virtual bool GetPoleVMax() const; - virtual bool IsPole( double u, double v ) const; // \ru Является ли точка особенной \en Whether the point is special + virtual bool IsPole( double u, double v, double paramPrecision = PARAM_PRECISION ) const; // \ru Является ли точка особенной \en Whether the point is special /** \} */ /** \ru \name Функции для работы в области определения поверхности diff --git a/C3d/Include/surf_cover_surface.h b/C3d/Include/surf_cover_surface.h index bfe8d8e..b8b1d55 100644 --- a/C3d/Include/surf_cover_surface.h +++ b/C3d/Include/surf_cover_surface.h @@ -127,7 +127,7 @@ public: virtual bool GetPoleUMax() const; virtual bool GetPoleVMin() const; virtual bool GetPoleVMax() const; - virtual bool IsPole( double u, double v ) const; // \ru Является ли точка особенной \en Whether the point is special + virtual bool IsPole( double u, double v, double paramPrecision = PARAM_PRECISION ) const; // \ru Является ли точка особенной \en Whether the point is special /** \} */ /** \ru \name Функции для работы в области определения поверхности diff --git a/C3d/Include/surf_curve_bounded_surface.h b/C3d/Include/surf_curve_bounded_surface.h index 69bd3a8..4d240e5 100644 --- a/C3d/Include/surf_curve_bounded_surface.h +++ b/C3d/Include/surf_curve_bounded_surface.h @@ -102,13 +102,13 @@ private: public : /// \ru Конструктор без установки пределов по u, v. \en Constructor without setting the u, v limits. - MbCurveBoundedSurface( MbSurface & initSurface ); + MbCurveBoundedSurface( const MbSurface & initSurface ); /// \ru Конструктор с установкой пределов по u, v. \en Constructor with setting the u, v limits. - MbCurveBoundedSurface( MbSurface & initSurface, double uin, double uax, double vin, double vax ); + MbCurveBoundedSurface( const MbSurface & initSurface, double uin, double uax, double vin, double vax ); /// \ru Конструктор с установкой пределов по u, v. \en Constructor with setting the u, v limits. - MbCurveBoundedSurface( MbSurface & initSurface, const MbRect & rect ); + MbCurveBoundedSurface( const MbSurface & initSurface, const MbRect & rect ); /// \ru Конструктор с установкой пределов по u, v. \en Constructor with setting the u, v limits. - MbCurveBoundedSurface( MbSurface & initSurface, const MbRect2D & rect ); + MbCurveBoundedSurface( const MbSurface & initSurface, const MbRect2D & rect ); /// \ru Конструктор с массивом контуров на поверхности. \en Constructor with array of contours on surface. MbCurveBoundedSurface( MbSurface & initSurface, RPArray & initCurves, bool sameContours ); /// \ru Конструктор с массивом контуров на плоскости (двумерных контуров). \en Constructor with array of contours on plane (two-dimensional contours). @@ -180,7 +180,7 @@ public : virtual bool GetPoleUMax() const; virtual bool GetPoleVMin() const; virtual bool GetPoleVMax() const; - virtual bool IsPole( double u, double v ) const; // \ru Является ли точка особенной \en Whether the point is special + virtual bool IsPole( double u, double v, double paramPrecision = PARAM_PRECISION ) const; // \ru Является ли точка особенной \en Whether the point is special /** \} */ /** \ru \name Функции для работы в области определения поверхности Функции PointOn, Derive... поверхностей корректируют параметры diff --git a/C3d/Include/surf_expansion_surface.h b/C3d/Include/surf_expansion_surface.h index 35990db..b009f7f 100644 --- a/C3d/Include/surf_expansion_surface.h +++ b/C3d/Include/surf_expansion_surface.h @@ -62,7 +62,7 @@ public: \en Second generating curve \~ */ MbExpansionSurface( const MbCurve3D & cr, const MbCurve3D & sp, bool sameCurve, bool sameSpine, - MbCurve3D * sl = c3d_null ); + const MbCurve3D * sl = c3d_null ); /** \brief \ru Конструктор по точке, образующей и направляющей. \en Constructor by point, generating curve and guide curve. \~ diff --git a/C3d/Include/surf_gregory_surface.h b/C3d/Include/surf_gregory_surface.h index 388eddb..8b10413 100644 --- a/C3d/Include/surf_gregory_surface.h +++ b/C3d/Include/surf_gregory_surface.h @@ -105,7 +105,7 @@ public: virtual bool GetPoleUMax() const; virtual bool GetPoleVMin() const; virtual bool GetPoleVMax() const; - virtual bool IsPole( double u, double v ) const; // \ru Является ли точка особенной \en Whether the point is special + virtual bool IsPole( double u, double v, double paramPrecision = PARAM_PRECISION ) const; // \ru Является ли точка особенной \en Whether the point is special /** \} */ /** \ru \name Функции для работы в области определения поверхности diff --git a/C3d/Include/surf_grid_surface.h b/C3d/Include/surf_grid_surface.h index 70146be..8e9cb60 100644 --- a/C3d/Include/surf_grid_surface.h +++ b/C3d/Include/surf_grid_surface.h @@ -376,7 +376,7 @@ private: 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. + // \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, diff --git a/C3d/Include/surf_join_surface.h b/C3d/Include/surf_join_surface.h index 6cec37f..57396fa 100644 --- a/C3d/Include/surf_join_surface.h +++ b/C3d/Include/surf_join_surface.h @@ -246,7 +246,7 @@ public: virtual bool GetPoleUMax() const; virtual bool GetPoleVMin() const; virtual bool GetPoleVMax() const; - virtual bool IsPole( double u, double v ) const; // \ru Является ли точка особенной \en Whether the point is special + virtual bool IsPole( double u, double v, double paramPrecision = PARAM_PRECISION ) const; // \ru Является ли точка особенной \en Whether the point is special /** \} */ /** \ru \name Функции для работы в области определения поверхности diff --git a/C3d/Include/surf_lofted_surface.h b/C3d/Include/surf_lofted_surface.h index 9bbfa06..cb183fa 100644 --- a/C3d/Include/surf_lofted_surface.h +++ b/C3d/Include/surf_lofted_surface.h @@ -94,9 +94,13 @@ protected: class MbLoftedSurfaceAuxiliaryData : public AuxiliaryData { public: DPtr data; ///< \ru Дополнительные данные о поверхности. \en Additional data about a surface. + MbVector3D normals[2]; ///< \ru Нормали первой и последней кривых. \en The first and last curves normals. MbLoftedSurfaceAuxiliaryData(); MbLoftedSurfaceAuxiliaryData( const MbLoftedSurfaceAuxiliaryData & init ); virtual ~MbLoftedSurfaceAuxiliaryData(); + void ResetNormals(); + void SetNormals( const MbVector3D n[2] ); + const MbVector3D & GetNormal( bool start, const MbCurve3D * cur ); }; mutable CacheManager cache; @@ -231,7 +235,7 @@ public: virtual bool GetPoleUMax() const; virtual bool GetPoleVMin() const; virtual bool GetPoleVMax() const; - virtual bool IsPole( double u, double v ) const; // \ru Является ли точка особенной \en Whether the point is special + virtual bool IsPole( double u, double v, double paramPrecision = PARAM_PRECISION ) const; // \ru Является ли точка особенной \en Whether the point is special /** \} */ /** \ru \name Функции для работы в области определения поверхности diff --git a/C3d/Include/surf_mesh_surface.h b/C3d/Include/surf_mesh_surface.h index cf6701a..d690328 100644 --- a/C3d/Include/surf_mesh_surface.h +++ b/C3d/Include/surf_mesh_surface.h @@ -21,7 +21,8 @@ class MATH_CLASS MbSurfaceCurve; class MATH_CLASS MbFunction; class MATH_CLASS MbSurfaceContiguousData; -class MbPatchWorkingData; +class MbRectPatchBaseData; +class MbCoonsPatchData; typedef std::map MapCurveParam; typedef std::map MapCrosses; @@ -35,10 +36,11 @@ typedef std::map MapCrosses; */ // --- enum MbeMeshSurfaceVersion { - msv_Ver0 = 0, ///< \ru Первая версия. \en The first version. - msv_Ver1, ///< \ru Вторая версия. \en The second version. - msv_Ver2, ///< \ru Третья версия. \en The third version. - msv_Ver3, ///< \ru Четвертая версия. \en The fourth version. + msv_Ver0 = 0, ///< \ru Нулевая версия. \en The first version. + msv_Ver1, ///< \ru Первая версия. \en The first version. + msv_Ver2, ///< \ru Вторая версия. \en The second version. + msv_Ver3, ///< \ru Третья версия. \en The third version. + msv_Ver4, ///< \ru Четвертая версия. \en The fourth version. msv_Count ///< \ru Количество версий. \en Count of versions. }; @@ -119,6 +121,8 @@ private: // \ru Последовательность точек пересечения кривых: \en Sequence of intersection points of curves: // \ru uCurves[0] и vCurves[0], uCurves[0] и vCurves[1], ... \en UCurves[0] and vCurves[0], uCurves[0] and vCurves[1], ... // \ru uCurves[1] и vCurves[0], uCurves[1] и vCurves[1], ... \en UCurves[1] and vCurves[0], uCurves[1] and vCurves[1], ... + SArray boundTwists[4];///< \ru Для границ сопряжения трансверсальные вектора и их прозводные, выраженные в СК связанной с границей. + ///<\ ru For conjugation boundaries, transverse vectors and their derivatives, expressed in the coordinate system associated with the boundary. SArray cornerTwists; ///< \ru Множество смешанных производных (сначала по u, потом по v) в угловых узлах сетки. \en Set of mixed derivatives (at first by v, then by u) at corner grid nodes. SArray cornerRegular;///< \ru Регулярность в углах поверхности. \en Regularity in the surface corners. // 3 x-------x 2 @@ -137,6 +141,7 @@ private: uint type1; ///< \ru Вид сопряжения заданный на curvesV[0]. \en Type of conjugation given on curvesV[0]. uint type2; ///< \ru Вид сопряжения, заданный на curvesU[nu-1]. \en Type of conjugation given on curvesU[nu-1]. uint type3; ///< \ru Вид сопряжения, заданный на curvesV[nv-1]. \en Type of conjugation given on curvesV[nv-1]. + bool g2Cont; ///< \ru Использовать форму Кунса второго порядка гладкости. \en Use the Koons form of the second order of smoothness. MbeMeshSurfaceVersion version; ///< \ru Версия реализации определяет форму поверхности. \en Version of implementation determines a shape of surface. @@ -156,7 +161,7 @@ private: class MbMeshSurfaceAuxiliaryData : public AuxiliaryData { public: DPtr data; ///< \ru Дополнительные данные о поверхности. \en Additional data about a surface. - DPtr mp; ///< \ru Дополнительные временные данные для ускорения вычислений. \en Additional temporary data to speed up computations. + DPtr mp; ///< \ru Дополнительные временные данные для ускорения вычислений. \en Additional temporary data to speed up computations. MbMeshSurfaceAuxiliaryData(); MbMeshSurfaceAuxiliaryData( const MbMeshSurfaceAuxiliaryData & init ); virtual ~MbMeshSurfaceAuxiliaryData(); @@ -196,6 +201,38 @@ public: /** \brief \ru Конструктор поверхности. \en Constructor of surface. \~ \details \ru Конструктор поверхности по двум семействам кривых. Каждая кривая семейства U должна пересекаться или + иметь точки скрещивания с каждой кривой семейства V. + \en Constructor of surface by two families of curves. Each curve of family U has to be intersected or + has intersection points with each curve of family V. \~ + \param[in] initU - \ru Множество кривых в направлении параметра u. + \en Set of curves at direction of parameter u. \~ + \param[in] initV - \ru Множество кривых в направлении параметра v. + \en Set of curves at direction of parameter v. \~ + \param[in] uClosed - \ru Замкнута ли поверхность по параметру u. + \en Whether the surface is closed by parameter u. \~ + \param[in] vClosed - \ru Замкнута ли поверхность по параметру v. + \en Whether the surface is closed by parameter v. \~ + \param[in] g2 - \ru Использовать форму Кунса второго порядка гладкости. + \en Use the Koons shape of the second order of smoothness. \~ + \param[in] same - \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. \~ + \param[in] types - \ru Ссылка на массив с типами сопряжений на границах. + \en Reference to array with types of conjugations at boundaries. \~ + \param[in] vers - \ru Версия реализации поверхности. + \en Version of surface implementation. \~ + */ + MbMeshSurface( RPArray & initU, RPArray & initV, + bool uClosed, bool vClosed, bool g2, + bool same, const SArray * types, + MbeMeshSurfaceVersion vers ); + + /** \brief \ru Конструктор поверхности. + \en Constructor of surface. \~ + \details \ru Конструктор поверхности по двум семействам кривых. Каждая кривая семейства U должна пересекаться или иметь точки скрещивания с каждой кривой семейства V. \en Constructor of surface by two families of curves. Each curve of family U has to be intersected or has intersection points with each curve of family V. \~ @@ -227,6 +264,43 @@ public: bool uClosed, bool vClosed, bool same, const SArray * types = c3d_null, MbeMeshSurfaceVersion vers = msv_Ver3 ); + + /** \brief \ru Конструктор поверхности. + \en Constructor of surface. \~ + \details \ru Конструктор поверхности по двум семействам кривых. Каждая кривая семейства U должна пересекаться или + иметь точки скрещивания с каждой кривой семейства V. + \en Constructor of surface by two families of curves. Each curve of family U has to be intersected or + has intersection points with each curve of family V. \~ + \param[in] initU - \ru Множество кривых в направлении параметра u. + \en Set of curves at direction of parameter u. \~ + \param[in] initV - \ru Множество кривых в направлении параметра v. + \en Set of curves at direction of parameter v. \~ + \param[in] parsU - \ru Множество параметров u для задающих кривых. + \en Set of parameters u for driving curves. \~ + \param[in] parsV - \ru Множество параметров v для задающих кривых. + \en Set of parameters v for driving curves. \~ + \param[in] uClosed - \ru Замкнута ли поверхность по параметру u. + \en Whether the surface is closed by parameter u. \~ + \param[in] vClosed - \ru Замкнута ли поверхность по параметру v. + \en Whether the surface is closed by parameter v. \~ + \param[in] g2 - \ru Использовать форму Кунса второго порядка гладкости. + \en Use the Koons shape of the second order of smoothness. \~ + \param[in] same - \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. \~ + \param[in] types - \ru Ссылка на массив с типами сопряжений на границах. + \en Reference to array with types of conjugations at boundaries. \~ + \param[in] vers - \ru Версия реализации поверхности. + \en Version of surface implementation. \~ + */ + MbMeshSurface( RPArray & initU, RPArray & initV, + SArray & parsU, SArray & parsV, + bool uClosed, bool vClosed, bool g2, + bool same, const SArray * types, + MbeMeshSurfaceVersion vers ); private: friend class CompositeMeshShellCreator; @@ -257,6 +331,8 @@ private: \en Reference to array with types of conjugations at boundaries. \~ \param[in] vers - \ru Версия реализации поверхности. \en Version of surface implementation. \~ + \param[in] g2 - \ru Использовать форму Кунса второго порядка гладкости. + \en Use the Koons shape of the second order of smoothness. \~ */ MbMeshSurface( c3d::SpaceCurvesSPtrVector & initU, c3d::SpaceCurvesSPtrVector & initV, c3d::DoubleVector & parsU, c3d::DoubleVector & parsV, @@ -264,7 +340,11 @@ private: bool uClosed, bool vClosed, const bool (&adjPatch)[4], const MbeMatingType( &types )[4], - MbeMeshSurfaceVersion vers ); + MbeMeshSurfaceVersion vers, bool g2 ); +#ifdef C3D_DEBUG + // \ru Проверить согласованность производых. \en Check the consistency of the derivatives. + bool TestSurfaceDerivatives() const; +#endif // C3D_DEBUG protected: /// \ru Конструктор-копия. \en Copy constructor. MbMeshSurface( const MbMeshSurface &, MbRegDuplicate * ); @@ -319,7 +399,7 @@ public: virtual bool GetPoleUMax() const; virtual bool GetPoleVMin() const; virtual bool GetPoleVMax() const; - virtual bool IsPole( double u, double v ) const; // \ru Является ли точка особенной \en Whether the point is special + virtual bool IsPole( double u, double v, double paramPrecision = PARAM_PRECISION ) const; // \ru Является ли точка особенной \en Whether the point is special /** \} */ /** \ru \name Функции для работы в области определения поверхности @@ -496,6 +576,9 @@ public: 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. @@ -524,6 +607,11 @@ private: // \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 = c3d_null ) 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; + // \ru Рассчитать параметры для границы патча. \en Calculate parameters for the patch boundary. + void PatchBoundExplore_v4( const MbCurve3D * curve, const MbFunction * fn, double par, size_t bnd, MbeMatingType tp, + MbCoonsPatchData & pd, ptrdiff_t ord ) 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; @@ -538,6 +626,15 @@ private: // \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 Prepare mixed derivatives at the boundaries of the mating. + void PrepareBoundaryTwists_v4( bool g2, bool read ); + // \ru Рассчитать смешанные производные старших порядков. \en Calculate high-order mixed derivatives. + void CalculateHighOrderTwists_v4( MbMeshSurface *(*adjSurf)[3], SArray (*extBounds)[4] ); + // \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 ); @@ -753,117 +850,5 @@ inline void MbMeshSurface::CheckParamsEx( double & u, double & v, MbMeshSurfaceA } -//------------------------------------------------------------------------------ -// \ru Получить граничные кривые MbMeshSurface. \en Get boundary curves of MbMeshSurface. -// --- -template -void GetBoundCurves( const MbMeshSurface & mesh, ConstCurvesVector & meshCurves ) //-V801 -{ // \ru Не менять порядок выдачи кривых \en Not to change an order of output of curves - meshCurves.reserve( meshCurves.size() + 4 ); - c3d::ConstSpaceCurveSPtr meshCurve; - - size_t cnt = mesh.GetUCurvesCount(); - if ( cnt > 0 ) { - meshCurve = mesh.GetUCurve( 0 ); - meshCurves.push_back( meshCurve ); - if ( cnt > 1 ) { - meshCurve = mesh.GetUCurve( --cnt ); - meshCurves.push_back( meshCurve ); - } - } - cnt = mesh.GetVCurvesCount(); - if ( cnt > 0 ) { - meshCurve = mesh.GetVCurve( 0 ); - meshCurves.push_back( meshCurve ); - if ( cnt > 1 ) { - meshCurve = mesh.GetVCurve( --cnt ); - meshCurves.push_back( meshCurve ); - } - } -} - - -//------------------------------------------------------------------------------ -// \ru Получить граничные кривые MbMeshSurface. \en Get boundary curves of MbMeshSurface. -// --- -template -void GetBoundCurves( const MbMeshSurface & mesh, ConstCurvesVector & meshCurves, c3d::BoolVector & tangentMatingFlags ) //-V801 -{ // \ru Не менять порядок выдачи кривых \en Not to change an order of output of curves - meshCurves.reserve( meshCurves.size() + 4 ); - tangentMatingFlags.reserve( tangentMatingFlags.size() + 4 ); - c3d::ConstSpaceCurveSPtr meshCurve; - - size_t cnt = mesh.GetUCurvesCount(); - if ( cnt > 0 ) { - meshCurve = mesh.GetUCurve( 0 ); - meshCurves.push_back( meshCurve ); - tangentMatingFlags.push_back( mesh.IsMatingType( trt_Tangent, 0 ) ); - - if ( cnt > 1 ) { - meshCurve = mesh.GetUCurve( --cnt ); - meshCurves.push_back( meshCurve ); - tangentMatingFlags.push_back( mesh.IsMatingType( trt_Tangent, 2 ) ); - } - } - cnt = mesh.GetVCurvesCount(); - if ( cnt > 0 ) { - meshCurve = mesh.GetVCurve( 0 ); - meshCurves.push_back( meshCurve ); - tangentMatingFlags.push_back( mesh.IsMatingType( trt_Tangent, 1 ) ); - if ( cnt > 1 ) { - meshCurve = mesh.GetVCurve( --cnt ); - meshCurves.push_back( meshCurve ); - tangentMatingFlags.push_back( mesh.IsMatingType( trt_Tangent, 3 ) ); - } - } -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Попытаться сделать параметры монотонно меняющимися и в пределах периода. - \en Try to make parameters monotonously changing and within the period. \~ - \details \ru Параметры местами не меняются. Пытаемся добиться монотонности прибавлением или вычитанием периода из значения параметра. - Получившийся в результате набор параметров должен помещаться в один период. - \en Parameters don't swap. Try to achieve monotony by addition or subtraction of period from value of parameter. - The resulting set of parameters has to be within single period. \~ - \param[in,out] params - \ru Множество параметров. Отсортирован после успешного выполнения. Если попытка не удалась - не изменяется. - \en Set of parameters. Ordered after successful execution. If attempt wasn't successful - doesn't change. \~ - \param[in] period - \ru Период. - \en Period. \~ - \return \ru true в случае успешного выполнения. - \en True in case of successful execution. \~ -*/ -//--- -bool MakeMonotoneParams( SArray & params, double period ); - - -/** \brief \ru Расчет параметризации поверхности. \en Calculate mesh surface parameters. - \details \ru Расчет параметров поверхности для выбранного направления. - \en Calculation of surface parameters for the selected direction.\~ - \param[in] dirU - \ru Выбранное направление поверхности. - \en Selected surface direction. \~ - \param[in] cls - \ru Замкнутость поверхности в направлении dirU. - \en Is the surface closed in the direction dirU. \~ - \param[in] curves - \ru Семейство кривых dirU. - \en Curves family dirU. \~ - \param[in] tcurves- \ru Семейство кривых !dirU. - \en Curves family !dirU. \~ - \param[in] tCurve - \ru Таблица пересечений кривых u и v. - \en The table of intersection of the curves u and v. \~ - \param[out] sParams - \ru Расчитанный набор параметров. - \en The calculated set of parameters. \~ -*/ -void SetParams_v3( bool dirU, bool cls, const RPArray & curves, const RPArray & tcurves, - const SArray & tCurve, SArray & sParams ); - - -/** \brief \ru Какую версию поверхности создавать в зависимости от версии математики. - \en Which version of the surface to create depending on the version of mathematics. \~ - \param[in] mathVers - \ru Версия математики. - \en Version of mathematics. \~ - \return \ru Версия поверхности по сети кривых. - \en Mesh surface version. \~ -*/ -MbeMeshSurfaceVersion GetMeshSurfaceVersion( const VERSION & mathVers ); #endif // __SURF_MESH_SURFACE_H diff --git a/C3d/Include/surf_offset_surface.h b/C3d/Include/surf_offset_surface.h index 831f2de..c2c4a58 100644 --- a/C3d/Include/surf_offset_surface.h +++ b/C3d/Include/surf_offset_surface.h @@ -231,7 +231,7 @@ public: virtual bool GetPoleUMax() const; virtual bool GetPoleVMin() const; virtual bool GetPoleVMax() const; - virtual bool IsPole ( double u, double v ) const; // \ru Является ли точка особенной. \en Whether the point is special. + virtual bool IsPole( double u, double v, double paramPrecision = PARAM_PRECISION ) const; // \ru Является ли точка особенной. \en Whether the point is special. /** \} */ /** \ru \name Функции для работы в области определения поверхности Функции PointOn, Derive... поверхностей корректируют параметры diff --git a/C3d/Include/surf_revolution_surface.h b/C3d/Include/surf_revolution_surface.h index 8b5b3d5..8e2fdc5 100644 --- a/C3d/Include/surf_revolution_surface.h +++ b/C3d/Include/surf_revolution_surface.h @@ -266,10 +266,10 @@ public: virtual void GetTesselation( const MbStepData & stepData, double u1, double u2, double v1, double v2, SArray & uu, SArray & vv ) const; - // \ru Существует ли полюс на границе параметрической области сплайновой кривой. \en Whether a pole exists on parametric region boundary of spline curve. + // \ru Существует ли полюс на границе параметрической области. \en Whether a pole exists on parametric region boundary. virtual bool GetPoleUMin() const; virtual bool GetPoleUMax() const; - virtual bool IsPole( double u, double v ) const; // \ru Является ли точка особенной. \en Whether the point is singular. + virtual bool IsPole( double u, double v, double paramPrecision = PARAM_PRECISION ) const; // \ru Является ли точка особенной. \en Whether the point is singular. virtual bool IsRectangular() const; // \ru Если true производные по u и v ортогональны. \en If true then derivatives with respect to u and v are orthogonal. virtual bool IsLineU() const; // \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. diff --git a/C3d/Include/surf_ruled_surface.h b/C3d/Include/surf_ruled_surface.h index 510a95c..85ac8f7 100644 --- a/C3d/Include/surf_ruled_surface.h +++ b/C3d/Include/surf_ruled_surface.h @@ -241,12 +241,12 @@ public: // \ru Дать двумерную матрицу преобразования из своей параметрической области в параметрическую область surf. \en Get two-dimensional transformation matrix from own parametric region to parametric region of 'surf'. virtual bool GetMatrixToSurface( const MbSurface & surf, MbMatrix & matr, VERSION version, double precision = METRIC_PRECISION ) const; - // \ru Существует ли полюс на границе параметрической области сплайновой кривой. \en Whether there is pole on boundary of parametric region of spline curve. + // \ru Существует ли полюс на границе параметрической области. \en Whether there is pole on boundary of parametric region. virtual bool GetPoleUMin() const; virtual bool GetPoleUMax() const; virtual bool GetPoleVMin() const; virtual bool GetPoleVMax() const; - virtual bool IsPole( double u, double v ) const; // \ru Является ли точка особенной. \en Whether the point is special. + virtual bool IsPole( double u, double v, double paramPrecision = PARAM_PRECISION ) const; // \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, diff --git a/C3d/Include/surf_section_surface.h b/C3d/Include/surf_section_surface.h index c387d4b..cc9fa78 100644 --- a/C3d/Include/surf_section_surface.h +++ b/C3d/Include/surf_section_surface.h @@ -209,15 +209,15 @@ public: static MbSectionSurface * Create( const MbCurve3D & rc, const MbCurve3D & g1, const MbCurve3D & g2, const MbCurve3D * c0, - MbeSectionShape f, - bool sense, - double uBeg, double uEnd, - MbFunction * func, - MbCurve * patt, - double buildSag, - double accuracy, - VERSION vers, - MbResultType & resType ); + MbeSectionShape f, + bool sense, + double uBeg, double uEnd, + const MbFunction * func, + const MbCurve * patt, + double buildSag, + double accuracy, + VERSION vers, + MbResultType & resType ); /** \ru \name Общие функции геометрического объекта \en \name Common functions of a geometric object @@ -309,7 +309,7 @@ public: virtual size_t GetVCount() const; virtual bool GetPoleVMin() const; // \ru Существует ли полюс на границе параметрической области. \en Whether a pole exists on parametric region boundary. virtual bool GetPoleVMax() const; // \ru Существует ли полюс на границе параметрической области. \en Whether a pole exists on parametric region boundary. - virtual bool IsPole( double u, double v ) const; // \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. /** \} */ /** \ru \name Общие функции поверхности diff --git a/C3d/Include/surf_sector_surface.h b/C3d/Include/surf_sector_surface.h index c8902ac..19a4f9d 100644 --- a/C3d/Include/surf_sector_surface.h +++ b/C3d/Include/surf_sector_surface.h @@ -171,7 +171,7 @@ public: SArray & uu, SArray & vv ) const; // \ru Существует ли полюс на границе параметрической области. \en Whether a pole exists on parametric region boundary. virtual bool GetPoleVMax() const; - virtual bool IsPole( double u, double v ) const; + virtual bool IsPole( double u, double v, double paramPrecision = PARAM_PRECISION ) const; virtual bool IsLineV() const; // \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. /** \} */ diff --git a/C3d/Include/surf_smooth_surface.h b/C3d/Include/surf_smooth_surface.h index d27a783..9323414 100644 --- a/C3d/Include/surf_smooth_surface.h +++ b/C3d/Include/surf_smooth_surface.h @@ -137,12 +137,12 @@ public: virtual bool IsVClosed() const; // \ru Проверка замкнутости по параметру v. \en Check of surface closedness in v direction. virtual double GetUPeriod() const; // \ru Вернуть период. \en Return period. - // \ru Существует ли полюс на границе параметрической области сплайновой кривой. \en Whether a pole exists on parametric region boundary of spline curve. + // \ru Существует ли полюс на границе параметрической области. \en Whether a pole exists on parametric region boundary. virtual bool GetPoleUMin() const; virtual bool GetPoleUMax() const; virtual bool GetPoleVMin() const; virtual bool GetPoleVMax() const; - virtual bool IsPole( double u, double v ) const; // \ru Является ли точка особенной. \en Whether the point is singular. + virtual bool IsPole( double u, double v, double paramPrecision = PARAM_PRECISION ) const; // \ru Является ли точка особенной. \en Whether the point is singular. /** \} */ /** \ru \name Функции для работы в области определения поверхности Функции PointOn и Derive... поверхностей сопряжения не корректируют @@ -383,7 +383,7 @@ void CorrectPolePoins(const MbSurface & surface, SArray & points ); // --- void CreateParams( const MbSurface & surface1, SArray & points1, const MbSurface & surface2, SArray & points2, - SArray * values, SArray * valuesDerive, + double radius, SArray * values, SArray * valuesDerive, bool °enerate1, bool °enerate2, ptrdiff_t & begN, ptrdiff_t & endN, SArray & params ); diff --git a/C3d/Include/surf_sphere_surface.h b/C3d/Include/surf_sphere_surface.h index cfef8af..4f951e1 100644 --- a/C3d/Include/surf_sphere_surface.h +++ b/C3d/Include/surf_sphere_surface.h @@ -245,10 +245,10 @@ public: virtual void SetLimit( double u1, double v1, double u2, double v2 ); virtual void SetExtendedParamRegion( double u1, double v1, double u2, double v2 ); virtual void IncludePoint( double u, double v ); // \ru Включить точку в область определения. \en Include a point into domain. - // \ru Существует ли полюс на границе параметрической области сплайновой кривой. \en Whether a pole exists on parametric region boundary of spline curve. + // \ru Существует ли полюс на границе параметрической области. \en Whether a pole exists on parametric region boundary. virtual bool GetPoleVMin() const; virtual bool GetPoleVMax() const; - virtual bool IsPole( double u, double v ) const; // \ru Является ли точка особенной. \en Whether the point is singular. + virtual bool IsPole( double u, double v, double paramPrecision = PARAM_PRECISION ) const; // \ru Является ли точка особенной. \en Whether the point is singular. virtual size_t GetUMeshCount() const; // \ru Выдать количество полигонов по u. \en Get the number of polygons in u-direction. virtual size_t GetVMeshCount() const; // \ru Выдать количество полигонов по v. \en Get the number of polygons in v-direction. diff --git a/C3d/Include/surf_spline_surface.h b/C3d/Include/surf_spline_surface.h index 9c37023..05f4775 100644 --- a/C3d/Include/surf_spline_surface.h +++ b/C3d/Include/surf_spline_surface.h @@ -378,12 +378,12 @@ public: virtual size_t GetUCount() const; virtual size_t GetVCount() const; - // \ru Существует ли полюс на границе параметрической области сплайновой кривой. \en Whether a pole exists on parametric region boundary of spline curve. + // \ru Существует ли полюс на границе параметрической области. \en Whether a pole exists on parametric region boundary. virtual bool GetPoleUMin() const; virtual bool GetPoleUMax() const; virtual bool GetPoleVMin() const; virtual bool GetPoleVMax() const; - virtual bool IsPole( double u, double v ) const; // \ru Является ли точка особенной. \en Whether the point is singular. + virtual bool IsPole( double u, double v, double paramPrecision = PARAM_PRECISION ) const; // \ru Является ли точка особенной. \en Whether the point is singular. /** \} */ /** \ru \name Функции для работы в области определения поверхности @@ -840,7 +840,7 @@ private: bool GetPoleUMax ( MbSplineSurfaceAuxiliaryData * ) const; bool GetPoleVMin ( MbSplineSurfaceAuxiliaryData * ) const; bool GetPoleVMax ( MbSplineSurfaceAuxiliaryData * ) const; - bool IsPole ( double u, double v, MbSplineSurfaceAuxiliaryData * ) const; // \ru Является ли точка особенной. \en Whether the point is singular. + 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; diff --git a/C3d/Include/surf_tessellation.h b/C3d/Include/surf_tessellation.h index 8d0c79a..0a47ee7 100644 --- a/C3d/Include/surf_tessellation.h +++ b/C3d/Include/surf_tessellation.h @@ -362,7 +362,7 @@ inline bool MbSurfaceWorkingData::Explore( double u0, double v0, bool ext0, doub { bool res = false; - // \\test-math\Kernel\Models\Building\Konkurs_2012b\60114\кабина\бампер.c3d + // \\omega\Kernel\Models\Building\Konkurs_2012b\60114\кабина\бампер.c3d // if ( (ext == ext0) && (::fabs(u0 - uv0.x) < EXTENT_EQUAL) && (::fabs(v0 - uv0.y) < EXTENT_EQUAL) ) { if ( (ext == ext0) && (u0 == uv0.x) && (v0 == uv0.y) ) { if ( ders[sdt_SurPoint].x != UNDEFINED_DBL && ders[sdt_DeriveU].x != UNDEFINED_DBL && ders[sdt_DeriveV].x != UNDEFINED_DBL ) { diff --git a/C3d/Include/surf_torus_surface.h b/C3d/Include/surf_torus_surface.h index f64df3a..4deebd6 100644 --- a/C3d/Include/surf_torus_surface.h +++ b/C3d/Include/surf_torus_surface.h @@ -263,10 +263,10 @@ public: virtual void SetExtendedParamRegion( double u1, double v1, double u2, double v2 ); virtual void IncludePoint( double u, double v ); // \ru Включить точку в область определения. \en Include a point into domain. - // \ru Существует ли полюс на границе параметрической области сплайновой кривой. \en Whether a pole exists on parametric region boundary of spline curve. + // \ru Существует ли полюс на границе параметрической области. \en Whether a pole exists on parametric region boundary. virtual bool GetPoleVMin() const; virtual bool GetPoleVMax() const; - virtual bool IsPole( double u, double v ) const; // \ru Является ли точка особенной. \en Whether the point is singular. + virtual bool IsPole( double u, double v, double paramPrecision = PARAM_PRECISION ) const; // \ru Является ли точка особенной. \en Whether the point is singular. virtual size_t GetUMeshCount() const; // \ru Выдать количество полигонов по u. \en Get the number of polygons in u-direction. virtual size_t GetVMeshCount() const; // \ru Выдать количество полигонов по v. \en Get the number of polygons in v-direction. diff --git a/C3d/Include/surface.h b/C3d/Include/surface.h index 39ca6b7..a4223cd 100644 --- a/C3d/Include/surface.h +++ b/C3d/Include/surface.h @@ -239,9 +239,9 @@ public: /// \ru Существует ли полюс на границе параметрической области. \en Whether a pole exists on parametric region boundary. virtual bool GetPoleVMax() const; /// \ru Является ли точка полюсом. \en Whether the point is a pole. - virtual bool IsPole( double u, double v ) const; + 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 ) const { return IsPole( uv.x, uv.y ); } + bool IsPole( const MbCartPoint & uv, double paramPrecision = PARAM_PRECISION ) const { return IsPole( uv.x, uv.y, paramPrecision ); } /** \} */ @@ -1960,6 +1960,7 @@ MATH_FUNC (MbeNewtonResult) NearestPoints( const MbSurface & surface0, bool ext0 \en Calculate parameters of the nearest points of surfaces. \~ \details \ru Вычислить параметры ближайших точек поверхностей и расстояние между этими точками. Криволинейные границы поверхностей не учитываются. \en Calculate parameters of the nearest points of surfaces and the distance between these points. Curvilinear boundaries of surfaces are not taken into account. \~ + \deprecated \ru Метод устарел. \en The method is deprecated. \~ \param[in] surface0 - \ru Поверхность. \en Surface. \~ \param[in] ext0 - \ru Признак поиска на продолжении поверхности surface0. diff --git a/C3d/Include/system_types.h b/C3d/Include/system_types.h index 98bf473..64dad0e 100644 --- a/C3d/Include/system_types.h +++ b/C3d/Include/system_types.h @@ -84,6 +84,26 @@ typedef uint32 VERSION; ///< \ru Версия. \en Version. \~ #define std_unique_ptr std::auto_ptr #endif +//------------------------------------------------------------------------------ +// \ru Умный указатель, обеспечивающий совместное владение объектом. +// \en Smart pointer that retains shared ownership of an object. +//--- +#define std_shared_ptr std::shared_ptr + +//------------------------------------------------------------------------------ +// \ru Шаблон функции, генерирующей обертку для объекта функции-члена. +// \en Template function generating a member function wrapper object. +//--- +#ifdef C3D_STANDARD_CXX_11_PARTIAL +// \ru Замена работает в большинстве случаев (в остальных случаях требуется напрямую использовать шаблоны STL). +// \en The replacement works in most cases (in the rest cases you need to use STL templates directly). + #define c3d_mem_fun std::mem_fn + #define c3d_mem_fun_ref std::mem_fn +#else + #define c3d_mem_fun std::mem_fun + #define c3d_mem_fun_ref std::mem_fun_ref +#endif + //------------------------------------------------------------------------------ // \ru Системные лимиты \en System limits //--- diff --git a/C3d/Include/templ_array2.h b/C3d/Include/templ_array2.h index 82a3424..3c394ff 100644 --- a/C3d/Include/templ_array2.h +++ b/C3d/Include/templ_array2.h @@ -258,7 +258,7 @@ template void Array2::SetElem( size_t ln, size_t cn, const Type & v ) { PRECONDITION( !!parr && ln < l && cn < c ); if ( !!parr && ln < l && cn < c ) - parr[ln][cn] = v; + parr[ln][cn] = v; // SKIP_SA } //------------------------------------------------------------------------------ @@ -306,7 +306,7 @@ template void Array2::Init( size_t ln, size_t cn, const Type & v ) { PRECONDITION( !!parr && ln < l && cn < c ); if ( !!parr && ln < l && cn < c ) - parr[ln][cn] = v; + parr[ln][cn] = v; // SKIP_SA } @@ -395,7 +395,7 @@ inline bool Array2::AddLine() if ( res ) memset( newLine, 0, c * sizeof(Type) ); } - parr[l - 1] = newLine; // \ru записать указатель в массив \en store pointer to the array + parr[l - 1] = newLine; // \ru записать указатель в массив \en store pointer to the array // SKIP_SA } return res; } @@ -557,7 +557,7 @@ bool assign_to_array( Array2 & arr, const Array2 & source ) Type ** sParr = source.parr; size_t n = arr.c * sizeof(Type); for ( size_t i = 0; i < arr.l; i++, aParr++, sParr++ ) - ::memcpy( *aParr, *sParr, n ); + ::memcpy( *aParr, *sParr, n ); // SKIP_SA } return true; } diff --git a/C3d/Include/templ_c_array.h b/C3d/Include/templ_c_array.h index dfce683..2410768 100644 --- a/C3d/Include/templ_c_array.h +++ b/C3d/Include/templ_c_array.h @@ -64,7 +64,7 @@ public : /// \ru Освободить память. \en Free memory. void FreeMemory() { SetArraySize( 0 ); } /// \ru Оператор доступа. \en An access operator. - Type & operator []( size_t idx ) const { PRECONDITION( idx < count ); return parr[idx]; } + Type & operator []( size_t idx ) const { PRECONDITION( idx < count ); return parr[idx]; } // SKIP_SA /// \ru Выделена ли память? \en Is memory allocated? bool IsNull () const { return parr == c3d_null; } /// \ru Выдать адрес начала массива. \en Get address of the beginning of an array. @@ -126,7 +126,7 @@ template inline void CcArray::Copy( const void * from, size_t cnt, size_t offset ) { PRECONDITION( (offset + cnt <= count) && (cnt ? from != c3d_null : true) ); - memcpy( parr + offset, from, cnt * sizeof(Type) ); + memcpy( parr + offset, from, cnt * sizeof(Type) ); // SKIP_SA } diff --git a/C3d/Include/templ_dptr.h b/C3d/Include/templ_dptr.h index 070ec4c..16335e4 100644 --- a/C3d/Include/templ_dptr.h +++ b/C3d/Include/templ_dptr.h @@ -10,11 +10,9 @@ #ifndef __TEMPL_DPTR_H #define __TEMPL_DPTR_H - #include #include - //------------------------------------------------------------------------------ /** \brief \ru Автоматический указатель. \en Smart pointer. \~ @@ -23,159 +21,196 @@ \ingroup Base_Tools_SmartPointers */ // --- -template +template class DPtr { public: - /// \ru Конструктор. \en Constructor. - DPtr(); + /// \ru Конструктор по умолчанию. \en Default constructor. + DPtr() : m_Ptr ( c3d_null ), m_Owner( c3d_null ) {} /// \ru Конструктор по указателю на объект. \en Constructor by pointer to an object. - DPtr( dtype * obj ); + /*explicit*/ DPtr( T * obj ); /// \ru Конструктор по автоматическому указателю на объект. \en Constructor by smart pointer to an object. - DPtr( const DPtr & dptr ); + DPtr( const DPtr & ); /// \ru Деструктор. \en Destructor. - ~DPtr(); + ~DPtr() { reset(); } public: /// \ru Оператор доступа. \en An access operator. - operator dtype* ( void ) const { return m_Ptr; } + operator T* ( void ) const { return m_Ptr; } /// \ru Оператор доступа. \en An access operator. - dtype & operator * ( void ) const { return *m_Ptr; } + T & operator * ( void ) const { return *m_Ptr; } // SKIP_SA /// \ru Оператор доступа. \en An access operator. - dtype * operator -> ( void ) const { return m_Ptr; } + T * operator -> ( void ) const { return m_Ptr; } /// \ru Оператор присваивания. \en The assignment operator. - DPtr & operator = ( dtype * pObj ); - /// \ru Оператор присваивания. \en The assignment operator. - DPtr & operator = ( const DPtr & src ); - /// \ru Оператор равенства. \en The equality operator. - bool operator == ( const DPtr & src ) const { return ( m_Ptr == src.m_Ptr ); } - /// \ru Оператор равенства. \en The equality operator. - bool operator == ( dtype * pObj ) const { return ( m_Ptr == pObj ); } - /// \ru Оператор неравенства. \en The inequality operator. - bool operator != ( const DPtr & src ) const { return ( !(operator == (src )) ); } - /// \ru Оператор неравенства. \en The inequality operator. - bool operator != ( dtype * pObj ) const { return ( !(operator == (pObj)) ); } + DPtr & operator = ( T * ); + /// \ru Оператор присваивания. \en The assignment operator. + DPtr & operator = ( const DPtr & src ); + +public: + /// \ru Функция освобождения объекта. \en A function of release an object. + DPtr & reset(); + /// \ru Выдать указать. \en Get pointer. + const T * get() const { return m_Ptr; } + /// \ru Выдать указать. \en Get pointer. + T * get() { return m_Ptr; } + /// \ru Выдать количество владеющих экземпляров DPtr. \en Get the number of DPtr objects that share ownership. + refcount_t use_count() const { return m_Owner ? m_Owner->use_count() : 0; } + +#ifdef C3D_STANDARD_CXX_11_PARTIAL + /// \ru Конструктор перемещения. \en Moving constructor. + DPtr( DPtr && src ) : m_Ptr( src.m_Ptr ), m_Owner( src.m_Owner ) + { + src.m_Ptr = c3d_null; + src.m_Owner = c3d_null; + } + /// \ru Оператор перемещения. \en Moving operator. + DPtr & operator = ( DPtr && src ) + { + std::swap( m_Ptr, src.m_Ptr ); + std::swap( m_Owner, src.m_Owner ); + return *this; + } +#endif // C3D_STANDARD_CXX_11_PARTIAL private: /// \ru Счетчик ссылок на объект. \en A counter of references to an object. - template - struct Owner { - dtype1 * m_Ptr; - uint m_RefCounter; - - Owner( dtype1 * obj ) + struct Owner // Поведение аналогично MtRefItem. + { + Owner( T * obj ) : m_Ptr( obj ) - , m_RefCounter(0) - {} - ~Owner() - { - PRECONDITION( m_RefCounter == 0 ); - delete m_Ptr; + , useCount( 0 ) + { + PRECONDITION( obj != c3d_null ); } - void Release() + void AddRef() const { ++useCount; } + void Release() const { - if ( m_RefCounter-- == 1 ) + PRECONDITION( useCount > 0 ); + if ( --useCount == 0 ) + { delete this; + } } + const T * get() const { return m_Ptr; } + T * get() { return m_Ptr; } + refcount_t use_count() const { return useCount; } + OBVIOUS_PRIVATE_COPY( Owner ); + + private: + T * m_Ptr; + mutable refcount_t useCount; + ~Owner() { PRECONDITION( useCount == 0 ); delete m_Ptr; } // Destructor should be private. }; private: - dtype * m_Ptr; ///< \ru Указатель на объект. \en A pointer to an object. - Owner * m_Owner; ///< \ru Счетчик ссылок на объект. \en A counter of references to an object. + T * m_Ptr; ///< \ru Указатель на объект. \en A pointer to an object. + Owner * m_Owner; ///< \ru Счетчик ссылок на объект. \en A counter of references to an object. }; - -//------------------------------------------------------------------------------- -/// \ru Конструктор. \en Constructor. -// --- -template -DPtr::DPtr() - : m_Ptr ( c3d_null ) - , m_Owner( c3d_null ) -{ -} - - //------------------------------------------------------------------------------- // \ru Конструктор по указателю на объект. \en Constructor by pointer to an object. // --- -template -DPtr::DPtr( dtype * obj ) - : m_Ptr ( obj ) +template +DPtr::DPtr( T * obj ) + : m_Ptr( obj ) , m_Owner( c3d_null ) { - if ( obj != c3d_null ) { - m_Owner = new Owner( obj ); - m_Owner->m_RefCounter++; + if ( obj != c3d_null ) + { + m_Owner = new Owner( obj ); + m_Owner->AddRef(); } } - //------------------------------------------------------------------------------- // \ru Конструктор копирования. \en Copy constructor. // --- -template -DPtr::DPtr( const DPtr & dptr ) +template +DPtr::DPtr( const DPtr & dptr ) : m_Ptr( dptr.m_Ptr ) , m_Owner( dptr.m_Owner ) { if ( m_Owner != c3d_null ) - m_Owner->m_RefCounter++; + m_Owner->AddRef(); // SKIP_SA } - //------------------------------------------------------------------------------- // \ru Оператор присваивания. \en Assignment operator. // --- -template -DPtr & DPtr::operator = ( dtype * pObj ) +template +DPtr & DPtr::operator = ( T * pObj ) { - if ( m_Ptr != pObj ) { - m_Ptr = pObj; - if ( m_Owner != c3d_null ) { - m_Owner->Release(); - m_Owner = c3d_null; - } - if ( pObj != c3d_null ) { - m_Owner = new Owner( pObj ); - m_Owner->m_RefCounter++; + if ( m_Ptr != pObj ) + { + reset(); + if ( pObj != c3d_null ) + { + m_Ptr = pObj; + m_Owner = new Owner( pObj ); + m_Owner->AddRef(); } } return *this; } - //------------------------------------------------------------------------------- // \ru Оператор присваивания. \en Assignment operator. // --- -template -DPtr & DPtr::operator = ( const DPtr & dptr ) +template +DPtr & DPtr::operator = ( const DPtr & dptr ) { - if ( m_Ptr != dptr.m_Ptr ) { - m_Ptr = dptr.m_Ptr; - if ( m_Owner != c3d_null ) { - m_Owner->Release(); - m_Owner = c3d_null; - } - if ( dptr.m_Ptr != c3d_null ) { + if ( m_Ptr != dptr.m_Ptr ) + { + reset(); + if ( dptr.m_Ptr != c3d_null ) + { + m_Ptr = dptr.m_Ptr; m_Owner = dptr.m_Owner; - m_Owner->m_RefCounter++; + m_Owner->AddRef(); } } return *this; } - //------------------------------------------------------------------------------- -// \ru Деструктор. \en Destructor. -// --- -template -DPtr::~DPtr() -{ - if ( m_Owner ) - m_Owner->Release(); +// \ru Функция освобождения объекта. \en A function of release an object. +//--- +template +DPtr & DPtr::reset() +{ + if ( m_Ptr == c3d_null ) + return *this; + + m_Ptr = c3d_null; + m_Owner->Release(); // SKIP_SA + m_Owner = c3d_null; + return *this; } +//------------------------------------------------------------------------------- +// +//--- +template +bool operator == ( const DPtr & left, const DPtr & right ) { return left.get() == right.get(); } +template +bool operator != ( const DPtr & left, const DPtr & right ) { return left.get() != right.get(); } + +/* +//------------------------------------------------------------------------------- +// +//--- +template +bool operator == ( const DPtr & left, const T2 * right ) { return left.get() == right; } +template +bool operator != ( const DPtr & left, const T2 * right ) { return left.get() != right; } +//------------------------------------------------------------------------------- +// +//--- +template +bool operator == ( const T1 * left, const DPtr & right ) { return left == right.get(); } +template +bool operator != ( const T1 * left, const DPtr & right ) { return left != right.get(); } +*/ #endif // __TEMPL_DPTR_H diff --git a/C3d/Include/templ_multimap.h b/C3d/Include/templ_multimap.h index afdc568..07e72fa 100644 --- a/C3d/Include/templ_multimap.h +++ b/C3d/Include/templ_multimap.h @@ -214,7 +214,7 @@ public: // \ru Получить текущее значение элемента. \en Get the current value of the element. ValType Value() const { - return !Empty() ? m_Ptr->m_val : (ValType)0; + return !Empty() ? m_Ptr->m_val : (ValType)0; // SKIP_SA } // \ru Получить пару с текущим ключом и текущим кзначением элемента. \en Get the pair with the current key and the current value of the element. Pair* GetPair() const diff --git a/C3d/Include/templ_pointer.h b/C3d/Include/templ_pointer.h index 0aa987d..4a42560 100644 --- a/C3d/Include/templ_pointer.h +++ b/C3d/Include/templ_pointer.h @@ -266,8 +266,18 @@ public: ~TPointer() { delete[] P; } public: char * operator = ( char src[] ) { delete[] P; return P = src; } - char * operator = ( const TPointer & src ) { delete[] P; return P = src.P; } + + char * operator = ( const TPointer & src ) + { + if ( &src != this ) { + delete[] P; + return P = src.P; + } + return c3d_null; + } + char & operator []( size_t i ) { return P[i]; } + #ifdef C3D_STANDARD_CXX_11_PARTIAL public: TPointer( TPointer && _Right ) diff --git a/C3d/Include/templ_rp_array.h b/C3d/Include/templ_rp_array.h index 528cb7f..5b37136 100644 --- a/C3d/Include/templ_rp_array.h +++ b/C3d/Include/templ_rp_array.h @@ -152,7 +152,7 @@ private: TEMPLATE_FRIEND bool set_Rarray_size TEMPLATE_SUFFIX ( RPArray &, size_t newSize ); TEMPLATE_FRIEND size_t find_in_array TEMPLATE_SUFFIX ( const RPArray & arr, const Type * el ); -#ifdef _MSC_VER +#if defined(_MSC_VER) && !defined(_MSVC_PERMISSIVE_OFF) TEMPLATE_FRIEND size_t find_in_array TEMPLATE_SUFFIX ( const RPArray & arr, const Type * el ); #endif // _MSC_VER @@ -720,7 +720,7 @@ size_t find_in_array( const RPArray & arr, const Type * el ) { } -#ifdef _MSC_VER // LF-Linux: ambiguous template specialization +#if defined(_MSC_VER) && !defined(_MSVC_PERMISSIVE_OFF) // LF-Linux: ambiguous template specialization //------------------------------------------------------------------------------- // \ru найти объект в массиве \en find an object in the array // --- diff --git a/C3d/Include/templ_s_array.h b/C3d/Include/templ_s_array.h index b26b7ea..608a9a6 100644 --- a/C3d/Include/templ_s_array.h +++ b/C3d/Include/templ_s_array.h @@ -786,7 +786,7 @@ void SArray::assign( Iterator first, Iterator last ) if ( set_array_size(*this, newCount, true) ) { PRECONDITION( newCount <= (ptrdiff_t)upper && count == 0 ); for ( ; first != last; ++first, ++count ) { - parr[count] = *first; + parr[count] = *first; // SKIP_SA } } } diff --git a/C3d/Include/templ_sparse_array2.h b/C3d/Include/templ_sparse_array2.h index 05750d6..bc6cbf9 100644 --- a/C3d/Include/templ_sparse_array2.h +++ b/C3d/Include/templ_sparse_array2.h @@ -554,7 +554,7 @@ inline bool SparseArray2::SetElem( size_t ln, size_t cn, const Type & item template inline SparseArray2 & SparseArray2::SetZero() { - std::for_each( data.begin(), data.end(), std::mem_fun_ref( &SparseRow::Clear ) ); + std::for_each( data.begin(), data.end(), c3d_mem_fun_ref( &SparseRow::Clear ) ); return *this; } @@ -607,7 +607,7 @@ inline bool SparseArray2::NzIndices( size_t ln, const NumberRange & search template inline void SparseArray2::NzUpdate() { - std::for_each( data.begin(), data.end(), std::mem_fun_ref( &SparseRow::NzUpdate ) ); + std::for_each( data.begin(), data.end(), c3d_mem_fun_ref( &SparseRow::NzUpdate ) ); } diff --git a/C3d/Include/templ_sptr.h b/C3d/Include/templ_sptr.h index df3e294..572c33c 100644 --- a/C3d/Include/templ_sptr.h +++ b/C3d/Include/templ_sptr.h @@ -50,25 +50,25 @@ public: m_pI->AddRef(); } /// \ru Конструктор копирования. \en Copy constructor. - SPtr( const SPtr & ptr ) : m_pI( c3d_null ) { assign(ptr.m_pI); } + SPtr( const SPtr & ptr ) : m_pI( c3d_null ) { assign(ptr.m_pI); } // SKIP_SA /// \ru Конструктор по совместимому указателю \en Constructor by compatible pointer template - SPtr( const SPtr<_T> & ptr ) : m_pI( ptr.get() ) { if ( m_pI != c3d_null ) { m_pI->AddRef();} } + SPtr( const SPtr<_T> & ptr ) : m_pI( c3d_null ) { assign(ptr.get()); } /// \ru Деструктор. \en Destructor. - ~SPtr() { if( m_pI != c3d_null ) m_pI->Release(); } + ~SPtr() { reset(); } public: // \ru Перегрузка операторов \en Operators overloading /// \ru Оператор преобразования к типу T* . \en An operator for conversion to the type T*. - operator T* ( void ) const { return m_pI; } + operator T* ( void ) const { return m_pI; } // SKIP_SA /// \ru Оператор преобразования к совместимому указателю. \en An operator for conversion to a compatible pointer. /* template operator SPtr<_T> () const { return SPtr<_T>( m_pI ); } */ /// \ru Оператор доступа. \en An access operator. - T & operator * () const { NULL_CHECK return *m_pI; } + T & operator * () const { NULL_CHECK return *m_pI; } // SKIP_SA /// \ru Оператор доступа. \en An access operator. - T * operator -> () const { NULL_CHECK return m_pI; } + T * operator -> () const { NULL_CHECK return m_pI; } // SKIP_SA /// \ru Оператор присваивания. \en The assignment operator. SPtr & operator = ( T * elem ) { return assign( elem ); } /// \ru Оператор присваивания. \en The assignment operator. @@ -103,11 +103,11 @@ public: /// \ru Функция присваивания указателем. \en A function of assignment by pointer. SPtr & assign( T * elem ); /// \ru Функция освобождения объекта. \en A function of release an object. - SPtr & reset( void ) { if( m_pI != c3d_null ) { m_pI->Release(); m_pI = c3d_null; } return *this; } + SPtr & reset( void ) { if( m_pI != c3d_null ) { m_pI->Release(); m_pI = c3d_null; } return *this; } // SKIP_SA /// \ru Функция доступа к элементу данных. \en A function of access to data element. - T * get() const { return m_pI; } + T * get() const { return m_pI; } // SKIP_SA /// \ru Функция отсоединяет объект. \en A function detaches an object. - T * detach() { T * obj = m_pI; m_pI = c3d_null; if ( obj != c3d_null ) obj->DecRef(); return obj; } + T * detach() { T * obj = m_pI; m_pI = c3d_null; if ( obj != c3d_null ) obj->DecRef(); return obj; } // SKIP_SA /// \ru Нулевой указатель? \en Is null pointer? bool is_null() const { return (( c3d_null == m_pI ) ? true : false ); } @@ -138,8 +138,8 @@ inline SPtr & SPtr::assign( T * elem ) { if ( m_pI != elem ) { - if ( elem != c3d_null ) { elem->AddRef(); } - if ( m_pI != c3d_null ) { m_pI->Release(); } + if ( elem != c3d_null ) { elem->AddRef(); } // SKIP_SA + if ( m_pI != c3d_null ) { m_pI->Release(); } // SKIP_SA m_pI = elem; } return *this; diff --git a/C3d/Include/templ_stack.h b/C3d/Include/templ_stack.h index 2109dee..4acf739 100644 --- a/C3d/Include/templ_stack.h +++ b/C3d/Include/templ_stack.h @@ -28,10 +28,11 @@ */ // --- template -class SStack: private SArray { +class SStack c3d_final: private SArray +{ public: /// \ru Конструктор. \en Constructor. - SStack( size_t i_upper = 0, uint16 i_delta = 1 ) + explicit SStack( size_t i_upper = 0, uint16 i_delta = 1 ) : SArray( i_upper, i_delta ) {} public: @@ -41,13 +42,17 @@ public: // \ru Оставить доступными следующие методы: \en Leave an access to the next methods: using SArray::Flush; ///< \ru Очистить стек. \en Clear the stack. - using SArray::Count; ///< \ru Количество элементов, содержащихся в стеке. \en The number of elements in stack. - using SArray::IsExist; ///< \ru Существует ли элемент. \en Whether an element exists. + using SArray::Count; ///< \ru Количество элементов, содержащихся в стеке. \en The number of elements in stack. + using SArray::IsExist; ///< \ru Существует ли элемент. \en Whether an element exists. using SArray::operator[]; ///< \ru Оператор прямого доступа - работает, как для массива. \en An operator of a direct access - it works as for an array. + using SArray::size; ///< \ru Количество элементов, содержащихся в стеке. \en The number of elements in stack. + using SArray::back; ///< \ru Количество элементов, содержащихся в стеке. \en The number of elements in stack. + using SArray::push_back; ///< \ru Количество элементов, содержащихся в стеке. \en The number of elements in stack. + using SArray::pop_back; ///< \ru Количество элементов, содержащихся в стеке. \en The number of elements in stack. + using SArray::empty; ///< \ru Количество элементов, содержащихся в стеке. \en The number of elements in stack. private: - SStack( const SStack & ); ///< \ru (!) Без реализации \en (!) There is no implementation - void operator =( const SStack & ); ///< \ru (!) Без реализации \en (!) There is no implementation + OBVIOUS_PRIVATE_COPY( SStack ); ///< \ru (!) Без реализации \en (!) There is no implementation }; @@ -55,8 +60,9 @@ private: /// \ru Добавить элемент в стек \en Add an element to the stack //--- template -void SStack::Push( const Type & obj ) { - SArray::Add( obj ); +void SStack::Push( const Type & obj ) +{ + SArray::push_back( obj ); } @@ -78,7 +84,7 @@ Type & SStack::Pop() { /// \ru Верхний элемент стека \en The top element of the stack //--- template -Type & SStack::Top() const { +Type & SStack::Top() const { return (*this)[SArray::count-1]; } diff --git a/C3d/Include/templ_type_modified.h b/C3d/Include/templ_type_modified.h index 302b5e4..273c395 100644 --- a/C3d/Include/templ_type_modified.h +++ b/C3d/Include/templ_type_modified.h @@ -32,6 +32,7 @@ private: bool modified_m; Type value_m; + typedef int WriteType; enum ValInit { valInit = 0 }; public : @@ -161,12 +162,24 @@ inline void TypeModified::SetModified( bool modified ) { #ifdef C3D_WINDOWS //_MSC_VER // LF_Linux //------------------------------------------------------------------------------ -// +// \ru В Visual Studio 2017 и более поздних версиях с включенной опцией /permissive- компилятор анализирует +// определения шаблонных функций и классов, идентифицируя используемые в них зависимые и независимые имена, +// как требует двухфазный поиск имен. +// В частности, независимые имена, которые не объявляются в контексте определения шаблона, +// вызывают диагностическое сообщение в соответствии с требованиями стандартов ISO C++. +// Поэтому в шаблонных функциях int заменен на зависимый тип WriteType, объявленный в шаблонном классе TypeModified. +// \en When the /permissive- option is set, the MSVC compiler (in Visual Studio 2017 and later) +// parses function and class template definitions, identifying dependent and non-dependent names +// used in templates as required for two-phase name look-up. +// In particular, non-dependent names that aren't declared in the context of a template definition +// cause a diagnostic message as required by the ISO C++ standards. +// Therefore, in the template functions int is replaced with the dependent type WriteType, declared in the TypeModified template class. +// See https://docs.microsoft.com/ru-ru/cpp/build/reference/permissive-standards-conformance?view=msvc-160#two-phase-name-look-up// --- // --- template reader& operator >> ( reader& in, TypeModified& ref ) { in >> ref.value_m; // \ru ИР K7 >> ref.modified_m; \en ИР K7 >> ref.modified_m; - int m; + typename TypeModified::WriteType m; in >> m; ref.modified_m = !!m; return in; @@ -178,7 +191,7 @@ reader& operator >> ( reader& in, TypeModified& ref ) { //--- template writer& operator << ( writer& out, const TypeModified& ref ) { - return out << ref.value_m << (int)ref.modified_m; + return out << ref.value_m << (typename TypeModified::WriteType)ref.modified_m; } #endif // C3D_WINDOWS diff --git a/C3d/Include/tool_log.h b/C3d/Include/tool_log.h index 55854c0..6a385e5 100644 --- a/C3d/Include/tool_log.h +++ b/C3d/Include/tool_log.h @@ -14,27 +14,44 @@ #include #include +namespace c3d //namespace c3d +{ + //------------------------------------------------------------------------------ -// \ru Потокобезопасные интерфейсы для ведение журнала сообщений и записи его в файл. -// Для каждого потока ведется отдельный лог, который записывается в отдельный файл. -// Доступны в дебаге. +// \ru Потокобезопасные интерфейсы для ведения журнала сообщений и записи его в файл. +// Для каждого потока ведется отдельный лог. +// Затем накопленные сообщения, сортированные по потокам записываются в файл. +// Интерфейсы доступны в дебаге. // \en Thread-safe interfaces for logging messages and writing the log to the file. -// Keep a separate log for each thread which is saved to a separate file. -// Available in debug configuration. +// A separate log is maintained for each thread. +// The collected messages, sorted by threads, are then written to a file. +// The interfaces are available in debug configuration. // -/* \ru Пример использования. \en Usage sample. - int k = 0; - START_LOGGING; // \ru Начинаем логирование. \en Start logging. - LOG_MSG( _T("Samplelog") ); // \ru Добавляем указанную строку в лог. \en Put a specified string to the log. - ... - // \ru Форматируем строку лога (оператор << Logger::Endl добавляет ее в лог). \en Format a log line (operator << Logger::Endl puts it to the log). - Logger::Get() << _T("Value ") << k << Logger::Endl; - ... - WRITE_LOG_FILE( _T("sample.log") ); // \ru Записываем лог в файл. \en Write the log to the file. - END_LOGGING; // \ru Заканчиваем логирование. \en Stop logging. +/* \ru Пример использования. + int k = 0; + SetLogDir( _T("C:\\AnoherDir") ); // Меняем умолчательную директорию для лог-файлов. + START_LOGGING; // Начинаем логирование. + LOG_MSG( _T("My sample log") ); // Добавляем указанную строку в лог. + ... + // Форматируем строку лога и добавляем ее в лог с помощью оператора << Logger::Endl. + c3d::Logger::Get() << _T("Value: ") << k << Logger::Endl; + ... + WRITE_LOG_FILE( _T("sample") ); // Записываем лог в файл sample.log. + END_LOGGING; // Отключаем логирование. + + \en Usage sample. + int k = 0; + SetLogDir( _T("C:\\AnoherDir") ); // Change default directory for log-files. + START_LOGGING; // Start logging. + LOG_MSG( _T("My sample log") ); // Put a specified string to the log. + ... + // Format a log line and puts it to the log using operator << Logger::Endl. + c3d::Logger::Get() << _T("Value: ") << k << Logger::Endl; + ... + WRITE_LOG_FILE( _T("sample") ); // Write the log to the file sample.log. + END_LOGGING; // Stop logging. */ // --- -#ifdef C3D_DEBUG //------------------------------------------------------------------------------ // \ru Класс позволяет форматировать строку для лога и добавлять ее в лог. @@ -42,72 +59,221 @@ // --- class MATH_CLASS Logger { +public: + + // \ru Тип сообщения. \en The message type. + enum MsgType + { + ms_info, + ms_warn, + ms_err + }; + public: // \ru Получить логгер. \en Get the logger. - static Logger& Get(); + static Logger & Get(); // \ru Следующие методы позволяют форматировать строку для лога. Работают с текущей строкой лога. - // \en Next methods allow to format a line to the log. Work with the current line of the log. + // \en Next methods can be used to format a log line. Work with the current line of the log. +#ifdef _UNICODE // \ru Добавить строку в текущую строку лога. \en Add a string to the current line of the log. - virtual Logger& operator << ( const TCHAR * ) = 0; + virtual Logger & operator << ( const TCHAR * ) = 0; +#endif + // \ru Добавить строку в текущую строку лога. \en Add a string to the current line of the log. + virtual Logger & operator << ( const char * ) = 0; // \ru Добавить integer в текущую строку лога. \en Add integer to the current line of the log. - virtual Logger& operator << ( const int & ) = 0; + virtual Logger & operator << ( const int & ) = 0; #if defined(PLATFORM_64) // \ru x32 совпадение типов ptrdiff_t и int \en x32 coincidence of ptrdiff_t and int types // \ru Добавить ptrdiff_t в текущую строку лога. \en Add ptrdiff_t to the current line of the log. - virtual Logger& operator << ( const ptrdiff_t & ) = 0; + virtual Logger & operator << ( const ptrdiff_t & ) = 0; #endif // \ru Добавить size_t в текущую строку лога. \en Add size_t to the current line of the log. - virtual Logger& operator << ( const size_t & ) = 0; + virtual Logger & operator << ( const size_t & ) = 0; // \ru Добавить double в текущую строку лога. \en Add double to the current line of the log. - virtual Logger& operator << ( const double & ) = 0; + virtual Logger & operator << ( const double & ) = 0; + // \ru Добавить признак тип сообщения в текущую строку лога. \en Add message type to the current line of the log. + virtual Logger & operator << ( MsgType type ) = 0; + // \ru Завершить форматирование текущей строки и добавить ее в лог. Следующий вызов оператора << создаст новую текущую строку. // \en Finish formatting of the current line and add it to the log. Next call to the operator << will create new current line. - virtual Logger& operator << ( Logger& (*man)( Logger& ) ) = 0; + virtual Logger & operator << ( Logger& (*man)( Logger& ) ) = 0; // \ru Манипулятор-признак завершения форматирования текущей строки лога. // \en Manipulator-indicator of finishing formatting of the current line of the log. - static Logger& Endl( Logger& ); + static Logger & Endl( Logger& ); }; -// \ru Начать или закончить логирование. \en Start or stop logging. -MATH_FUNC(void) SetLogging( bool allow ); -// \ru Записать лог в файл. Лог для каждого потока записывается в отдельный файл. -// \en Write the log to the file. Log of each thread writes to a separate file. +//------------------------------------------------------------------------------ +/** \brief \ru Переключатель логирования в области видимости. + \en Logging switch in a scope. \~ + \details \ru Вспомогательный класс для логирования в области видимости. + В конструкторе логирование включается, в деструкторе - отключается. + Если в конструкторе было указано имя файла, то перед отключением логирования + деструктор записывает накопленный лог в файл. + \en Helper class for the logging in the scope. + The logging starts in the constructor and ends in the destructor. + If a file name was defined in the constructor, then before ending the logging, + the destructor writes the collected log to the file. + \ru Пример использования: + { + // Начинаем логирование, лог будет записан в файл myLogFile.log. + c3d::LogHelper log( true, _T("myLogFile") ); + + // Добавляем указанную строку в лог. + LOG_MSG( _T("My formatted message") ); + ... + // Форматируем строку лога и добавляем ее в лог с помощью оператора << Logger::Endl. + c3d::Logger::Get() << _T("Value ") << k << Logger::Endl; + ... + } // При выходе из области кода логирование заканчивается и лог записывается в файл. + + \en Example of use: + { + // Start logging, the log will be written to the file myLogFile.log. + c3d::LogHelper log( true, _T("myLogFile") ); + + // Put a specified string to the log. + LOG_MSG( _T("My formatted message") ); + ... + // Format a log line and put it to the log using the operator << Logger::Endl. + c3d::Logger::Get() << _T("Value ") << k << Logger::Endl; + ... + } // When leaving the code scope the logging stops and the log is written to the file. + \ingroup Base_Tools +*/ +// --- +class MATH_CLASS LogHelper +{ +#ifdef C3D_DEBUG + bool _enabled; + c3d::string_t _file; +#endif + +public: + +#ifdef C3D_DEBUG + // \ru Параметр enable определяет, стартовать ли логирование. + // \en The enable parameter defines whether to start logging. + LogHelper( bool enable = true, const TCHAR* file = c3d_null ); + + // \ru Если в конструкторе было указано имя файла, то деструктор записывает накопленный лог в файл. + // \en If a file name was defined in the contructor, the destructor writes the collected log to the file. \~ + ~LogHelper(); +#else + LogHelper( bool, const TCHAR * ) {} + ~LogHelper() {} +#endif + +}; + +#ifdef C3D_DEBUG + +//------------------------------------------------------------------------------ +// \ru Функции логирования. \en Logging functions. +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +/** \brief \ru Установить директорию для логов. \en Set log directory. \~ + \details \ru По умолчанию лог-файлы сохраняются в директорию, установленную переменной LOG_PATH. + Функция позволяет изменить директорию для логов. + \en By default log-files are saved to the directory< defined by LOG_PATH variable. + The function allows changing the directory for logs. \~ + \ingroup Base_Tools +*/ +// --- +MATH_FUNC(void) SetLogDir( const TCHAR * name ); + +//------------------------------------------------------------------------------ +/** \brief \ru Начать или закончить логирование. \en Start or stop logging. \~ + \details \ru Начать или закончить логирование. \en Start or stop logging. \~ + \ingroup Base_Tools +*/ +// --- +MATH_FUNC(void) SetLogging( bool enable ); + +//------------------------------------------------------------------------------ +/** \brief \ru Записать лог в файл. \en Write the log to the file. \~ + \details \ru Записываются в файл сообщения, сортированные по потокам. + \en Write messages, sorted by threads, to the file. \~ + \ingroup Base_Tools +*/ +// --- MATH_FUNC(void) WriteLog( const TCHAR *fileName ); -// \ru Записать указанную строку в лог. \en Write a specified string to the log. +//------------------------------------------------------------------------------ +/** \brief \ru Записать указанную строку в лог. \en Write a specified string to the log. \~ + \details \ru Записать указанную строку в лог. \en Write a specified string to the log. \~ + \ingroup Base_Tools +*/ +// --- MATH_FUNC(void) LogMessage( const c3d::string_t &msg ); +//------------------------------------------------------------------------------ +/** \brief \ru Записать указанную строку и тип сообщения в лог. + \en Write a specified string and the message type to the log. \~ + \details \ru Записать указанную строку и тип сообщения в лог. + \en Write a specified string and the message type to the log. \~ + \ingroup Base_Tools +*/ +// --- +MATH_FUNC(void) LogMessage( const c3d::string_t &msg, Logger::MsgType type ); + + +//------------------------------------------------------------------------------ // \ru Макросы для операций логирования. \en Logging macros. +//------------------------------------------------------------------------------ + +// \ru Информация о месте. \en The place information. +#ifdef C3D_WINDOWS +#define __LOCATION__ __FILE__ "(" __DEFTOSTR__(__LINE__) "): function " __FUNCTION__ "(): " +#else +inline std::string __location() { + std::string s( __FILE__ "(" __DEFTOSTR__( __LINE__ ) "): function " ); + return s + std::string( __PRETTY_FUNCTION__ ) + "(): "; +} + +#define __LOCATION__ __location().c_str() +#endif // \ru Начать логирование. \en Start logging. -#define START_LOGGING SetLogging( true ); +#define START_LOGGING c3d::SetLogging( true ); // \ru Закончить логирование. \en Stop logging. -#define END_LOGGING SetLogging( false ); -// \ru Положить форматированную строку в лог. \en Put a formatted string to the log. -#define LOG_MSG(msg) LogMessage( msg ); +#define END_LOGGING c3d::SetLogging( false ); // \ru Записать лог в файл. Лог для каждого потока записывается в отдельный файл. // \en Write the log to the file. Log of each thread writes to a separate file. -#define WRITE_LOG_FILE(fileName) WriteLog( fileName ); +#define WRITE_LOG_FILE(fileName) c3d::WriteLog( fileName ); -#else +// \ru Положить в лог форматированную строку. \en Put a formatted string to the log. +#define LOG_MSG(msg) c3d::LogMessage( msg ); +// \ru Положить в лог форматированную строку с указанием места. \en Put a formatted string with the place info to the log. +#define LOG_MSG_PLACE(msg) c3d::Logger::Get() << __LOCATION__ << msg << Logger::Endl; +// \ru Положить в лог форматированную строку с типом сообщения и указанием места. \en Put a formatted string with the message type and the place to the log. +#define LOG_MSG_PLACE_TYPE(msg,type) c3d::Logger::Get() << __LOCATION__ << type << msg << Logger::Endl; + +#else + +//------------------------------------------------------------------------------ +// \ru Логирование работает только в Debug. \en Logging works in Debug Only. +//------------------------------------------------------------------------------ + +inline void CALL_DECLARATION SetLogDir( const TCHAR * ) {} inline void CALL_DECLARATION SetLogging( bool ){} inline void CALL_DECLARATION WriteLog( const TCHAR * ){} inline void CALL_DECLARATION LogMessage( const c3d::string_t & ){} +inline void CALL_DECLARATION LogMessage( const c3d::string_t &, Logger::MsgType ){} -#define START_LOGGING -#define END_LOGGING -#define LOG_MSG(msg) -#define WRITE_LOG_FILE(fileName) +#define __LOCATION__ "" +#define START_LOGGING c3d::SetLogging( true ); +#define END_LOGGING c3d::SetLogging( false ); +#define WRITE_LOG_FILE(fileName) c3d::WriteLog( fileName ); +#define LOG_MSG(msg) c3d::LogMessage( msg ); +#define LOG_MSG_PLACE(msg) LOG_MSG(msg) +#define LOG_MSG_PLACE_TYPE(msg,type) LOG_MSG(msg) #endif - -namespace c3d //namespace c3d -{ - //------------------------------------------------------------------------------ /** \brief \ru Включить контроль утечек памяти. \en Enable memory leakage control. \~ diff --git a/C3d/Include/tool_memory_leaks_check.h b/C3d/Include/tool_memory_leaks_check.h index 30bb993..2692568 100644 --- a/C3d/Include/tool_memory_leaks_check.h +++ b/C3d/Include/tool_memory_leaks_check.h @@ -12,7 +12,7 @@ #include #if ( defined(_MSC_VER) && (_MSC_VER > 1800) ) - #define ENABLE_MEMORY_LEAKS_CHECK +//#define ENABLE_MEMORY_LEAKS_CHECK #endif @@ -22,19 +22,34 @@ namespace c3d // namespace C3D #ifdef ENABLE_MEMORY_LEAKS_CHECK //------------------------------------------------------------------------------ -/** \brief \ru Базовый класс для контролируемых классов. - \en . \~ - \details \ru На конструкторе объект регистрируется в менеджере утечек, в деструкторе удаляется из списка зарегистрированных. +/** \brief \ru Базовый класс для контролируемых по утечкам классов. + \en Base class for leak-controlled classes. \~ + \details \ru Базовый класс для контролируемых по утечкам классов. + В конструкторе объект регистрируется в менеджере утечек, в деструкторе удаляется из списка зарегистрированных. Информация о всех объектах, которые остались в регистраторе, будет выведена. \n - \en . \n \~ + \en Base class for leak-controlled classes. \n \~ \ingroup Base_Tools */ // --- -class MATH_CLASS MemoryLeaksVerifiable -{ +class MATH_CLASS MemoryLeaksVerifiable { + friend class MemoryLeaksCatcher; + +private: + size_t m_index; ///< \ru Индекс данного объекта в контейнере зарегистрированных объектов. \en The index of this object in the container of registered objects. + protected: MemoryLeaksVerifiable(); virtual ~MemoryLeaksVerifiable(); + MemoryLeaksVerifiable( const MemoryLeaksVerifiable & ); + MemoryLeaksVerifiable( MemoryLeaksVerifiable && ); + MemoryLeaksVerifiable & operator=( const MemoryLeaksVerifiable & ); + MemoryLeaksVerifiable & operator=( MemoryLeaksVerifiable && ); + +private: + /// \ru Задать индекс данного объекта в контейнере зарегистрированных объектов. \en Set the index of this object in the container of registered objects. + void SetIndex( size_t ); + /// \ru Получить индекс данного объекта в контейнере зарегистрированных объектов. \en Get the index of this object in the container of registered objects. + size_t GetIndex() const; }; #else @@ -44,6 +59,3 @@ class MATH_CLASS MemoryLeaksVerifiable {}; #endif // ENABLE_MEMORY_LEAKS_CHECK } // namespace C3D - - - diff --git a/C3d/Include/tool_memory_leaks_utils.h b/C3d/Include/tool_memory_leaks_utils.h index 1becc43..fc677ca 100644 --- a/C3d/Include/tool_memory_leaks_utils.h +++ b/C3d/Include/tool_memory_leaks_utils.h @@ -18,8 +18,8 @@ namespace c3d // namespace C3D { #ifdef ENABLE_MEMORY_LEAKS_CHECK -typedef std::unordered_map MemoryLeaksRegisteredData; -typedef std::unique_ptr MemoryLeaksControllerPtr; +typedef std::vector< std::pair > MemoryLeaksRegisteredData; +typedef std::unique_ptr MemoryLeaksControllerPtr; //---------------------------------------------------------------------------------------- /** \brief \ru Контроллер утечек памяти. diff --git a/C3d/Include/tool_multithreading.h b/C3d/Include/tool_multithreading.h index cb55318..20bbeb1 100644 --- a/C3d/Include/tool_multithreading.h +++ b/C3d/Include/tool_multithreading.h @@ -530,12 +530,6 @@ inline void CacheManager::CleanAll( bool doPostproc, bool force ) #endif if ( IsSubscribed() ) UnsubcribeOnCleaning(); -#ifdef CACHE_DELETE_LOCK - if ( lock != c3d_null ) { - delete lock; - lock = c3d_null; - } -#endif } } diff --git a/C3d/Include/tool_string_util.h b/C3d/Include/tool_string_util.h index 7e6aa3a..22d77d3 100644 --- a/C3d/Include/tool_string_util.h +++ b/C3d/Include/tool_string_util.h @@ -72,7 +72,7 @@ inline wchar_t * wcsnewdup( const wchar_t * str, size_t minLen = 0 ) if ( len < minLen ) len = minLen; - return wcscpy( new wchar_t[len + 1], str ); + return wcscpy( new wchar_t[len + 1], str ); // SKIP_SA } //------------------------------------------------------------------------------ diff --git a/C3d/Include/topology.h b/C3d/Include/topology.h index 1040ef9..81f5491 100644 --- a/C3d/Include/topology.h +++ b/C3d/Include/topology.h @@ -668,8 +668,7 @@ public : bool ChangeCarrierBorne( const MbSurface & item, MbSurface & init, const MbMatrix & matr ); /// \ru Построение нормалей грани face и векторов от ребра в обе стороны. \en Construction of normals of a face and vectors from an edge to both sides. bool GetTraverses( const MbFace * face, const MbFace * other, bool plus, double t, - double paramStep, double metricStep, MbCartPoint & p0, - MbVector3D & leftNorm, MbVector3D & rightNorm, MbVector3D & left, MbVector3D &right, + double paramStep, double metricStep, MbCartPoint & p0, MbTwoTraverses & traverses, VERSION version = Math::DefaultMathVersion() ) const; /// \ru Построить вектор от ребра вне/внутрь грани (out==true/false). \en Construct a vector from edge to the outside/inside of a face(out==true/false). bool GetOutTraverse( const MbFace & face, bool plus, double t, double metricStep, MbCartPoint3D & q0, MbVector3D & outv, @@ -815,6 +814,33 @@ public : */ bool CuttingEdge( SArray & params, bool beginSafe, double eps, const MbSurface * surface, RPArray & edges ); + /** \brief \ru Разбить ребро по параметрам его кривой на несколько его частей. + \en Split the edge by the curve parameters into several pieces. \~ + \details \ru . Если beginSafe == true - ребро сохранит начальный участок, + Если beginSafe == false - ребро сохранит конечный участок. + По параметру 'eps' отсеиваются значения в контейнере 'params', совпадающие друг с другом и с начальным и конечным параметрами кривой пересечения. + Параметр 'surface' необходим только для толерантной кривой пересечения. + Контейнер 'edges' содержит отрезанные части. Отрезанные части встраиваются в циклы смежных граней. + \en . If beginSafe == true then the edge saves its starting piece, + If beginSafe == false then the edge saves its ending piece. + According to the parameter 'eps' drop out value in the container 'params', coinciding with each other and with the initial and final parameters of the intersection curve. + The parameter 'surface' plays a role only for tolerant edge. + The container 'edges' contains cut parts. The cut parts will be embedded in the loops of adjacent faces. \~ + \param[in] params - \ru Параметры кривой пересечения для разбиения ребра, + \en Parameters of intersection curve of edge to split, \~ + \param[in] beginSafe - \ru Ребро сохранит начальную половину (true) или ребро сохранит конечную половину (false), + \en The edge will keep a beginning piece (true) or the edge will keep an end piece (false) \~ + \param[in] eps - \ru Точность совпадения параметров разбиения, + \en Precision matching options of parameters to split, \~ + \param[in] surface - \ru Для толерантной кривой требуется указать поверхность грани, к кривой которой относятся параметры резки. + \en For tolerant curve it is required to specify a surface of face which contain a curve parameters belongs to. \~ + \param[out] edges - \ru Отрезанные части ребра. + \en The container of cut parts. \~ + \return \ru Возвращает true, если ребро было порезано. + \en Returns true, if the edge was cut. \~ + */ + bool CuttingEdge( SArray & params, bool beginSafe, double eps, const MbSurface * surface, + c3d::EdgesSPtrVector & edges ); /** \brief \ru Разбить ребро по точкам изменения выпуклости-вогнутости. \en Split the edge by points where the convexity changes. \~ @@ -1227,6 +1253,11 @@ public : /// \ru Найти ребро цикла по имени. \en Find loop edge by name. const MbCurveEdge * FindEdgeByName( const MbName & ) const; + /// \ru Найти вершину цикла по хешу имени. \en Find loop vertex by hash of a name. + const MbVertex * FindVertexByHash( const SimpleName h ) const; + /// \ru Найти ребро цикла по хешу имени. \en Find loop edge by hash of a name. + const MbCurveEdge * FindEdgeByHash( const SimpleName h ) const; + /// \ru Создать двумерный контур по циклу. \en Create two-dimensional contour by loop. MbContour & MakeContour( const MbSurface & surf, bool faceSense, bool doExact, MbRegDuplicate * iReg, bool calculateMetricLength = true ) const; @@ -1591,6 +1622,11 @@ public: /// \ru Найти ребро по имени. \en Find edge by name. const MbCurveEdge * FindEdgeByName( const MbName & ) const; + /// \ru Найти вершину по хешу имени. \en Find vertex by hash of a name. + const MbVertex * FindVertexByHash( const SimpleName h ) const; + /// \ru Найти ребро по хешу имени. \en Find edge by hash of a name. + const MbCurveEdge * FindEdgeByHash( const SimpleName h ) const; + /// \ru Установить метку ориентированного ребра. \en Set a label for an oriented edge. void SetOrientedLabel ( const MbCurveEdge & edge, MbeLabelState n, void * key = c3d_null ); /// \ru Вычислить ближайшее расстояние до ребра и ближайшие точки грани и ребра. \en Calculate the nearest distance to an edge and the nearest points of an edge. @@ -1638,7 +1674,7 @@ public: \en Two-dimensional normal of border at its closest point. \~ \param[out] loopNumber - \ru Индекс ближайшего цикла. \en Index of nearest loop. \~ - \param[out] loopNumber - \ru Индекс ближайшего ребра в цикле. + \param[out] edgeNumber - \ru Индекс ближайшего ребра в цикле. \en Index of nearest edge. \~ \param[out] corner - \ru 0, если проекция не располагается на стыке ребер, 1, если проекция располагается в конце ориентированного ребра с индексом edgeLoc, @@ -1976,5 +2012,11 @@ void MbFace::GetNeighborFaces( FacesVector & neighborFaces ) const } } +//------------------------------------------------------------------------------ +// \ru Найти минимальное расстояние до границы грани, а также смежную грань к ближайшей точке. +// \en Find the minimum distance to the edge of a face, as well as the adjacent face to the closest point. +// --- +void DistanceToBorderWithAdjFace( const MbFace & face, const MbSurface *& adjSurf, const MbCartPoint & p0, + double & dist, double & eps, size_t & loop, size_t & edge ); #endif // __TOPOLOGY_H diff --git a/C3d/Include/topology_faceset.h b/C3d/Include/topology_faceset.h index 838fc13..6a6bef2 100644 --- a/C3d/Include/topology_faceset.h +++ b/C3d/Include/topology_faceset.h @@ -779,6 +779,13 @@ public : /// \ru Найти грань по имени. \en Find face by name. MbFace * FindFaceByName ( const MbName & ); + /// \ru Найти вершину по хешу имени. \en Find vertex by hash of a name. + const MbVertex * FindVertexByHash( const SimpleName h ) const; + /// \ru Найти ребро по хешу имени. \en Find edge by hash of a name. + const MbCurveEdge * FindEdgeByHash ( const SimpleName h ) const; + /// \ru Найти грань по хешу имени. \en Find face by hash of a name. + const MbFace * FindFaceByHash ( const SimpleName h ) const; + /** \brief \ru Объединить подобные грани. \en Merge similar faces. \~ \details \ru Объединить подобные грани. @@ -882,9 +889,9 @@ void MbFaceShell::GetVertices( VerticesVector & vertices ) const } } else { - size_t count = faceSet.size(); - vertices.reserve( vertices.size() + count * 2 ); - for ( size_t i = 0; i < count; ++i ) + size_t facesCnt = faceSet.size(); + vertices.reserve( vertices.size() + facesCnt * 2 ); + for ( size_t i = 0; i < facesCnt; ++i ) faceSet[i]->GetVertices( vertices ); } } diff --git a/C3d/Include/tri_lump.h b/C3d/Include/tri_lump.h index 934f116..8b21708 100644 --- a/C3d/Include/tri_lump.h +++ b/C3d/Include/tri_lump.h @@ -66,7 +66,7 @@ public: } DEPRECATE_DECLARE - const MbFace & GetFace() const { return *face; } // deprecated + const MbFace & GetFace() const { return *face; } ///< \deprecated \ru Метод устарел. \en The method is deprecated. }; diff --git a/C3d/Lib/x32/Debug/c3d.lib b/C3d/Lib/x32/Debug/c3d.lib index 0f7efc7..194e770 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 1b814fe..8b4efb6 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 d213f2b..ffb52bb 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 da5cb45..e4a3e01 100644 Binary files a/C3d/Lib/x64/Release/c3d.lib and b/C3d/Lib/x64/Release/c3d.lib differ