- C3d aggiornamento delle librerie ( 117987).
This commit is contained in:
SaraP
2024-04-16 14:59:59 +02:00
parent 11460c8668
commit 827b79f766
95 changed files with 2803 additions and 854 deletions
+2 -2
View File
@@ -462,8 +462,8 @@ MATH_FUNC (MbContour *) DuplicateContour( const MbContour & cntr,
\en Create an offset curve. \~
\details \ru Создать эквидистантную кривую по базовой кривой и смещению в крайних точках. \n
\en Create the offset curve for a given curve with offset in the begin and the end points. \n \~
\param[in] curve - \ru Базовая кривая.
\en Base curve. \~
\param[in] curve - \ru Базовая кривая. Не может быть контуром или ломаной.
\en Base curve. Cannot be a contour or polyline. \~
\param[in] offset1 - \ru Смещение в точке Tmin базовой кривой.
\en Offset distance on point Tmin of base curve. \~
\param[in] offset2 - \ru Смещение в точке Tmax базовой кривой.
+3 -6
View File
@@ -14,12 +14,6 @@
#ifndef __ACTION_DIRECT_H
#define __ACTION_DIRECT_H
#include <templ_s_array.h>
#include <templ_array2.h>
#include <templ_rp_array.h>
#include <hash32.h>
#include <mb_enum.h>
#include <op_direct_mod_parameter.h>
class MATH_CLASS MbCartPoint3D;
@@ -42,6 +36,9 @@ struct MATH_CLASS NurbsBlockValues;
struct MATH_CLASS NurbsValues;
struct MATH_CLASS TransformValues;
template <class Type> class Array2;
template <class Type> class SArray;
template <class Type> class RPArray;
//------------------------------------------------------------------------------
/** \brief \ru Модифицировать тело по матрице.
+3 -49
View File
@@ -267,7 +267,7 @@ bool ArFind( const ParamsVector & arParam, double t, ptrdiff_t & id )
if ( arParam[idLeft] >= t ) { // \ru Если локальная левая не левая \en If the local left bound is not the left
idRight = idLeft; // \ru Установить новую правую \en Set new right bound
idLeft = 0; // \ru Установить левую минимальной \en Set the left bound to minimum
rangeId = idLeft; // \ru Вычислить новый диапазон \en Calculate the new range
rangeId = idRight - idLeft; // \ru Вычислить новый диапазон \en Calculate the new range
}
}
}
@@ -581,55 +581,9 @@ bool ArePointsOnLine( const PointsVector & pnts, double metricEps = METRIC_EPSIL
\en True if points lie on plane, \n otherwise false. \~
\ingroup Base_Algorithms
*/ // ---
template <class SpacePointsVector>
bool IsPlanar( const SpacePointsVector & pnts, MbPlacement3D * place, double mEps = METRIC_EPSILON )
{
bool isPlanar = false;
mEps = ::fabs( mEps );
const size_t pntsCnt = pnts.size();
template <class SpacePoints>
MATH_FUNC (bool) IsPlanar( const SpacePoints & pnts, MbPlacement3D * place, double mEps = METRIC_EPSILON );
if ( pntsCnt > 2 ) {
MbCartPoint3D pnt0( pnts[0] ), pnt_i, pnt_j;
MbVector3D vx, vy;
bool noPlace = true;
for ( size_t i = 1; i < pntsCnt && noPlace; i++ ) {
pnt_i = pnts[i];
if ( !c3d::EqualPoints( pnt_i, pnt0, mEps ) ) {
for ( size_t j = 1; j < pntsCnt && noPlace; j++ ) {
pnt_j = pnts[j];
if ( !c3d::EqualPoints( pnt_j, pnt0, mEps ) && !c3d::EqualPoints( pnt_j, pnt_i, mEps ) ) {
vx.Init( pnt0, pnt_i );
vy.Init( pnt0, pnt_j );
if ( !vx.Colinear( vy ) )
noPlace = false;
}
}
}
}
if ( !noPlace ) {
isPlanar = true;
MbPlacement3D wrkPlace( vx, vy, pnt0 );
if ( pntsCnt > 3 ) {
MbCartPoint3D pnt;
for ( size_t k = 1; k < pntsCnt; k++ ) {
pnt = pnts[k];
wrkPlace.PointProjection( pnt, pnt0 );
if ( !c3d::EqualPoints( pnt, pnt0, mEps ) ) {
isPlanar = false;
break;
}
}
}
if ( isPlanar && place != nullptr )
place->Init( wrkPlace );
}
}
return isPlanar;
}
//------------------------------------------------------------------------------
+11
View File
@@ -189,4 +189,15 @@ MATH_FUNC (bool) Corner( MbCurve * crv1, MbCurve * crv2,
const MbCartPoint & p1, const MbCartPoint & p2 );
//------------------------------------------------------------------------------
// Скругление двух последовательных кривых curve1 и curve2 радиусом rad.
// Предполагается, что конец кривой curve1 совпадает с началом кривой curve2.
// ---
MbArc * FilletTwoCurves( const MbCurve & curve1,
const MbCurve & curve2,
double rad,
double & tCross1, // параметр, соответствующий точке касания curve1 и дуги окружности
double & tCross2 ); // параметр, соответствующий точке касания curve2 и дуги окружности
#endif // __ALG_CURVE_FILLET_H
+2 -3
View File
@@ -381,10 +381,9 @@ public :
size_t SetProperties( const MbProperties & ) override; // \ru Установить свойства объекта. \en Set properties of object.
MbePrompt GetPropertyName() override; // \ru Выдать заголовок свойства объекта. \en Get a name of object property.
/// \ru Преобразование в текущий формат. \en Conversion into a current format.
void ConvertColors();
private:
void operator = ( const MbVisual & ); // \ru Не реализовано \en Not implemented
bool IsConverted() const;
void operator = ( const MbVisual & ); // \ru Не реализовано \en Not implemented
DECLARE_PERSISTENT_CLASS_NEW_DEL( MbVisual )
}; // MbVisual
+52 -31
View File
@@ -11,7 +11,6 @@
#include <templ_sptr.h>
#include <mb_cart_point.h>
#include <mb_operation_result.h>
#include <mb_matrix3d.h>
#include <set>
#include <map>
@@ -23,20 +22,45 @@ class MbHRepSolid;
\{
*/
//----------------------------------------------------------------------------------------
/** \brief \ru Код результата контроля столкновений или измерений.
\en Codes of collision detection or measuring query.
*/
//---
enum CDM_result
{
/*
Attention: (!) Dont reorder codes because they are sorted by priority.
*/
CDM_RESULT_None,
/// \ru Успешный результат измерительного запроса (например, запрос на минимальное расстояние).
/// \en Successful result of a measurement request (for example, a distance query).
CDM_RESULT_MeasuringSucceed,
/// \ru Столкновний не выявлено. Пересечений нет или поиск был прерван.
/// \en No collision was detected. There are no intersections or the search was aborted.
CDM_RESULT_NoCollisionDetected,
/// \ru Выявлено хотя бы одно объемное пересечение (коллизия).
/// \en Volume intersection (collision) detected.
CDM_RESULT_CollisionDetected,
/// \ru Неизвестная ошибка или внутрисистемная ошибка.
/// \en Unknown error or internal system error.
CDM_RESULT_Error,
};
//----------------------------------------------------------------------------------------
/// \ru Объект из набора контроля столкновений. \en Object from the set of collision detection.
//---
typedef const MbHRepSolid * cdet_item;
typedef MbResultType cdet_result; ///< \ru Код результата контроля столкновений. \en Result code of collision queries.
typedef CDM_result cdet_result; ///< \ru Код результата контроля столкновений. \en Result code of collision queries.
//----------------------------------------------------------------------------------------
// \ru Код результата контроля столкновений. \en Codes of collision detection.
// Codes of collision detection. Deprecated values, use CDM_result instead.
//---
const cdet_result CDET_RESULT_Intersected = rt_Intersect;
const cdet_result CDET_RESULT_NoIntersection = rt_NoIntersect;
const cdet_result CDET_RESULT_Ok = rt_Success;
const cdet_result CDET_RESULT_None = rt_None;
const cdet_result CDET_RESULT_Error = rt_Error;
const CDM_result CDET_RESULT_Intersected = CDM_RESULT_CollisionDetected;
const CDM_result CDET_RESULT_NoIntersection = CDM_RESULT_NoCollisionDetected;
const CDM_result CDET_RESULT_Ok = CDM_RESULT_MeasuringSucceed;
const CDM_result CDET_RESULT_None = CDM_RESULT_None;
const CDM_result CDET_RESULT_Error = CDM_RESULT_Error;
//----------------------------------------------------------------------------------------
// \ru Геометрический объект пользователя. \en User geometric item.
@@ -67,24 +91,24 @@ struct MATH_CLASS cdet_query
enum cback_res ///< Result code of the callback function
{
CBACK_VOID
, CBACK_SUFFICIENT ///< This code means that an app stops collision query for given pair of lumps
, CBACK_SKIP ///< Skip testing a given pair of the lumps
, CBACK_NEED ///< Enable testing a given pair of the lumps
, CBACK_BREAK ///< Break search of all collisions of the set
, CBACK_SUFFICIENT ///< This code means that an app stops collision query for given pair of lumps.
, CBACK_SKIP ///< Skip testing the given pair.
, CBACK_NEED ///< Enable testing the given pair.
, CBACK_BREAK ///< Break search of all collisions of the set.
, CBACK_SEARCH_MORE = CBACK_VOID ///< This code notifies a collision detector to continue working at cases CDET_INTERSECTED, CDET_TOUCHED.
};
enum message ///< Code of notification
{
CDET_NONE // No messages.
, CDET_QUERY_STARTED // The collision query is started for the all solids
, CDET_STARTED // The collision query is started for the given pair
, CDET_FINISHED // Collision detector complete searching a collisions for the given pair of lumps.
CDET_NONE ///< No messages.
, CDET_QUERY_STARTED ///< The collision query is started for the all objects of the scene set.
, CDET_STARTED ///< The collision query is started for the given pair of geometric objects.
, CDET_FINISHED ///< Collision detector complete searching collisions for the given pair of geometric objects.
// The codes below indicates the intersection state for a pair.
, CDET_NO_INTERSECTION // Definitely the pair has no intersection (this enum value for internal use only).
, CDET_TOUCHED // Touched faces has been founded with no penetration of the solids.
, CDET_INTERSECTED // The collided pair of objects founded.
, CDET_INCLUDED // The included pair of objects founded.
, CDET_NO_INTERSECTION ///< Definitely the pair has no intersection (this enum value for internal use only).
, CDET_TOUCHED ///< Touched faces has been founded with no penetration of the solids.
, CDET_INTERSECTED ///< The collided pair of objects founded.
, CDET_INCLUDED ///< The included pair of objects founded.
};
struct geom_element ///< Structure representing a collision detection geometry.
@@ -129,7 +153,7 @@ struct MATH_CLASS cdet_query_result: public cdet_query
cdet_query_result()
: cdet_query( QueryFunc )
, result( CDET_RESULT_NoIntersection )
, result( CDM_RESULT_NoCollisionDetected )
{}
cdet_query_result( const cdet_query_result & cQuery )
@@ -147,16 +171,16 @@ private:
{
case CDET_QUERY_STARTED: // The collision query is started for all solids of the scene.
{
q->result = CDET_RESULT_NoIntersection;
q->result = CDM_RESULT_NoCollisionDetected;
return CBACK_VOID;
}
case CDET_INTERSECTED: // First intersection is founded.
{
q->result = CDET_RESULT_Intersected;
q->result = CDM_RESULT_CollisionDetected;
return CBACK_SUFFICIENT;
}
case CDET_FINISHED: // A pair of solids is finished.
return (q->result == CDET_RESULT_Intersected) ? CBACK_BREAK : CBACK_VOID;
return (q->result == CDM_RESULT_CollisionDetected) ? CBACK_BREAK : CBACK_VOID;
default:
return CBACK_VOID;
@@ -341,17 +365,17 @@ typedef enum
CDET_EXAM_EnableComponentsOnly // Test collisions between components only.
, CDET_EXAM_Enabled // Enable the pair to test collisions.
, CDET_EXAM_Disabled // Reject the collision test of the pair.
} CDET_exam_status;
} CDM_exam_status;
//----------------------------------------------------------------------------------------
//
//---
struct MATH_CLASS CDET_item_data
struct MATH_CLASS CDM_item_data
{
cdet_item comp; // Descriptor of the component owning the inctance.
cdet_item inst; // Descriptor of the instance.
cdet_app_item appItem; // Application pointer for the instance or the component.
CDET_item_data()
CDM_item_data()
{
comp = inst = CDET_NULL;
appItem = CDET_APP_NULL;
@@ -361,7 +385,7 @@ struct MATH_CLASS CDET_item_data
//----------------------------------------------------------------------------------------
//
//---
typedef CDET_exam_status (*CDET_exam_func)( cdet_query *, const CDET_item_data &, const CDET_item_data & );
typedef CDM_exam_status (*CDM_exam_func)( cdet_query *, const CDM_item_data &, const CDM_item_data & );
/** \} */ // Collision_Detection
@@ -457,9 +481,6 @@ private:
MbProximityParameters & operator = ( const MbProximityParameters & ); // not implemented
};
#endif // __CDET_DATA_H
// eof
+7 -8
View File
@@ -10,7 +10,6 @@
#define __CDET_UTILITY_H
#include <cdet_data.h>
#include <mt_ref_item.h>
class MtRefItem;
class MbItem;
@@ -108,15 +107,15 @@ public:
/**
\brief \ru Проверить соударения между геометрическими объектами набора.
\en Check collisions between geometric objects of the set. \~
\return \ru Функция вернет CDET_RESULT_Intersected при обранужении хотя бы одной коллизии.
\en The function will return CDET_RESULT_Intersected if it detects at least one collision.
\return \ru Функция вернет CDM_RESULT_CollisionDetected при обранужении хотя бы одной коллизии.
\en The function will return CDM_RESULT_CollisionDetected if it detects at least one collision.
*/
cdet_result CheckCollisions( cdet_query & );
/**
\brief \ru Проверить соударения между геометрическими объектами набора.
\en Check collisions between geometric objects of the set. \~
\return \ru Функция вернет CDET_RESULT_Intersected при обранужении хотя бы одной коллизии.
\en The function will return CDET_RESULT_Intersected if it detects at least one collision.
\return \ru Функция вернет CDM_RESULT_CollisionDetected при обранужении хотя бы одной коллизии.
\en The function will return CDM_RESULT_CollisionDetected if it detects at least one collision.
*/
cdet_result CheckCollisions();
@@ -167,11 +166,11 @@ public: // the functions below can be deprecated in future version.
public: /*
Deprecated and testing functions
*/
void SetCallback( CDET_exam_func );
void SetCallback( CDM_exam_func );
// Use AppItem() insead this
cdet_app_item Component( size_t solIdx ) const;
/*DEPRECATE_DECLARE*/ cdet_app_item Component(size_t solIdx) const; // It in use yet.
// The func is deprecated. Instead, use CheckCollisions
cdet_result InterferenceDetect( void * formalPar = nullptr ) const;
DEPRECATE_DECLARE cdet_result InterferenceDetect( void * formalPar = nullptr ) const;
// The func is deprecated. Use SetDistanceTracking instead.
void SetDistanceComputationObjects( const MbLumpAndFaces &, const MbLumpAndFaces & );
// The func is deprecated. Use AddSolid/AddItem instead.
+18
View File
@@ -854,6 +854,10 @@ public:
virtual Mae_AnnotationType IsA() const;
/// \ru Получить групповой тип объекта. \en Get the group type of the object.
virtual Mae_AnnotationType Type() const;
/// \ru Получить значение. \en Get the value.
double GetValue() const { return value; }
/// \ru Задать значение. \en Set the value.
void SetValue( const double val ) { value = val; }
OBVIOUS_PRIVATE_COPY( MaSurfaceCondition )
};
@@ -878,6 +882,10 @@ public:
virtual Mae_AnnotationType IsA() const;
/// \ru Получить групповой тип объекта. \en Get the group type of the object.
virtual Mae_AnnotationType Type() const;
/// \ru Получить значение. \en Get the value.
double GetValue() const { return value; }
/// \ru Задать значение. \en Set the value.
void SetValue( const double val ) { value = val; }
OBVIOUS_PRIVATE_COPY(MaShapeTolerance)
};
@@ -920,5 +928,15 @@ void MaAnnotationItem::GetAnnotationText( Out dest ) const {
std::copy( annotationText.begin(), annotationText.end(), dest );
}
//------------------------------------------------------------------------------
// Получить геометрию PMI
// ---
c3d::ItemsSPtrVector GetPMIGeometry( const MbPMI & it );
//------------------------------------------------------------------------------
// Преобразовать текстовый элемент
// ---
SPtr<MbTextItem> CreateTextItem( const MaTextItem & it );
SPtr<MaTextItem> CreateTextItem( const MbTextItem & it );
#endif // __CONV_ANNOTATION_ITEM_H
+73 -39
View File
@@ -16,6 +16,7 @@
#include <mb_data.h>
#include <conv_predefined.h>
#include <reference_item.h>
#include <conv_requestor.h>
#include <tool_cstring.h>
#include <map>
@@ -309,11 +310,11 @@ enum eMsgDetail {
*/
struct C3DConverterDebugSettings {
/// \ru Включить вывод отладочной информации в CERR. \en Enable debug info out into the CERR stream.
bool enableCERRout;
bool enableCERRout { false };
/// \ru Включить вывод обхода дерева модели, реализованной на стороне пользователя. \en Enable logging the traverse of the user-implemented model tree.
bool cerrOutUserTreeTraverse;
bool cerrOutUserTreeTraverse { false };
/// \ru Включить вывод обхода промежуточного дерева модели. \en Enable logging the traverse of the intermediate model tree.
bool cerrOutIntermediateTreeTraverse;
bool cerrOutIntermediateTreeTraverse { false };
/** \brief \ru Сохранить двойник модели.
\en Save the twin of the model. \~
@@ -323,41 +324,29 @@ struct C3DConverterDebugSettings {
the original implementation of the model document.\~
*/
bool saveModelTwin;
bool saveModelTwin { false };
/// \ru Включить вывод статистики импортируемых объектов. \en Enable logging the statistic of imported objects.
bool cerrOutImportStatistic;
bool cerrOutImportStatistic { false };
/// \ru Добавлять целочисленный атрибут со значением id элемента из обменного файла. \en Attach int attribute which's value based on id from exchange file.
bool attachThisIdAttribute;
bool attachThisIdAttribute { false };
/// \ru Идентификатор элемента, для которого сделать вывод информации для тонкой отладки. \en Id of element for each save data for fine debugging.
ptrdiff_t elementIdFineDebug;
ptrdiff_t elementIdFineDebug { -1 };
/// \ru Путь для сохранения информации для тонкой отладки. \en Fine for saving data for fine debugging.
c3d::string_t pathFineDebug;
c3d::string_t pathFineDebug {};
/// \ru Режим логирования. \en Logging mode.
eLoggingMode loggingMode;
eLoggingMode loggingMode { elm_LoggingOff };
/// \ru Идентификатор для логирования. \en Id for logging.
ptrdiff_t idForLogging;
ptrdiff_t idForLogging { -1 };
/// \ru Конструктор. \en Conctuctor.
C3DConverterDebugSettings()
: enableCERRout( false )
, cerrOutUserTreeTraverse( false )
, cerrOutIntermediateTreeTraverse( false )
, cerrOutImportStatistic( false )
, saveModelTwin( false )
, attachThisIdAttribute( false )
, elementIdFineDebug( -1 )
, pathFineDebug()
, loggingMode( elm_LoggingOff )
, idForLogging( -1 )
{
}
~C3DConverterDebugSettings() {}
C3DConverterDebugSettings() = default;
~C3DConverterDebugSettings() = default;
};
@@ -411,7 +400,7 @@ public:
*/
class CONV_CLASS IConvertorProperty3D {
public :
virtual ~IConvertorProperty3D() {}
virtual ~IConvertorProperty3D() = default;
public:
/// \ru Получить имя документа. \en Get document's name.
@@ -500,22 +489,37 @@ public:
// \return \ru true - обычная работа, false - через API. \en true - ordinary work, false - via API. \~
// */
virtual bool CanShowMessages() const = 0;
/// \ru Дать данные вычисления триангуляции (для конвертера JT, STL и VRML). \en Get data for step calculation during triangulation (for JT, STL, VRML only).
virtual MbStepData TesselationParameters() const { return MbStepData(); }
/// \ru Дать данные вычисления триангуляции уровня детализации (для конвертера JT). \en Get data for step calculation during triangulation of LOD0 (for JTonly).
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 Выполнять ли слияние подобных граней. \en Whether to join similar faces.
virtual bool JoinSimilarFaces() const { return true; }
/// \ru Добавлять ли удаленные грани в качестве оболочек. \en Whether to add removed faces as shells.
virtual bool AddRemovedFacesAsShells() const { return false; }
/// \ru Получить запросчик масштабного коэффициента единиц длины. \en Get scale requester.
virtual SPtr<IScaleRequestor> GetScaleRequester() const { return SPtr<IScaleRequestor>{}; }
/// \ru Получить запросчик сшивки. \en Get stitch requester.
virtual SPtr<IStitchRequestor> GetStitchRequester() const { return SPtr<IStitchRequestor>{}; }
/// \ru Получить генератор однострочного идентификтора изделия. \en Get generator of one-line product identifier.
virtual SPtr<IProductIdMaker> ProductIdentifierGenerator() const { return SPtr<IProductIdMaker>(); }
/// \ru Получить настройки для выдачи отладочной информации. \en Get the settings of debug info.
virtual C3DConverterDebugSettings GetDebugSettings() const { return C3DConverterDebugSettings(); };
/// \ru Получить пользовательский преобразователь строк. \en Get user string transformer.
virtual SPtr<IC3DCharEncodingTransformer> GetUserCharEncodingTransformer() const { return SPtr<IC3DCharEncodingTransformer>( nullptr ); }
/// \ru Создавать раскрашенные копии компонент при импорте. \en Create colored replicas of components on import.
DEPRECATE_DECLARE virtual bool ImportComponentsWithColoredReplica() { return false; }
}; // IConvertorProperty3D
@@ -565,6 +569,8 @@ public:
bool attatchIdAttributes; ///< \ru Следует ли формировать атрибут на основе идентификатора элемнта в файле. \en Whether to attatch the element's id in file as attribute.
bool auditEnabled;
SPtr<IProductIdMaker> pruductIdMaker; ///< \ru Генератор однострочного идентификатора по данным об изделии. \en Generator of a single-line id based on product information attribute.
SPtr<IScaleRequestor> scaleRequester; /// \ru Запросчик масштабного коэффициента единиц длины. \en Scale requester.
SPtr<IStitchRequestor> stitchRequester; /// \ru Запросчик сшивки. \en Stitch requester.
C3DConverterDebugSettings debugSettings;
/// \ru Сведения о сообщениях конвертера. \en Converter message data.
@@ -579,30 +585,41 @@ public:
public:
ConvConvertorProperty3D(); ///< \ru Конструктор. \en Constructor.
~ConvConvertorProperty3D() override {};///< \ru Деструктор. \en Destructor.
~ConvConvertorProperty3D() override = default;///< \ru Деструктор. \en Destructor.
/// \ru Получить имя документа. \en Get document's name.
const std::string GetDocumentName () const override { return docName; };
/// \ru Получить имя файла для конвертирования. \en Get file name for converting.
const c3d::path_string FullFilePath () const override { return fileName; };
/// \ru Является ли файл текстовым. \en Whether the file is a text file.
bool IsFileAscii () const override;
/// \ru Получить версию формата при экспорте. \en Get the version of format for export.
long int GetFormatVersion () const override;
/// \ru Следует ли экспортировать только поверхности ( введено для работы конвертера IGES ). \en Whether to export only surfaces (introduced for work with converter IGES ).
bool IsOutOnlySurfaces() const override;
/// \ru Является ли экспортируемый документ сборкой. \en Whether the document for export is an assembly.
bool IsAssembling () const override { return true; };
bool IsAssembling () const override { return true; };
/// \ru Получить значение разрешения на импорт экспорт объектов определенного типа. \en Get the value of permission for import-export of objects of a certain type.
bool GetIoPermission( MbeIOPermiss nPermission ) const override;
/// \ru Получить значения разрешений на импорт экспорт объектов определенных типов. \en Get values of permission for import-export of objects of certain types.
void GetIoPermissions( std::vector<bool>& ioPermissions ) const override;
void GetIoPermissions( std::vector<bool>& ioPermissions ) const override;
/// \ru Установить разрешение на импорт экспорт объектов определенного типа. \en Set permission for import-export of objects of a certain type.
void SetIoPermission( MbeIOPermiss nPermission, bool isSet ) override;
/// \ru Получить значение специфичной строки для конвертера. \en Get the value of a certain string for the converter.
bool GetPropertyString ( MbeConverterStrings nString, std::string & propertyString ) const override;
bool GetPropertyString ( MbeConverterStrings nString, std::string & propertyString ) const override;
/// \ru Установить значение специфичной строки для конвертера. \en Set the value of a certain string for the converter.
void SetPropertyString ( MbeConverterStrings nString, const std::string & propertyString ) override;
/// \ru Представление текста в аннотационных объектах. \en Text representation in annotation objects.
eTextForm GetAnnotationTextRepresentation () const override;
/** \brief \ru Следует ли компоненты экспортировать в разные файлы (если позволяет формат).
@@ -612,17 +629,21 @@ public:
*/
bool ExportComponentsSeparately() const override;
/// \ru Получить ЛСК, относительно которой позиционирована модель. \en Get the location, the model is placed in.
MbPlacement3D GetOriginLocation() const override;
/// \ru Заменять ли принудительно СК компонент на правые. \en Replace components' placements to right-oriented.
bool ReplaceLocationsToRight() const override;
/** \brief \ru Сшивать ли поверхности автоматически.
\en If surfaces should be stitched automatically. \~
\return \ru true - Сшивать поверхности автоматически, false - Спросить пользователя, сшивать ли поверхности.
\en true - Stitch surfaces automatically, false - Ask user first time. \~
\param[out] stitchPrecision - \ru Точность сшивки.
\en Stitch precision. \~
*/ bool EnableAutoStitch( double& /*stitchPrecision*/ ) const override;
*/
bool EnableAutoStitch( double& /*stitchPrecision*/ ) const override;
/// \ru Получить множитель единиц длины по отношению к миллиметру. \en Get the factor of the length units to millimeters.
double LengthUnitsFactor() const override;
@@ -651,20 +672,33 @@ public:
/// \ru Дать данные вычисления триангуляции (для конвертера STL и VRML). \en Get data for step calculation during triangulation (for STL, VRML only).
MbStepData TesselationParameters() const override;
/// \ru Дать данные вычисления триангуляции уровня детализации (для конвертера JT). \en Get data for step calculation during triangulation of LOD0 (for JTonly).
MbStepData LOD0TesselationParameters() const override;
/// \ru Получить флаг сохранения совпадающих точек швов. (для конвертера STL и VRML). \en Whether to keep coincident points of seams (for STL, VRML only).
bool DualSeams() const override;
/// \ru Задать флаг сохранения совпадающих точек швов. (для конвертера STL и VRML). \en Whether to keep coincident points of seams (for STL, VRML only).
void DualSeams( bool );
/// \ru Получить настройки для выдачи отладочной информации. \en Get the settings of debug info.
C3DConverterDebugSettings GetDebugSettings() const override;
/// \ru Выполнять ли слияние подобных граней. \en Whether to join similar faces.
bool JoinSimilarFaces() const override { return joinSimilarFaces; }
bool JoinSimilarFaces() const override;
/// \ru Добавлять ли удаленные грани в качестве оболочек. \en Whether to add removed faces as shells.
bool AddRemovedFacesAsShells() const override { return addRemovedFacesAsShells; }
bool AddRemovedFacesAsShells() const override;
/// \ru Получить генератор однострочного идентификтора изделия. \en Get generator of one-line product identifier.
SPtr<IProductIdMaker> ProductIdentifierGenerator() const override { return pruductIdMaker; }
SPtr<IProductIdMaker> ProductIdentifierGenerator() const override;
/// \ru Получить запросчик масштабного коэффициента единиц длины. \en Get scale requester.
SPtr<IScaleRequestor> GetScaleRequester() const override;
/// \ru Получить запросчик сшивки. \en Get stitch requester.
SPtr<IStitchRequestor> GetStitchRequester() const override;
/// \ru Получить пользовательский преобразователь строк. \en Get user string transformer.
SPtr<IC3DCharEncodingTransformer> GetUserCharEncodingTransformer() const override;
@@ -711,21 +745,21 @@ public:
class CONV_CLASS IC3DCharEncodingTransformerStep : public IC3DCharEncodingTransformer
{
public:
virtual ~IC3DCharEncodingTransformerStep() {}
~IC3DCharEncodingTransformerStep() override = default;
//------------------------------------------------------------------------------
/** \brief \ru Преобразовать строку C3D в строку STD.
\en Transform C3D string to the STD one. \~
\ingroup Base_Tools_String
*/
virtual bool C3DToStd( const c3d::string_t& from, std::string & to );
bool C3DToStd( const c3d::string_t& from, std::string & to ) override;
//------------------------------------------------------------------------------
/** \brief \ru Преобразовать строку STD в строку C3D.
\en Transform STD string to the C3D one. \~
\ingroup Base_Tools_String
*/
virtual bool StdToC3D( const std::string & from, c3d::string_t& to );
bool StdToC3D( const std::string & from, c3d::string_t& to ) override;
};
@@ -740,21 +774,21 @@ public:
class CONV_CLASS IC3DCharEncodingTransformerUTF8 : public IC3DCharEncodingTransformer
{
public:
virtual ~IC3DCharEncodingTransformerUTF8() {}
~IC3DCharEncodingTransformerUTF8() override = default;
//------------------------------------------------------------------------------
/** \brief \ru Преобразовать строку C3D в строку STD.
\en Transform C3D string to the STD one. \~
\ingroup Base_Tools_String
*/
virtual bool C3DToStd( const c3d::string_t& from, std::string & to );
bool C3DToStd( const c3d::string_t& from, std::string & to ) override;
//------------------------------------------------------------------------------
/** \brief \ru Преобразовать строку STD в строку C3D.
\en Transform STD string to the C3D one. \~
\ingroup Base_Tools_String
*/
virtual bool StdToC3D( const std::string & from, c3d::string_t& to );
bool StdToC3D( const std::string & from, c3d::string_t& to ) override;
};
#endif // __CONV_EXCHANGE_SETTINGS_H
+4
View File
@@ -23,6 +23,7 @@
class MbPlacement3D;
class MbName;
class MbModel;
class MbAttributeContainer;
@@ -236,6 +237,9 @@ public:
/// \ru Сбросить итераторы вставок. \en Reset instances itrerators.
void ResetInstanceIterators();
/// \ru Инициализировать документ по двойнику. \en Build document by twin.
void InitDocumentByTwin( MbModel const& );
};
+8
View File
@@ -29,6 +29,7 @@ class IConvertorProperty3D;
class IConfigurationSelector;
class IAttributeNamesCollector;
class IConverterEventLogger;
class IConverterMetadataReceiver;
/**
\addtogroup Exchange_Interface
@@ -433,6 +434,13 @@ public:
*/
virtual void SetDeveloperEventLogger( SPtr<IConverterEventLogger> importEventLogger ) = 0;
/** \brief \ru Установить передачу метаданных.
\en Set metadata transfer. \~
\param[in] importEventLogger - \ru Указатель на устанавливаемый обработчик.
\en Pointer to handler to be set. \~
*/
virtual void SetMetadataTransferCallback( SPtr<IConverterMetadataReceiver> metadataTransferCallback ) = 0;
/** \brief \ru Прочитать файл формата SAT.
\en Read a file of SAT format. \~
+15
View File
@@ -117,4 +117,19 @@ public:
};
//------------------------------------------------------------------------------
/**
\brief \ru Интерфейс передачи метаданных.
\en Metadata transfer. \~
*/
// ---
class IConverterMetadataReceiver : public MbRefItem
{
public:
virtual bool InitMetadataForItem(const c3d::string_t& category, const c3d::string_t& nameInCategory, const c3d::string_t& contentType) = 0;
virtual void CloseMetadataForItem(const c3d::string_t& category, const c3d::string_t& nameInCategory) = 0;
virtual void TransferMetadataForItem(const c3d::string_t& category, const c3d::string_t& nameInCategory, const char* metadataBuffer, unsigned long int bufferCapacity) = 0;
};
#endif // __CONV_REQUESTOR_H
+329
View File
@@ -0,0 +1,329 @@
////////////////////////////////////////////////////////////////////////////////
/**
\file
\brief Создание топологических объектов по данным конвертеров.
*/
////////////////////////////////////////////////////////////////////////////////
#ifndef __CONV_TOPOLOGY_CREATOR_H
#define __CONV_TOPOLOGY_CREATOR_H
#include <vector>
#include <memory>
#include <templ_sptr.h>
#include <topology.h>
#include <se_elementary.h>
class MbSolid;
namespace c3d
{
namespace converter
{
//------------------------------------------------------------------------------
/** \brief \ru Менеджер вспомогательных операций работы с граничным представлением конвертеров.
\en . \~
\note \ru ЭКСПЕРИМЕНТАЛЬНАЯ.
\en EXPEREIMENTAL. \~
*/
class IConverterBrepManager
{
public:
virtual bool MakeSTEPEntities( MbSolid const & c3dBrep, std::vector<std::shared_ptr<const converter::SeBase>>&& enitites ) = 0;
IConverterBrepManager() = default;
virtual ~IConverterBrepManager() = default;
private:
IConverterBrepManager( IConverterBrepManager const & ) = delete;
IConverterBrepManager( IConverterBrepManager && ) = delete;
const IConverterBrepManager& operator =( IConverterBrepManager const & ) = delete;
};
CONV_FUNC( std::shared_ptr<IConverterBrepManager> ) GetConverterBrepManager();
CONV_FUNC( void ) ReleaseConverterBrepManager( std::shared_ptr<IConverterBrepManager>& );
class ITopologyCreator;
//------------------------------------------------------------------------------
/** \brief \ru Перечисление типов ошибок входных данных.
\en Enumeration of input error types . \~
\note \ru ЭКСПЕРИМЕНТАЛЬНАЯ.
\en EXPEREIMENTAL. \~
*/
enum ETcCheckError {
eTcErrLoopTopo, /// \ru Цикл не замкнут топологически. \en Loop is not closed topologically .
eTcErrFacePlusMinus, /// \ru Некорректные указания на левые/правые грани. \en Incorrect pointers to the left/right faces.
eTcErrCurveType, /// \ru Некорректный тип кривой. \en Incorrect curve type .
eTcErrCount /// \ru Количество типов ошибок. \en Number of error types.
};
//------------------------------------------------------------------------------
/** \brief \ru Базовый класс топологических объектов.
\en . \~
\note \ru ЭКСПЕРИМЕНТАЛЬНАЯ.
\en EXPEREIMENTAL. \~
*/
class CONV_CLASS TcObject
{
protected:
mutable std::vector< ETcCheckError > aErr;
int thisID;
public:
/// \ru Конструктор. \en Constructor.
TcObject();
///< \ru Конструктор копирования. \en Copy constructor.
TcObject( const TcObject& init );
/// \ru Деструктор. \en Destructor.
~TcObject() {};
// Проверить исходные данные. \en Check input data.
virtual bool CheckInputData( ITopologyCreator& topCreator ) const;
// Исправить исходные данные. \en Heal input data.
virtual bool HealAllInputData( ITopologyCreator& topCreator );
virtual bool HealInputData( ITopologyCreator& topCreator, const ETcCheckError& err );
};
//------------------------------------------------------------------------------
/** \brief \ru Грань.
\en Face. \~
\note \ru ЭКСПЕРИМЕНТАЛЬНАЯ.
\en EXPEREIMENTAL. \~
*/
class CONV_CLASS TcFace : public TcObject
{
SPtr<MbSurface> surface; ///< \ru Поверхность грани. \en Face surface.
std::vector<size_t> loops; ///< \ru Индексы циклов в TopologyCreator. \en Loops indexes in TopologyCreator.
bool faceSense; ///< \ru Ориентация грани. \en Face orientation.
SPtr<MbFace> mbFace; ///< \ru Созданная грань. \en Created face.
public:
/// \ru Конструктор. \en Constructor.
TcFace( MbSurface & _surface, const std::vector<size_t> & _loops, bool _faceSense );
///< \ru Конструктор копирования. \en Copy constructor.
TcFace( const TcFace & init );
///< \ru Оператор присваивания. \en Assignment operator.
const TcFace & operator= ( const TcFace & init );
/// \ru Деструктор. \en Destructor.
~TcFace();
/// \ru Выдать грань. \en Get face.
MbFace * GetFace() const;
/// \ru Создать грань. \en Create face.
void Create( ITopologyCreator & topCreator );
// Проверить исходные данные. \en Check input data.
virtual bool CheckInputData( ITopologyCreator& topCreator) const;
// Исправить исходные данные. \en Heal input data.
virtual bool HealInputData( ITopologyCreator& topCreator, const ETcCheckError& err );
};
//------------------------------------------------------------------------------
/** \brief \ru Цикл.
\en Loop. \~
*/
class CONV_CLASS TcLoop : public TcObject
{
std::vector<size_t> orientedEdges; ///< \ru Индексы ориентированных ребер в TopologyCreator. \en Oriented edges indexes in TopologyCreator.
SPtr<MbLoop> mbLoop; ///< \ru Созданный цикл. \en Created loop.
public:
/// \ru Конструктор. \en Constructor.
TcLoop( const std::vector<size_t> & _orientedEdges );
///< \ru Конструктор копирования. \en Copy constructor.
TcLoop( const TcLoop & init );
///< \ru Оператор присваивания. \en Assignment operator.
const TcLoop & operator= ( const TcLoop & init );
/// \ru Деструктор. \en Destructor.
~TcLoop();
/// \ru Выдать цикл. \en Get loop.
MbLoop * GetLoop() const;
/// \ru Выдать ориентированные ребра. \en Get oriented edges.
void GetOrientedEdges( std::vector<size_t>& aEdges ) const;
/// \ru Создать цикл. \en Create loop.
void Create( ITopologyCreator & topCreator );
// Проверить исходные данные. \en Check input data.
virtual bool CheckInputData( ITopologyCreator& topCreator) const;
// Исправить исходные данные. \en Heal input data.
virtual bool HealInputData( ITopologyCreator& topCreator, const ETcCheckError& err );
};
//------------------------------------------------------------------------------
/** \brief \ru Ориентированное ребро.
\en Oriented edge. \~
\note \ru ЭКСПЕРИМЕНТАЛЬНАЯ.
\en EXPEREIMENTAL. \~
*/
class CONV_CLASS TcOrientedEdge : public TcObject
{
size_t curveEdge; ///< \ru Индекс ребра в TopologyCreator. \en Edge index in TopologyCreator.
bool orient; ///< \ru Ориентация ребра. \en Edge orientation.
SPtr<MbOrientedEdge> mbOrientedEdge; ///< \ru Созданное ориентированное ребро. \en Created oriented edge.
public:
/// \ru Конструктор. \en Constructor.
TcOrientedEdge( size_t _curveEdge, bool _orient );
///< \ru Конструктор копирования. \en Copy constructor.
TcOrientedEdge( const TcOrientedEdge & init );
///< \ru Оператор присваивания. \en Assignment operator.
const TcOrientedEdge & operator= ( const TcOrientedEdge & init );
/// \ru Деструктор. \en Destructor.
~TcOrientedEdge();
/// \ru Выдать ориентированное ребро. \en Get oriented edge.
MbOrientedEdge * GetOrientedEdge() const;
/// \ru Выдать индекс грани справа от ребра. \en Get index of the face to the right of the edge.
size_t GetFacePlusIndex( ITopologyCreator& topCreator ) const;
/// \ru Выдать индекс грани слева от ребра. \en Get index of the face to the left of the edge.
size_t GetFaceMinusIndex( ITopologyCreator& topCreator ) const;
/// \ru Выдать ориентацию ребро. \en Get orientation.
bool GetOrient() const { return orient; }
/// \ru Выдать индекс ребра. \en Get index of the edge.
size_t GetCurveEdge() const { return curveEdge; }
/// \ru Создать ориентированное ребро. \en Create oriented edge.
void Create( ITopologyCreator & topCreator );
//// Проверить исходные данные. \en Check input data.
//virtual bool CheckInputData( TopologyCreator& topCreator) const;
//// Исправить исходные данные. \en Heal input data.
//virtual bool HealInputData( TopologyCreator& topCreator, const ETcCheckError& err );
};
//------------------------------------------------------------------------------
/** \brief \ru Ребро.
\en Edge. \~
\note \ru ЭКСПЕРИМЕНТАЛЬНАЯ.
\en EXPEREIMENTAL. \~
*/
class CONV_CLASS TcCurveEdge : public TcObject
{
SPtr<MbCurve3D> curve3D; ///< \ru Трехмерная кривая ребра. \en 3D curve of edge.
size_t facePlus, faceMinus; ///< \ru Индексы граней ребра в TopologyCreator. \en Edge faces indexes in TopologyCreator.
size_t begVertex, endVertex; ///< \ru Индексы вершин ребра в TopologyCreator. \en Edge vertices indexes in TopologyCreator.
SPtr<MbCurveEdge> mbCurveEdge; ///< \ru Созданное ребро. \en Created edge.
public:
/// \ru Конструктор. \en Constructor.
TcCurveEdge( MbCurve3D & _curve3D, size_t _facePlus, size_t _faceMinus, size_t _begVertex, size_t _endVertex );
///< \ru Конструктор копирования. \en Copy constructor.
TcCurveEdge( const TcCurveEdge & init );
///< \ru Оператор присваивания. \en Assignment operator.
const TcCurveEdge & operator= ( const TcCurveEdge & init );
/// \ru Деструктор. \en Destructor.
~TcCurveEdge();
/// \ru Выдать ребро. \en Get edge.
MbCurveEdge * GetCurveEdge() const;
/// \ru Выдать индекс начальной вершины. \en Get index of the begin vertex.
size_t GetBegVertex( const bool orient ) const { return orient? begVertex : endVertex; }
/// \ru Выдать индекс конечной вершины. \en Get index of the end vertex.
size_t GetEndVertex( const bool orient ) const { return orient? endVertex : begVertex; }
/// \ru Выдать индекс грани справа от ребра. \en Get index of the face to the right of the edge.
size_t GetFacePlus() const { return facePlus; }
/// \ru Выдать индекс грани слева от ребра. \en Get index of the face to the left of the edge.
size_t GetFaceMinus() const { return faceMinus; }
/// \ru Создать ребро. \en Create edge.
void Create( ITopologyCreator & topCreator );
// Проверить исходные данные. \en Check input data.
bool CheckInputData( ITopologyCreator& topCreator ) const final;
// Исправить исходные данные. \en Heal input data.
bool HealInputData( ITopologyCreator& topCreator, const ETcCheckError& err ) final;
};
//------------------------------------------------------------------------------
/** \brief \ru Вершина.
\en Vertex. \~
\note \ru ЭКСПЕРИМЕНТАЛЬНАЯ.
\en EXPEREIMENTAL. \~
*/
class CONV_CLASS TcVertex : public TcObject
{
MbCartPoint3D point; ///< \ru Трехмерная точка. \en 3D point.
SPtr<MbVertex> mbVertex; ///< \ru Созданная вершина. \en Created vertex.
public:
/// \ru Конструктор. \en Constructor.
TcVertex( const MbCartPoint3D & _point );
///< \ru Конструктор копирования. \en Copy constructor.
TcVertex( const TcVertex & init );
///< \ru Оператор присваивания. \en Assignment operator.
const TcVertex & operator= ( const TcVertex & init );
/// \ru Деструктор. \en Destructor.
~TcVertex();
/// \ru Выдать вершину. \en Get vertex.
MbVertex * GetVertex() const;
/// \ru Создать вершину. \en Create vertex.
void Create( ITopologyCreator & topCreator );
//// Проверить исходные данные. \en Check input data.
//virtual bool CheckInputData( TopologyCreator& topCreator) const;
//// Исправить исходные данные. \en Heal input data.
//virtual bool HealInputData( TopologyCreator& topCreator, const ETcCheckError& err );
};
//------------------------------------------------------------------------------
/** \brief \ru Класс для создания тела по данным топологии.
\en Class for creating a solid by topology data. \~
\note \ru ЭКСПЕРИМЕНТАЛЬНАЯ.
\en EXPEREIMENTAL. \~
*/
class CONV_CLASS ITopologyCreator
{
public:
/// \ru Конструктор по умолчанию пустой. \en Default constructor.
ITopologyCreator() = default;
/// \ru Деструктор. \en Destructor.
virtual ~ITopologyCreator() = default;
/// \ru Инициализировать. \en Initialize.
virtual void Init( const std::vector<TcFace> & _faces, const std::vector<TcLoop> & _loops, const std::vector<TcOrientedEdge> & _orientedEdges, const std::vector<TcCurveEdge> & _curveEdges, const std::vector<TcVertex> & _vertices ) = 0;
/// \ru Выдать грань. \en Get face.
virtual TcFace * GetFace( size_t ) = 0;
/// \ru Выдать цикл. \en Get loop.
virtual TcLoop * GetLoop( size_t ) = 0;
/// \ru Выдать ориентированное ребро. \en Get oriented edge.
virtual TcOrientedEdge * GetOrientedEdge( size_t ) = 0;
/// \ru Выдать ребро. \en Get edge.
virtual TcCurveEdge * GetCurveEdge( size_t ) = 0;
/// \ru Выдать вершину. \en Get vertex.
virtual TcVertex * GetVertex( size_t ) = 0;
/// \ru Создать тело. \en Create solid.
virtual SPtr<MbSolid> CreateSolid() = 0;
private:
ITopologyCreator( ITopologyCreator const & ) = delete;
ITopologyCreator( ITopologyCreator && ) = delete;
ITopologyCreator const & operator=( ITopologyCreator const & ) = delete;
};
/// \ru Получить формирователь граничного представления C3D по 3D-данным. \en Get C3D boundary representation generator.
CONV_FUNC( std::shared_ptr<ITopologyCreator> ) GetC3DTopologyBuilder();
/// \ru Завершить работу формирователя граничного представления формата STEP. \en Release STEP boundary representation generator.
CONV_FUNC (void) ReleaseC3DTopologyBuilder( std::shared_ptr<ITopologyCreator>& );
};
};
#endif //__CONV_TOPOLOGY_CREATOR_H
+3
View File
@@ -146,6 +146,9 @@ private:
// \ru Проверить и установить признак замкнутости. \en Check and set the flag of closedness.
void CheckClosed();
// \ru Скорректировать нулевую первую производную в крайней точке. \en Correct the zero first derivative at the limit point.
void CorrectZeroDerivative( double t, MbVector & fd ) const;
private:
void operator = ( const MbCharacterCurve & ); // \ru Не реализовано. \en Not implemented.
+2
View File
@@ -183,6 +183,8 @@ private:
void CheckClosed();
// \ru Рассчитать вспомогательные данные. \en Calculate auxiliary data.
void CalculateAuxData( bool hardSave = true ) const;
// \ru Скорректировать нулевую первую производную в крайней точке. \en Correct the zero first derivative at the limit point.
void CorrectZeroDerivative( double t, MbVector3D & fd ) const;
private:
void operator = ( const MbCharacterCurve3D & ); // \ru Не реализовано. \en Not implemented.
+2 -2
View File
@@ -180,7 +180,7 @@ public:
double GetTMax() const override; // \ru Вернуть максимальное значение параметра. \en Get the maximum value of parameter.
bool IsClosed() const override; // \ru Проверка замкнутости кривой. \en Check for curve closedness.
bool IsStraight( bool ignoreParams = false ) const override; // \ru Признак прямолинейности кривой. \en An attribute of curve straightness.
bool IsSmoothConnected( double angleEps ) const override; // \ru Являются ли стыки контура\кривой гладкими? \en Whether the joints of contour\curve are smooth.
bool IsSmoothConnected( double angleEps, bool ignoreLimits = false ) const override; // \ru Являются ли стыки контура\кривой гладкими? \en Whether the joints of contour\curve are smooth.
/** \} */
/** \ru \name Функции для работы в области определения кривой.
@@ -651,7 +651,7 @@ DEPRECATE_DECLARE_REPLACE( CheckClosed )
void SegmentsReserve( size_t additionalSpace ) { segments.Reserve( additionalSpace ); } ///< \ru Зарезервировать место под столько элементов. \en Reserve memory for this number of elements.
void SegmentsAdjust () { segments.Adjust(); } ///< \ru Удалить лишнюю память. \en Free the unnecessary memory.
template <class CurvesVector>
template <class CurvesVector>
bool GetSegments( CurvesVector & segms ) const; ///< \ru Получить сегменты контура. \en Get contour segments.
void SetMetricLength( double len ) const { ScopedRecursiveLock ll( GetLock() ); metricLength = len; }
+8 -7
View File
@@ -124,7 +124,7 @@ public:
double GetTMin () const override; // \ru Вернуть минимальное значение параметра \en Get the minimum value of parameter
double GetTMax () const override; // \ru Вернуть максимальное значение параметра \en Get the maximum value of parameter
bool IsClosed() const override; // \ru Проверка замкнутости кривой \en Check for curve closedness
bool IsSmoothConnected( double angleEps ) const override; // \ru Являются ли стыки контура\кривой гладкими? \en Whether the joints of contour\curve are smooth.
bool IsSmoothConnected( double angleEps, bool ignoreLimits = false ) const override; // \ru Являются ли стыки контура\кривой гладкими? \en Whether the joints of contour\curve are smooth.
bool IsStraight( bool ignoreParams = false ) const override; // \ru Признак прямолинейности кривой \en An attribute of curve straightness
/** \} */
@@ -191,7 +191,7 @@ public:
// \ru Изменить направление \en Change direction
void Inverse( MbRegTransform * iReg = nullptr ) override;
// \ru Согласовать параметризацию сегментов, если до инвертации она была согласованной. \en Agree on segment parameterization, if it was consistent before inversion.
// \ru Согласовать параметризацию сегментов, если до инвертирования она была согласованной. \en Agree on segment parameterization, if it was consistent before inversion.
bool NormalizeReparametrization();
/// \ru Подобные ли кривые для объединения (слива). \en Whether the curves to union (joining) are similar.
bool IsSimilarToCurve( const MbCurve3D & other, double precision = METRIC_PRECISION ) const override;
@@ -359,16 +359,16 @@ public:
*/
ptrdiff_t FindSegment( double & t, double & tSeg ) const;
/** \brief \ru Найти параметер контура.
/** \brief \ru Найти параметр контура.
\en Find a contour segment. \~
\details \ru Найти параметер контура по номеру сегмента и параметру сегмента. \n
\details \ru Найти параметр контура по номеру сегмента и параметру сегмента. \n
\en Find a contour parameter by segment number and segment parameter. \n \~
\param[in] iSeg - \ru Номер сегмента (индекс).
\en Segment nukmber (index). \~
\en Segment number (index). \~
\param[in] tSeg - \ru Параметр сегмента контура.
\en Segment parameter. \~
\return \ru Возвращает параметр контура или UNDEFINED_DBL в случае неудачи.
\en Returns the contour parameter or UNDEFINED_DBL if fdailure. \~
\en Returns the contour parameter or UNDEFINED_DBL if failure. \~
*/
double FindParameter( size_t iSeg, double tSeg ) const;
@@ -445,8 +445,9 @@ public:
/// \ru Проверка непрерывности контура. \en Check for contour continuity.
bool CheckConnection( double eps = METRIC_PRECISION ) const;
void CalculateParamLength(); ///< \ru Рассчитать параметрическую длину. \en Calculate parametric length.
void CheckClosed( double /*closedEps*/ ); ///< \ru Установить признак замкнутости контура. \en Set the closedness attribute of contour.
void CheckClosed( double closedEps = Math::LengthEps ); ///< \ru Установить признак замкнутости контура. \en Set the closedness attribute of contour.
/// \ru Содержат ли контура идентичные сегменты. \en Whether contours contains identical segments.
bool IsSameSegments( const MbContour3D &, double accuracy = METRIC_PRECISION ) const;
/// \ru Нахождение точки сегмента контура по индексу сегмента. \en Finding the point of a contour segment by segment index.
+1 -1
View File
@@ -187,7 +187,7 @@ public :
void ChangeContour( MbContour & );
bool IsPlanar( double accuracy = METRIC_EPSILON ) const override; // \ru Определить, является ли кривая плоской. \en Determine whether the curve is planar.
bool IsSmoothConnected( double angleEps ) const override; // \ru Определить, является ли контур гладким. \en Define whether the contour is smooth.
bool IsSmoothConnected( double angleEps, bool ignoreLimits = false ) const override; // \ru Определить, является ли контур гладким. \en Define whether the contour is smooth.
// \ru Дать плоскую кривую и плейсмент, если пространственная кривая плоская (после использования вызывать DeleteItem на двумерную кривую). \en Get planar curve and placement if the space curve is planar (after the using call DeleteItem for two-dimensional curves)
bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place3d, bool saveParams, PlanarCheckParams params = PlanarCheckParams() ) const override;
// \ru Дать поверхностную кривую, если пространственная кривая поверхностная (после использования вызывать DeleteItem на аргументы). \en Get surface curve if the space curve is surface (after the using call DeleteItem for arguments)
+2
View File
@@ -173,6 +173,8 @@ public :
bool IsInRectForDeform( const MbRect & r ) const override; // \ru Виден ли объект в заданном прямоугольнике для деформации \en Whether the object is visible in the specified rectangle for the deformation
bool IsStraight( bool ignoreParams = false ) const override; // \ru Является ли линия прямолинейной \en Whether the line is straight
// \ru Определить, являются ли кривая инверсно такой же. \en Define whether an inversed curve is the same.
bool IsInverseSame( const MbCurve & curve, double accuracy = LENGTH_EPSILON ) const override;
// \ru Положение точки относительно кривой. \en The point position relative to the curve.
// \ru iloc_InItem = 1 - точка находится слева по направлению, \en Iloc_InItem = 1 - the point is on the left,
+3 -1
View File
@@ -29,12 +29,14 @@ class MbRegTransform;
r(t) = basisCurve(t) + (Offset0(t) * normal(t)), где normal(t) - нормаль базовой кривой. \n
Базовой кривой для эквидистантной кривой не может служить другая эквидистантная кривая.
В подобной ситуации выполняется переход к первичной базовой кривой.
В качестве базовой кривой для эквидистантной кривой не могут быть заданы контур или ломаная.
\en Offset extended curve is constructed by shifting points of the base curve along a normal to it. \n
The "offsetTmin, offsetTmax" parameters set shift of base curve on begin and end points.
Radius-vector of the curve in the method PointOn(double&t,MbCartPoint3D&r) is described by the function \n
r(t) = basisCurve(t) + (Offset0(t) * normal(t)), where normal(t) - normal of base curve. \n
Base curve for offset curve can not be other offset curve.
In such situation it changes to the initial base curve. \~
In such situation it changes to the initial base curve.
A contour or polyline cannot be specified as the base curve for an equidistant curve. \~
\ingroup Curves_2D
*/
// ---
+3 -1
View File
@@ -32,6 +32,7 @@ class MATH_CLASS MbSpine;
а две другие оси ортогональны ей.
Базовой кривой для эквидистантной кривой не может служить другая эквидистантная кривая.
В подобной ситуации выполняется переход к первичной базовой кривой.
В качестве базовой кривой для эквидистантной кривой не могут быть заданы контур или ломаная.
\en Offset curve is constructed by shifting points of the base curve along some vector,
direction of which can be changed along the curve. \n
Vector "offset" sets the offset of start point of the base curve.
@@ -40,7 +41,8 @@ class MATH_CLASS MbSpine;
One of the axes of the moving local coordinate system is always the same as the tangent of the base curve,
and the other two axes are orthogonal to it.
Base curve for offset curve can not be other offset curve.
In this situation it changes to the initial base curve. \~
In this situation it changes to the initial base curve.
A contour or polyline cannot be specified as the base curve for an equidistant curve. \~
\ingroup Curves_3D
*/
// ---
+1 -1
View File
@@ -124,7 +124,7 @@ public :
void GetAnalyticalFunctionsBounds( std::vector<double> & params ) const override;
bool IsPlanar( double accuracy = METRIC_EPSILON ) const override; // \ru Является ли кривая плоской \en Whether a curve is planar
bool IsSmoothConnected( double angleEps ) const override; // \ru Являются ли стыки контура\кривой гладкими? \en Whether the joints of contour\curve are smooth.
bool IsSmoothConnected( double angleEps, bool ignoreLimits = false ) const override; // \ru Являются ли стыки контура\кривой гладкими? \en Whether the joints of contour\curve are smooth.
// \ru Ближайшая точка кривой к плейсменту \en The nearest point of a curve by the placement
double DistanceToPlace( const MbPlacement3D & place, double & t0, double & angle ) const override;
+1 -1
View File
@@ -252,7 +252,7 @@ public :
int Orientation() const; // \ru Ориентация замкнутого многоугольника \en Orientation of a closed polygon
bool IsDegenerate( double eps = Math::LengthEps ) const override; // \ru Проверка вырожденности кривой \en Check for curve degeneracy
bool IsSmoothConnected( double angleEps ) const override; // \ru Являются ли стыки контура\кривой гладкими? \en Whether the joints of a contour\curve are smooth.
bool IsSmoothConnected( double angleEps, bool ignoreLimits = false ) const override; // \ru Являются ли стыки контура\кривой гладкими? \en Whether the joints of a contour\curve are smooth.
bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = nullptr, double epsilon = EPSILON ) const override; // \ru Непрерывна ли первая производная? \en Have the first derivative the continuous?
// \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length.
+1 -1
View File
@@ -172,7 +172,7 @@ public :
MbCurve * GetMapPsp( const MbMatrix3D &, double zNear, MbRect1D * pRgn = nullptr ) const override; // \ru Дать перспективную плоскую проекцию кривой. \en Get a planar geometric projection of a curve.
size_t GetCount() const override;
bool IsSmoothConnected( double angleEps ) const override; // \ru Являются ли стыки контура\кривой гладкими? \en Whether the joints of a contour\curve are smooth.
bool IsSmoothConnected( double angleEps, bool ignoreLimits = false ) const override; // \ru Являются ли стыки контура\кривой гладкими? \en Whether the joints of a contour\curve are smooth.
bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = nullptr, double epsilon = EPSILON ) const override; // \ru Непрерывна ли первая производная? \en Have the first derivative the continuous?
// \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length.
+2 -2
View File
@@ -77,7 +77,7 @@ public :
void Init( double t1, double t2, double begFirstDerValue );
/// \ru Установить параметрическую область кривой. \en Set curve parametric range.
void InitScaledEnds( double scaleDer1, double scaleDer2 );
/// \ru Установить параметрическую область кривой пропорциональную метрической длине кривой. \en Set the parametric area of the curve proportional to the metric length of the curve.
/// \ru Установить параметрическую область кривой пропорциональную метрической длине кривой. Ожидается, что первая производная базовой кривой r'(t) является непрерывной функцией параметра t по всей ее длине \en Set the parametric area of the curve proportional to the metric length of the curve. The first derivative of the base curve r'(t) is expected to be a continuous function of the parameter t over its entire length
bool InitProportional( double t1, double t2 );
/// \ru Установить пользовательскую функцию репараметризации. \en Set users reparameterization function.
bool InitByUsersFunction( MbFunction & repFunc );
@@ -185,7 +185,7 @@ public :
bool IsBounded() const override; // \ru Признак ограниченной кривой \en Attribute of a bounded curve
bool IsDegenerate( double eps = Math::LengthEps ) const override; // \ru Проверка вырожденности кривой \en Check for curve degeneracy
bool IsStraight( bool ignoreParams = false ) const override; // \ru Является ли линия прямолинейной \en Whether the line is straight
bool IsSmoothConnected( double angleEps ) const override; // \ru Являются ли стыки контура\кривой гладкими? \en Whether the joints of a contour\curve are smooth.
bool IsSmoothConnected( double angleEps, bool ignoreLimits = false ) const override; // \ru Являются ли стыки контура\кривой гладкими? \en Whether the joints of a contour\curve are smooth.
bool IsCompleteInRect( const MbRect & r ) const override; // \ru Виден ли объект полностью в в заданном прямоугольнике \en Whether the object is completely visible in the given rectangle
double CalculateMetricLength() const override; // \ru Посчитать метрическую длину \en Calculate the metric length
bool HasLength( double & length ) const override; // \ru Метрическая длина кривой \en Metric length of a curve
+2 -2
View File
@@ -76,7 +76,7 @@ public :
void Init( double t1, double t2, double begFirstDerValue );
/// \ru Установить параметрическую область кривой. \en Set curve parametric range.
void InitScaledEnds( double scaleDer1, double scaleDer2 );
/// \ru Установить параметрическую область кривой пропорциональную метрической длине кривой. \en Set the parametric area of the curve proportional to the metric length of the curve.
/// \ru Установить параметрическую область кривой пропорциональную метрической длине кривой. Ожидается, что первая производная базовой кривой r'(t) является непрерывной функцией параметра t по всей ее длине \en Set the parametric area of the curve proportional to the metric length of the curve. The first derivative of the base curve r'(t) is expected to be a continuous function of the parameter t over its entire length
bool InitProportional( double t1, double t2 );
/// \ru Установить пользовательскую функцию репараметризации. \en Set users reparameterization function.
bool InitByUsersFunction( MbFunction & repFunc );
@@ -150,7 +150,7 @@ public :
void CalculateLocalGabarit( const MbMatrix3D &, MbCube & ) const override; // \ru Рассчитать габарит относительно л.с.к. \en Calculate bounding box relative to the local coordinate system
bool IsDegenerate( double eps = METRIC_PRECISION ) const override; // \ru Проверка вырожденности кривой \en Check for curve degeneracy
bool IsSmoothConnected( double angleEps ) const override; // \ru Являются ли стыки контура\кривой гладкими? \en Whether the joints of a contour\curve are smooth.
bool IsSmoothConnected( double angleEps, bool ignoreLimits = false ) const override; // \ru Являются ли стыки контура\кривой гладкими? \en Whether the joints of a contour\curve are smooth.
double Curvature ( double ) const override; // \ru Кривизна кривой \en Curvature of the curve
double Step ( double t, double sag ) const override; // \ru Вычисление шага по стрелке прогиба. \en Calculation of parameter step by the sag.
+2 -2
View File
@@ -193,7 +193,7 @@ public:
double Step ( double t, double sag ) const override; // \ru Вычисление шага по стрелке прогиба. \en Calculation of parameter step by the sag.
double DeviationStep( double t, double angle ) const override; // \ru Вычисление шага по углу отклонения нормали. \en Calculation of parameter step by the deviation angle.
void SetTesselation( const MbContourOnSurface & contour, size_t indSegment ); // \ru Установить разбиение из контура. \en Set tessellation from contour.
void SetTesselation( const MbContourOnSurface & contour, size_t indSegment ); // \ru Установить разбиение из контура. \en Set tessellation from contour.
double MetricStep ( double t, double length ) const override; // \ru Вычисление шага параметра по длине. \en Calculation of parameter step by the given length.
MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = nullptr,
@@ -206,7 +206,7 @@ public:
void ChangeCarrier ( const MbSpaceItem & item, MbSpaceItem & init ) override; // \ru Изменить носитель. \en Change the carrier.
bool ChangeCarrierBorne( const MbSpaceItem &, MbSpaceItem &, const MbMatrix & matr ) override; // \ru Изменить носимые элементы. \en Change a carrier elements.
bool IsPlanar( double accuracy = METRIC_EPSILON ) const override; // \ru Определить, является ли кривая плоской. Прямолинейные кривые являются плоскими, но без определённой ЛСК. \en Determine whether the curve is planar. Straight lines is planar but without certain placement.
bool IsSmoothConnected( double angleEps ) const override; // \ru Определить, являются ли стыки контура\кривой гладкими. \en Determine whether the joints of contour\curve are smooth.
bool IsSmoothConnected( double angleEps, bool ignoreLimits = false ) const override; // \ru Определить, являются ли стыки контура\кривой гладкими. \en Determine whether the joints of contour\curve are smooth.
void CalculateGabarit( MbCube & ) const override; // \ru Вычислить габарит кривой. \en Calculate bounding box of a curve.
double GetMetricLength() const override; // \ru Вычислить метрическую длину кривой. \en Calculate the metric length of a curve.
double GetLengthEvaluation() const override; // \ru Оценить метрическую длину кривой. \en Estimate the metric length of a curve.
+1 -1
View File
@@ -453,7 +453,7 @@ public:
void ChangeCarrier ( const MbSpaceItem & item, MbSpaceItem & init ) override; // \ru Изменить носитель. \en Change the carrier.
bool ChangeCarrierBorne( const MbSpaceItem & item, MbSpaceItem & init, const MbMatrix & matr ) override; // \ru Изменение носимые элементы. \en Change a carrier elements.
bool IsPlanar( double accuracy = METRIC_EPSILON ) const override; // \ru Определить, является ли кривая плоской. \en Determine whether the curve is planar.
bool IsSmoothConnected( double angleEps ) const override; // \ru Определить, являются ли стыки контура\кривой гладкими. \en Determine whether the joints of contour\curve are smooth.
bool IsSmoothConnected( double angleEps, bool ignoreLimits = false ) const override; // \ru Определить, являются ли стыки контура\кривой гладкими. \en Determine whether the joints of contour\curve are smooth.
double DistanceToPlace( const MbPlacement3D & place, double & t0, double & angle ) const override; // \ru Вычислить ближайшую точку кривой к плейсменту. \en Calculate the curve point nearest to a placement.
// \ru Дать плоскую кривую и плейсмент, если пространственная кривая плоская (после использования вызывать DeleteItem на двумерную кривую). \en Get the planar curve and placement if the spatial curve is planar (call DeleteItem for two-dimensional curve after using ).
+16 -4
View File
@@ -472,8 +472,19 @@ public :
virtual bool IsStraight( bool ignoreParams = false ) const;
/// \ru Определить, является ли кривая вырожденной. \en Define whether the curve is degenerate..
virtual bool IsDegenerate( double eps = Math::LengthEps ) const;
/// \ru Определить, являются ли стыки контура/кривой гладкими. \en Define whether joints of contour/curve are smooth.
virtual bool IsSmoothConnected( double angleEps ) const;
/** \brief \ru Определить, являются ли стыки контура/кривой гладкими.
\en Define whether joints of contour/curve are smooth. \~
\details \ru Определить, являются ли стыки контура/кривой гладкими.\n
\en Define whether joints of contour/curve are smooth. \n \~
\param[in] angleEps - \ru Угловая точность для проверки гладкости.
\en Angular accuracy for checking smoothness. \~
\param[in] ignoreLimits - \ru Не проводить проверку на концах замкнутой кривой.
\en Do not check at the ends of a closed curve. \~
\return \ru true, если кривая гладкая.
\en true if the curve is smooth. \~
*/
virtual bool IsSmoothConnected( double angleEps, bool ignoreLimits = false ) const;
/// \ru Вычислить параметрическую длину кривой. \en Calculate the parametric length of a curve.
double GetParamLength() const { return GetTMax() - GetTMin(); }
@@ -1214,9 +1225,10 @@ public :
void CorrectParameter ( double & t ) const;
/// \ru Сделать копию с измененным направлением. \en Create a copy with changed direction.
MbCurve * InverseDuplicate() const;
MbCurve * InverseDuplicate() const;
/// \ru Определить, являются ли кривая инверсно такой же. \en Define whether an inversed curve is the same.
bool IsInverseSame( const MbCurve & curve, double accuracy = LENGTH_EPSILON ) const;
virtual bool IsInverseSame( const MbCurve &, double accuracy = LENGTH_EPSILON ) const;
/** \brief \ru Определить, является ли кривая репараметризованно такой же.
\en Define whether a reparameterized curve is the same. \~
+14 -2
View File
@@ -679,8 +679,20 @@ public :
virtual bool IsStraight( bool ignoreParams = false ) const;
/// \ru Является ли кривая плоской? \en Is a curve planar?
virtual bool IsPlanar ( double accuracy = METRIC_EPSILON ) const;
/// \ru Являются ли стыки контура/кривой гладкими? \en Are joints of contour/curve smooth?
virtual bool IsSmoothConnected( double angleEps ) const;
/** \brief \ru Определить, являются ли стыки контура/кривой гладкими.
\en Define whether joints of contour/curve are smooth. \~
\details \ru Определить, являются ли стыки контура/кривой гладкими.\n
\en Define whether joints of contour/curve are smooth. \n \~
\param[in] angleEps - \ru Угловая точность для проверки гладкости.
\en Angular accuracy for checking smoothness. \~
\param[in] ignoreLimits - \ru Не проводить проверку на концах замкнутой кривой.
\en Do not check at the ends of a closed curve. \~
\return \ru true, если кривая гладкая.
\en true if the curve is smooth. \~
*/
virtual bool IsSmoothConnected( double angleEps, bool ignoreLimits = false ) const;
/// \ru Изменить носитель. Для поверхностных кривых. \en Change the carrier. For surface curves.
virtual void ChangeCarrier( const MbSpaceItem & item, MbSpaceItem & init );
+6 -6
View File
@@ -48,7 +48,7 @@ protected :
public :
/// \ru Конструктор по функции. \en Constructor by function.
MbCompositeFunction( MbFunction & segment, bool same ); // \ru same - функции или их копии \en Sames - functions or their copies
MbCompositeFunction( MbFunction & segment, bool same ); // \ru same - функции или их копии \en same - functions or their copies
/// \ru Конструктор по набору функции. \en Constructor by functions.
template <class FunctionVector>
MbCompositeFunction( const FunctionVector & initSegments, bool same ); // \ru same - функции или их копии \en same - functions or their copies
@@ -113,7 +113,7 @@ public:
double GetLimitValue( size_t n ) const override; // \ru Дать значение на конце ( 1 - в начале, 2 - в конце) \en Get the value at the end (1 - at start point, 2 - at end point)
void SetLimitDerive( size_t n, double newValue, double dt ) override; // \ru Установить значение на конце ( 1 - в начале, 2 - в конце) \en Set the value at the end (1 - at start point, 2 - at end point)
double GetLimitDerive( size_t n ) const override; // \ru Дать значение на конце ( 1 - в начале, 2 - в конце) \en Get the value at the end (1 - at start point, 2 - at end point)
bool InsertValue( double t, double newValue ) override; // \ru Установить значение для параметра t. \en Set the value for the pdrdmeter t.
bool InsertValue( double t, double newValue ) override; // \ru Установить значение для параметра t. \en Set the value for the parameter t.
/// \ ru Определение точек излома контура. \en The determination of contour smoothness break points.
void BreakPoints( std::vector<double> & vBreaks, double precision = ANGLE_REGION ) const override;
@@ -140,16 +140,16 @@ public:
*/
ptrdiff_t FindSegment( double & t, double & tSeg ) const;
/** \brief \ru Найти параметер контура.
/** \brief \ru Найти параметр контура.
\en Find a contour segment. \~
\details \ru Найти параметер контура по номеру сегмента и параметру сегмента. \n
\details \ru Найти параметр контура по номеру сегмента и параметру сегмента. \n
\en Find a contour parameter by segment number and segment parameter. \n \~
\param[in] iSeg - \ru Номер сегмента (индекс).
\en Segment nukmber (index). \~
\en Segment number (index). \~
\param[in] tSeg - \ru Параметр сегмента контура.
\en Segment parameter. \~
\return \ru Возвращает параметр контура или UNDEFINED_DBL в случае неудачи.
\en Returns the contour parameter or UNDEFINED_DBL if fdailure. \~
\en Returns the contour parameter or UNDEFINED_DBL if failure. \~
*/
double FindParameter( size_t iSeg, double tSeg ) const;
+21 -70
View File
@@ -2,8 +2,7 @@
/**
\file
\brief \ru Тестовый программный интерфейс геометрического решателя C3D Solver.
\en Testing program interface of C3D Solver.
\~
\en Testing program interface of C3D Solver. \~
\details \ru Данный файл содержит типы данных и вызовы, предназначенные для тестирования
и отладки, поэтому могут быть изменены или удалены из API C3D Solver
@@ -13,17 +12,14 @@
\en This file contains data types and calls for testing and debugging, so they
can be modified or removed from the C3D Solver API in future versions. To use
the 2D constraint solver, it is recommended to use only the interface declared
in the header files gce_api.h and gce_types.h.
\~
in the header files gce_api.h and gce_types.h. \~
*/
//////////////////////////////////////////////////////////////////////////////////////////
#ifndef __GC_API_H
#define __GC_API_H
#include <mb_matrix.h>
#include <math_version.h>
//
#include <gce_types.h>
#include <gce_kompas_interface.h>
@@ -119,18 +115,14 @@ GCE_FUNC(GCE_s_state) GCE_DefinitionState( GCE_system gSys );
GCE_FUNC(GCE_result) GCE_CheckSatisfaction( GCE_system gSys, VERSION c3dVer = GetCurrentMathFileVersion() );
//----------------------------------------------------------------------------------------
/// \ru Выдать координаты переменных геометрической модели, \en Get coordinates of variables of geometric models
/// \ru значения которых не зависят от изменения входных переменных in_coords; \en which do not depend on changes of input variables in_coords;
// The function for testing purposes.
/// \ru Выдать координаты переменных геометрической модели, значения которых не
/// \ru зависят от изменения входных переменных in_coords.
/// \en Get coordinates of variables of geometric models which do not depend on
/// \en changes of input variables in_coords.
// ---
GCE_FUNC(bool) GCE_GetOutVarCoordinates( GCE_system gcContext,
const SArray<var_item> & in_coords,
const SArray<constraint_item> & drvCons,
SArray<var_item> & outCoords );
//----------------------------------------------------------------------------------------
/// \ru Задать фиксацию координаты параметрического объекта \en Specify fixation of a parametric object coordinate
//---
GCE_FUNC(constraint_item) GCE_FixCoordinate( GCE_system gSys, geom_item g, coord_name crd );
GCE_FUNC(bool) GCE_GetOutVarCoordinates( GCE_system gSys, const SArray<var_item> & inCoords,
const SArray<constraint_item> & drvCons, SArray<var_item> & outCoords );
//----------------------------------------------------------------------------------------
/// \ru Задать ограничение "Радиальный размер" \en Specify "Radial dimension" constraint
@@ -154,7 +146,7 @@ GCE_FUNC(void) GCE_ResetMovingMode( GCE_system );
\ru По этому вызову солвер запоминает текущее состояние замороженных объектов,
как обязательное к исполнению и перераспределяет их начальное приближение для
минимизации неудовлетворенных ограничений. После успешного вызова GCE_Evaluate
замороженные объекты снова займут свое обязательное положение. Незамороженные
замороженные объекты снова найдут свое обязательное положение. Незамороженные
объекты подстроятся под замороженные в соотвествии с заданными ограничениями.
\note
@@ -162,7 +154,7 @@ GCE_FUNC(void) GCE_ResetMovingMode( GCE_system );
\en The call is intended to replay an old-version evaluation for the start values of the frozen coordinates.
*/
//---
GCE_FUNC( bool ) GCE_InitFrozenCoords( GCE_system gSys );
GCE_FUNC(bool) GCE_InitFrozenCoords( GCE_system gSys );
//----------------------------------------------------------------------------------------
/** \brief \ru Собрать плохо-обусловленную часть системы ограничений.
@@ -199,7 +191,7 @@ GCE_FUNC( bool ) GCE_InitFrozenCoords( GCE_system gSys );
information about the status of each constraint use the call GCE_ConstraintStatus.
*/
// ---
GCE_FUNC(bool) GCE_CollectLinearDependedConstrains( GCE_system, SArray<constraint_item> & );
GCT_FUNC(bool) GCE_CollectLinearDependedConstrains( GCE_system, SArray<constraint_item> & );
/**
\}
@@ -211,51 +203,14 @@ GCE_FUNC(bool) GCE_CollectLinearDependedConstrains( GCE_system, SArray<constrain
*/
//----------------------------------------------------------------------------------------
/**
\attention \ru Функция устарела. Рекомендуется использовать #GCE_AddSymmetry.
\en The function is obsolete. It is recommended to use #GCE_AddSymmetry. \~
*/
// Deprecated call intended to maintaint previous versions.
//---
GCE_FUNC(constraint_item) GCE_FormPointSymmetry( GCE_system gcContext, geom_item pnt[2], geom_item curve, int8 );
GCE_FUNC(constraint_item) GCE_FixCoordinate(GCE_system gSys, geom_item g, coord_name crd);
//----------------------------------------------------------------------------------------
/**
\attention \ru Функция устарела. Рекомендуется использовать #GCE_AddIncidence.
\en The function is obsolete. It is recommended to use #GCE_AddIncidence. \~
*/
GCE_FUNC(constraint_item) GCE_FormPointOnCurve( GCE_system, geom_item, geom_item );
//----------------------------------------------------------------------------------------
/**
\attention \ru Устаревшая функция. Вызов будет удален в одной из следующих версий.
Вместо неё используйте #GCE_PrepareMovingGeoms.
\en An obsolete function. The call will be removed in one of the next versions.
Use #GCE_PrepareMovingGeoms instead. \~
*/
//---
GCE_FUNC(GCE_result) GCE_PrepareMovingOfGeoms( GCE_system, SArray<geom_item> &, double, double );
//----------------------------------------------------------------------------------------
/**
\attention \ru Функция устарела. Вместо неё применять #GCE_CoordDOF.
\en The function is deprecated. Use #GCE_CoordDOF instead. \~
*/
//-2017--
GCE_FUNC(ptrdiff_t) GCE_GetCoordinateDOF( GCE_system, geom_coord<> );
//----------------------------------------------------------------------------------------
/**
\attention \ru Функция устарела. Вместо неё применять #GCE_AddFixedLength.
\en The function is obsolete Use #GCE_AddFixedLength instead. \~
*/
//---
GCE_FUNC(constraint_item) GCE_FormFixedLength( GCE_system, geom_item );
//----------------------------------------------------------------------------------------
/*
\attention \ru Функция устарела. Вместо неё применять #GCE_FixCoordinate.
\en The function is obsolete Use #GCE_FixCoordinate instead. \~
*/
// Deprecated call intended to maintaint previous versions.
// \ru Функция устарела. Вместо неё применять #GCE_FixCoordinate.
// \en The function is obsolete Use #GCE_FixCoordinate instead.
//---
GCE_FUNC(constraint_item) GCE_FormFixedCoordinate( GCE_system, geom_coord<> );
@@ -268,34 +223,30 @@ const GCE_s_state GCE_STATE_OverConstrained = GCE_STATE_UnresolvedRedundancy;
Deprecated typenames and constants (2019.06)
*/
typedef GCE_s_state GcConstraintStatus;
const GCE_s_state tcs_Unknown = GCE_STATE_Unknown;
const GCE_s_state tcs_WellConstrained = GCE_STATE_WellConstrained;
const GCE_s_state tcs_UnderConstrained= GCE_STATE_UnderConstrained;
const GCE_s_state tcs_OverConstrained = GCE_STATE_OverConstrained;
//----------------------------------------------------------------------------------------
/*
Internal use only
Internal use only.
*/
//---
GCE_FUNC(GCE_system) GCE_RestoreFromJournal( const char * fName );
//----------------------------------------------------------------------------------------
/**
\note Used only for testing
\note Used only for testing.
*/
//---
GCE_FUNC(GCE_diagnostic_pars) GCE_DiagnosticPars( GCE_system gSys );
//----------------------------------------------------------------------------------------
/**
\note Used only for testing
\note Used only for testing.
*/
// ---
GCE_FUNC(size_t) GCT_InConstraintsFullCount( GCE_system gSys );
//----------------------------------------------------------------------------------------
// Measure a dimension value (it used for testing purposes only)
// Measure a dimension value (it used for testing purposes only).
//---
GCE_FUNC(double) GCT_Measure( GCE_system gSys, constraint_type cType, geom_item g1, geom_item g2 );
+119 -28
View File
@@ -31,45 +31,85 @@
class MtVectorN;
template <class Type> class RPArray;
//////////////////////////////////////////////////////////////////////////////////////////
//
/// \ru Ограничение для подмножества координат \en Constraint for subset of coordinates
/**\ru Как правило, это алгебраические уравнение общего вида f(x1,x2,..,xn) = g(x1,x2,..,xn)
явно-выраженной форме: x1 = g(x2,x3,..,xn).
\en As a rule, it is an algebraic equation of a general form f(x1,x2,..,xn) = g(x1,x2,..,xn)
or, as a special case, it is an equation in explicit form: x1 = g(x2,x3,..,xn). \~
//----------------------------------------------------------------------------------------
/** \brief \ru Интерфейс численного уравнения, выраженного через набо координат.
\en Interface of the numeric equation expressed via a set of coordinates.
\details \ru Как правило, это алгебраические уравнение общего вида f(x1,x2,..,xn) = g(x1,x2,..,xn)
явно-выраженной форме: x1 = g(x2,x3,..,xn).
\en As a rule, it is an algebraic equation of a general form f(x1,x2,..,xn) = g(x1,x2,..,xn)
or, as a special case, it is an equation in explicit form: x1 = g(x2,x3,..,xn). \~
*/
//////////////////////////////////////////////////////////////////////////////////////////
struct GCE_CLASS ItAlgebraicConstraint
//---
struct GCE_CLASS ItNumericEquation
{
/// \ru Выдать координату с индексом crdIdx. \en Get coordinate with crdIdx index.
virtual ItGeomCoord * GetCoord( ptrdiff_t crdIdx ) const = 0;
/// \ru Количество координат, связанных с уравнением. \en Count of coordinates connected with the equation.
virtual ptrdiff_t GetCoordCount() const = 0;
/// \ru Вычисление первой производной по координате и значений функции. \en The first derivative by coordinate and the function values calculation.
virtual bool CalcDerive( ItGeomCoord &, const std::vector<double> & /*argLine*/, double & /*fd*/, double & /*f*/ ) const { return false; }
/// \ru Выдать координату зависимой переменной (для уравнений заданных в явно-выраженной форме). \en Get the coordinate of dependent variable (for explicit equations).
virtual ptrdiff_t GetDependedCoordIdx() const = 0;
/// \ru Признак уравнения, заданного в форме присвоения, по правилам КОМПАС-3D V12. \en Flag of equation specified in form of assignment, by the rules of KOMPAS-3D V12.
/**\ru Уравнения, заданные в явно выраженной форме, считающиеся присвоением выражения зависимой переменной: x1 = g(x2,x3,..,xn).
Такие уравнения стремимся вычислять иерархическим способом, сверху-вниз.
\en Equations specified explicitly, considered to be the assignment of dependent variable: x1 = g(x2,x3,..,xn).
It is preferred to compute such equations by hierarchical top-down method. \~
enum eval_result_code: char
{
EVAL_RESULT_Undefined = 0,
EVAL_RESULT_Ok,
EVAL_RESULT_OutOfDomaint
};
struct eval_result
{
eval_result_code resCode = EVAL_RESULT_Undefined;
double funDer = MB_MAXDOUBLE; // Derivative value.
double funVal = MB_MAXDOUBLE; // Function value.
};
/// \ru Выдать координату с индексом crdIdx. \en Get coordinate with crdIdx index.
virtual ItCoord* Coord( size_t crdIdx ) const = 0;
/// \ru Количество координат, связанных с уравнением. \en Count of coordinates connected with the equation.
virtual size_t NumCoords() const = 0;
/// \ru Вычисление первой производной по координате и значений функции. \en The first derivative by coordinate and the function values calculation.
virtual eval_result Evaluate(const ItCoord* crd, const std::vector<double>& crdVals) const;
/// \ru Выдать координату зависимой переменной (для уравнений заданных в явно-выраженной форме). \en Get the coordinate of dependent variable (for explicit equations).
virtual const ItCoord* DependedCoord() const = 0;
/** \brief \ru Признак уравнения, заданного в форме присвоения (начиная с Компас V12).
\en Flag of equation specified in form of assignment.
\details
\ru Уравнения, заданные в явно выраженной форме, считающиеся присвоением выражения зависимой переменной: x1 = g(x2,x3,..,xn).
Такие уравнения стремимся вычислять иерархическим способом, сверху-вниз.
\en Equations specified explicitly, considered to be the assignment of dependent variable: x1 = g(x2,x3,..,xn).
It is preferred to compute such equations by hierarchical top-down method. \~
*/
virtual bool IsAssignmentForm() const = 0;
virtual refcount_t AddRef() const = 0;
virtual refcount_t Release() const = 0;
virtual bool IsExplicit() const = 0;
public:
virtual refcount_t AddRef() const = 0;
virtual refcount_t Release() const = 0;
private:
// It will be removed
virtual bool CalcDerive( ItGeomCoord &, const MtVectorN &, double &, double & ) const { return false; }
// It will be removed.
virtual ItGeomCoord * GetCoord( ptrdiff_t ) const { return nullptr; }
// It will be removed.
virtual bool CalcDerive( ItGeomCoord &, const std::vector<double> & /*argLine*/, double & /*fd*/, double & /*f*/ ) const { return false; }
// It will be removed.
virtual ptrdiff_t GetCoordCount() const { return 0; }
// It will be removed.
virtual ptrdiff_t GetDependedCoordIdx() const { return -1; }
protected:
~ItAlgebraicConstraint() {}
~ItNumericEquation() {}
};
//----------------------------------------------------------------------------------------
// \ru Вычисление первой производной по координате и значений функции. \en The first derivative by coordinate and the function values calculation.
//---
inline ItNumericEquation::eval_result ItNumericEquation::Evaluate(const ItCoord* crd, const std::vector<double>& crdVals) const
{
eval_result res;
ItGeomCoord * gCrd = dynamic_cast<ItGeomCoord*>(const_cast<ItCoord*>(crd));
if ( gCrd!=nullptr && CalcDerive(*gCrd, crdVals, res.funDer, res.funVal))
{
res.resCode = EVAL_RESULT_Ok;
}
return res;
}
using ItAlgebraicConstraint = ItNumericEquation;
/**
\addtogroup Constraints2D_API
\{
@@ -142,6 +182,57 @@ GCE_FUNC(MbCartPoint) GCE_GetPoint( GCE_system gSys
*/
GCE_FUNC(geom_item) GCE_AddGeom( GCE_system gSys, IfGeom2d & );
//----------------------------------------------------------------------------------------
/** \brief \ru Варианты выравнивания направлений.
\en Variants of alignment. \~
\details \en Значение опции выравнивания используется для выбора из альтернативных решений
ограничения, такого как `GCE_TANGENT`.
\en The alignment value is used to alternate between solutions of a constraint such as `GCE_TANGENT`.
\note \ru Значения этого перечисления могут быть использованы для постоянного хранения и
останутся неизменными в следующих версиях.
\en Values of this enum can be used for permanent storage and will be kept
in the future versions. \~
*/
//---
typedef enum
{
GCE_NO_ALIGNMENT = 0, ///< \ru Неопределенное значение выравнивания (=не применима к данному ограничению). \en Undefined alignment value (=not applicable to this constraint).
GCE_COORIENTED, ///< \ru Для касания это сонаправленные касательные вектора (=нормали). \en For tangency, these are co-directional tangent vectors (=normal).
GCE_OPPOSITE, ///< \ru Для касания это противонаправленные касательные вектора (=нормали). \en For tangency, these are the opposing tangent vectors (=normal).
/** \brief \ru Поддерживать способ выравнивания согласно начальному или текущему положению геометрии (соответствует поведению прежних версий).
\en Maintain the alignment according to the initial or current position of the geometry (reproduces behaviour from previous versions). \~ */
GCE_CLOSEST,
/** \brief \ru Автоматически выбрать опцию выравнивания, используя начальное приближение геометрии.
\en Automatically determine alignment options using initial geometry approximation. \~ */
GCE_AUTO_ALIGNMENT,
} GCE_alignment;
//----------------------------------------------------------------------------------------
/// \ru Задать ориентацию касания. \en Set the tangent orientation.
/**
\param[in] \ru gSys Система ограничений.
\en gSys System of constraints. \~
\param[in] \ru constraint Дескриптор ограничения.
\en constraint Constraint's descriptor. \~
\param[in] \ru alignment Опция выравнивания касания кривых.
\en alignment Curve tangency alignment option. \~
\return \ru В случае успешного вызова функция вернет новое значение выравнивания, заданного вызовом.
\en If the call is successful, the function will return the new alignment value specified by the call. \~
\details
\ru В настоящее время функция применяется к ограничению касания (GCE_TANGENT). Данный вызов устанавливает
сонаправленность или противонаправленность касательных (GCE_COORIENTED, GCE_OPPOSITE),
либо делает выбор автоматически, если задать опцию GCE_AUTO_ALIGNMENT. Когда выбрана опцию GCE_CLOSEST,
солвер будет поддерживать взаимную ориентацию согласно текущего размещения геометрии.
\en The function currently applies to the tangency constraint (GCE_TANGENT). The call sets whether
the direction of the geometry tangents are cooriented/opposite or makes the selection automatically
if you set the GCE_AUTO_ALIGNMENT option. When the option GCE_CLOSEST is selected the C3D Solver
should maintain the current geometry positions. \~
*/
//---
GCE_FUNC(GCE_alignment) GCE_SetAlignment( GCE_system gSys, constraint_item constraint, GCE_alignment alignment = GCE_AUTO_ALIGNMENT );
#endif // __GCE_KOMPAS_INTERFACE_H
+1
View File
@@ -363,6 +363,7 @@ typedef enum
} GCE_bisec_variant;
//----------------------------------------------------------------------------------------
/// \ru Координаты вектора. \en Vector coordinates.
//---
+22 -35
View File
@@ -60,48 +60,35 @@ enum color_code: char
template<bool boolVal>
bool boolFunc() { return boolVal; }
/*
//----------------------------------------------------------------------------------------
/// \ru Цветовая маркировка, например, для графовых объектов \en Color marking, for example: for graph objects
//---
template<typename ColorValue = color_code >
struct color_traits
{
static color_code white() { return white_color; }
static color_code gray() { return gray_color; }
static color_code green() { return green_color; }
static color_code red() { return red_color; }
static color_code black() { return black_color; }
};
template<>
struct color_traits<char>
{
static char white() { return 0; }
static char gray() { return 1; }
static char green() { return 2; }
static char red() { return 3; }
static char black() { return 4; }
};
*/
//----------------------------------------------------------------------------------------
/// \ru Графовые характеристики типов. \en Graph datatype traits.
//---
template< class Graph >
template<class Graph>
struct graph_traits
{
/*
Ассоциативные типы данных концепции графа.
Associative datatypes of the graph concept.
*/
typedef typename Graph::vertex vertex; // Тип, интерпретируемый, как вершина графа.
typedef typename Graph::edge edge; // Тип, интерпретируемый, как ребро графа
typedef typename Graph::vertex_iterator vertex_iterator; // Обход всех вершин графа
typedef typename Graph::adjacency_iterator adjacency_iterator; // Обход смежных вершин некоторой вершины
typedef typename Graph::vertices_size_t vertices_size_t; // Целочисленный тип размера графа
typedef typename Graph::degree_size_t degree_size_t; // Целочисленный тип вершинной степени
typedef typename Graph::edge_iterator edge_iterator; // Итератор обхода исходящих ребер [или неориентированных ребер]
using vertex = typename Graph::vertex ; // Тип, интерпретируемый, как вершина графа.
using edge = typename Graph::edge ; // Тип, интерпретируемый, как ребро графа.
using vertex_iterator = typename Graph::vertex_iterator ; // Обход всех вершин графа.
using adjacency_iterator = typename Graph::adjacency_iterator; // Обход смежных вершин некоторой вершины.
using vertices_size_t = typename Graph::vertices_size_t ; // Целочисленный тип размера графа.
using degree_size_t = typename Graph::degree_size_t ; // Целочисленный тип вершинной степени.
using edge_iterator = typename Graph::edge_iterator ; // Итератор обхода исходящих ребер [или неориентированных ребер].
};
//----------------------------------------------------------------------------------------
/** \brief \ru Подходящий тип ассоциативного контейнера для хранения данных, ассоциированных с вершинами графа.
\en A suitable type of associative container for storing data associated with graph vertices. \~.
*/
//---
template<class Graph, class Property>
struct property_map
{
private:
using type = struct{};
};
//----------------------------------------------------------------------------------------
@@ -1112,8 +1099,8 @@ struct color_label
template <typename Iterator>
struct _IterTraits
{
typedef typename Iterator::value_type value_type;
typedef typename Iterator::reference reference;
using value_type = typename Iterator::value_type;
using reference = typename Iterator::reference;
};
template <typename T>
+159 -250
View File
@@ -27,7 +27,7 @@
template<class Graph>
struct DefaultDFSVisitor
{
typedef typename Graph::vertex vertex;
using vertex = typename Graph::vertex;
/// Встретили "обратное" ребро (дуга, если орграф) dfs-дерева.
/**
@@ -71,11 +71,11 @@ struct DefaultBicompVisitor
{
/// Найден блок, как последовательность ребер
template<class EdgeIterator>
void BlockFounded( EdgeIterator, EdgeIterator, const Graph & ) {}
void BlockFounded(EdgeIterator, EdgeIterator, const Graph&) {}
/// Обнаружена точка сочленения (articulation vertex)
template<class Vertex>
void CutNode( Vertex, const Graph & ) {}
void CutNode(Vertex, const Graph&) {}
/// Функция обратного вызова: Фильтрация для точек сочленения
/**
@@ -85,34 +85,32 @@ struct DefaultBicompVisitor
отфильтрованная точка сочленения всегда будет принадлежать одному блоку.
*/
template<class Vertex>
bool IsFilteredCut( Vertex, const Graph & ) const { return false; }
bool IsFilteredCut(Vertex, const Graph&) const { return false; }
};
//////////////////////////////////////////////////////////////////////////////////////////
//
/// Посетитель обхода в глубину для поиска блоков и точек сочленения
/// Посетитель обхода в глубину для поиска блоков и точек сочленения.
/**
Класс является автономным и не нуждается в уточнении наследованием от него.
Graph - предполагается, что это неориентированный граф.
BicompVisitor - надстроенный визитер, посетитель этого визитера, который
реализует события обнаружения блока, точки сочленения и
фильтрацию вершин, которые принудительно запрещается быть
точками сочленения.
BicompVisitor - надстроенный визитер, посетитель этого визитера, который реализует
события обнаружения блока, точки сочленения и фильтрацию вершин, которые
принудительно запрещается быть точками сочленения.
*/
//////////////////////////////////////////////////////////////////////////////////////////
template< class Graph, class BicompVisitor = DefaultBicompVisitor<Graph> >
class BicompDFSVisitor: public DefaultDFSVisitor<Graph>
class BicompDFSVisitor final: public DefaultDFSVisitor<Graph>
{
public:
typedef typename Graph::adjacency_iterator adjacency_iterator;
typedef typename Graph::edge edge;
using adjacency_iterator= typename Graph::adjacency_iterator;
using vertex = typename Graph::vertex;
using edge = typename Graph::edge;
public:
static const typename Graph::vertex_index NO_VERTEX = (size_t)-1;
BicompDFSVisitor( BicompVisitor & vis )
BicompDFSVisitor(BicompVisitor& vis)
: m_graph( nullptr )
, m_bicompVis( vis )
, m_dfsCounter( 1 )
@@ -122,8 +120,8 @@ public:
, m_stackEdges()
{}
/// Встретили поперечное или прямое ребро
void ForwardOrCrossEdge( typename Graph::vertex_index v, typename Graph::vertex_index u, const Graph & )
/// Встретили поперечное или прямое ребро.
void ForwardOrCrossEdge(vertex v, vertex u, const Graph&)
{
C3D_UNUSED_PARAMETER( u );
C3D_UNUSED_PARAMETER( v );
@@ -134,42 +132,42 @@ public:
/**
Вершина u является предком вершине v в dfs-дереве.
*/
void BackEdge( typename Graph::vertex_index v, typename Graph::vertex_index u, const Graph & g )
void BackEdge(vertex v, vertex u, const Graph& g)
{
C3D_UNUSED_PARAMETER( g );
PRECONDITION( m_graph == &g );
PRECONDITION( num[u] < num[v] );
PRECONDITION( father[v] != NO_VERTEX );
PRECONDITION( father[v] != Graph::NullVertex() );
if ( u != father[v] )
{
// Здесь vu - есть обратное ребро входящее в вершину u, которая выше, чем v в d-дереве;
m_stackEdges.push_back( edge(v,u) ); // вставить ребро vu;
lval[v] = min_of( lval[v], num[u] ); // см.лемму 6;
// Здесь vu - есть обратное ребро входящее в вершину u, которая выше, чем v в d-дереве.
m_stackEdges.push_back( edge(v,u) ); // вставить ребро vu.
lval[v] = min_of( lval[v], num[u] ); // см.лемму 6.
}
}
/// Посещение вершины: Вызывается один раз для каждой вершины, когда она впервые начинает просматриваться
void DiscoverNode( typename Graph::vertex_index v, const Graph & g )
void DiscoverNode(vertex v, const Graph& g)
{
C3D_UNUSED_PARAMETER( g );
C3D_ASSERT( m_graph == &g );
PRECONDITION( num[v] == 0 );
PRECONDITION( lval[v] == 0 );
num[v] = lval[v] = m_dfsCounter++;
num[v] = lval[v] = m_dfsCounter++;
}
/// Вершина рассмотрена: Означает, что все исходящие ребра вершины рассмотрены
void FinishNode( typename Graph::vertex_index u, const Graph & g )
void FinishNode(vertex u, const Graph& g)
{
PRECONDITION( m_graph == &g );
typename Graph::vertex_index v = father[u];
vertex v = father[u];
// СЛУЧАЙ 1: Вершина v - корневая, завершен обход fds-дерева.
if ( v == NO_VERTEX )
if ( v == Graph::NullVertex() )
{
// Оценить является ли u - точкой сочленения
// Сколько раз стартовая вершина стала папой (столько же в ней стыкуется блоков)
if ( _ChildrenNb(u, g) > 1)
if ( NumChildren(u, g) > 1)
{
// В корневой вершине стыкуются 2 или более блоков - значит она же является и точкой сочленения.
m_bicompVis.CutNode( u, g );
@@ -177,7 +175,7 @@ public:
// Извещение о найденном блоке
if ( !m_stackEdges.empty() ) // Все что есть в m_stackEdges - следует считать последним найденным блоком.
{
m_bicompVis.BlockFounded( m_stackEdges.begin(), m_stackEdges.end(), g );
m_bicompVis.BlockFounded(m_stackEdges.begin(), m_stackEdges.end(), g);
// После извещения визитера - вычищаем стек
m_stackEdges.clear();
}
@@ -194,7 +192,7 @@ public:
// (!) Если вершина v не корень d-дерева, то можно утверждать, что она - есть точка сочленения;
// См. теорему 8.2. [М.О.Асанов]
if ( father[v] != NO_VERTEX ) // если v корневая вершина, то оценки для неё делаются в конце обхода дерева
if ( father[v] != Graph::NullVertex() ) // если v корневая вершина, то оценки для неё делаются в конце обхода дерева
{
m_bicompVis.CutNode( v, *m_graph );
}
@@ -237,64 +235,64 @@ public:
}
/// Означает, что начато рассмотрение корневой вершины будущего дерева обхода
void StartNode( typename Graph::vertex_index v, const Graph & g )
void StartNode(vertex v, const Graph& g)
{
C3D_UNUSED_PARAMETER( v );
_Init( g );
PRECONDITION( father[v] == NO_VERTEX );
InitVisitor( g );
PRECONDITION( father[v] == Graph::NullVertex() );
PRECONDITION( num[v] == 0 && lval[v] == 0 );
}
/// Заход в ребро dfs-дерева, вызывается перед переходом от посещенной вершины v к еще не посещенной вершине u
void TreeEdge( typename Graph::vertex_index v, typename Graph::vertex_index u, const Graph & g )
void TreeEdge(vertex v, vertex u, const Graph& g)
{
C3D_UNUSED_PARAMETER( g );
PRECONDITION( m_graph == &g );
PRECONDITION( father[u] == NO_VERTEX );
PRECONDITION( father[u] == Graph::NullVertex() );
m_stackEdges.push_back( edge(v,u) ); // Вставить ребро vu;
father[u] = v; // зафиксируем отца для вершины u;
}
private:
/// Количество сыновей вершины
size_t _ChildrenNb( typename Graph::vertex_index u, const Graph & g ) const
// Количество сыновей вершины.
size_t NumChildren(vertex u, const Graph& g) const
{
PRECONDITION( m_graph == &g );
// Оценить является ли u - точкой сочленения
size_t fatherNb = 0; // Сколько раз вершина u стала папой
std::pair<adjacency_iterator,adjacency_iterator> adjIterPair = g.AdjacentVertices( u );
for ( ; adjIterPair.first != adjIterPair.second; ++adjIterPair.first )
size_t fatherNb = 0; // Сколько раз вершина u стала папой
for ( vertex adjNode: g.AdjacentVertices(u) )
{
if ( father[*adjIterPair.first] == u )
if ( father[adjNode] == u )
{
++fatherNb;
}
}
return fatherNb;
}
void _Init( const Graph & graph )
void InitVisitor(const Graph& graph)
{
m_graph = &graph;
const typename Graph::vertices_size_t vertNb = graph.NumVertices();
m_dfsCounter = 1;
num.assign( vertNb, 0 );
father.assign( vertNb, NO_VERTEX );
lval.assign( vertNb, 0 );
InitPropertyMap(num, graph, 0);
InitPropertyMap(father, graph, Graph::NullVertex());
InitPropertyMap(lval, graph, 0);
m_stackEdges.clear();
}
private:
const Graph * m_graph; ///< Рассматриваемый граф, для которого ищутся точки сочленения
BicompVisitor & m_bicompVis; ///< Посетитель алгоритмов этого класса
ptrdiff_t m_dfsCounter; ///< Счетчик вершин dfs-дерева
std::vector<size_t> num; ///< Нумерация порядка обхода вершин d-дерева
std::vector<size_t> lval; ///< Массив значений функции L[v] на каждую вершину - см.теорию стр.166, [Asan], Лемма 6;
std::vector<typename Graph::vertex_index> father;///< Отец вершины в dfs-дереве
std::vector<edge> m_stackEdges; ///< Стек ребер для обслуживания нахождения блоков
using NumVertexMap = typename property_map<Graph,size_t>::type;
using FatherVertexMap = typename property_map<Graph,vertex>::type;
const Graph* m_graph; ///< Рассматриваемый граф, для которого ищутся точки сочленения.
BicompVisitor& m_bicompVis; ///< Посетитель алгоритмов этого класса.
ptrdiff_t m_dfsCounter; ///< Счетчик вершин dfs-дерева.
NumVertexMap num; ///< Нумерация порядка обхода вершин d-дерева.
NumVertexMap lval; ///< Массив значений функции L[v] на каждую вершину - см.теорию стр.166, [Asan], Лемма 6.
FatherVertexMap father; ///< Отец вершины в dfs-дереве.
std::vector<edge> m_stackEdges; ///< Стек ребер для обслуживания нахождения блоков.
private:
BicompDFSVisitor & operator = ( const BicompDFSVisitor & );
BicompDFSVisitor & operator= ( const BicompDFSVisitor& );
};
//----------------------------------------------------------------------------------------
@@ -304,21 +302,20 @@ template<class Graph>
struct DFSVertexInfo
{
private:
using vertex_index = typename Graph::vertex_index;
using vertex = typename Graph::vertex;
using adjacency_iterator = typename Graph::adjacency_iterator;
public:
vertex_index m_node;
adjacency_iterator m_iter;
adjacency_iterator m_last;
vertex m_node;
adjacency_iterator m_iter, m_last;
DFSVertexInfo( vertex_index v, adjacency_iterator iter, adjacency_iterator last )
DFSVertexInfo( vertex v, adjacency_iterator iter, adjacency_iterator last )
: m_node( v )
, m_iter( iter )
, m_last( last )
{}
DFSVertexInfo( vertex_index v, const Graph & graph )
DFSVertexInfo( vertex v, const Graph & graph )
: m_node( v )
, m_iter()
, m_last()
@@ -342,42 +339,35 @@ public:
};
//----------------------------------------------------------------------------------------
/// Алгоритм обхода в глубину графа смежности
/// Алгоритм обхода в глубину графа смежности.
/**
Вычислительная сложность алгоритма практически линейная, если считать что
методы визитера выполняются за константное время.
\param graph Граф смежности
\param vis Посетитель алгоритма
\param graph Граф смежных вершин.
\param vis Посетитель алгоритма.
*/
//---
template<class Graph, class Visitor>
void DepthFirstSearch( const Graph & graph, Visitor & vis )
template<class Graph, class Visitor, class ColourMap>
void DepthFirstSearch(const Graph& graph, Visitor& vis, ColourMap& colourMap)
{
typedef typename Graph::vertices_size_t vertices_size_t;
typedef typename Graph::vertex_index vertex_index;
typedef typename Graph::adjacency_iterator adjacency_iterator;
const vertices_size_t vCount = graph.NumVertices();
using vertices_size_t = typename Graph::vertices_size_t;
using vertex_t = typename Graph::vertex;
using adjacency_iterator = typename Graph::adjacency_iterator;
std::vector<DFSVertexInfo<Graph>> stack;
std::vector<color_code> colourMap( vCount, white_color ); // Отображение: вершина -> цвет.
// Пометить, как рассмотренные, игнорируемые вершины
for ( vertex_index xIdx = 0; xIdx<vCount; ++xIdx )
// Preliminary marking of graph vertices.
for (vertex_t v: graph.Vertices())
{
if ( vis.Ignored(xIdx,graph) )
{
colourMap[xIdx] = black_color;
}
colourMap[v] = vis.Ignored(v,graph) ? black_color : white_color;
}
adjacency_iterator vIter, vLast;
vertex_index srcNode;
adjacency_iterator vIter, vLast;
for ( vertex_index startNode = 0; startNode < vCount; ++startNode )
for (vertex_t startNode: graph.Vertices())
{
if ( colourMap[startNode] == white_color ) // Начинаем с x-вершины
if ( colourMap[startNode] == white_color ) // Начинаем с x-вершины.
{
colourMap[startNode] = gray_color;
vis.StartNode( startNode, graph );
@@ -387,6 +377,7 @@ void DepthFirstSearch( const Graph & graph, Visitor & vis )
while ( !stack.empty() )
{
vertex_t srcNode;
{
DFSVertexInfo<Graph> & curr = stack.back();
vIter = curr.m_iter;
@@ -395,40 +386,40 @@ void DepthFirstSearch( const Graph & graph, Visitor & vis )
stack.pop_back();
}
while ( vIter != vLast )
while (vIter != vLast)
{
const vertex_index trgNode = *vIter;
const vertex_t trgNode = *vIter;
++vIter;
vis.ExamineEdge( srcNode, trgNode, graph );
vis.ExamineEdge(srcNode, trgNode, graph);
switch ( colourMap[trgNode] ) // Переход по дереву к следующей вершине
switch (colourMap[trgNode]) // Переход по дереву к следующей вершине.
{
case white_color:
{
vis.TreeEdge( srcNode, trgNode, graph ); // "древесное" ребро
vis.TreeEdge( srcNode, trgNode, graph ); // "древесное" ребро.
colourMap[trgNode] = gray_color;
stack.push_back( DFSVertexInfo<Graph>( srcNode, vIter, vLast ) );
stack.push_back( DFSVertexInfo<Graph>(srcNode, vIter, vLast) );
vis.DiscoverNode( srcNode = trgNode, graph );
c3d::tie( vIter, vLast ) = graph.AdjacentVertices( srcNode );
c3d::tie( vIter, vLast ) = graph.AdjacentVertices(srcNode);
break;
}
case gray_color: // Встетили обратное ребро
case gray_color: // Встетили обратное ребро.
{
vis.BackEdge( srcNode, trgNode, graph );
vis.BackEdge(srcNode, trgNode, graph);
break;
}
default: // Встретили "прямое" или "кросс-ребро" в ориентированном графе
default: // Встретили "прямое" или "кросс-ребро" в ориентированном графе.
{
vis.ForwardOrCrossEdge( srcNode, trgNode, graph );
vis.ForwardOrCrossEdge(srcNode, trgNode, graph);
break;
}
}
}
// Событие завершения обхода текущей вершины
// Событие завершения обхода текущей вершины.
colourMap[srcNode] = black_color;
vis.FinishNode( srcNode, graph );
vis.FinishNode(srcNode, graph);
}
}
}
@@ -531,12 +522,12 @@ void dfs_fixed_depth( const Graph & graph, ColorMap & colorMap, Visitor & vis )
*/
//////////////////////////////////////////////////////////////////////////////////////////
/*
template<class Graph, class Prop>
template<class Graph, class Property>
class EdgePropertyMap
{
typedef Graph::vertex_descriptor vertex_descriptor;
typedef Graph::edge_descriptor edge_descriptor;
typedef std::pair<edge_descriptor,Prop> pair;
typedef std::pair<edge_descriptor,Property> pair;
class node
{
public:
@@ -551,14 +542,14 @@ class EdgePropertyMap
std::vector<node> nodes;
public:
const Prop & operator[]( edge_descriptor ) const;
Prop & operator[]( edge_descriptor );
const Property & operator[]( edge_descriptor ) const;
Property & operator[]( edge_descriptor );
};
*/
//////////////////////////////////////////////////////////////////////////////////////////
//
/// Инкапсуляция алгоритма поиска 2-связных компонент и/или точек сочленения
/// Инкапсуляция алгоритма поиска 2-связных компонентов и/или точек сочленения.
/**
ПЛАНИРУЕТСЯ ЗАМЕНИТЬ ЭТОТ АЛГОРИТМ НА БОЛЕЕ ОБЩИЙ НО НЕ МЕНЕЕ ЭФФЕКТИВНЫЙ:
DepthFirstSearch + BicompDFSVisitor
@@ -571,7 +562,7 @@ public:
\par РЕФАКТОРИНГ
1) Нужно обобщить это алгоритм с библиотекой MtGraph
2) Возможно снабдить это класс-алгоритм посетителем поиска компонент.
2) Возможно снабдить это класс-алгоритм посетителем поиска компонентов.
Это, например, позволит генерировать два варианта алгоритма поиска блоков:
Вариант, когда нужно найти только вершины сочленения (без блоков) вариант,
когда нужно искать шарниры и/или блоки;
@@ -643,7 +634,7 @@ const std::vector<typename Graph::vertex_index> & MtBicompSearch<Graph>::SearchC
template<class Graph>
void MtBicompSearch<Graph>::Init()
{
const vertex_size_t vertNb = m_graph.NumVertecies();
const vertex_size_t vertNb = m_graph.NumVertices();
m_dfsCounter = 1;
num.assign( vertNb, 0 );
father.assign( vertNb, -1 );
@@ -653,14 +644,14 @@ void MtBicompSearch<Graph>::Init()
}
//----------------------------------------------------------------------------------------
/// Запустить алгоритм
// Запустить алгоритм.
//---
template<class Graph>
void MtBicompSearch<Graph>::Perform()
{
PRECONDITION( m_cutnodes.empty() );
const vertex_size_t vertNb = m_graph.NumVertecies();
const vertex_size_t vertNb = m_graph.NumVertices();
for ( vertex_index startIdx = 0; startIdx<vertNb; ++startIdx ) // startIdx - корень d-дерева
{
if ( num[startIdx] == 0 )
@@ -753,18 +744,15 @@ void MtBicompSearch<Graph>::BiComp( const vertex_index vIdx )
}
}
//////////////////////////////////////////////////////////////////////////////////////////
//
// Посетитель алгоритма поиска компонент сильной связности
//
//////////////////////////////////////////////////////////////////////////////////////////
//---------------------------------------------------------------------------------------
// Посетитель алгоритма поиска компонент сильной связности.
//---
struct DefaultSCVisitor
{
// Вызывается алгоритмом перед началом обхода всего графа
// Вызывается алгоритмом перед началом обхода всего графа.
template<class Graph>
inline void Start( const Graph & ) {}
// Вызывается, когда найден очередной компонент сильной связности в орграфе
// Вызывается, когда найден очередной компонент сильной связности в орграфе.
/*
Аргументы: граф и пара вершинных итераторов, пробегающих подмножество компонента.
*/
@@ -775,10 +763,8 @@ struct DefaultSCVisitor
inline bool IsFiltered( const Graph &, Vertex ) { return false; }
};
//////////////////////////////////////////////////////////////////////////////////////////
/**
\brief \ru Алгоритм поиска компонент сильной связности в орграфе.
//---------------------------------------------------------------------------------------
/** \brief \ru Алгоритм поиска компонентов сильной связности в орграфе.
\en Algorithm for searching strongly connected components in a digraph.
\details
\ru Напомним, что две вершины орграфа считаются сильно связанными, если
@@ -790,151 +776,76 @@ struct DefaultSCVisitor
вершины компонента сильной связости принадлежат классу взаимной достижимости вершин. \~
\note \ru Алгоритм #MtStrongComponents имеет линейную сложность вычислений.
*/
//////////////////////////////////////////////////////////////////////////////////////////
template <class Graph, class SCVisitor, class VertexPropertyMap>
//---
template <class Graph, class SCVisitor, class NumVertexMap>
class MtStrongComponents
{
public: // Ассоциативные типы.
typedef typename graph_traits<Graph>::vertex vertex;
typedef typename graph_traits<Graph>::edge edge;
typedef typename graph_traits<Graph>::edge_iterator edge_iterator;
typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator;
typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator;
typedef void (*InitNumVertexMap)(NumVertexMap&, const Graph&, const size_t& val);
public:
MtStrongComponents( const Graph &, SCVisitor & );
void operator() (); ///< Исполнить алгоритм поиска сильных компонентов.
private:
// DFS-алгоритм для поиска компонент сильной связности в графе ограничений.
void StrongSearch( vertex, std::vector<vertex> & );
private:
const Graph & m_diGraph; ///< Ориентированный граф.
SCVisitor & m_vis; ///< Посетитель алгоритма поиска компонент сильной связности.
size_t m_counter; ///< Порядок DFS-обхода.
VertexPropertyMap num; ///< Вспомогательный массив порядковых номеров обхода в глубину.
VertexPropertyMap lval; ///< Массив для промежуточных целочисленных вычислений.
private:
MtStrongComponents( const MtStrongComponents & );
MtStrongComponents & operator = ( const MtStrongComponents & );
};
//----------------------------------------------------------------------------------------
//
//---
template <class Graph, class Vis, class VPropMap>
MtStrongComponents<Graph,Vis,VPropMap>::MtStrongComponents( const Graph & b_graph, Vis & vis )
: m_diGraph( b_graph )
MtStrongComponents(const Graph& g, SCVisitor& vis, InitNumVertexMap initFunc = DefaultInitFunc)
: m_diGraph( g )
, m_vis( vis )
, num( b_graph.NumVertices() )
, lval( b_graph.NumVertices() )
, num()
, lval()
, m_counter( 1 )
{}
, initNumVertexMap(initFunc)
{}
MtStrongComponents( const MtStrongComponents & ) = delete;
MtStrongComponents & operator = ( const MtStrongComponents & ) = delete;
//----------------------------------------------------------------------------------------
// Главный алгоритм поиска компонент сильной связности в графе ограничений
//---
template <class Graph, class Vis, class VPropMap>
void MtStrongComponents<Graph,Vis,VPropMap>::operator() ()
{
m_vis.Start( m_diGraph );
std::vector<vertex> stack;
stack.reserve( m_diGraph.NumVertices() );
m_counter = 1;
vertex_iterator vIter, vLast;
for ( c3d::tie(vIter,vLast) = m_diGraph.Vertices(); vIter!=vLast; ++vIter )
public:
void operator() () ///< Исполнить алгоритм поиска сильных компонентов.
{
num[*vIter] = 0;
Perform( m_diGraph.Vertices() );
}
for ( c3d::tie(vIter,vLast) = m_diGraph.Vertices(); vIter!=vLast; ++vIter )
// Главный алгоритм поиска компонентов сильной связносити для указанных вершин.
template<class VertexRange>
void Perform(const VertexRange & nodesRng)
{
if ( num[*vIter] == 0 && !m_vis.IsFiltered(m_diGraph,*vIter) )
StrongSearch( *vIter, stack );
}
}
initNumVertexMap(num, m_diGraph, 0);
initNumVertexMap(lval, m_diGraph, 0);
m_vis.Start(m_diGraph);
//#define _RECURSIVE_STRONG_SEARCH 1
#ifdef _RECURSIVE_STRONG_SEARCH
//----------------------------------------------------------------------------------------
/// Алгоритм поиска компонент сильной связности в орграфе
/**
Алгоритм применяется для разбиения графа ограничений на независимо
решаемые подсистемы (сегменты). Рекурсивный вариант. Описание алгоритма приведено
в книжке Асанова по теории графов, стр.171.\n
\param vx - корневая вершина поддерева DFS
\param stack - стек рассмотренных вершин, для которых не установлена компонентная принадлежность
*/
//---
template <class Graph, class Vis, class VPropMap>
void MtStrongComponents<Graph,Vis,VPropMap>::StrongSearch( vertex vx, std::vector<vertex> & stack )
{
PRECONDITION( !m_vis.IsFiltered(m_diGraph,vx) );
num[vx] = m_counter;
lval[vx] = m_counter;
++m_counter;
stack.push_back( vx );
std::vector<vertex> stack;
stack.reserve(m_diGraph.NumVertices());
m_counter = 1;
edge_iterator eIter, eLast; // итераторы обхода инцидентных ребер
for ( c3d::tie(eIter,eLast) = m_diGraph.OutArcs(vx); eIter!=eLast; ++eIter )
{
vertex w = m_diGraph.Target( *eIter ); // Выходящая вершина прямого ребра
PRECONDITION( w != vx ); // Граф не ориентированный !!!
if ( w != vx && !m_vis.IsFiltered(m_diGraph,w) ) // игнорируем обратное ребро из w в vx, а также отфильтрованные узлы;
{
if ( num[w] == 0 ) // <v,w> - "древесная" дуга
{
StrongSearch( w, stack );
if ( lval[w] < lval[vx] ) // При выходе из рекурсии значение l(w) должно быть уже насчитано;
lval[vx] = lval[w];
}
else
{
const size_t wNum = num[w];
if ( wNum < num[vx] && wNum < lval[vx] ) // <v,w> - "поперечная" или "обратная" дуга
{
// Предположение: В стеке лежат вершины, из которых вершина vx достижима;
if ( std::find(stack.rbegin(), stack.rend(), w) != stack.rend() )
{
lval[vx] = wNum;
}
}
}
}
}
const size_t vNum = num[vx];
if ( lval[vx] == vNum ) // vx - корневая вершина очередной компоненты сильной связности
{
// Обнаружен очередной сильный компонент
if ( !stack.empty() && num[stack.back()] >= vNum )
for (const vertex & node: m_diGraph.Vertices())
{
// Посчитать размер компонента
typename std::vector<vertex>::reverse_iterator vIter, vLast;
vIter = stack.rbegin();
vLast = stack.rend();
ptrdiff_t compSize = 0;
for ( ; vIter != vLast && num[*vIter] >= vNum; ++vIter, ++compSize );
// Передать диапазон компонента визитеру
typename std::vector<vertex>::iterator cIter, cLast;
cIter = cLast = stack.end();
std::advance( cIter, -compSize );
m_vis.Component( m_diGraph, cIter, cLast );
stack.erase( cIter, cLast ); // очистить верхушку стека
num[node] = 0;
}
}
}
#else // _RECURSIVE_STRONG_SEARCH
for (const vertex & node: nodesRng)
{
if (num[node] == 0 && !m_vis.IsFiltered(m_diGraph,node))
StrongSearch(node, stack);
}
}
private:
// DFS-алгоритм для поиска компонентов сильной связности в графе ограничений.
void StrongSearch( vertex, std::vector<vertex> & );
static void DefaultInitFunc(NumVertexMap& pMap, const Graph& g, const size_t& val)
{
pMap.assign(g.NumVertices(), val);
}
private:
const Graph & m_diGraph; ///< Ориентированный граф.
SCVisitor & m_vis; ///< Посетитель алгоритма поиска компонентов сильной связности.
size_t m_counter; ///< Порядок DFS-обхода.
NumVertexMap num; ///< Вспомогательный массив порядковых номеров обхода в глубину.
NumVertexMap lval; ///< Массив для промежуточных целочисленных вычислений.
InitNumVertexMap initNumVertexMap; ///< Function initializing the vertex property map.
};
//----------------------------------------------------------------------------------------
/// Стековый элемент для алгоритма обхода в глубину.
@@ -980,7 +891,7 @@ struct DFS_element
};
//----------------------------------------------------------------------------------------
/// Алгоритм поиска компонент сильной связности в орграфе.
/// Алгоритм поиска компонентов сильной связности в орграфе.
/**
Алгоритм применяется для разбиения графа ограничений на независимо-решаемые
подсистемы (сегменты). Описание алгоритма приведено в книжке Асанова по
@@ -1004,11 +915,11 @@ void MtStrongComponents<Graph,Vis,VPropMap>::StrongSearch( vertex rootVert, std:
dfsStack.push_back( DfsStackElem( rootVert, m_diGraph ) );
DfsStackElem * topElem = &dfsStack.back();
while( !dfsStack.empty() ) // Цикл возвратов из стека (одна итерация - одно возвращение против древесного ребра )
while( !dfsStack.empty() ) // Цикл возвратов из стека (одна итерация - одно возвращение против древесного ребра).
{
while ( topElem->iter != topElem->last )
{
vertex w = m_diGraph.Target( *topElem->iter ); // Выходящая вершина прямого ребра <v,w>
vertex w = m_diGraph.Target( *topElem->iter ); // Выходящая вершина прямого ребра <v,w>.
PRECONDITION( w != topElem->node ); // Граф не ориентированный !!!
if ( (w != topElem->node) && !m_vis.IsFiltered(m_diGraph,w) ) // игнорируем обратное ребро из w в vx, а также отфильтрованные узлы;
{
@@ -1025,7 +936,7 @@ void MtStrongComponents<Graph,Vis,VPropMap>::StrongSearch( vertex rootVert, std:
else
{
const size_t wNum = num[w];
if ( wNum < num[topElem->node] && wNum < lval[topElem->node] ) // <v,w> - "поперечная" или "обратная" дуга
if ( wNum < num[topElem->node] && wNum < lval[topElem->node] ) // <v,w> - "поперечная" или "обратная" дуга.
{
// Предположение: В стеке лежат вершины, из которых вершина vx достижима;
if ( std::find(comStack.rbegin(), comStack.rend(), w) != comStack.rend() )
@@ -1041,9 +952,9 @@ void MtStrongComponents<Graph,Vis,VPropMap>::StrongSearch( vertex rootVert, std:
PRECONDITION( dfsStack.back().iter == dfsStack.back().last );
PRECONDITION( topElem == &dfsStack.back() );
// Завершено посещение узла sElem->m_node
// Завершено посещение узла sElem->m_node.
const size_t vNum = num[topElem->node/*vx*/];
if ( lval[topElem->node/*vx*/] == vNum ) // vx - корневая вершина очередной компоненты сильной связности
if ( lval[topElem->node/*vx*/] == vNum ) // vx - корневая вершина очередной компоненты сильной связности.
{
// Обнаружен очередной сильный компонент
if ( !comStack.empty() && num[comStack.back()] >= vNum )
@@ -1063,7 +974,7 @@ void MtStrongComponents<Graph,Vis,VPropMap>::StrongSearch( vertex rootVert, std:
comStack.erase( cIter, cLast ); // очистить верхушку стека
}
}
// Возвращение против древесного ребра <v,w>, где w-просмотренная вершина, v-вершина из которой пришли в w;
// Возвращение против древесного ребра <v,w>, где w-просмотренная вершина, v-вершина из которой пришли в w.
{
const vertex w = topElem->node;
dfsStack.pop_back();
@@ -1082,8 +993,6 @@ void MtStrongComponents<Graph,Vis,VPropMap>::StrongSearch( vertex rootVert, std:
}
}
#endif // _RECURSIVE_STRONG_SEARCH
#endif // __GRAPH_ALGORITHMS_H
/** \} */ // Base_GraphLib
+21 -21
View File
@@ -54,7 +54,7 @@ int SimpleNameCompare( const SimpleName & h1, const SimpleName & h2 ) {
// ---
inline
bool IsGoodSimpleName( const SimpleName & s ) {
return (bool)(s > 0);
return static_cast<bool>(s > 0);
}
#else // SIMPLENAME_AS_CLASS
@@ -219,9 +219,9 @@ SimpleName Hash32( uint8 * k, size_t length, SimpleName _c = INIT_HASH32_VAL )
// handle most of the key
while ( len >= 12 )
{
a += ((uint32)k[0] + ((uint32)k[1]<<8) + ((uint32)k[2] <<16) + ((uint32)k[3] <<24)); // SKIP_SA
b += ((uint32)k[4] + ((uint32)k[5]<<8) + ((uint32)k[6] <<16) + ((uint32)k[7] <<24)); // SKIP_SA
c += ((uint32)k[8] + ((uint32)k[9]<<8) + ((uint32)k[10]<<16) + ((uint32)k[11]<<24)); // SKIP_SA
a += (static_cast<uint32>(k[0]) + (static_cast<uint32>(k[1])<<8) + (static_cast<uint32>(k[2]) <<16) + (static_cast<uint32>(k[3]) <<24)); // SKIP_SA
b += (static_cast<uint32>(k[4]) + (static_cast<uint32>(k[5])<<8) + (static_cast<uint32>(k[6]) <<16) + (static_cast<uint32>(k[7]) <<24)); // SKIP_SA
c += (static_cast<uint32>(k[8]) + (static_cast<uint32>(k[9])<<8) + (static_cast<uint32>(k[10])<<16) + (static_cast<uint32>(k[11])<<24)); // SKIP_SA
mix ( a, b, c );
k += 12;
len -= 12;
@@ -231,18 +231,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 )
{
case 11: c += ((uint32)k[10]<<24); // SKIP_SA
case 10: c += ((uint32)k[9] <<16); // SKIP_SA
case 9 : c += ((uint32)k[8] <<8 ); // SKIP_SA
case 11: c += (static_cast<uint32>(k[10])<<24); // SKIP_SA
case 10: c += (static_cast<uint32>(k[9]) <<16); // SKIP_SA
case 9 : c += (static_cast<uint32>(k[8]) <<8 ); // SKIP_SA
// \ru Первый байт с резервируется для length \en The first byte c is reserved for 'length'
case 8 : b += ((uint32)k[7] <<24); // SKIP_SA
case 7 : b += ((uint32)k[6] <<16); // SKIP_SA
case 6 : b += ((uint32)k[5] <<8 ); // SKIP_SA
case 5 : b += ((uint32)k[4]); // SKIP_SA
case 4 : a += ((uint32)k[3] <<24); // SKIP_SA
case 3 : a += ((uint32)k[2] <<16); // SKIP_SA
case 2 : a += ((uint32)k[1] <<8 ); // SKIP_SA
case 1 : a += ((uint32)k[0]); // SKIP_SA
case 8 : b += (static_cast<uint32>(k[7]) <<24); // SKIP_SA
case 7 : b += (static_cast<uint32>(k[6]) <<16); // SKIP_SA
case 6 : b += (static_cast<uint32>(k[5]) <<8 ); // SKIP_SA
case 5 : b += (static_cast<uint32>(k[4])); // SKIP_SA
case 4 : a += (static_cast<uint32>(k[3]) <<24); // SKIP_SA
case 3 : a += (static_cast<uint32>(k[2]) <<16); // SKIP_SA
case 2 : a += (static_cast<uint32>(k[1]) <<8 ); // SKIP_SA
case 1 : a += (static_cast<uint32>(k[0])); // SKIP_SA
// \ru case 0: Ничего не добавляем. \en case 0: Add nothing.
}
@@ -275,7 +275,7 @@ SimpleName Hash32Ptr( T * k ) { return c3d::Hash32( reinterpret_cast<uint8 *>(&k
// ---
inline
SimpleName HashStr( const c3d::string_t & str ) {
return c3d::Hash32( (uint8*)str.c_str(), str.length() * sizeof(TCHAR) );
return c3d::Hash32( const_cast<uint8*>(reinterpret_cast<const uint8 *>(str.c_str())), str.length() * sizeof(TCHAR) );
}
@@ -291,7 +291,7 @@ inline
SimpleName HashStr( const char * c_str )
{
PRECONDITION( c_str );
return c3d::Hash32( (uint8*)c_str, strlen(c_str) * sizeof(char) );
return c3d::Hash32( const_cast<uint8 *>(reinterpret_cast<const uint8*>(c_str)), strlen(c_str) * sizeof(char) );
}
@@ -308,11 +308,11 @@ SimpleName HashStr( const wchar_t * w_str )
{
PRECONDITION( w_str );
#ifndef __MOBILE_VERSION__
return c3d::Hash32( (uint8*)w_str, wcslen(w_str) * sizeof(wchar_t) );
return c3d::Hash32( const_cast<uint8 *>(reinterpret_cast<const uint8*>(w_str)), wcslen(w_str) * sizeof(wchar_t) );
#else // __MOBILE_VERSION__
uint16 * hashBuf = Ucs4ToUtf16((uint32*)w_str);
uint16 * hashBuf = Ucs4ToUtf16(const_cast<uint32 *>(reinterpret_cast<const uint32*>(w_str)));
uint16 * hashBufPointer = hashBuf;
SimpleName hash = c3d::Hash32( (uint8*)hashBufPointer, wcslen(w_str) * 2 );
SimpleName hash = c3d::Hash32( reinterpret_cast<uint8*>(hashBufPointer), wcslen(w_str) * 2 );
delete[] hashBuf;
return hash;
#endif // __MOBILE_VERSION__
@@ -415,7 +415,7 @@ SimpleName Hash32SN( SimpleName k1, SimpleName k2 )
arr[0] = LoUint32( (size_t)k1 );
arr[1] = LoUint32( (size_t)k2 );
#endif // SIMPLENAME_AS_CLASS
return c3d::Hash32( (uint8*)arr, 2 * sizeof(uint) ); // \ru длина - 4 * 2 = 8 \en length - 4 * 2 = 8
return c3d::Hash32( reinterpret_cast<uint8*>(arr), 2 * sizeof(uint) ); // \ru длина - 4 * 2 = 8 \en length - 4 * 2 = 8
}
+3 -3
View File
@@ -297,7 +297,7 @@ struct ClusterReference
size_t clusterIndex; ///< \ru Индекс кластера в массиве кластеров iobuf_Seq. \en Index of the cluster in the cluster array of iobuf_Seq.
uint16 offset; ///< \ru Смещение в данном кластере. \en Offset in the cluster.
ClusterReference() : clusterIndex ( SYS_MAX_T ), offset ( (uint16)-1 ) {}
ClusterReference() : clusterIndex ( SYS_MAX_T ), offset ( static_cast<uint16>(-1) ) {}
explicit ClusterReference( size_t idx, uint16 off ) : clusterIndex( idx ), offset( off ) {}
ClusterReference( const ClusterReference & ref ) : clusterIndex( ref.clusterIndex ), offset( ref.offset ) {}
@@ -312,7 +312,7 @@ struct ClusterReference
ClusterReference & operator = ( const ClusterReference & ref ) {
clusterIndex = ref.clusterIndex; offset = ref.offset; return *this;
}
bool IsValid() const { return clusterIndex != SYS_MAX_T && offset != (uint16)-1; }
bool IsValid() const { return clusterIndex != SYS_MAX_T && offset != static_cast<uint16>(-1); }
};
//------------------------------------------------------------------------------
@@ -842,7 +842,7 @@ inline bool IsGoodFile( const FileSpace & file, const iobuf_Seq & owner )
for ( size_t i = 0, fileCount = file.Count(); i < fileCount && good ; i++ )
{
size_t fileIndex = file[i];
good = ( (ptrdiff_t)fileIndex >= 0 && (ptrdiff_t)fileIndex < (ptrdiff_t)clustersCount );
good = ( static_cast<ptrdiff_t>(fileIndex) >= 0 && static_cast<ptrdiff_t>(fileIndex) < static_cast<ptrdiff_t>(clustersCount) );
}
return good;
+8 -8
View File
@@ -23,27 +23,27 @@ class writer;
// \ru операторов << и >> \en operators << and >>
//---
#define KNOWN_OBJECTS_RW_REF_OPERATORS(Class) \
friend reader & CALL_DECLARATION operator >> ( reader & in, Class & ref ); \
friend reader & CALL_DECLARATION operator >> ( reader & in, Class & ref ); \
friend writer & CALL_DECLARATION operator << ( writer & out, const Class & ref ); \
friend writer & CALL_DECLARATION operator << ( writer & out, Class & ref ) { return operator << ( out, (const Class &)ref ); }
friend writer & CALL_DECLARATION operator << ( writer & out, Class & ref ) { return operator << ( out, static_cast<const Class &>(ref) ); }
#define KNOWN_OBJECTS_RW_PTR_OPERATORS(Class) \
friend reader & CALL_DECLARATION operator >> ( reader & in, Class *& ptr ); \
friend reader & CALL_DECLARATION operator >> ( reader & in, Class *& ptr ); \
friend writer & CALL_DECLARATION operator << ( writer & out, const Class * ptr ); \
friend writer & CALL_DECLARATION operator << ( writer & out, Class * ptr ) { return operator << ( out, (const Class *)ptr ); }
friend writer & CALL_DECLARATION operator << ( writer & out, Class * ptr ) { return operator << ( out, static_cast<const Class *>(ptr) ); }
// \ru тоже для экспорта/импорта \en for export/import too
// \ru DLLFUNC -> __declspec( dllexport ) или __declspec( dllimport ) объявляется специально \en DLLFUNC -> __declspec( dllexport ) or __declspec( dllimport ) are specially declared
// \ru для этих дефайнов в файлах типа ????_def.h (см. MATH_FUNC_EX выше) \en for this definitions in files like ?????_def.h (see MATH_FUNC_EX above)
#define KNOWN_OBJECTS_RW_REF_OPERATORS_EX(Class, DLLFUNC) \
friend DLLFUNC reader & CALL_DECLARATION operator >> ( reader & in, Class & ref ); \
friend DLLFUNC reader & CALL_DECLARATION operator >> ( reader & in, Class & ref ); \
friend DLLFUNC writer & CALL_DECLARATION operator << ( writer & out, const Class & ref ); \
friend DLLFUNC writer & CALL_DECLARATION operator << ( writer & out, Class & ref ) { return operator << ( out, (const Class &)ref ); }
friend DLLFUNC writer & CALL_DECLARATION operator << ( writer & out, Class & ref ) { return operator << ( out, static_cast<const Class &>(ref) ); }
#define KNOWN_OBJECTS_RW_PTR_OPERATORS_EX(Class, DLLFUNC) \
friend DLLFUNC reader & CALL_DECLARATION operator >> ( reader & in, Class *& ptr ); \
friend DLLFUNC reader & CALL_DECLARATION operator >> ( reader & in, Class *& ptr ); \
friend DLLFUNC writer & CALL_DECLARATION operator << ( writer & out, const Class * ptr ); \
friend DLLFUNC writer & CALL_DECLARATION operator << ( writer & out, Class * ptr ) { return operator << ( out, (const Class *)ptr ); }
friend DLLFUNC writer & CALL_DECLARATION operator << ( writer & out, Class * ptr ) { return operator << ( out, static_cast<const Class *>(ptr) ); }
#endif // __IO_DEFINES_H
+49 -49
View File
@@ -356,7 +356,7 @@ struct TapeClassContainer
/// \ru Функция сравнения двух TapeClass для поиска. \en Function of two TapeClass comparison for a search.
static int TapeClass_Search( const TapeClass & t1, size_t d )
{
return ( ( t1.hashValue == *(ClassDescriptor*)d ) ? 0 : (( t1.hashValue > *(ClassDescriptor*)d ) ? 1 : -1 ) );
return ( ( t1.hashValue == *reinterpret_cast<ClassDescriptor*>(d) ) ? 0 : (( t1.hashValue > *reinterpret_cast<ClassDescriptor*>(d) ) ? 1 : -1 ) );
}
/// \ru Функция сравнения двух TapeClass для сортировки при вставке. \en Function of two TapeClass comparison for sorting while inserting.
static int TapeClass_Compare( const TapeClass & t1, const TapeClass & t2 )
@@ -486,7 +486,7 @@ MATH_FUNC( const char * ) pureName( const char * name );
inline
uint16 hash( const char * name )
{
const uint16 * c = (const uint16 *)name;
const uint16 * c = reinterpret_cast<const uint16 *>(name);
uint16 h = uint16(strlen(name)); // Mix in the string length.
uint16 l = h;
@@ -604,12 +604,12 @@ reader & __readWchar( reader & ps, TCHAR * & s )
len != SYS_MAX_UINT32 &&
!ps.eof() )
{
uint16 * readBuf = new uint16[(size_t)len + 1]; // \ru длина (количество символов) вычитываемой строки с терминальным нулем \en length (number of symbols) of string being read with terminating 0
size_t size = sizeof(uint16) * (size_t)len; // \ru длина (в байтах) вычитываемой строки без терминального нуля \en length (in bytes) of string being read without terminating null
uint16 * readBuf = new uint16[static_cast<size_t>(len) + 1]; // \ru длина (количество символов) вычитываемой строки с терминальным нулем \en length (number of symbols) of string being read with terminating 0
size_t size = sizeof(uint16) * static_cast<size_t>(len); // \ru длина (в байтах) вычитываемой строки без терминального нуля \en length (in bytes) of string being read without terminating null
if ( ps.readBytes(readBuf, size) )
// \ru прочли сколько нужно - добавить ограничивающий 0 \en have read as much as necessary - the terminating 0 is to be added
readBuf[(size_t)len] = 0;
readBuf[static_cast<size_t>(len)] = 0;
else {
// \ru прочли не все, скорее всего ошибка - очистить строку \en not everything has been read, must be an error - clear the string
delete [] readBuf;
@@ -619,9 +619,9 @@ reader & __readWchar( reader & ps, TCHAR * & s )
if ( readBuf ) { // is OK
#ifdef _UNICODE // TCHAR == wchar_t
#if __SIZEOF_WCHAR_T__ == 2 // sizeof(wchar_t) == sizeof(uint16)
s = (TCHAR *)readBuf; // \ru собственно ничего конвертировать не нужно \en nothing to convert
s = reinterpret_cast<TCHAR *>(readBuf); // \ru собственно ничего конвертировать не нужно \en nothing to convert
#else // sizeof(wchar_t) == sizeof(uint32)
s = (TCHAR *)Utf16ToUcs4(readBuf); // \ru Конвертировать UTF-16 в WCHAR \en Convert from UTF-16 to WCHAR
s = reinterpret_cast<TCHAR *>(Utf16ToUcs4(readBuf)); // \ru Конвертировать UTF-16 в WCHAR \en Convert from UTF-16 to WCHAR
delete [] readBuf;
#endif
#else // _UNICODE
@@ -661,11 +661,11 @@ reader & __readWcharT( reader & ps, wchar_t * & s )
!ps.eof() )
{
uint16 * readBuf = new uint16[(size_t)len + 1]; // \ru длина (количество символов) вычитываемой строки с терминальным нулем \en length (number of symbols) of string being read with terminating 0
size_t size = sizeof(uint16) * (size_t)len; // \ru длина (в байтах) вычитываемой строки без терминального нуля \en length (in bytes) of string being read without terminating null
size_t size = sizeof(uint16) * static_cast<size_t>(len); // \ru длина (в байтах) вычитываемой строки без терминального нуля \en length (in bytes) of string being read without terminating null
if ( ps.readBytes(readBuf, size) )
// \ru прочли сколько нужно - добавить ограничивающий 0 \en have read as much as necessary - the terminating 0 is to be added
readBuf[(size_t)len] = 0;
readBuf[static_cast<size_t>(len)] = 0;
else {
// \ru прочли не все, скорее всего ошибка - очистить строку \en not everything has been read, must be an error - clear the string
delete [] readBuf;
@@ -674,9 +674,9 @@ reader & __readWcharT( reader & ps, wchar_t * & s )
if ( readBuf ) { // is OK
#if __SIZEOF_WCHAR_T__ == 2 // sizeof(wchar_t) == sizeof(uint16)
s = (wchar_t *)readBuf; // \ru собственно ничего конвертировать не нужно \en nothing to convert
s = reinterpret_cast<wchar_t *>(readBuf); // \ru собственно ничего конвертировать не нужно \en nothing to convert
#else // sizeof(wchar_t) == sizeof(uint32)
s = (wchar_t *)Utf16ToUcs4(readBuf); // \ru Конвертировать UTF-16 в WCHAR \en Convert from UTF-16 to WCHAR
s = reinterpret_cast<wchar_t *>(Utf16ToUcs4(readBuf)); // \ru Конвертировать UTF-16 в WCHAR \en Convert from UTF-16 to WCHAR
delete [] readBuf;
#endif
}
@@ -810,7 +810,7 @@ writer & operator << ( writer & ps, signed int i )
if ( IsVersion16bit( ps.MathVersion() ) )
ps.setState( io::fail ); // \ru в Linux-версии 16-битные файлы не поддерживаются \en 16-bit files are not supported in Linux
else {
int32 val = (int32)i;
int32 val = static_cast<int32>(i);
ps.writeBytes( &val, sizeof(val) );
}
return ps;
@@ -869,7 +869,7 @@ reader & operator >> ( reader & ps, signed int & i )
else {
int32 val = 0;
ps.readBytes( &val, sizeof(val) );
i = (signed int)val;
i = static_cast<signed int>(val);
}
return ps;
#else // C3D_WINDOWS
@@ -878,7 +878,7 @@ reader & operator >> ( reader & ps, signed int & i )
else {
int32 val = 0;
ps.readBytes( &val, sizeof(val) );
i = (signed int)val;
i = static_cast<signed int>(val);
}
return ps;
#endif // C3D_WINDOWS
@@ -905,7 +905,7 @@ reader & operator >> ( reader & ps, unsigned int & i )
else {
uint32 val = 0;
ps.readBytes( &val, sizeof(val) );
i = (unsigned int)val;
i = static_cast<unsigned int>( val );
}
return ps;
#else // C3D_WINDOWS
@@ -914,7 +914,7 @@ reader & operator >> ( reader & ps, unsigned int & i )
else {
uint32 val = 0;
ps.readBytes( &val, sizeof(val) );
i = (unsigned int)val;
i = static_cast<unsigned int>( val );
}
return ps;
#endif // C3D_WINDOWS
@@ -1023,7 +1023,7 @@ reader & operator >> ( reader & ps, int64 & val )
inline
reader & operator >> ( reader & ps, signed char & ch )
{
ch = (signed char)ps.readByte();
ch = static_cast<signed char>(ps.readByte());
return ps;
}
@@ -1034,7 +1034,7 @@ reader & operator >> ( reader & ps, signed char & ch )
inline
reader & operator >> ( reader & ps, unsigned char & ch )
{
ch = (unsigned char)ps.readByte();
ch = static_cast<unsigned char>(ps.readByte());
return ps;
}
@@ -1045,7 +1045,7 @@ reader & operator >> ( reader & ps, unsigned char & ch )
inline
reader & operator >> ( reader & ps, char & ch )
{
ch = (char)ps.readByte();
ch = static_cast<char>(ps.readByte());
return ps;
}
@@ -1360,7 +1360,7 @@ void WriteCOUNT( writer & out, size_t count )
if ( HiUint32( count ) != 0 )
out.setState( io::underflow64to32 );
uint32 _count = (uint32)LoUint32(count);
uint32 _count = static_cast<uint32>(LoUint32(count));
out << _count;
}
}
@@ -1378,10 +1378,10 @@ void WriteINT_T( writer & out, ptrdiff_t count )
else
{
// \ru OV_x64 проверить переполнение при записи 64-битных данных в 32-битный поток \en OV_x64 check for overflow while writing 64-bit data to 32-bit stream
if ( (int64)count > (int64)SYS_MAX_INT32 || (int64)count < (int64)SYS_MIN_INT32 )
if ( static_cast<int64>(count) > static_cast<int64>(SYS_MAX_INT32) || static_cast<int64>(count) < static_cast<int64>(SYS_MIN_INT32) )
out.setState( io::underflow64to32 );
int32 _count = (int32)LoUint32(count);
int32 _count = static_cast<int32>(LoUint32(count));
out << _count;
}
}
@@ -1412,7 +1412,7 @@ size_t ReadCOUNT ( reader & in, bool uint_val = true )
_count = SYS_MAX_T;
}
count = (size_t)_count;
count = static_cast<size_t>(_count);
// \ru OV_x64 проверить переполнение при чтении 64-битных данных в 32-битной задаче \en OV_x64 check for overflow while reading 64-bit data in 32-bit task
if ( HiUint32(count) != HiUint32(_count) )
@@ -1426,13 +1426,13 @@ size_t ReadCOUNT ( reader & in, bool uint_val = true )
uint _count = 0;
in >> _count;
count = (size_t)_count;
count = static_cast<size_t>(_count);
}
else
{
uint32 _count = 0;
in >> _count;
count = (size_t)_count;
count = static_cast<size_t>(_count);
}
if ( count == SYS_MAX_UINT32 )
@@ -1459,7 +1459,7 @@ ptrdiff_t ReadINT_T( reader & in, bool uint_val = true )
{
int64 _count = 0;
in.readInt64( _count );
count = (ptrdiff_t)_count;
count = static_cast<ptrdiff_t>(_count);
// \ru OV_x64 проверить переполнение при чтении 64-битных данных в 32-битной задаче \en OV_x64 check for overflow while reading 64-bit data in 32-bit task
if ( HiInt32(count) != HiInt32(_count) )
@@ -1472,13 +1472,13 @@ ptrdiff_t ReadINT_T( reader & in, bool uint_val = true )
{
int _count = 0;
in >> _count;
count = (ptrdiff_t)_count;
count = static_cast<ptrdiff_t>(_count);
}
else
{
int32 _count = 0;
in >> _count;
count = (ptrdiff_t)_count;
count = static_cast<ptrdiff_t>(_count);
}
}
@@ -1494,7 +1494,7 @@ void WriteCOUNT( void * out, VERSION version, size_t count )
{
if ( IsVersion64bit(version) )
{
const uint64 count64 = (uint64)count;
const uint64 count64 = static_cast<uint64>(count);
::memcpy( out, &count64, sizeof(count64) );
}
else
@@ -1503,8 +1503,8 @@ void WriteCOUNT( void * out, VERSION version, size_t count )
//OV_x64 if ( count > (int64)_I32_MAX || count < (int64)_I32_MIN )
//OV_x64 out.setState( io::underflow64to32 );
PRECONDITION( count <= (size_t)SYS_MAX_UINT32/*_UI32_MAX*/ );
const uint32 count32 = (uint32)LoUint32(count);
PRECONDITION( count <= static_cast<size_t>(SYS_MAX_UINT32)/*_UI32_MAX*/ );
const uint32 count32 = static_cast<uint32>(LoUint32(count));
::memcpy( out, &count32, sizeof(count32) );
}
@@ -1518,7 +1518,7 @@ void WriteCOUNT( void * out, VERSION version, ptrdiff_t count )
{
if ( IsVersion64bit(version) )
{
const int64 count64 = (int64)count;
const int64 count64 = static_cast<int64>(count);
::memcpy( out, &count64, sizeof(count64) );
}
else
@@ -1527,8 +1527,8 @@ void WriteCOUNT( void * out, VERSION version, ptrdiff_t count )
//OV_x64 if ( count > (int64)_I32_MAX || count < (int64)_I32_MIN )
//OV_x64 out.setState( io::underflow64to32 );
PRECONDITION( count <= (ptrdiff_t)SYS_MAX_INT32/*_I32_MAX*/ && count >= (ptrdiff_t)SYS_MIN_INT32/*_I32_MIN*/ );
const int32 count32 = (int32)LoUint32(count);
PRECONDITION( count <= static_cast<ptrdiff_t>(SYS_MAX_INT32)/*_I32_MAX*/ && count >= static_cast<ptrdiff_t>(SYS_MIN_INT32)/*_I32_MIN*/ );
const int32 count32 = static_cast<int32>(LoUint32(count));
::memcpy( out, &count32, sizeof(count32) );
}
@@ -1547,7 +1547,7 @@ size_t ReadCOUNT ( void * in, VERSION version )
uint64 count64 = 0;
::memcpy( &count64, in, sizeof(count64) );
PRECONDITION( count64 <= SYS_MAX_T/*SIZE_MAX*/ );
count = (size_t)count64;
count = static_cast<size_t>(count64);
// \ru OV_x64 проверить переполнение при чтении 64-битных данных в 32-битной задаче \en OV_x64 check for overflow while reading 64-bit data in 32-bit task
//OV_x64 if ( HiUint32( count ) != HiUint32( _count ) )
@@ -1834,7 +1834,7 @@ void ReadCluster( reader & in, uint16 clusterSize, Cluster & cl )
cl.m_l = length;
// \ru ...а читаем - сколько было занято \en ...but read as much as has been occupied
in.readBytes( (uint8*)cl.m_f, length );
in.readBytes( reinterpret_cast<uint8*>(cl.m_f), length );
}
//----------------------------------------------------------------------------------------
@@ -1853,7 +1853,7 @@ void WriteCluster( writer & out, const Cluster & cl, uint16 /*clusterSize*/ )
uint16 len = cl.m_l;
PRECONDITION( len <= clusterSize );
out << len;
out.writeBytes( (const uint8*)cl.m_f, len );
out.writeBytes( reinterpret_cast<const uint8*>(cl.m_f), len );
}
//----------------------------------------------------------------------------------------
@@ -1865,7 +1865,7 @@ size_t WriteClusterInfo( void * out, VERSION version, const Cluster & obj )
WriteCOUNT( out, version, obj.m_f );
uint16 len = obj.m_l;
::memcpy( (uint8*)out + LenCOUNT(version), &len, sizeof( len ) );
::memcpy( static_cast<uint8*>(out) + LenCOUNT(version), &len, sizeof( len ) );
return Cluster::SizeOf( version );
}
@@ -1879,7 +1879,7 @@ size_t ReadClusterInfo( void * in, VERSION version, Cluster & obj )
size_t off = ReadCOUNT( in, version );
uint16 len = 0;
::memcpy( &len, (uint8*)in + LenCOUNT(version), sizeof( len ) );
::memcpy( &len, static_cast<uint8*>(in) + LenCOUNT(version), sizeof( len ) );
obj.AllocFile( off, len ); // \ru запомнить смещение в файле и кол-во байт \en memorize the shift in file and the number of bytes
@@ -1893,16 +1893,16 @@ size_t ReadClusterInfo( void * in, VERSION version, Cluster & obj )
inline
size_t WriteClusterBody( void * out, VERSION version, const Cluster & obj, uint16 clusterSize )
{
uint8 * m = (uint8 *)out;
uint8 * m = static_cast<uint8 *>(out);
// \ru кол-во заполненных байт в кластере \en the number of filled bytes in the cluster
uint16 l = obj._len();
PRECONDITION( l <= clusterSize );
*(uint16*)m = l;
*reinterpret_cast<uint16*>(m) = l;
m += sizeof(uint16);
if ( l > clusterSize )
return (size_t)-1;
return static_cast<size_t>(-1);
if ( l ) {
memcpy( m, obj._ptr(), l ); // \ru теперь данные кластера \en the cluster data now
@@ -1919,16 +1919,16 @@ size_t WriteClusterBody( void * out, VERSION version, const Cluster & obj, uint1
inline
size_t ReadClusterBody( void * in, VERSION version, Cluster & obj, uint16 clusterSize )
{
uint8 * m = (uint8 *)in;
uint8 * m = static_cast<uint8 *>(in);
// \ru прочитать кол-во заполненных байт кластера и заполнить соответствующее поле в нем \en read the number of filled bytes in the cluster and fill its corresponding field
uint16 l = *(uint16*)m;
uint16 l = *reinterpret_cast<uint16*>(m);
PRECONDITION( l <= clusterSize );
obj.SetClusterLength( l );
m += sizeof(uint16);
if ( l > clusterSize )
return (size_t)-1;
return static_cast<size_t>(-1);
if ( l ) {
memcpy( obj._getMemPointer(), m, l ); // \ru теперь данные кластера \en the cluster data now
@@ -1971,10 +1971,10 @@ size_t ReadClusterBody( void * in, VERSION version, Cluster & obj, uint16 cluste
// for objects which type is exactly known while reading and writing.
//---
#define IMP_KNOWN_OBJECTS_RW_REF_OPERATORS(Class) \
writer & CALL_DECLARATION operator << ( writer & out, Class & ref ) { return operator << ( out, (const Class &)ref ); }
writer & CALL_DECLARATION operator << ( writer & out, Class & ref ) { return operator << ( out, static_cast<const Class &>(ref) ); }
#define IMP_KNOWN_OBJECTS_RW_PTR_OPERATORS(Class) \
writer & CALL_DECLARATION operator << ( writer & out, Class * ptr ) { return operator << ( out, (const Class *)ptr ); }
writer & CALL_DECLARATION operator << ( writer & out, Class * ptr ) { return operator << ( out, static_cast<const Class *>(ptr) ); }
//------------------------------------------------------------------------------
// \ru Реализация функций записи по неконстантной ссылке/указателю (объявленных в KNOWN_OBJECTS_RW_REF_OPERATORS_EX_BASE, KNOWN_OBJECTS_RW_PTR_OPERATORS_EX_BASE)
@@ -1983,10 +1983,10 @@ size_t ReadClusterBody( void * in, VERSION version, Cluster & obj, uint16 cluste
// for objects which type is exactly known while reading and writing.
//---
#define IMP_KNOWN_OBJECTS_RW_REF_OPERATORS_EX(Class, DLLFUNC) \
DLLFUNC writer & CALL_DECLARATION operator << ( writer & out, Class & ref ) { return operator << ( out, (const Class &)ref ); }
DLLFUNC writer & CALL_DECLARATION operator << ( writer & out, Class & ref ) { return operator << ( out, static_cast<const Class &>(ref) ); }
#define IMP_KNOWN_OBJECTS_RW_PTR_OPERATORS_EX(Class, DLLFUNC) \
DLLFUNC writer & CALL_DECLARATION operator << ( writer & out, Class * ptr ) { return operator << ( out, (const Class *)ptr ); }
DLLFUNC writer & CALL_DECLARATION operator << ( writer & out, Class * ptr ) { return operator << ( out, static_cast<const Class *>(ptr) ); }
//----------------------------------------------------------------------------------------
+9 -5
View File
@@ -95,9 +95,12 @@
#define MATH_22_HF1_VERSION 0x16000002L ///< \ru Версия файла - 22.0 HF1. \en The file version - 22.0 HF1. \~ \ingroup Base_Tools
#define MATH_22_HF2_VERSION 0x16000003L ///< \ru Версия файла - 22.0 HF2. \en The file version - 22.0 HF2. \~ \ingroup Base_Tools
#define MATH_22_HF3_VERSION 0x16000004L ///< \ru Версия файла - 22.0 HF3. \en The file version - 22.0 HF3. \~ \ingroup Base_Tools
#define MATH_22_HF4_VERSION 0x16000005L ///< \ru Версия файла - 22.0 HF4. \en The file version - 22.0 HF4. \~ \ingroup Base_Tools
#define MATH_22_HF5_VERSION 0x16000006L ///< \ru Версия файла - 22.0 HF5. \en The file version - 22.0 HF5. \~ \ingroup Base_Tools
#define MATH_22_UHF_VERSION 0x16000011L ///< \ru Версия файла - 22.0 UHF (Upper Hot Fix). \en The file version - 22.0 UHF (Upper Hot Fix). \~ \ingroup Base_Tools
#define C3D_2023_VERSION 0x16001001L ///< \ru Версия файла - C3D 2023. \en The file version - C3D 2023. \~ \ingroup Base_Tools
#define MATH_23_VERSION 0x17000001L ///< \ru Версия файла - 23.0. \en The file version - 23.0. \~ \ingroup Base_Tools
#define MATH_23_UHF_VERSION 0x17000101L ///< \ru Версия файла - 23.0 UHF (Upper Hot Fix). \en The file version - 23.0 UHF (Upper Hot Fix). \~ \ingroup Base_Tools
//------------------------------------------------------------------------------
/// \ru Является ли версия файла 16-битной. \en Whether there is a 16-bit file version. \~ \ingroup Base_Tools
@@ -151,9 +154,10 @@ enum MbeWritableReleaseVersion
wrv_C3D_2022 = C3D_2022_VERSION, ///< \ru Версия файла - C3D 2022. \en The file version - C3D 2022.
wrv_MATH_22 = MATH_22_VERSION, ///< \ru Версия файла - 22.0. \en The file version - 22.0.
wrv_C3D_2023 = C3D_2023_VERSION, ///< \ru Версия файла - C3D 2023. \en The file version - C3D 2023.
wrv_MATH_23 = MATH_23_VERSION, ///< \ru Версия файла - 23.0. \en The file version - 23.0.
wrv_PrevRelease = wrv_MATH_22, ///< \ru Версия потока предпоследнего релиза. \en The previous release version.
wrv_LastRelease = wrv_C3D_2023, ///< \ru Версия потока последнего релиза. \en The last release version.
wrv_PrevRelease = wrv_C3D_2023, ///< \ru Версия потока предпоследнего релиза. \en The previous release version.
wrv_LastRelease = wrv_MATH_23, ///< \ru Версия потока последнего релиза. \en The last release version.
wrv_MaxPossible = SYS_MAX_INT32 ///< \ru Использовать последнюю версия потока. \en Use current working version.
};
@@ -162,7 +166,7 @@ enum MbeWritableReleaseVersion
/// \ru Версия потока предпоследнего релиза. \en The previous release version. \~ \ingroup Base_Tools
// ---
inline VERSION GetPrevReleaseMathFileVersion() {
return (VERSION)wrv_PrevRelease;
return static_cast<VERSION>( wrv_PrevRelease );
}
@@ -170,7 +174,7 @@ inline VERSION GetPrevReleaseMathFileVersion() {
/// \ru Версия потока последнего релиза. \en The last release version. \~ \ingroup Base_Tools
// ---
inline VERSION GetLastReleaseMathFileVersion() {
return (VERSION)wrv_LastRelease;
return static_cast<VERSION>( wrv_LastRelease );
}
+1 -1
View File
@@ -473,7 +473,7 @@ public :
*/
// ---
inline double MbCartPoint3D::DistanceToPoint2( const MbCartPoint3D & to ) const {
double coordDiff[3] = { ( x - to.x ), ( y - to.y ), ( z - to.z ) };
double coordDiff[3] = { ( x - to.x ), ( y - to.y ), ( z - to.z ) }; // SKIP_SA
coordDiff[0] *= coordDiff[0];
coordDiff[1] *= coordDiff[1];
coordDiff[2] *= coordDiff[2];
+18 -4
View File
@@ -19,7 +19,7 @@
#include <vector>
constexpr size_t CUBE_CONTROL_POINTS_COUNT = 26; ///< \ru Количество характерных точек куба. \en The number of control points of thebounding box.
constexpr size_t CUBE_CONTROL_POINTS_COUNT = 26; ///< \ru Количество характерных точек куба. \en The number of control points of the bounding box.
constexpr size_t CUBE_VERTEX_COUNT = 8; ///< \ru Количество вершин куба. \en The number of the bounding box vertices.
constexpr size_t CUBE_EDGES_COUNT = 12; ///< \ru Количество рёбер куба. \en The number of the bounding box edges.
constexpr size_t CUBE_FACES_COUNT = 6; ///< \ru Количество граней куба. \en The number of the bounding box faces.
@@ -55,7 +55,7 @@ typedef MbCubeTree<MbCube, MbCube, MbCartPoint3D, MbVector3D> CubesTree;
\en The bounding box. \~
\details \ru Габаритный параллелепипед - это область 3D-пространства, ограниченная
прямым параллелепипедом, грани которого параллельным плоскостям системы координат.\n
Используется для быстрой оценки близости или непересечения трёхмерных объектов,
Используется для быстрой оценки близости или не пересечения трёхмерных объектов,
содержащихся в параллелепипеде. Габаритный параллелепипед описывается парой точек,
расположенных на главной диагонали куба.
\en The bounding box is a domain (block) of 3D-space bounded by parallelepiped
@@ -195,6 +195,20 @@ public :
\en A rectangle covering a required projection. \~
*/
void ProjectionRect( const MbPlacement3D & place, MbRect & rect ) const;
/**
\brief \ru Проекция на плейсмент вдоль вектора в любом из двух направлений.
\en A projection onto the placement along a vector in either of two directions. \~
\details \ru Вычисляет прямоугольник, охватывающий проекцию куба на плейсмент вдоль вектора в любом из двух направлений.
\en Calculates a rectangle covering a projection of the box onto the placement along a vector in either of two directions. \~
\param[in] place - \ru Локальная система координат.
\en A local coordinate system. \~
\param[in] dir - \ru Вектор направления.
\en A direction vector. \~
\param[out] rect - \ru Прямоугольник, охватывающий искомую проекцию.
\en A rectangle covering a required projection. \~
*/
void ProjectionRect( const MbPlacement3D & place, const MbVector3D & dir, MbRect & rect ) const;
/// \ru Вычислить параметрический интервал кривой, охватывающий проекцию куба на кривую. \en Calculate a parametric interval of the curve covering the projection of the box on the curve.
void ProjectionRect( const MbCurve3D & curve, bool ext, MbRect1D & rect ) const;
@@ -407,7 +421,7 @@ public :
/// \ru Дать размер диагонали куба. \en Give the size of box diagonal.
double GetDiagonal() const;
/** \brief \ru Вычислить расстояние до ближайшей грани габаритного суба.
/** \brief \ru Вычислить расстояние до ближайшей грани габаритного куба.
\en Calculate the distance to the nearest boundary of the bounding box. \~
\details \ru Найденное расстояние до ближайшей границы имеет отрицательное значение, если точка находится внутри, и положительное - если снаружи.
\en The calculated distance is negative if the point is inside, and is positive if it is outside. \~
@@ -423,7 +437,7 @@ public :
/** \brief \ru Вычислить расстояние до куба.
\en Calculate the distance to the box. \~
\details \ru Возвращается ноль, если кубы пересекаются или один содержится в другом.
\en It returns zero if the boexs intersect or one is contained in the other. \~
\en It returns zero if the boxes intersect or one is contained in the other. \~
\param[in] cube - \ru Другой куб.
\en Other cube. \~
\param[in] eps - \ru Метрическая точность.
+2 -2
View File
@@ -158,7 +158,7 @@ private:
MbCubeTree( const MbCubeTree & ); // не реализовано / not implemented
MbCubeTree & operator = ( const MbCubeTree & ); // не реализовано / not implemented
public:
/// \ru Деструктор. \en Destuctror.
/// \ru Деструктор. \en Destructor.
~MbCubeTree();
public:
@@ -281,7 +281,7 @@ public:
/// \ru Выдать индекс объекта дерева, ближайшего к точке, и квадрат расстояния до него. \en Get tree objects index that are closest to the point, and squared distance to object.
double FindNearestObject ( const Point & pnt, const MbTreeDistanceToElementBase<Point> & calc, size_t & index ) const;
/// \ru Выдать набор индексов объектов дерева, которые хотя бы частично лежат внутри заданной сферы. \en Get an array of tree object indices at least partially lying inside a given sphere.
void FindObjectsInsideSphere( const Point & pnt, double radius, const MbTreeDistanceToElementBase<Point> & calc, c3d::IndicesVector & indices ) const;
void FindObjectsInsideSphere( const Point & pnt, double radius, const MbTreeDistanceToElementBase<Point> & calc, c3d::IndicesVector & indices ) const;
private:
// функции инициализация и заполнение ветвей дерева / internal functions for initialization, filling branches
+3 -3
View File
@@ -192,7 +192,7 @@ private:
bool exact; ///< \ru Выполнить построение полигональных объектов на числах double (true) на числах float (false). \en Polygonal objects will created on double data (true) on float data (false).
bool wire; ///< \ru Строить изолинии поверхностей. \en Construct isolines of surfaces. \~
bool grid; ///< \ru Строить триангуляцию поверхностей. \en Construct triangulations of surfaces. \~
bool seam; ///< \ru Дублировать точки триангуляции на швах (true) замкнутых поверхностей, не дублировать точки триангуляции на швах (false). \en Flag for not ignore the seam edges. \~
bool seam; ///< \ru Дублировать точки триангуляции на швах замкнутых поверхностей. \en Duplicate triangulation points at the seams of closed surfaces. \~
bool quad; ///< \ru Строить четырёхугольники (true) при триангуляции поверхностей (по возможности). \en Build quadrangles (true) in triangulations of surfaces (if possible). \~
bool fair; ///< \ru Удалить вырожденные треугольники (true). \en Degenerate triangles removing (if surface has pole). \~
bool mere; ///< \ru Использовать специальный алгоритм для плоской поверхности (true). \en Use a special algorithm for a flat surface. \~
@@ -239,7 +239,7 @@ public:
void SetWire( bool w ) { wire = w; }
/// \ru Установить флаг строить триангуляцию поверхностей. \en Set flag constructing triangulations of surfaces. \~
void SetGrid( bool g ) { grid = g; }
/// \ru Установить флаг шовных ребер. \en Set flag for seam edges. \~
/// \ru Установить флаг дублирования точек триангуляции на швах замкнутых поверхностей. \en Set the flag for duplicating triangulation points at the seams of closed surfaces. \~
void SetSeam( bool s ) { seam = s; }
/// \ru Установить флаг строить четырёхугольники при триангуляции поверхностей (по возможности).. \en Set flag for build quadrangles in triangulations of surfaces (if possible). \~
void SetQuad( bool q ) { quad = q; }
@@ -254,7 +254,7 @@ public:
bool Wire() const { return wire;}
/// \ru Строить триангуляцию поверхностей? \en Whether to construct triangulations of surfaces? \~
bool Grid() const { return grid; }
/// \ru Дублировать точки триангуляции на швах? \en Get flag for seam edges. \~
/// \ru Дублировать точки триангуляции на швах замкнутых поверхностей? \en Whether to duplicate triangulation points at the seams of closed surfaces? \~
bool Seam() const { return seam; }
/// \ru Строить четырёхугольники при триангуляции поверхностей (по возможности).? \en Whether to build quadrangles in triangulations of surfaces (if possible)? \~
bool Quad() const { return quad; }
+20 -8
View File
@@ -730,9 +730,11 @@ ptrdiff_t KnotIndex( size_t degree, const KnotsVector & knots, double & t )
size_t low = degree - 1;
size_t high = knots.size() - degree;
ptrdiff_t mid = low;
double knot_low = knots[low];
double knot_high = knots[high];
if ( t <= knots[low] ) {
t = knots[low];
if ( t <= knot_low ) {
t = knot_low;
size_t countKnt = knots.size();
size_t lowP = low;
lowP++;
@@ -743,19 +745,29 @@ ptrdiff_t KnotIndex( size_t degree, const KnotsVector & knots, double & t )
}
mid = low;
}
else if ( t >= knots[high] ) {
t = knots[high];
else if ( t >= knot_high ) {
t = knot_high;
// BUG_82980 while ( (high > 0) && (knots[high] == t) ) {
while ( (high + 1 > degree) && (knots[high] == t) ) {
high--;
}
mid = high;
}
else if ( c3d::ArFind(knots, t, mid) ) {
while ( knots[mid] == t ) {
mid++;
else {
// \ru Поиск выполнятеся быстрее, если значение индекса близко к искомому.
// \en The search perform faster if the index value close to the one looking for.
size_t count = high - low;
if ( count > c3d::LIMIT_COUNT ) {
double average = ( knot_high - knot_low ) / count;
if ( average > NULL_EPSILON )
mid = (ptrdiff_t)( (t - knot_low) / average );
}
if ( c3d::ArFind(knots, t, mid) ) {
while ( knots[mid] == t ) {
mid++;
}
mid--;
}
mid--;
}
return mid;
}
+1 -1
View File
@@ -31,7 +31,7 @@ enum MbeLocalSystemType {
\en Local coordinate system in two dimensional space. \~
\details \ru Локальная система координат в двумерном пространстве. \n
В большинстве случаев система координат (СК) является правой, а векторы системы ортонормированы.
С помощью преобразований система координат может стать левой и не ортонормированнной.
С помощью преобразований система координат может стать левой и не ортонормированной.
Локальная система координат является декартовой,
Точка в декартовой системе координат определяется двумя координатами x, y.
\en Local coordinate system in two dimensional space. \n
+15 -7
View File
@@ -45,7 +45,7 @@ enum MbeLocalSystemType3D
//------------------------------------------------------------------------------
/** \brief \ru Локальная система координат в трёхмерном пространстве.
/** \brief \ru Локальная система координат (ЛСК) в трёхмерном пространстве.
\en Local coordinate system in three dimensional space. \~
\details \ru Локальная система координат в трёхмерном пространстве. \n
В большинстве случаев система координат является правой, а векторы системы ортонормированы.
@@ -76,13 +76,13 @@ enum MbeLocalSystemType3D
Для ускорения преобразования координат локальная система имеет дополнительные данные - флаг состояния.\n
Для получения данных системы координат извне следует пользоваться методами Get...\n
Для модификации данных системы координат извне следует пользоваться методами Set..., которые автоматически сбрасывают флаг системы в неустановленное состояние.\n
\en Local coordinate system in three dimensional space. \n
\en Local coordinate system (LCS) in three dimensional space. \n
Local coordinate system is described by the initial point and three non-parallel vectors.
In most cases the system of coordinates is right, and vectors of system are orthonormalized.
A coordinate system can become left and not orthonormalized via transformations.
Local coordinate system is Cartesian.
A point is defined by three coordinates x, y, z in the Cartesian coordinate system.\n
A local coordinate system may act both as a cylindrical or a sphricial coordinate system.\n
A local coordinate system may act both as a cylindrical or a spherical coordinate system.\n
A point in a cylindrical coordinate system is defined by three coordinates r, f, z: \n
r, f - polar coordinates of point projection to the main plane;\n
r - length of radius-vector projection; \n
@@ -151,7 +151,7 @@ public: /** \ru \name Конструкторы.
MbPlacement3D();
/// \ru Конструктор по точке. \en Constructor by point.
explicit MbPlacement3D( const MbCartPoint3D & org );
/// \ru Конструктор двум векторам и точке. \en Constructor by point and two vectors.
/// \ru Конструктор по двум векторам и точке, ортогонализует вектор `Y` и нормализует все оси. \en Constructor for two vectors and a point. It orthogonalizes the `Y` vector and normalizes all axes.
explicit MbPlacement3D( const MbVector3D & axisX, const MbVector3D & axisY, const MbCartPoint3D & org );
/// \ru Конструктор копирования. \en Copy-constructor.
MbPlacement3D( const MbPlacement3D & place );
@@ -194,8 +194,16 @@ public: /** \}
/// \ru Инициализировать по началу. \en Initialize by origin.
MbPlacement3D & Init( const MbCartPoint3D & org );
// \ru Методы инициализации по началу и двум векторам осям \en Methods for initialization by origin and two vectors of axes
/// \ru Инициализировать по точке и двум векторам (оси X, Y). \en Initialize by a point and two vectors (X and Y axes).
MbPlacement3D & InitXY( const MbCartPoint3D & p, const MbVector3D & axisX, const MbVector3D & axisY, bool reset );
/** \brief \ru Инициализировать по точке и осям `X`,`Y`.
\en Initialize by a point and two vectors (`X` and `Y` axes).
\param[in] p - \ru Задает начало ЛСК. \en Specifies the origin of LCS. \~
\param[in] axisX - \ru Задает ось `X` ЛСК. \en Specifies axis `X` of LCS. \~
\param[in] axisY - \ru Задает ось `Y` ЛСК. \en Specifies axis `Y` of LCS. \~
\param[in] setOrtho - \ru Если setOrtho == true, то ось `Y` ортогонализуется к `X`, а ось ЛСК нормализуются.
\en If setOrtho == true, then the `Y` is orthogonalized to `X`, and the LCS axis is normalized. \~
*/
MbPlacement3D & InitXY( const MbCartPoint3D & p, const MbVector3D & axisX, const MbVector3D & axisY, bool setOrtho );
/// \ru Инициализировать по точке и двум векторам (оси X, Z). \en Initialize by a point and two vectors (X and Z axes).
MbPlacement3D & InitXZ( const MbCartPoint3D & p, const MbVector3D & axisX, const MbVector3D & axisZ );
/// \ru Инициализировать по точке и двум векторам (оси Y, Z). \en Initialize by a point and two vectors (Y and Z axes).
@@ -244,7 +252,7 @@ public: /** \}
bool IsOrt() const { return !!(CheckFlag() & MB_ORTOGONAL); }
/// \ru Выдать признак ортогональности СК. \en Get orthogonality property of coordinate system.
bool IsOrthogonal() const { CheckFlag(); return ( !(flag & MB_AFFINE) || !!(flag & MB_ORTOGONAL) ); }
/// \ru Проверить, является ли СК афинной (если нет - то она ортонормированная). \en Check if a coordinate system is affine (otherwise it is orthonormalized).
/// \ru Проверить, является ли СК аффинной (если нет - то она ортонормированная). \en Check if a coordinate system is affine (otherwise it is orthonormalized).
bool IsAffine() const { return !!(CheckFlag() & MB_AFFINE ); }
/// \ru Проверить, что СК ортонормированная. \en Check if coordinate system is orthonormalized.
bool IsNormal() const { return ( !IsAffine() ); }
+269 -28
View File
@@ -22,6 +22,8 @@
#include <curve.h>
#include <curve3d.h>
//#define PMI_RAD_DIAM_USE_CALLOUT_INSTEAD_OF_DIM_PLUS_PROJ_CRV
//----------------------------------------------------------------------------------------
/** \brief \ru Элемент текста объекта аннотации.
\en Reference-counted object. \~
@@ -44,10 +46,24 @@ public:
virtual bool IsSame( const MbTextItem & to, double accuracy ) const = 0;
DECLARE_PERSISTENT_CLASS( MbTextItem );
/// \ru Присутствует ли тэг. \en Wether a tag present.
bool IsTagPresent( const c3d::string_t & tag ) const;
/// \ru Присутствуют ли тэги. \en Wether tags present.
bool IsHasTags( ) const;
/// \ru Добавить тэг, если он не пустой. \en Add a non-empty tag.
void AddTag( const c3d::string_t& tag );
protected:
/// \ru Пользователские тэги, не предназначенные для сериализации. \en User tags not for serialization.
std::vector<c3d::string_t> m_userTags;
/// \ru Конструктор по умолчанию. \en Default constructor.
MbTextItem();
OBVIOUS_PRIVATE_COPY( MbTextItem )
MbTextItem( const MbTextItem & it );
};
@@ -70,6 +86,27 @@ enum class MbeTextLiteralForm
};
#ifdef PMI_RAD_DIAM_USE_CALLOUT_INSTEAD_OF_DIM_PLUS_PROJ_CRV
//----------------------------------------------------------------------------------------
/** \brief \ru Тип кривой аннотации.
dimensionCurve и projectionCurve используются совместно для линейных и диаметральных размеров,
для всех остальных аннотаций используется callout, в том числе для диаметрального размера,
изображенного с помощью одной кривой типа callout с двумя терминаторами.
callout содержит 0/1/2 терминатора, dimensionCurve - 1/2, projectionCurve - 0.
callout и projectionCurve ссылаются на геометрический объект, dimensionCurve - нет.
\en Type of curve with terminators. \~
\ingroup Legend
*/
// ---
enum class MbeCalloutCurveType
{
callout = 0, ///< \ru Кривая-выноска, связанная с характеризуемым геометрическим объектом. \en Callout.
dimensionCurve = 1, ///< \ru Размерная кривая, связанная с проекционной кривой. \en Dimension curve.
projectionCurve = 2 ///< \ru Проекционная кривая размера, связанная с характеризуемым геометрическим объектом, не содержит терминаторы. \en Projection curve.
};
#else
//----------------------------------------------------------------------------------------
/** \brief \ru Тип кривой с терминаторами.
\en Type of curve with terminators. \~
@@ -77,12 +114,13 @@ enum class MbeTextLiteralForm
*/
// ---
enum class MbeCalloutCurveType
{
{
callout = 0, ///< \ru Кривая-выноска. \en Callout.
dimensionCurve = 1, ///< \ru Размерная кривая. \en Dimension curve.
projectionCurve = 2 ///< \ru Кривая к характеризуемому объекту. \en Projection curve.
dimensionCurve = 1, ///< \ru Размерная кривая. \en Dimension curve.
projectionCurve = 2 ///< \ru Кривая к характеризуемому объекту. \en Projection curve.
};
#endif // PMI_RAD_DIAM_USE_CALLOUT_INSTEAD_OF_DIM_PLUS_PROJ_CRV
//----------------------------------------------------------------------------------------
/** \brief \ru Тип численной характеристики.
@@ -256,6 +294,11 @@ class MATH_CLASS MbValueRange final : public TapeBase {
bool m_nominalDefined; ///< \ru Признак, определён ли номинал. \en Flag if the value is defined.
bool m_rangeDefined; ///< \ru Признак, определён ли диапазон. \en Flag if the range is defined.
public:
/** \brief \ru Конструктор по умолчанию.
\en Default constructor. \~
*/
MbValueRange();
/** \brief \ru Конструктор.
\en Constructor. \~
\param[in] valie - \ru Номинал.
@@ -283,9 +326,6 @@ public:
*/
MbValueRange( double value, double lower, double upper );
/// \ru Конструктор по умолчанию удалён. \en Default constructor obviously deleted.
MbValueRange() = delete;
/// \ru Конструктор копирования реализован по умолчанию. \en Copy constructor has default implementation.
MbValueRange( const MbValueRange & ) = default;
@@ -375,7 +415,7 @@ class MATH_CLASS MbTerminator final : public MbRefItem, public TapeBase
\param[in] sizeY - \ru Размер терминатора по координате y расположения.
\en Size of the terminator in the y direction of the location.. \~
*/
MbTerminator( const MbPlacement & location, const c3d::string_t & type, double sizeX, double sizeY );
MbTerminator( const MbPlacement & location, const c3d::string_t & type, const double sizeX, const double sizeY );
public:
/** \brief \ru Создать терминатор.
\en Create terminator. \~
@@ -390,7 +430,7 @@ public:
\return \ru Экземпляр терминатора, если строка типа не пуста и размеры больше Math::lengthEpsilon, иначе нулевой указатель.
\en Instance of terminator, if the type string not empty and sizses greater than Math::lengthEpsilon, otherwise null pointer. \~
*/
static SPtr<MbTerminator> Create( const MbPlacement & location, const c3d::string_t & type, double sizeX, double sizeY );
static SPtr<MbTerminator> Create( const MbPlacement & location, const c3d::string_t & type, const double sizeX, const double sizeY );
/// \ru Получить положение терминатора. \en Get terminator's location.
MbPlacement GetLocation() const;
@@ -413,6 +453,9 @@ public:
/// \ru Создать копию объекта. \en Create a copy of an object.
SPtr<MbTerminator> Clone() const;
// Посчитать сетку для терминатора
static void CalculateMeshPmiTerminator( MbMesh & mesh, const MbPlacement3D & location, const double sizeX, const double sizeY, const bool isSameDir = false );
DECLARE_PERSISTENT_CLASS( MbTerminator )
};
@@ -420,7 +463,7 @@ IMPL_PERSISTENT_OPS( MbTerminator )
//----------------------------------------------------------------------------------------
/** \brief \ru Кривая к терминаторами.
/** \brief \ru Кривая с терминаторами.
\en Curve with terminators. \~
\details \ru Может быть связана с характеризуемым объектом. \n
\en Can have reference to the characterized object. \n\~
@@ -431,7 +474,7 @@ class MATH_CLASS MbCalloutCurve final : public MbRefItem, public TapeBase
{
SPtr<MbCurve> m_curve; ///< \ru Кривая-выноска. \en Callout curve.
std::vector<SPtr<MbTerminator>> m_terminators; ///< \ru Терминаторы. \en Termniators.
SPtr<MbTopologyItem> m_characterizedObject; ///< \ru Характеризуемый объект. \en Charactrrized object.
SPtr<MbTopologyItem> m_characterizedObject; ///< \ru Характеризуемый объект. \en Characterized object.
MbeCalloutCurveType m_curveType; ///< \ru Вид кривой. \en Callout type.
public:
@@ -469,6 +512,20 @@ public:
*/
SPtr<MbTerminator> GetTerminator( size_t index ) const;
/** \brief \ru Получить характеризуемые объект.
\en Get characterized object. \~
\return \ru Характеризуемый объект.
\en Characterized object. \~
*/
SPtr<MbTopologyItem> GetCharacterizedObject() const { return m_characterizedObject; }
/** \brief \ru Задать характеризуемые объект.
\en Set characterized object. \~
\return \ru Характеризуемый объект.
\en Characterized object. \~
*/
void SetCharacterizedObject( SPtr<MbTopologyItem> obj );
/** \brief \ru Получить вид кривой-выноски.
\en Get type of callout curve. \~
\return \ru Вид кривой-выноски.
@@ -476,6 +533,11 @@ public:
*/
MbeCalloutCurveType GetCurveType() const;
#ifdef PMI_RAD_DIAM_USE_CALLOUT_INSTEAD_OF_DIM_PLUS_PROJ_CRV
bool ChangeDimensionCurveTypeToCallout();
#endif // PMI_RAD_DIAM_USE_CALLOUT_INSTEAD_OF_DIM_PLUS_PROJ_CRV
/// \ru Создать копию объекта. \en Create a copy of an object.
SPtr<MbCalloutCurve> Clone( MbRegDuplicate * = nullptr ) const;
@@ -539,12 +601,8 @@ public:
\en Numerical values, \~
\param[in] callouts - \ru Линии-выноски.
\en Callout lines. \~
\return \ru Численное значение линейного размера с объектами привязки.
\en Numerical value of a linear dimension with bind objects. \~
\note \ru В контейнере выносных линий обязательно должна присутствовать размерная линия. Количество проекционных линий:
- В случае линейного, углового или диаметрального размера размера две или ни одной.
- В случае радиального размера ни одной.
\en . \~
\return \ru Численное значение шероховатости поверхности.
\en Numerical value of surface condition. \~
*/
static SPtr<MbNumericalCharacteristic> CreateSurfaceRoughness( MbValueRange && rangeValue, std::vector<SPtr<MbCalloutCurve>> && callouts );
@@ -555,12 +613,8 @@ public:
\en Numerical values, \~
\param[in] callouts - \ru Линии-выноски.
\en Callout lines. \~
\return \ru Численное значение линейного размера с объектами привязки.
\en Numerical value of a linear dimension with bind objects. \~
\note \ru В контейнере выносных линий обязательно должна присутствовать размерная линия. Количество проекционных линий:
- В случае линейного, углового или диаметрального размера размера две или ни одной.
- В случае радиального размера ни одной.
\en . \~
\return \ru Численное значение линейного допуска формы.
\en Numerical value of shape tolerance. \~
*/
static SPtr<MbNumericalCharacteristic> CreateShapeTolerance( MbValueRange && rangeValue, std::vector<SPtr<MbCalloutCurve>> && callouts );
@@ -584,9 +638,26 @@ public:
/// \ru Опредлен ли диапазон. \en Whether the range is defined.
bool IsRangeDefined( double & lower, double & upper ) const;
/// \ru Получить количество выносных линий. \en Get the number of callout curves.
size_t GetDecoratedCurvesCount() const;
SPtr<MbCalloutCurve> GetDecoratedCurve( size_t index ) const;
/// \ru Получить выносную линию по индексу. \en Get the callout curve by index.
SPtr<MbCalloutCurve> GetDecoratedCurve( const size_t index ) const;
/// \ru Получить характеризуемый объект выносной линии по индексу выносной линии. \en Get the characterized object of the callout curve by curve's index.
SPtr<MbTopologyItem> GetCalloutCharacterizedObject( const size_t index ) const;
/// \ru Получить геометрические объекты привязки. \en
void GetCalloutCharacterizedObjects( std::vector<SPtr<MbTopologyItem>> & aTopo ) const;
/// \ru Получить выносные линии размера, пристыкованные к геометрии. \en
void GetCalloutCurvesProjectionCurves( std::vector<SPtr<MbCalloutCurve>> & aCrv ) const;
/// \ru Получить размерную линию размера, имеющую стыковку с выносными линиями. \en
SPtr<MbCalloutCurve> GetCalloutCurvesDimensionCurve() const;
/// \ru Получить обычные выносные линии аннотации. \en
void GetCalloutCurvesGeneral( std::vector<SPtr<MbCalloutCurve>> & aCrv ) const;
/// \ru Являются ли объекты равными. \en Are the objects equal.
bool IsSame( const MbNumericalCharacteristic & to, double accuracy ) const;
@@ -672,7 +743,7 @@ public:
const c3d::ItemsSPtrVector & pmiVisual = c3d::ItemsSPtrVector(),
const std::vector<SPtr<MbTextItem>> & pmiText = std::vector<SPtr<MbTextItem>>() );
/** \brief \ru Создать элемент вида "Технические требования".
/** \brief \ru Создать элемент аннотации вида "Технические требования".
\en Create annotation item of the "Tehcnical requirements" type. \~
\param[in] plane - \ru Плоскость для отображения плоских элементов,
\en Plane for planar elements transformation into space, \~
@@ -692,8 +763,67 @@ public:
const c3d::ItemsSPtrVector & pmiVisual = c3d::ItemsSPtrVector(),
const std::vector<SPtr<MbTextItem>> & pmiText = std::vector<SPtr<MbTextItem>>() );
/** \brief \ru Создать элемент вида "Технические требования".
\en Create annotation item of the "Tehcnical requirements" type. \~
/** \brief \ru Создать элемент аннотации вида шероховатость поверхности.
\en Create annotation item of the surface condition type. \~
\param[in] rangeValue - \ru Численные значения,
\en Numerical values, \~
\param[in] callouts - \ru Линии-выноски.
\en Callout lines. \~
\return \ru Численное значение линейного размера с объектами привязки.
\en Numerical value of a linear dimension with bind objects. \~
\param[in] plane - \ru Плоскость для отображения плоских элементов,
\en Plane for planar elements transformation into space, \~
\param[in] pmiName - \ru Название элемента аннотации,
\en Captrion of the annotation element, \~
\param[in] pmiVisual - \ru Геометрические компоненты элемента аннотации,
\en Geometric items ot the annotation element, \~
\param[in] pmiText \ru Текстовые компоненты элемента аннотации.
\en Text items ot the annotation element. \~
\return \ru Возвращает указатель на элемент аннотации, если передаётся хотя бы один
ненулевой текстовый или геометрический элемент, иначе нулевой указатель.
\en Returns pointer to new annotation element if only at least one text or geometric
element is given, otherwise null pointer. \~
\en . \~
*/
static SPtr<MbPMI> CreateSurfaceRoughness( MbValueRange && rangeValue,
std::vector<SPtr<MbCalloutCurve>> && callouts,
const MbPlacement3D & plane = MbPlacement3D::global,
const c3d::string_t & pmiName = c3d::string_t(),
const c3d::ItemsSPtrVector & pmiVisual = c3d::ItemsSPtrVector(),
const std::vector<SPtr<MbTextItem>> & pmiText = std::vector<SPtr<MbTextItem>>() );
/** \brief \ru Создать элемент аннотации вида допуск формы.
\en Create annotation item of the shape tolerance type. \~
\param[in] rangeValue - \ru Численные значения,
\en Numerical values, \~
\param[in] callouts - \ru Линии-выноски.
\en Callout lines. \~
\return \ru Численное значение линейного размера с объектами привязки.
\en Numerical value of a linear dimension with bind objects. \~
\param[in] plane - \ru Плоскость для отображения плоских элементов,
\en Plane for planar elements transformation into space, \~
\param[in] pmiName - \ru Название элемента аннотации,
\en Captrion of the annotation element, \~
\param[in] pmiVisual - \ru Геометрические компоненты элемента аннотации,
\en Geometric items ot the annotation element, \~
\param[in] pmiText \ru Текстовые компоненты элемента аннотации.
\en Text items ot the annotation element. \~
\return \ru Возвращает указатель на элемент аннотации, если передаётся хотя бы один
ненулевой текстовый или геометрический элемент, иначе нулевой указатель.
\en Returns pointer to new annotation element if only at least one text or geometric
element is given, otherwise null pointer. \~
\en . \~
*/
static SPtr<MbPMI> CreateShapeTolerance( MbValueRange && rangeValue,
std::vector<SPtr<MbCalloutCurve>> && callouts,
const MbPlacement3D & plane = MbPlacement3D::global,
const c3d::string_t & pmiName = c3d::string_t(),
const c3d::ItemsSPtrVector & pmiVisual = c3d::ItemsSPtrVector(),
const std::vector<SPtr<MbTextItem>> & pmiText = std::vector<SPtr<MbTextItem>>() );
/** \brief \ru Создать элемент аннотации вида численная характеристика.
\en Create annotation item of the "Numerical Characteristic" type. \~
\param[in] numericalCharacteristics - \ru Численная характеристика,
\en Numerical characteristics, \~
\param[in] plane - \ru Плоскость для отображения плоских элементов,
@@ -741,8 +871,77 @@ public:
const c3d::ItemsSPtrVector & pmiVisual = c3d::ItemsSPtrVector(),
const std::vector<SPtr<MbTextItem>> & pmiText = std::vector<SPtr<MbTextItem>>() );
/** \brief \ru Создать выносные линии размера:
одна размерная кривая типа MbeCalloutCurveType::dimensionCurve
и две проекционных кривых типа MbeCalloutCurveType::projectionCurve.
\en Create callout curves:
one dimension curve of type MbeCalloutCurveType::dimensionCurve
and two projection curves of type MbeCalloutCurveType::projectionCurve. \~
\param[inout] addTo - \ru Хранилище выносных линий,
\en Callout lines storage, \~
\param[in] dimLocation - \ru Плоскость для отображения плоских элементов,
\en Plane for planar elements transformation into space, \~
\param[in] dimCurve - \ru Кривая для построения размерной выносной линии,
\en Curves for creation dimension callout curves, \~
\param[in] projectionCurves - \ru Кривые для построения проекционных выносных линий,
\en Curves for creation projection callout curves, \~
\param[in] projectionCurvesObj - \ru Характеризуемые объекты топологии, на которые ссылаются проекционные кривые,
\en Characterized topology objects referenced by projection curves, \~
\param[in] dimCurveTerminators - \ru Терминаторы размерной кривой.
\en Dimension curve terminators. \~
\return \ru Возвращает true в случае корректного создания выносных линий.
\en Returns true if callout curves are created correctly. \~
*/
static bool CreateDimensionCalloutCurves( std::vector<SPtr<MbCalloutCurve>> & addTo,
const MbPlacement3D dimLocation,
const MbCurve3D * dimCurve,
const std::vector<MbCurve3D *> & projectionCurves,
const std::vector < SPtr<MbTopologyItem>> & projectionCurvesObj,
const std::vector<SPtr<MbTerminator>> & dimCurveTerminators = std::vector<SPtr<MbTerminator>>() );
/** \brief \ru Создать выносную линию типа MbeCalloutCurveType::callout.
\en Create callout curve of type MbeCalloutCurveType::callout. \~
\param[inout] addTo - \ru Хранилище выносных линий,
\en Callout lines storage, \~
\param[in] location - \ru Плоскость для отображения плоских элементов,
\en Plane for planar elements transformation into space, \~
\param[in] calloutCurve - \ru Кривая для построения выносной линии,
\en Curves for creation callout curves, \~
\param[in] obj - \ru Характеризуемый объект топологии,
\en Characterized topology object, \~
\param[in] terminators - \ru Терминаторы выносной линии.
\en Callout curve terminators. \~
\return \ru Возвращает true в случае корректного создания выносной линии.
\en Returns true if callout curve is created correctly. \~
*/
static bool CreateGeneralCalloutCurve( std::vector<SPtr<MbCalloutCurve>> & addTo,
const MbPlacement3D location,
const MbCurve3D * calloutCurve,
const SPtr<MbTopologyItem> & obj,
const std::vector<SPtr<MbTerminator>> & terminators = std::vector<SPtr<MbTerminator>>() );
/** \brief \ru Создать терминатор выносной линии.
\en Create terminator of callouc curve. \~
\param[in] pmiLocation - \ru Плоскость для отображения плоских элементов,
\en Plane for planar elements transformation into space, \~
\param[in] dimensionCurve - \ru Кривая выносной линии,
\en Callout curve, \~
\param[in] type - \ru Тип терминатора,
\en Termitanor type, \~
\param[in] parameterOnCurve - \ru Значение параметра на размерной кривой. Если не указан, должен быть равен UNDEFINED_DBL,
\en Parameter value on the dimensional curve. If not known, must be equal UNDEFINED_DBL, \~
\param[in] sizeX - \ru Размер терминатора по координате x расположения,
\en Size of the terminator in the x direction of the location, \~
\param[in] sizeY - \ru Размер терминатора по координате y расположения,
\en Size of the terminator in the y direction of the location, \~
\param[in] sameDirection - \ru Признак сонаправленности с касательной к кривой в точке размещения.
В случае неопределённого значения параметра - признак направленности внутрь.
\en Flag of the same direction with the tangent to the curve at the location point.
In case parameter id undefined it shows if the arrow's direction is inner. \~
*/
static SPtr<MbTerminator> CreateTerminator( const MbPlacement3D & pmiLocation, const MbCurve3D & dimensionCurve, const c3d::string_t & type, double parameterOnCurve,
const double sizeX, const double sizeY, const bool sameDirection );
protected:
/** \brief \ru Конструктор.
\en Constructor. \~
@@ -772,10 +971,15 @@ public:
/// \ru Получить плоскость для отображения плоских элементов. \en Get plane for planar elements transformation into space.
MbPlacement3D GetLocation() const;
/// \ru Задать плоскость для отображения плоских элементов. \en Set plane for planar elements transformation into space.
void SetLocation( const MbPlacement3D & loc );
/// \ru Получить название элемента аннотации. \en Get captrion of the annotation element.
c3d::string_t GetTitle() const;
/// \ru Задать название элемента аннотации. \en Set captrion of the annotation element.
void SetTitle( const c3d::string_t & t );
/// \ru Получить количество геометрических элементов. \en Get count of geometric items.
size_t GeometricElementsCount() const;
@@ -788,6 +992,9 @@ public:
*/
c3d::ItemSPtr GetGeometricElement( size_t elementIndex ) const;
/// \ru Добавить геометрические элементы. \en Add geometric items.
void AddGeometricElements( const c3d::ItemsSPtrVector & elems );
/// \ru Получить количество текстовых элементов. \en Get count of text items.
size_t TextElementsCount() const;
@@ -800,8 +1007,26 @@ public:
*/
SPtr<MbTextItem> GetTextElement( size_t elementIndex ) const;
/// \ru Задать текстовые элементы. \en Reset text items.
void ResetTextElemets( const std::vector<SPtr<MbTextItem>> & texts );
/// \ru Получить текстовые элементы. \en Reset text items.
void GetTextElements( std::vector<SPtr<MbTextItem>> & texts );
/// \ru Задать численную характеристику. \en Set numerical characteristics.
void SetNumericalCharacteristics( SRef<MbNumericalCharacteristic> numericahCharacteristics );
/// \ru Получить численную характеристику. \en Get numerical characteristics.
SPtr<MbNumericalCharacteristic> GetNumericalCharacteristics() const;
/// \ru Заданы ли численные значения. \en Is numeric values defined.
bool IsValueOrRangeDefined() const;
/// \ru Это размер. \en Is it dimension.
const bool IsDimension() const;
/// \ru Преобразовать в элемент Технические Требования, если это возможно. \en Convert to Technical Requirements element if it is possible.
bool ConvertToTechnicalRequirements();
MbeSpaceType IsA () const final; // \ru Тип объекта. \en A type of an object.
MbeSpaceType Type () const final; // \ru Групповой тип объекта. \en Group type of object.
@@ -829,4 +1054,20 @@ private:
IMPL_PERSISTENT_OPS( MbPMI )
/** \brief \ru Контейнер текстовых блоков.
\en Container of text blocks. \~
\ingroup Exchange_Base
*/
typedef std::vector< SPtr<MbTextItem> > vector_of_mbtext;
typedef SPtr<MbPMI> PmiSPtr;
/** \brief \ru Контейнер объектов аннотации.
\en Container of annotation objects. \~
\ingroup Exchange_Base
*/
typedef std::vector<PmiSPtr> vector_of_pmi;
typedef std::vector<PmiSPtr> PmiSptrVector;
#endif /* __MB_PMI_H */
+1
View File
@@ -1154,6 +1154,7 @@ enum MbePrompt
IDS_PROP_0892, ///< \ru Диффузное отражение (компонент green). \en Diffuse reflection (green component).
IDS_PROP_0893, ///< \ru Диффузное отражение (компонент blue). \en Diffuse reflection (blue component).
IDS_PROP_0894, ///< \ru Диффузное отражение (компонент alpha). \en Diffuse reflection (alpha component).
IDS_PROP_0895, ///< \ru Зеркальное отражение объекта. \en Specular reflection for an object.
IDS_PROP_0900, ///< \ru Сопряжение в точке. \en Conjugation at point.
IDS_PROP_0901, ///< \ru Тип сопряжения. \en Conjugation type.
+12 -5
View File
@@ -21,7 +21,7 @@
\{ */
constexpr double MB_INFINITY = std::numeric_limits<double>::infinity(); ///< \ru Значение, обозначающее бесконечность для double. \en Value representing infinity for double.
constexpr double MB_QNAN = std::numeric_limits<double>::quiet_NaN(); ///< \ru "Тихое" нечисло. \en Quiet Not-A-Number.
constexpr double MB_QNAN = std::numeric_limits<double>::quiet_NaN(); ///< \ru "Тихое" не число. \en Quiet Not-A-Number.
constexpr double MB_MAXDOUBLE = 1.0E+300; ///< \ru Максимальное значение double 1.7976931348623158E+308. \en Maximum value of double 1.7976931348623158E+308.
constexpr double MB_MINDOUBLE = 1.0E-300; ///< \ru Минимальное значение double 2.2250738585072014E-308. \en Minimum value of double 2.2250738585072014E-308.
@@ -117,7 +117,7 @@ constexpr double PARAM_ACCURACY = 1E-5; ///< \ru Наибольшая пар
constexpr double PARAM_NEAR = 1E-4; ///< \ru Параметрическая близость. \en Parametric proximity.
constexpr ptrdiff_t UNDEFINED_INT_T = SYS_MIN_ST; ///< \ru Неопределенный int. \en Undefined int.
constexpr size_t FAIR_MAX_DEGREE = 11; ///< \ru Максимальный порядок NURBS при аппроксимации. \en Maxinum degree of the NURBS approximation.
constexpr size_t FAIR_MAX_DEGREE = 11; ///< \ru Максимальный порядок NURBS при аппроксимации. \en Maximum degree of the NURBS approximation.
constexpr double M_PI2 = M_PI * 2.0; ///< \ru Отношение длины окружности к её радиусу, 2.0 * M_PI, 6.28318530717958647692 \en Relation between circle length and its radius, 2.0 * M_PI, 6.28318530717958647692
constexpr double M_DEGRAD = M_PI / 180.0; ///< \ru Коэффициент перевода градусов в радианы. \en Factor of conversion from degrees to radians.
@@ -225,6 +225,13 @@ constexpr float MB_EMISSION = 0.0f; ///< \ru Коэффициент из
constexpr uint32 MB_DEFCOLOR = 0x7F7F7F; ///< \ru Цвет по умолчанию при импорте и экспорте (серый). \en Default color for import and export (grey).
constexpr uint32 MB_C3DCOLOR = 0xFF7F00; ///< \ru Цвет по умолчанию для геометрических объектов. \en Default color for geometric objects.
constexpr uint32 MB_AMBIENT_UINT32 = 0xFF666666; ///< \ru Коэффициент рассеянного освещения (фон). Эквивалент MB_AMBIENT. \en Coefficient of backlighting (equivalent of MB_AMBIENT).
constexpr uint32 MB_SPECULARITY_UINT32 = 0xFFCCCCCC; ///< \ru Коэффициент зеркального отражения (эквивалент MB_SPECULARITY). \en Coefficient of specular reflection (equivalent of MB_SPECULARITY).
constexpr uint32 MB_EMISSION_UINT32 = 0xFF000000; ///< \ru Коэффициент излучения (эквивалент MB_SPECULARITY). \en Emissivity coefficient (equivalent of MB_SPECULARITY).
constexpr uint8 MB_OPACITY_UINT8 = 255; ///< \ru Коэффициент суммарного отражения (коэффициент непрозрачности). Эквивалент MB_OPACITY. \en Coefficient of total reflection (equivalent of MB_OPACITY).
constexpr uint8 MB_SHININESS_UINT8 = 50; ///< \ru Блеск (показатель степени в законе зеркального отражения). Эквивалент MB_SHININESS. \en Shininess (index according to the law of specular reflection). Equivalent of MB_SHININESS.
/// \ru Битовые флаги для матрицы и локальной системы координат. \en Bit flags for matrix and local coordinate system.
constexpr uint8 MB_IDENTITY = 0x00; ///< \ru Единичная матрица. \en Identity.
constexpr uint8 MB_TRANSLATION = 0x01; ///< \ru Присутствует смещение. \en Translation.
@@ -243,7 +250,7 @@ constexpr uint8 MB_UNSET = 0x80; ///< \ru Битовые флаги н
class MATH_CLASS MbRefItem;
class VersionContainer;
// \ru Управление реализацией переменных в Math. \en Managing variables implemenetation in Math.
// \ru Управление реализацией переменных в Math. \en Managing variables implementation in Math.
#define USE_VAR_CLASSES
//------------------------------------------------------------------------------
@@ -615,7 +622,7 @@ MATH_FUNC(const char *) C3DFileNameOnly( const char * path );
#endif
// Supress a warning "unreferenced formal parameter"
// Suppress a warning "unreferenced formal parameter"
#define C3D_UNUSED_PARAMETER( param ) (void*)(&param)
@@ -673,7 +680,7 @@ extern "C"
\en Get information about the c3d file. \~
\details \ru Эта функция - обертка для функций GetC3dVersionInfo и GetC3dBuildInfo. Возвращает строку с информацией о версии файла или варианте сборки файла. \n
\en This function is a wrapper for the GetC3dVersionInfo and GetC3dBuildInfo functions. Returns a string with information about the file version or build version of the file. \n \~
\param[in] needVersionInfo - \ru needVersionInfo == true - возвращается информация о версии файла, иначе информаиця о варианте сборки файла.
\param[in] needVersionInfo - \ru needVersionInfo == true - возвращается информация о версии файла, иначе информация о варианте сборки файла.
\en need Version Info == true - returns information about the file version, otherwise information about the file build option. \~
\return \ru Возвращает строку с запрошенной информацией.
\en Returns a string with the requested information. \~
+8 -8
View File
@@ -15,14 +15,14 @@
#include <mb_enum.h>
class MATH_CLASS MbVector;
class MATH_CLASS MbCartPoint3D;
class MATH_CLASS MbHomogeneous3D;
class MATH_CLASS MbFloatVector3D;
class MATH_CLASS MbAxis3D;
class MATH_CLASS MbPlacement3D;
class MATH_CLASS MbMatrix3D;
class MATH_CLASS MbProperties;
class MbVector;
class MbCartPoint3D;
class MbHomogeneous3D;
class MbFloatVector3D;
class MbAxis3D;
class MbPlacement3D;
class MbMatrix3D;
class MbProperties;
//------------------------------------------------------------------------------
+1 -1
View File
@@ -20,7 +20,7 @@ class MATH_CLASS MbTriangle;
namespace c3d // namespace C3D
{
typedef MbTriangle MeshTriangle; ///< \ru Треугольник. \en Triangles vector.
typedef MbTriangle MeshTriangle; ///< \ru Треугольник. \en Triangle.
typedef std::vector<MbTriangle> MeshTrianglesVector; ///< \ru Вектор треугольников. \en Mesh triangles vector.
}
+1 -2
View File
@@ -10,11 +10,10 @@
#define __OP_DIRECT_MOD_PARAMETERS_H
#include <mb_axis3d.h>
#include <solid.h>
struct DirectModValues;
struct DirectModValues;
//------------------------------------------------------------------------------
+6 -2
View File
@@ -4796,7 +4796,7 @@ struct MATH_CLASS VariableSectionValues
{
private:
const IVariableSectionData & _sectionData; ///< \ru Интерфейс для получения сечений в кинематической операции с динамической параметризацией сечения. \en An interface for obtaining sections for sweeping operation with variable section. \~
std::set<const MbFunction *> _constrFuncs; ///< \ru Функции ограничений, наложенных на образующие контуры. \en Functions of constraints imposed on generating contours. \~
std::set<const MbFunction *> _constrFuncs; ///< \ru Функции ограничений, наложенных на образующие контуры. Область определения функций должна быть [0, 1]. Значение параметра интерпретируется как часть метрической длины части траектории, соответствующей области определения элемента. \en Functions of constraints imposed on generating contours. The domain of functions must be [0, 1]. The parameter value is interpreted as part of the metric length of the spine's part corresponding to the domain of sweeping solid with variable section. \~
std::map<size_t, std::set<const MbSpaceItem *>> _constrObjs; ///< \ru Ассоциативный контейнер: ключ - индекс образующего контура, значение - множество пространственных объектов, используемых в ограничениях, наложенных на соответствующий образующий контур. \en Associative container: key - index of generating contour, value - set of space items used in constraints imposed on the corresponding generating contour. \~
c3d::DoubleVector _spineTValsForReqSections; ///< \ru Значения параметра направляющей кривой, в которых обязательно должны быть построены сечения. \en Spine curve's parameter values in which sections must be constructed. \~
bool _splitAtG1Corners; ///< \ru Разбивать элемент на грани вдоль образующей кривой и вдоль траектории в местах стыковки сегментов образующей кривой, траектории и внешних объектов ограничений (кривых), которые стыкуются с гладкостью G1 и выше. \en Split into faces along generating curve and along spine at points where segments of generating curve, spine or curves used in constraints join smoothly (G1 and up). \~
@@ -4814,7 +4814,11 @@ public:
/** \brief \ru Добавить функцию ограничения, наложенного на образующие контуры.
\en Add function of constraint imposed on generating contours. \~
\details \ru Добавить функцию ограничения, наложенного на образующие контуры.
\en Add function of constraint imposed on generating contours. \~
Область определения функции должна быть [0, 1]. Значение параметра интерпретируется
как часть метрической длины части траектории, соответствующей области определения элемента.
\en Add function of constraint imposed on generating contours.
The domain of a function must be [0, 1]. The parameter value is interpreted as part of the metric
length of the spine's part corresponding to the domain of sweeping solid with variable section. \~
\param[in] func - \ru Функция ограничения, наложенного на образующие контуры.
\en Function of constraint imposed on generating contours. \~
\return \ru true, если функция была добавлена.
+16 -8
View File
@@ -1153,6 +1153,8 @@ public:
SPtr<MbFunction> scaling; ///< \ru Функция масштабирования образующей кривой. \en The function of curve scale.
SPtr<MbFunction> winding; ///< \ru Функция вращения образующей кривой. \en The function of curve rotation.
c3d::ConstSurfaceSPtr surface; ///< \ru Поверхность для управления направляющей кривой MbSpine. \en The surface for guide curve control (for MbSpine).
private:
bool fixShellSelfInt; ///< \ru Флаг обработки по устранению самопересечений оболочки. \en Flag for shell self-intersection fix.
public:
@@ -1163,13 +1165,14 @@ public:
\en Constructor of sweeping operation parameters for construction of closed shell
without the thin wall with keeping the angle inclination. \~
*/
EvolutionValues()
: SweptValues( )
, mode ( eom_KeepingAngle )
, range ( 0.0 )
, scaling ( nullptr )
, winding ( nullptr )
, surface ( nullptr )
EvolutionValues ()
: SweptValues ()
, mode ( eom_KeepingAngle )
, range ( 0.0 )
, scaling ( nullptr )
, winding ( nullptr )
, surface ( nullptr )
, fixShellSelfInt( false )
{}
/// \ru Конструктор копирования. \en Copy-constructor.
EvolutionValues( const EvolutionValues & other );
@@ -1240,10 +1243,15 @@ public:
const MbFunction * GetWinding() const { return winding; }
MbFunction * SetWinding() { return winding; }
///< \ru Выдать поверхность для направляющей кривой MbSpine. \en Get the surface for guide curve MbSpine.
/// \ru Выдать поверхность для направляющей кривой MbSpine. \en Get the surface for guide curve MbSpine.
const MbSurface * GetSurface() const { return surface; }
void SetSurface( const MbSurface & surf );
/// \ru Устранять ли самопересечения оболочки. \en Whether to fix shell self-intersections.
bool FixShellSelfIntersections() const { return fixShellSelfInt; }
/// \ru Устранять ли самопересечения оболочки. \en Whether to fix shell self-intersections.
void SetFixShellSelfIntersections( bool b ) { fixShellSelfInt = b; }
public:
/// \ru Оператор присваивания. \en Assignment operator.
EvolutionValues & operator = ( const EvolutionValues & other );
+17 -1
View File
@@ -320,6 +320,17 @@ public:
*/
virtual bool SetValue( double v, const std::set<ItTreeVariable *> & unfixedDVars ) = 0;
/** \brief \ru Вычислить строковое значение.
\en Calculate string value. \~
\details \ru Вычислить строковое значение узла.\n
\en Calculate string value of node.\n \~
\param[out] varName - \ru Значение.
\en Value. \~
\return \ru Код результата разбора строки.
\en String parsing result code. \~
*/
virtual EquTreeResCode GetStringValue( c3d::string_t & varName ) const { varName = _T(""); return equTreeResCode_InvalidVariableType; }
/** \brief \ru Вычислить значение и производные.
\en Calculate a value and derivatives. \~
\details \ru Вычислить значение и производные. \n
@@ -960,6 +971,7 @@ public :
\{ */
EquTreeResCode GetValue ( double & fvalue ) const override;
EquTreeResCode GetStringValue ( c3d::string_t & svalue ) const override;
EquTreeResCode CalculateDerives( double &, double &, double &, double &, const VarsDerives & ) const override;
void GetUsedVariables ( SSArray<ItTreeVariable*> &, SSArray<ItUserFunc*> & ) const override;
@@ -1281,6 +1293,7 @@ public:
// \ru вычисление значения функции и производной по переменной V \en calculate the value of a function and the derivative with respect to V
EquTreeResCode GetValue ( double & fvalue ) const override;
EquTreeResCode GetStringValue ( c3d::string_t & sVal ) const override;
EquTreeResCode CalculateDerives( double &, double &, double &, double &, const VarsDerives & ) const override;
void GetUsedVariables( SSArray<ItTreeVariable*> &, SSArray<ItUserFunc*> & ) const override;
bool SetValue ( double, const std::set<ItTreeVariable *> & ) override { return false; }// \ru не реализовано \en not implemented
@@ -1360,7 +1373,8 @@ public:
private:
void operator = ( const BTreeOperation & ); // \ru не реализовано \en not implemented
EquTreeResCode GetValue( double par1, double par2, double & value ) const;
// \ru выдать значение параметра для экстремума( если это возможно ). \en get value of parameter of extremum( if it is possible ).
// \ru Вычисление значения функции строковых переменных. \en Get value of a function for string variables.
EquTreeResCode GetValue( c3d::string_t & par1, c3d::string_t & par2, double & value ) const;
virtual bool GetCharacterPoints( std::vector<CharacterPointInfo> &, const ItTreeVariable & ) const;
// \ru Только для внутреннего использования! \en For internal use only!
size_t GetPseudoOrderByVar( ItTreeVariable & var ) const override;
@@ -1401,6 +1415,7 @@ public :
// \ru вычисление значения функции и производной по переменной V \en calculate the value of a function and the derivative with respect to V
EquTreeResCode GetValue ( double &fvalue ) const override;
EquTreeResCode GetStringValue ( c3d::string_t & sVal ) const override;
EquTreeResCode CalculateDerives( double &, double &, double &, double &, const VarsDerives & ) const override;
void GetUsedVariables( SSArray<ItTreeVariable*> &, SSArray<ItUserFunc*> & ) const override;
@@ -1463,6 +1478,7 @@ public :
// \ru вычисление значения функции и производной по переменной V \en calculate the value of a function and the derivative with respect to V
EquTreeResCode GetValue ( double & fVal ) const override;
EquTreeResCode GetStringValue ( c3d::string_t & sVal ) const override;
EquTreeResCode CalculateDerives ( double &, double &, double &, double &, const VarsDerives & ) const override;
void GetUsedVariables ( SSArray<ItTreeVariable *> &, SSArray<ItUserFunc *> & ) const override;
+29 -10
View File
@@ -97,6 +97,7 @@ enum EquTreeResCode {
equTreeResCode_CyclicRelation, ///< \ru Ошибка: Найдена замкнутая зависимость. \en Error: There is found a closed dependence.
equTreeResCode_PowDomain, ///< \ru Ошибка: недопустимое значение аргумента для степенной функции. \en Error: Invalid argument value for power function.
equTreeResCode_WrongFuncFormat, ///< \ru Ошибка: Выражение содержит функцию, не соответствующую своему формату. \en Error: Expression contains a function which does not correspond to its format.
equTreeResCode_InvalidVariableType, ///< \ru Ошибка: Тип переменной не соответствует типу переменной в выражении. \en Error: The variable type does not match the variable type in the expression.
// \ru ДОБАВЛЯТЬ НОВЫЕ СООБЩЕНИЯ ТОЛЬКО ПЕРЕД ЭТОЙ СТРОКОЙ; \en ADD NEW MESSAGES ONLY BEFORE THIS STRING;
equTreeResCode_Last ///< \ru Конец диапазона ошибок. \en End of errors range.
@@ -118,6 +119,21 @@ struct ItCoord
};
//-----------------------------------------------------------------------------
/** \brief \ru Типы переменной дерева.
\en Types of tree variable. \~
\details \ru Типы переменной дерева.
\en Types of tree variable. \~
\ingroup Parser
*/
// ---
enum class VarType
{
vr_double, ///< \ru Вещественная переменная. \en Real variable.
vr_string ///< \ru Строковая переменная. \en String variable.
};
//------------------------------------------------------------------------------
/** \brief \ru Интерфейс переменной.
\en Interface of variable. \~
@@ -129,27 +145,30 @@ struct ItCoord
struct MATH_CLASS ItTreeVariable
{
ItTreeVariable() {}
virtual ~ItTreeVariable() {}
/// \ru Дать имя. \en Get name.
virtual const c3d::string_t & GetName() const = 0;
/// \ru Установить имя. \en Set name.
virtual void SetName( const c3d::string_t & ) = 0;
/// \ru Дать имя. \en Get name.
virtual const c3d::string_t & GetName() const = 0;
/// \ru Установить имя. \en Set name.
virtual void SetName( const c3d::string_t & ) = 0;
/// \ru Дать переменную. \en Get variable.
virtual double GetValue() const = 0;
virtual double GetValue() const = 0;
/// \ru Установить переменную. \en Set variable.
virtual void SetValue( double ) = 0;
virtual void SetValue( double ) = 0;
/// \ru Дать координату. \en Get coordinate.
virtual const ItCoord & GetCoord() const = 0;
virtual const ItCoord & GetCoord() const = 0;
/// \ru Вычислить размер в байтах. \en Get size in bytes.
virtual size_t SizeOf() const = 0;
virtual size_t SizeOf() const = 0;
/// \ru Дать тип переменной. \en Get type of variable.
virtual VarType IsA() const = 0;
/// \ru Захватить \en Catch.
virtual refcount_t AddRef () const = 0;
/// \ru Отпустить. \en Free.
virtual refcount_t Release() const = 0;
/// \ru Установить имя. Обработка нулевого указателя. \en Set name. Null pointer processing.
virtual void SetName( const TCHAR * s ) { SetName(c3d::string_t(s ? s : _T(""))); };
virtual void SetName( const TCHAR * s ) = 0;
/// \ru Операторы чтения, записи. \en Reading and writing operators.
DECLARE_PERSISTENT_OPS_BASE( ItTreeVariable, MATH_FUNC_EX )
+45
View File
@@ -14,6 +14,20 @@
#include <tool_cstring.h>
#include <reference_item.h>
//-----------------------------------------------------------------------------
/** \brief \ru Тип переменной.
\en Type of a variable. \~
\details \ru Тип переменной.
\en Type of a variable. \~
\ingroup Parser
*/
// ---
enum class MbVarType
{
vr_double, ///< \ru Вещественная переменная. \en Real variable.
vr_string ///< \ru Строковая переменная. \en String variable.
};
//------------------------------------------------------------------------------
/** \brief \ru Переменная.
@@ -41,9 +55,40 @@ public:
double Value() const;
/// \ru Присвоить значение переменной. \en Assign a value to a variable.
void Assignment( double value );
/// \ru Тип переменной. \en Value type.
virtual MbVarType IsA() const;
OBVIOUS_PRIVATE_COPY( MbVar )
};
//------------------------------------------------------------------------------
/** \brief \ru Строковая переменная.
\en String variable. \~
\details \ru Строковая переменная.
\en String variable. \~
\ingroup Parser
*/
// ---
class MATH_CLASS MbStringVar : public MbVar {
private:
c3d::string_t _stringValue; ///< \ru Строковое значение переменной. \en A string value of variable.
public:
/// \ru Конструктор. \en Constructor.
MbStringVar( const c3d::string_t & name );
/// \ru Деструктор. \en Destructor.
virtual ~MbStringVar();
/// \ru Строковое значение переменной. \en A value of variable.
const c3d::string_t & GetStringValue() const;
/// \ru Присвоить значение переменной. \en Assign a value to a variable.
void SetStringValue( const c3d::string_t & stringValue );
/// \ru Тип переменной. \en Value type.
MbVarType IsA() const override;
OBVIOUS_PRIVATE_COPY( MbStringVar )
};
#endif // __VAR_H
+85 -20
View File
@@ -12,6 +12,7 @@
#include <pars_tree_variable.h>
#include <math_define.h>
#include <mb_variables.h>
#include <io_tape_define.h>
#include <io_define.h>
@@ -44,23 +45,24 @@ public:
//-----------------------------------------------------------------------------
/** \brief \ru Переменная.
\en Variable. \~
\details \ru Переменная. \n
\en Variable. \n \~
/** \brief \ru Вещественная переменная.
\en Real variable. \~
\details \ru Вещественная переменная. \n
\en Real variable. \n \~
\ingroup Parser
*/
// ---
class MATH_CLASS MbTreeVariable : public TapeBase, public ItTreeVariable
{
private:
MbCoord m_coord; ///< \ru Координата. \en Coordinate.
MbCoord m_coord; ///< \ru Координата. \en Coordinate.
c3d::string_t m_name; ///< \ru Имя переменной. \en A name of variable.
mutable size_t useCount; ///< \ru Количество использований. \en The number of uses.
public:
/// \ru Конструктор по имени и значению. \en Constructor by the name and the value.
/// \ru Конструктор по имени и значению. \en Constructor by the name and the value.
MbTreeVariable( const c3d::string_t & name, double v );
/// \ru Деструктор. \en Destructor.
virtual ~MbTreeVariable();
public:
@@ -70,22 +72,16 @@ public:
void SetName ( const c3d::string_t & name ) override { m_name = name; }
/// \ru Установить имя. Обработка нулевого указателя. \en Set name. Null pointer processing.
void SetName( const TCHAR* s ) override { m_name.assign( s ? s : _T("") ); };
/// \ru Получение значение. \en Get value.
/// \ru Получение значение. \en Get value.
double GetValue () const override { return m_coord.GetValue(); }
/// \ru Установить значение. \en Set value.
/// \ru Установить значение. \en Set value.
void SetValue ( double v ) override { m_coord.SetValue( v ); }
/// \ru Получить координату. \en Get coordinate.
/// \ru Получить координату. \en Get coordinate.
const MbCoord & GetCoord () const override { return m_coord; }
/// \ru Вычислить размер переменной в байтах. \en Get size of variable in bytes.
size_t SizeOf () const override {
#ifdef C3D_WINDOWS //_MSC_VER // method SizeOf()
return /*m_name.*/sizeof( m_name ) + sizeof( TCHAR ) * (m_name.length()) + m_coord.SizeOf();
#else // C3D_WINDOWS
// \ru необходимо корректное вычилсение размера занимаемой памяти std::string \en there must be a correct calculation of size of memory allocated for std::string
return sizeof(m_name) + m_coord.SizeOf(); // \ru если данный SizeOf требуется для выделения памяти \en if the given SizeOf is required for the memory allocation
// \ru то все Ок, поскольку std::string сам разберется с выделением памяти себе. \en then everything is OK because std::string controls the memory allocation for itself.
#endif // C3D_WINDOWS
}
/// \ru Вычислить размер переменной в байтах. \en Get size of variable in bytes.
size_t SizeOf() const override { return m_coord.SizeOf() + sizeof(m_name) + sizeof(size_t); }
/// \ru Дать тип переменной. \en Get type of variable.
VarType IsA() const override { return VarType::vr_double; }
/// \ru Создать копию переменной. \en Create a copy of variable.
MbTreeVariable & Duplicate() const { return *new MbTreeVariable( GetName(), GetValue() ); }
/// \ru Увеличить счетчик использований. \en Increase a counter of uses.
@@ -95,8 +91,77 @@ public:
/// \ru Операторы чтения, записи. \en Reading and writing operators.
DECLARE_PERSISTENT_CLASS_NEW_DEL( MbTreeVariable )
};
};
IMPL_PERSISTENT_OPS( MbTreeVariable )
//-----------------------------------------------------------------------------
/** \brief \ru Строковая переменная дерева разбора выражения.
\en String variable for an expression parse tree. \~
\details \ru Строковая переменная дерева разбора выражения.
\en String variable for an expression parse tree. \~
\ingroup Parser
*/
// ---
class MATH_CLASS MbTreeStringVariable : public TapeBase, public ItTreeVariable
{
private:
c3d::string_t m_name; ///< \ru Имя переменной. \en A name of variable.
c3d::string_t m_value; ///< \ru Строковое значение переменной. \en A string value of variable.
MbCoord m_coord; ///< \ru Вспомогательный объект, используется для совместимости интерфейса. \en Auxiliary object, used for interface compatibility.
mutable size_t m_useCount; ///< \ru Количество использований. \en The number of uses.
public:
/// \ru Конструктор по имени и значению. \en Constructor by the name and the value.
MbTreeStringVariable( const c3d::string_t & name, const c3d::string_t & value )
: m_name ( name )
, m_value ( value )
, m_coord ( -MB_MAXDOUBLE )
, m_useCount( 0 )
{}
/// \ru Деструктов. \en Destructor.
virtual ~MbTreeStringVariable() {}
public:
/// \ru Получить имя. \en Get name.
const c3d::string_t & GetName () const override { return m_name; }
/// \ru Установить имя. \en Set name.
void SetName ( const c3d::string_t & name ) override { m_name = name; }
/// \ru Установить имя. Обработка нулевого указателя. \en Set name. Null pointer processing.
void SetName( const TCHAR* s ) override { m_name.assign(s ? s : _T("")); };
/// \ru Дать строковую переменную. \en Get string variable.
const c3d::string_t & GetStringValue() const { return m_value; }
/// \ru Установить строковую переменную. \en Set string variable.
void SetStringValue( const c3d::string_t & value ) { m_value = value; }
/// \ru Вычислить размер переменной в байтах. \en Get size of variable in bytes.
size_t SizeOf() const override { return sizeof(m_name) + sizeof(m_value) + sizeof(MbCoord) + sizeof(size_t); }
/// \ru Дать тип переменной. \en Get type of variable.
VarType IsA() const override { return VarType::vr_string; }
/// \ru Создать копию переменной. \en Create a copy of variable.
MbTreeStringVariable & Duplicate() const { return *new MbTreeStringVariable(m_name, m_value); }
/// \ru Дать переменную. \en Get variable.
double GetValue() const override { return -MB_MAXDOUBLE; }
/// \ru Установить переменную. \en Set variable.
void SetValue( double ) override {}
/// \ru Дать координату. \en Get coordinate.
const ItCoord & GetCoord() const override { return m_coord; }
/// \ru Увеличить счетчик использований. \en Increase a counter of uses.
refcount_t AddRef () const override { return ++m_useCount; }
/// \ru Уменьшить счетчик использований и удалить объект, если он никому уже не нужен. \en Decrease a counter of uses and delete an object if it is not used any more.
refcount_t Release() const override;
/// \ru Операторы чтения, записи. \en Reading and writing operators.
DECLARE_PERSISTENT_CLASS_NEW_DEL( MbTreeStringVariable )
};
IMPL_PERSISTENT_OPS( MbTreeStringVariable )
#endif // __MBVARIABLE_H
+1
View File
@@ -42,6 +42,7 @@ struct ItEquVarCreator
virtual bool CreateFunc ( const c3d::string_t &, const std::vector<c3d::string_t> & parNames ) = 0;
virtual bool CreateInterval( const c3d::string_t & ) = 0;
virtual bool CreateVariable( const c3d::string_t &) = 0;
virtual ItTreeVariable * CreateUnnamedVariable( const c3d::string_t & ) = 0;
virtual ItTreeVariable * GetVariable( const TCHAR * ) = 0;
virtual ItIntervalTreeVariable * GetIntervalVariable( const TCHAR * ) = 0;
+358
View File
@@ -0,0 +1,358 @@
////////////////////////////////////////////////////////////////////////////////
/**
\file
\brief \ru Сущности для передачи кривых STEP.
\en Entities for STEP curves.
*/
////////////////////////////////////////////////////////////////////////////////
#ifndef __SE_CURVE_H
#define __SE_CURVE_H
#include <vector>
#include <se_elementary.h>
namespace c3d
{
namespace converter {
//------------------------------------------------------------------------------
/** \brief \ru Тип узлов B-сплайна STEP.
\en B-spline knots vector type. \~
\note \ru ЭКСПЕРИМЕНТАЛЬНАЯ.
\en EXPEREIMENTAL. \~
*/
enum class SeBKnotsType {
UniformKnots, ///< \ru Однородный узловой вектор. \en Uniform knots vector.
QuasiUniformKnots, ///< \ru Квазиоднородный узловой вектор. \en Quasi-uniform knots vector.
PiecewiseBezierKnots, ///< \ru Узловой вектор кривой Безье. \en Bezier knots vector.
Unspecified ///< \ru Узловой вектор общего вида. \en General knots vector.
};
//------------------------------------------------------------------------------
/** \brief \ru Форма B-сплайна STEP.
\en Form of STEP B-spline. \~
\note \ru ЭКСПЕРИМЕНТАЛЬНАЯ.
\en EXPEREIMENTAL. \~
*/
enum class SeBCurveForm {
EllipticArc, ///< \ru Дуга эллипса. \en Elliptic arc.
PolylineForm, ///< \ru Ломаная. \en Polyline.
ParabolicArc, ///< \ru Участок параболы. \en Part of parabola.
CircularArc, ///< \ru Дуга окружности. \en Circular arc.
Unspecified, ///< \ru Общего вида. \en General type.
HyperbolicArc ///< \ru Участок гиперболы. \en Part of hyperbola.
};
//------------------------------------------------------------------------------
/** \brief \ru Форма ограничения кривой STEP.
\en . \~
\note \ru ЭКСПЕРИМЕНТАЛЬНАЯ.
\en EXPEREIMENTAL. \~
*/
enum class SeTrimForm {
Parameter, ///< \ru Усечение параметром. \en Trim by parameter.
Unspecified, ///< \ru Неизвестный тип. \en Trim undefined.
Cartesian, ///< \ru Усечение точкой. \en Trim by point.
};
//------------------------------------------------------------------------------
/** \brief \ru Прямая STEP.
\en . \~
\note \ru ЭКСПЕРИМЕНТАЛЬНАЯ.
\en EXPEREIMENTAL. \~
*/
class CONV_CLASS SeLineCurve final : public SeBase {
size_t m_point; ///< \ru Точка. \en Point.
size_t m_direction; ///< \ru Направление. \en Direction.
public:
/// \ru Получить точку. \en Get point.
size_t GetPoint() const;
/// \ru Получить направление. \en Get direction.
size_t GetDirection() const;
/// \ru Создать прямую. \en Create a line.
static std::shared_ptr<SeLineCurve> Create(
size_t const thisId,
size_t const point,
size_t const direction
);
VISITING_CLASS( SeLineCurve )
private:
/// \ru Конструктор. \en Constructor.
SeLineCurve(
size_t const thisId,
size_t const point,
size_t const direction
);
};
//------------------------------------------------------------------------------
/** \brief \ru Коническое сечение STEP.
\en Conic section STEP. \~
\note \ru ЭКСПЕРИМЕНТАЛЬНАЯ.
\en EXPEREIMENTAL. \~
*/
class CONV_CLASS SeConic : public SeBase {
size_t m_postion; ///< \ru Локальная система координат. \en PLacement.
public:
/// \ru Получить локальную систему координат. \en Get placement.
size_t GetPosition() const;
protected:
/// \ru Конструктор. \en Constructor.
SeConic(
size_t const thisId,
size_t const position
);
};
//------------------------------------------------------------------------------
/** \brief \ru Окружность STEP.
\en STEP circle. \~
\note \ru ЭКСПЕРИМЕНТАЛЬНАЯ.
\en EXPEREIMENTAL. \~
*/
class CONV_CLASS SeCircleCurve final : public SeConic {
double m_radius; ///< \ru Радиус. \en Radius.
public:
/// \ru Получить радиус. \en Get radius.
double GetRadius() const;
/// \ru Создать окружность. \en Create a circle.
static std::shared_ptr<SeCircleCurve> Create(
size_t const thisId,
size_t const center,
double const radius
);
VISITING_CLASS( SeCircleCurve )
private:
/// \ru Конструктор. \en Constructor.
SeCircleCurve(
size_t const thisId,
size_t const position,
double const radius
);
};
//------------------------------------------------------------------------------
/** \brief \ru Ограниченная кривая STEP.
\en Bounded curve. \~
\note \ru ЭКСПЕРИМЕНТАЛЬНАЯ.
\en EXPEREIMENTAL. \~
*/
class CONV_CLASS SeBoundedCurve : public SeBase {
protected:
SeBoundedCurve(size_t const thisId);
};
//------------------------------------------------------------------------------
/** \brief \ru B-сплайн с узлами STEP.
\en . \~
\note \ru ЭКСПЕРИМЕНТАЛЬНАЯ.
\en EXPEREIMENTAL. \~
*/
class CONV_CLASS SeBSplineWithKnotsCurve final : public SeBase {
ptrdiff_t m_degree; ///< \ru . \en .
std::vector<size_t> m_points; ///< \ru Опорные точки. \en Base points.
SeBCurveForm m_form; ///< \ru Форма. \en Form.
bool m_isClosed; ///< \ru Замкнутость. \en Is closed.
bool m_isSelfIntersected; ///< \ru Самопересечение. \en Is self-intersectin.
std::vector<ptrdiff_t> m_knotMultiplicities; ///< \ru Множители узлов. \en Knots multiplicities.
std::vector<double> m_knots; ///< \ru Узлы. \en Knots.
SeBKnotsType m_knotsType; ///< \ru Тип вектора. \en Type of knots vector.
public:
/// \ru . \en .
size_t GetDegree() const;
/// \ru Получить количество контрольных точек. \en Get count of control points.
size_t GetPointsCount() const;
/// \ru Получить контрольную точку по индексу. \en Get control point by index.
size_t GetPoint( size_t index ) const;
/// \ru Получить форму кривой. \en Get curve's form.
SeBCurveForm GetForm() const;
/// \ru Получить признак замкнутости кривой. \en Is curve closed.
bool IsClosed() const;
/// \ru Получить признак самопересечения кривой. \en Is curve slef-intersecting.
bool IsSelfIntersected() const;
/// \ru Получить количество множителей узлов. \en Get count of knots multiplicities.
size_t GetKnotMultiplicitiesCount() const;
/// \ru Получить множитель узла по индексу. \en Get knots multiplicity by index.
ptrdiff_t GetKnotMultiplicity( size_t index ) const;
/// \ru Получить количество узлов. \en Get count of knots.
size_t GetKnotsCount() const;
/// \ru Получить узел по индексу. \en Get knot by index.
double GetKnot( size_t index ) const;
/// \ru Получить тип вектора. \en Get type of vector.
SeBKnotsType GetKnotsType() const;
/// \ru . \en .
static std::shared_ptr<SeBSplineWithKnotsCurve> Create(
size_t const thisId,
ptrdiff_t const degree,
std::vector<size_t> && controlPointsList,
SeBCurveForm const curveForm,
bool const isClosed,
bool const isSelfIntersected,
std::vector<ptrdiff_t> && knotMultiplicities,
std::vector<double> && knots,
SeBKnotsType const knotsType
);
VISITING_CLASS( SeBSplineWithKnotsCurve )
private:
/// \ru Конструктор. \en Constructor.
SeBSplineWithKnotsCurve(
size_t const thisId,
ptrdiff_t const degree,
std::vector<size_t> && controlPointsList,
SeBCurveForm const curveForm,
bool const isClosed,
bool const isSelfIntersected,
std::vector<ptrdiff_t> && knotMultiplicities,
std::vector<double> && knots,
SeBKnotsType const knotsType
);
};
//------------------------------------------------------------------------------
/** \brief \ru Ломаная STEP.
\en STEP polyline. \~
\note \ru ЭКСПЕРИМЕНТАЛЬНАЯ.
\en EXPEREIMENTAL. \~
*/
class CONV_CLASS SePolylineCurve final : public SeBoundedCurve {
std::vector<size_t> m_points; ///< \ru Точки ломаной. \en Points of polyline.
public:
/// \ru Получить количество точек. \en Get count of points.
size_t GetPointsCount() const;
/// \ru Получить точку по индексу. \en Get point by index.
double GetPoint( size_t index ) const;
/// \ru Создать ломаную. \en Create polyline.
static std::shared_ptr<SePolylineCurve> Create(
size_t const thisId,
std::vector<size_t> && points
);
VISITING_CLASS( SePolylineCurve )
private:
/// \ru Конструктор. \en Constructor.
SePolylineCurve(
size_t const thisId,
std::vector<size_t> && points
);
};
//------------------------------------------------------------------------------
/** \brief \ru Ограниченная кривая STEP.
\en . \~
\note \ru ЭКСПЕРИМЕНТАЛЬНАЯ.
\en EXPEREIMENTAL. \~
*/
class CONV_CLASS SeTrimmedCurve final : public SeBoundedCurve {
size_t m_baseCurve; ///< \ru Усекаемая кривая. \en Trimmed curve.
std::array<double,2> m_trimmingParameters; ///< \ru Пераметры усечения. \en Trimming parameters.
bool m_sense; ///< \ru Признак сонаправленности. \en Is trimmed curve co-directed to the base one.
SeTrimForm m_masterRepresentation; ///< \ru . \en .
public:
/// \ru Получить усекаемую кривую. \en Get curve to trim.
size_t GetBaseCurve() const;
/// \ru Получить первый параметр усечения. \en Get first trimming parameter.
double GetTrim1() const;
/// \ru Получить второй параметр усечения. \en Get second trimming parameter.
double GetTrim2() const;
/// \ru Получить признак сонаправленности. \en Is trimmed curve co-directed to the base one.
bool GetSense() const;
/// \ru Получить главное представление. \en Get master representation.
SeTrimForm GetMasterRepresentation() const;
/// \ru Создать усечённую кривую. \en Create trimmed curve.
static std::shared_ptr<SeTrimmedCurve> Create(
size_t const thisId,
size_t const baseCurve,
double trim1,
double trim2,
bool const sense,
SeTrimForm const masterRepresentation
);
VISITING_CLASS( SeTrimmedCurve )
private:
/// \ru Конструктор. \en Constructor.
SeTrimmedCurve(
size_t const thisId,
size_t const baseCurve,
double const trim1,
double const trim2,
bool const sense,
SeTrimForm const masterRepresentation
);
};
//------------------------------------------------------------------------------
/** \brief \ru Составная кривая STEP.
\en Composite curve STEP. \~
\note \ru ЭКСПЕРИМЕНТАЛЬНАЯ.
\en EXPEREIMENTAL. \~
*/
class CONV_CLASS SeCompositeCurve final : public SeBoundedCurve {
std::vector<size_t> m_segments; ///< \ru Сеггменты составной кривой. \en .
bool m_isSelfIntersected; ///< \ru Является ли кривая самопересекающейся. \en Wether the curve is slef-intersectng.
public:
/// \ru Получить количество сегментов. \en Get segments count.
size_t GetSegmentsCount() const;
/// \ru Получить сггмент по индексу. \en Get degment by index.
size_t GetSegment( size_t index ) const;
/// \ru Получить признак самопересечения. \en Wether the curve is slef-intersectng.
bool IsSelfIntersected() const;
/// \ru Создать составную кривую. \en Create composite curve.
static std::shared_ptr<SeCompositeCurve> Create(
size_t const thisId,
std::vector<size_t> && segments,
bool const isSelfIntersected
);
VISITING_CLASS( SeCompositeCurve )
private:
/// \ru Конструктор. \en Constructor.
SeCompositeCurve(
size_t const thisId,
std::vector<size_t> && segments,
bool const isSelfIntersected
);
};
}
}
#endif
+172
View File
@@ -0,0 +1,172 @@
////////////////////////////////////////////////////////////////////////////////
/**
\file
\brief \ru Базовый класс сущностей StepEntity и объекты для передачи примитивов.
\en Base class StepEntity of entities and objects for geometric primitives
*/
////////////////////////////////////////////////////////////////////////////////
#ifndef SE_ELEMENTARY_H
#define SE_ELEMENTARY_H
#include <math_define.h>
#include <templ_visitor.h>
#include <array>
#include <memory>
namespace c3d
{
namespace converter
{
//------------------------------------------------------------------------------
/** \brief \ru Абстрактная сущность STEP.
\en Abstract STEP entity. \~
\note \ru ЭКСПЕРИМЕНТАЛЬНАЯ.
\en EXPEREIMENTAL. \~
*/
class CONV_CLASS SeBase
{
size_t m_thisId; ///< \ru Собственный идентификатор. \en Own identifier.
public:
/// \ru Предопределённое значнение некорректного идентификатора объекта. \en Pre-defined value for invalid identifier.
static const size_t forbiddenId = 0;
/// \ru Получить собственный идентификатор. \en Get own identifier.
size_t ThisId() const;
/// \ru Деструктор. \en Destructor.
virtual ~SeBase() = default;
/// \ru Принять посетителя. \en Accept a visitor.
virtual void Accept( Visitor & visitor ) = 0;
protected:
/// \ru Конструктор. \en Constructor.
SeBase( size_t thisId );
/// \ru Конструктор копировани удалён. \en Copy constructor removed.
SeBase( SeBase const & ) = delete;
/// \ru Конструктор перемещения удалён. \en Move constructor removed.
SeBase( SeBase && ) = delete;
/// \ru Оператор присваивания удалён. \en Assignment operator removed.
const SeBase& operator =( SeBase const & ) = delete;
};
//------------------------------------------------------------------------------
/** \brief \ru Точка STEP.
\en Point STEP. \~
\note \ru ЭКСПЕРИМЕНТАЛЬНАЯ.
\en EXPEREIMENTAL. \~
*/
class CONV_CLASS SePoint : public SeBase
{
std::array<double,3> m_xyz; ///< \ru Координаты. \en Coordinates.
public:
/// \ru Получить значение координаты по индексу: 0 - x, 1- y, 2 - z. \en Get component by index: 0 - x, 1- y, 2 - z.
double operator[]( size_t ) const;
VISITING_CLASS( SePoint )
/// \ru Создать точку. \en Create a point.
static std::shared_ptr<SePoint> Create( size_t thisId, double x, double y, double z );
private:
/// \ru Конструктор. \en Constructor.
SePoint( size_t thisId, double x, double y, double z );
};
//------------------------------------------------------------------------------
/** \brief \ru Вектор STEP.
\en Vector STEP. \~
\note \ru ЭКСПЕРИМЕНТАЛЬНАЯ.
\en EXPEREIMENTAL. \~
*/
class CONV_CLASS SeVector : public SeBase
{
size_t m_direction; ///< \ru Направление. \en Direction.
double m_magnitude; ///< \ru Длина. \en Magintude.
public:
/// \ru Получить направление. \en Get a direction.
size_t GetDirction() const;
/// \ru Получить длину. \en Get magnitude.
double GetMagnitude() const;
VISITING_CLASS( SeVector )
/// \ru Создать вектор. \en Create a vector.
static std::shared_ptr<SeVector> Create( size_t thisId, size_t direction, double magnitude );
private:
/// \ru Конструктор. \en Constructor.
SeVector( size_t thisId, size_t direction, double magnitude );
};
//------------------------------------------------------------------------------
/** \brief \ru Направление STEP.
\en . \~
\note \ru ЭКСПЕРИМЕНТАЛЬНАЯ.
\en EXPEREIMENTAL. \~
*/
class CONV_CLASS SeDirection : public SeBase
{
std::array<double,3> m_xyz; ///< \ru Координаты. \en Coordinates.
public:
/// \ru Получить значение координаты по индексу: 0 - x, 1- y, 2 - z, прочее - ислключение. \en Get component by index: 0 - x, 1- y, 2 - z, other - exception.
double operator[]( size_t ) const;
VISITING_CLASS( SeDirection )
/// \ru Создать направление. \en Create a direction.
static std::shared_ptr<SeDirection> Create( size_t thisId, double x, double y, double z );
private:
/// \ru Конструктор. \en Constructor.
SeDirection( size_t thisId, double x, double y, double z );
};
//------------------------------------------------------------------------------
/** \brief \ru Локалькая система координат STEP.
\en STEP placement. \~
\note \ru ЭКСПЕРИМЕНТАЛЬНАЯ.
\en EXPEREIMENTAL. \~
*/
class CONV_CLASS SePlacement3D : public SeBase
{
size_t m_origin,///< \ru Начало. \en Origin.
m_axisZ, ///< \ru Ось z. \en Z axis.
m_axisX; ///< \ru Ось x. \en X axis.
public:
/// \ru Создать локальную систему координат. \en Create a placement.
static std::shared_ptr<SePlacement3D> Create( size_t thisId, size_t origin, size_t axisZ, size_t axisX );
/// \ru Получить начало. \en Get origin.
size_t GetOrigin() const;
/// \ru получить ось z. \en Get axis z.
size_t GetAxisZ() const;
/// \ru Получить ось x. \en Get axis x.
size_t GetAxisX() const;
VISITING_CLASS( SePlacement3D )
private:
/// \ru Конструктор. \en Constructor.
SePlacement3D( size_t thisId, size_t origin, size_t axisZ, size_t axisX );
};
}
};
#endif //SE_ELEMENTARY_H
+319
View File
@@ -0,0 +1,319 @@
////////////////////////////////////////////////////////////////////////////////
/**
\file
\brief Объекты для передачи поверхностей StepEntity.
*/
////////////////////////////////////////////////////////////////////////////////
#ifndef __SE_SURFACE_H
#define __SE_SURFACE_H
#include <se_elementary.h>
namespace c3d
{
namespace converter
{
//------------------------------------------------------------------------------
/** \brief \ru Плоскость.
\en Plane. \~
*/
class CONV_CLASS SePlane : public SeBase
{
size_t m_placement; ///< \ru Локальная система координат. \en Location.
public:
/// \ru . \en .
static std::shared_ptr<SePlane> Create( size_t thisId, size_t placement );
/// \ru . \en .
size_t GetPlacement() const;
VISITING_CLASS( SePlane )
private:
/// \ru Конструктор. \en Constructor.
SePlane( size_t thisId, size_t placement );
};
//------------------------------------------------------------------------------
/** \brief \ru Цилиндр.
\en Cylinder surface. \~
*/
class CONV_CLASS SeCylinderSurface : public SeBase
{
size_t m_placement; ///< \ru Локальная система координат. \en Location.
double m_radius; ///< \ru . \en .
public:
/// \ru . \en .
static std::shared_ptr<SeCylinderSurface> Create( size_t thisId, size_t placement, double radius );
/// \ru . \en .
size_t GetPlacement() const;
/// \ru . \en .
double GetRadius() const;
VISITING_CLASS( SeCylinderSurface )
private:
/// \ru Конструктор. \en Constructor.
SeCylinderSurface( size_t thisId, size_t placement, double radius );
};
//------------------------------------------------------------------------------
/** \brief \ru Конус.
\en Cone surface. \~
*/
class CONV_CLASS SeConeSurface : public SeBase
{
size_t m_placement; ///< \ru Локальная система координат. \en Location.
double m_radius, ///< \ru . \en .
m_semiAngle; ///< \ru . \en .
public:
/// \ru . \en .
static std::shared_ptr<SeConeSurface> Create( size_t thisId, size_t placement, double radius, double semiAngle );
/// \ru . \en .
size_t GetPlacement() const;
/// \ru . \en .
double GetRadius() const;
/// \ru . \en .
double GetSemiAngle() const;
VISITING_CLASS( SeConeSurface )
private:
/// \ru Конструктор. \en Constructor.
SeConeSurface( size_t thisId, size_t placement, double radius, double semiAngle );
};
//------------------------------------------------------------------------------
/** \brief \ru Сфера.
\en Sphere surface. \~
*/
class CONV_CLASS SeSphereSurface : public SeBase
{
size_t m_placement; ///< \ru Локальная система координат. \en Location.
double m_radius; ///< \ru . \en .
public:
/// \ru . \en .
static std::shared_ptr<SeSphereSurface> Create( size_t thisId, size_t placement, double radius );
/// \ru . \en .
size_t GetPlacement() const;
/// \ru . \en .
double GetRadius() const;
VISITING_CLASS( SeSphereSurface )
private:
/// \ru Конструктор. \en Constructor.
SeSphereSurface( size_t thisId, size_t placement, double radius );
};
//------------------------------------------------------------------------------
/** \brief \ru Тор.
\en Torus surface. \~
*/
class CONV_CLASS SeTorusSurface : public SeBase
{
size_t m_placement; ///< \ru Локальная система координат. \en Location.
double m_majorRadius, ///< \ru . \en .
m_minorRadius; ///< \ru . \en .
public:
/// \ru . \en .
static std::shared_ptr<SeTorusSurface> Create( size_t thisId, size_t placement, double majorRadius, double minorRadius );
/// \ru . \en .
size_t GetPlacement() const;
/// \ru . \en .
double GetMajorRadius() const;
/// \ru . \en .
double GetMinorRadius() const;
VISITING_CLASS( SeTorusSurface )
private:
/// \ru Конструктор. \en Constructor.
SeTorusSurface( size_t thisId, size_t placement, double majorRadius, double minorRadius );
};
//------------------------------------------------------------------------------
/** \brief \ru Сплайновая поверхность.
\en Spline surface. \~
*/
class CONV_CLASS SeSplineSurface : public SeBase
{
size_t m_uDegree, ///< \ru . \en .
m_vDegree; ///< \ru . \en .
std::vector<size_t> m_uMultipliers, ///< \ru . \en .
m_vMultipliers; ///< \ru . \en .
std::vector<double> m_uKnots, ///< \ru . \en .
m_vKnots; ///< \ru . \en .
std::vector<std::vector<size_t>> m_Points;
std::vector<std::vector<double>> m_Weights;
bool m_uClosed, m_vClosed;
public:
/// \ru . \en .
static std::shared_ptr<SeSplineSurface> Create(size_t thisId, size_t uDegree, size_t vDegree,
std::vector<size_t>&& uMultipliers, std::vector<size_t>&& vMultipliers,
std::vector<double>&& uKnots, std::vector<double>&& vKnots,
std::vector<std::vector<size_t>>&& points,
std::vector<std::vector<double>>&& weights,
bool uClosed, bool vClosed);
/// \ru . \en .
size_t GetUDegree() const;
/// \ru . \en .
size_t GetVDegree() const;
/// \ru . \en .
size_t UMultipliersCount() const;
/// \ru . \en .
size_t GetUMultiplier( size_t index ) const;
/// \ru . \en .
size_t VMultipliersCount() const;
/// \ru . \en .
size_t GetVMultiplier( size_t index ) const;
/// \ru . \en .
size_t UKnotsCount() const;
/// \ru . \en .
double GetUKnot( size_t index ) const;
/// \ru . \en .
size_t VKnotsCount() const;
/// \ru . \en .
double GetVKnot( size_t index ) const;
/// \ru . \en .
size_t PointLinesCount() const;
/// \ru . \en .
size_t PointColumnsCount() const;
/// \ru . \en .
size_t GetPoint( size_t i, size_t j ) const;
/// \ru . \en .
size_t WeightLinesCount() const;
/// \ru . \en .
size_t WeightColumnsCount() const;
/// \ru . \en .
double GetWeight( size_t i, size_t j ) const;
/// \ru . \en .
bool IsUClosed() const;
/// \ru . \en .
bool IsVClosed() const;
VISITING_CLASS( SeSplineSurface )
private:
/// \ru Конструктор. \en Constructor.
SeSplineSurface( size_t thisId, size_t uDegree, size_t vDegree,
std::vector<size_t> && uMultipliers, std::vector<size_t> && vMultipliers,
std::vector<double> && uKnots, std::vector<double> && vKnots,
std::vector<std::vector<size_t>> && points,
std::vector<std::vector<double>> && weights,
bool uClosed, bool vClosed );
};
//------------------------------------------------------------------------------
/** \brief \ru Поверхность выдавливания.
\en Extrusion surface. \~
*/
class CONV_CLASS SeExtrusionSurface : public SeBase
{
size_t m_curve;
size_t m_direction;
public:
/// \ru . \en .
static std::shared_ptr<SeExtrusionSurface> Create( size_t thisId, size_t curve, size_t direction );
/// \ru . \en .
size_t GetCurve() const;
/// \ru . \en .
size_t GetDirection() const;
VISITING_CLASS( SeExtrusionSurface )
private:
/// \ru Конструктор. \en Constructor.
SeExtrusionSurface( size_t thisId, size_t curve, size_t direction );
};
//------------------------------------------------------------------------------
/** \brief \ru Поверхность вращения.
\en Revolution surface. \~
*/
class CONV_CLASS SeRevolutionSurface : public SeBase
{
size_t m_curve;
size_t m_axis;
public:
/// \ru . \en .
static std::shared_ptr<SeRevolutionSurface> Create( size_t thisId, size_t curve, size_t axis );
/// \ru . \en .
size_t GetCurve() const;
/// \ru . \en .
size_t GetAxis() const;
VISITING_CLASS( SeRevolutionSurface )
private:
/// \ru Конструктор. \en Constructor.
SeRevolutionSurface( size_t thisId, size_t curve, size_t axis );
};
//------------------------------------------------------------------------------
/** \brief \ru Эквидистантная поверхность.
\en Offset surface. \~
*/
class CONV_CLASS SeOffsetSurface : public SeBase
{
size_t m_basisSurface;
double m_distance;
public:
/// \ru . \en .
static std::shared_ptr<SeOffsetSurface> Create( size_t thisId, size_t basisSurface, double distance );
/// \ru . \en .
size_t GetBasisSurface() const;
/// \ru . \en .
double GetDistance() const;
VISITING_CLASS( SeOffsetSurface )
private:
/// \ru Конструктор. \en Constructor.
SeOffsetSurface( size_t thisId, size_t basisSurface, double distance );
};
}
}
#endif //__SE_SURFACE_H
+254
View File
@@ -0,0 +1,254 @@
////////////////////////////////////////////////////////////////////////////////
/**
\file
\brief Объекты для передачи топологии StepEntity.
*/
////////////////////////////////////////////////////////////////////////////////
#ifndef __SE_TOPOLOGY_H
#define __SE_TOPOLOGY_H
#include <se_elementary.h>
namespace c3d
{
namespace converter
{
//------------------------------------------------------------------------------
/** \brief \ru Твердое тело.
\en Solid. \~
*/
class CONV_CLASS SeSolid : public SeBase
{
size_t m_shell;
public:
/// \ru . \en .
static std::shared_ptr<SeSolid> Create( size_t thisId, size_t shell );
/// \ru . \en .
size_t GetShell() const;
VISITING_CLASS( SeSolid )
private:
/// \ru Конструктор. \en Constructor.
SeSolid( size_t thisId, size_t shell );
};
//------------------------------------------------------------------------------
/** \brief \ru Открытая оболочка.
\en Open shell. \~
*/
class CONV_CLASS SeOpenShell : public SeBase
{
std::vector<size_t> m_faces;
public:
/// \ru . \en .
static std::shared_ptr<SeOpenShell> Create( size_t thisId, std::vector<size_t> && faces );
/// \ru . \en .
size_t FacesCount() const;
/// \ru . \en .
size_t GetFace( size_t index ) const;
VISITING_CLASS( SeOpenShell )
private:
/// \ru Конструктор. \en Constructor.
SeOpenShell( size_t thisId, std::vector<size_t> && faces );
};
//------------------------------------------------------------------------------
/** \brief \ru Замкнутая оболочка.
\en Closed shell. \~
*/
class CONV_CLASS SeClosedShell : public SeBase
{
std::vector<size_t> m_faces;
public:
/// \ru . \en .
static std::shared_ptr<SeClosedShell> Create( size_t thisId, std::vector<size_t> && faces );
/// \ru . \en .
size_t FacesCount() const;
/// \ru . \en .
size_t GetFace( size_t index ) const;
VISITING_CLASS( SeClosedShell )
private:
/// \ru Конструктор. \en Constructor.
SeClosedShell( size_t thisId, std::vector<size_t> && faces );
};
//------------------------------------------------------------------------------
/** \brief \ru Грань.
\en Face. \~
*/
class CONV_CLASS SeAdvancedFace : public SeBase
{
size_t m_surface;
std::vector<size_t> m_bounds;
bool m_sameSense;
public:
/// \ru . \en .
static std::shared_ptr<SeAdvancedFace> Create( size_t thisId, size_t surface, std::vector<size_t> && bounds, bool sameSense );
/// \ru . \en .
size_t GetSurface() const;
/// \ru . \en .
size_t BoundsCount() const;
/// \ru . \en .
size_t GetBound( size_t index ) const;
/// \ru . \en .
bool IsSameSense() const;
VISITING_CLASS( SeAdvancedFace )
private:
/// \ru Конструктор. \en Constructor.
SeAdvancedFace( size_t thisId, size_t surface, std::vector<size_t> && bounds, bool sameSense );
};
//------------------------------------------------------------------------------
/** \brief \ru Граница грани.
\en Face bound. \~
*/
class CONV_CLASS SeFaceBound : public SeBase
{
size_t m_loop;
bool m_orientation;
public:
/// \ru . \en .
static std::shared_ptr<SeFaceBound> Create( size_t thisId, size_t loop, bool orientation );
/// \ru . \en .
size_t GetLoop() const;
/// \ru . \en .
bool GetOrientation() const;
VISITING_CLASS( SeFaceBound )
private:
/// \ru Конструктор. \en Constructor.
SeFaceBound( size_t thisId, size_t loop, bool orientation );
};
//------------------------------------------------------------------------------
/** \brief \ru Цикл.
\en Loop. \~
*/
class CONV_CLASS SeLoop : public SeBase
{
std::vector<size_t> m_edgeList;
public:
/// \ru . \en .
static std::shared_ptr<SeLoop> Create( size_t thisId, std::vector<size_t> && edgeList );
/// \ru . \en .
size_t EdgesCount() const;
/// \ru . \en .
size_t GetOrientedEdge( size_t index ) const;
VISITING_CLASS( SeLoop )
private:
/// \ru Конструктор. \en Constructor.
SeLoop( size_t thisId, std::vector<size_t> && edgeList );
};
//------------------------------------------------------------------------------
/** \brief \ru Ориентированное ребро.
\en Oriented edge. \~
*/
class CONV_CLASS SeOrientedEdge : public SeBase
{
size_t m_edge;
bool m_orientation;
public:
/// \ru . \en .
static std::shared_ptr<SeOrientedEdge> Create( size_t thisId, size_t edge, bool orientation );
/// \ru . \en .
size_t GetEdge() const;
/// \ru . \en .
bool GetOrientation() const;
VISITING_CLASS( SeOrientedEdge )
private:
/// \ru Конструктор. \en Constructor.
SeOrientedEdge( size_t thisId, size_t edge, bool orientation );
};
//------------------------------------------------------------------------------
/** \brief \ru Ребро.
\en Edge. \~
*/
class CONV_CLASS SeEdge : public SeBase
{
size_t m_curve;
size_t m_begVertex, m_endVertex;
bool m_sameSense;
public:
/// \ru . \en .
static std::shared_ptr<SeEdge> Create( size_t thisId, size_t curve, size_t begVertex, size_t endVertex, bool sameSense );
/// \ru . \en .
size_t GetCurve() const;
/// \ru . \en .
size_t GetBegVertex() const;
/// \ru . \en .
size_t GetEndVertex() const;
/// \ru . \en .
bool IsSameSense() const;
VISITING_CLASS( SeEdge )
private:
/// \ru Конструктор. \en Constructor.
SeEdge( size_t thisId, size_t curve, size_t begVertex, size_t endVertex, bool sameSense );
};
//------------------------------------------------------------------------------
/** \brief \ru Вершина.
\en Vertex. \~
*/
class CONV_CLASS SeVertex : public SeBase
{
size_t m_point;
public:
/// \ru . \en .
static std::shared_ptr<SeVertex> Create( size_t thisId, size_t point );
/// \ru . \en .
size_t GetPoint() const;
VISITING_CLASS( SeVertex )
private:
/// \ru Конструктор. \en Constructor.
SeVertex( size_t thisId, size_t point );
};
}
}
#endif //__SE_TOPOLOGY_H
+2
View File
@@ -221,6 +221,8 @@ public:
bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const override; // \ru Является ли объект копией. \en Whether the object is a copy.
bool SetEqual ( const MbSpaceItem & ) override; // \ru Сделать равным. \en Make equal.
bool IsSimilar( const MbSpaceItem & ) const override; // \ru Являются ли объекты подобными. \en Determine whether the objects are similar.
// \ru Подобные ли поверхности для объединения (слива). \en Whether the surfaces to union (joining) are similar.
bool IsSimilarToSurface( const MbSurface & surf, VERSION version, double precision = METRIC_PRECISION ) const override;
void GetProperties( MbProperties & properties ) override; // \ru Выдать свойства объекта. \en Get properties of the object.
/** \} */
+7 -3
View File
@@ -313,7 +313,7 @@ public:
void CalculateGabarit( MbCube & ) const override; // \ru Рассчитать габарит поверхности. \en Calculate bounding box of surface.
void CalculateLocalGabarit( const MbMatrix3D &, MbCube & ) const override; // \ru Рассчитать габарит относительно л.с.к. \en Calculate bounding box relative to the local coordinate system.
void SetLimit( double u1, double v1, double u2, double v2 ) override;
bool SetLimit( double u1, double v1, double u2, double v2 ) override;
void SetExtendedParamRegion( double u1, double v1, double u2, double v2 ) override;
void IncludePoint( double u, double v ) override; // \ru Включить точку в область определения. \en Include point into domain.
@@ -458,8 +458,12 @@ bool MbConeSurface::CheckVParam( double & v ) const
// \ru Получить v-параметр полюса \en Get v parameter of pole
// ---
inline
double MbConeSurface::GetVPole() const {
return -radius/tgAngleH;
double MbConeSurface::GetVPole() const {
if ( (-DOUBLE_EPSILON < tgAngleH) && (tgAngleH < DOUBLE_EPSILON) ) { // Избежать деления на 0.
return ( tgAngleH * radius > 0.0 ? -MAX_OVERALL_DIM : MAX_OVERALL_DIM );
}
return -radius / tgAngleH;
}
+1 -1
View File
@@ -339,7 +339,7 @@ public :
void CalculateGabarit( MbCube & ) const override; // \ru Рассчитать габарит поверхности. \en Calculate bounding box of surface.
void CalculateLocalGabarit( const MbMatrix3D &, MbCube & ) const override; // \ru Рассчитать габарит относительно л.с.к. \en Calculate bounding box relative to the local coordinate system.
void SetLimit( double u1, double v1, double u2, double v2 ) override; // \ru Установить пределы. \en Set limits.
bool SetLimit( double u1, double v1, double u2, double v2 ) override; // \ru Установить пределы. \en Set limits.
void IncludePoint( double u, double v ) override; // \ru Расширить параметрические границы поверхности. \en Extend parametric bounds of surface.
double GetParamDelta() const override; // \ru Дать максимальное приращение параметра. \en Get the maximal increment of parameter.
+1 -1
View File
@@ -306,7 +306,7 @@ public:
double GetRadius() const override; // \ru Дать физический радиус объекта или ноль, если это невозможно. \en Get the physical radius of the object or null if it impossible.
void SetLimit( double u1, double v1, double u2, double v2 ) override;
bool SetLimit( double u1, double v1, double u2, double v2 ) override;
void SetExtendedParamRegion( double u1, double v1, double u2, double v2 ) override;
void IncludePoint( double u, double v ) override; // \ru Включить точку в область определения \en Include point into domain
+3 -3
View File
@@ -195,7 +195,7 @@ public:
size_t GetUMeshCount() const override; // \ru Выдать количество полигонов по u. \en Get the count of polygons by u.
size_t GetVMeshCount() const override; // \ru Выдать количество полигонов по v. \en Get the count of polygons by v.
void SetLimit( double u1, double v1, double u2, double v2 ) override;
bool SetLimit( double u1, double v1, double u2, double v2 ) override;
bool IsLineU() const override; // \ru Если true все производные по U выше первой равны нулю. \en If true, then all the derivatives by U higher the first one are equal to zero.
bool IsLineV() const override; // \ru Если true все производные по V выше первой равны нулю. \en If true, then all the derivatives by V higher the first one are equal to zero.
/** \} */
@@ -245,7 +245,8 @@ IMPL_PERSISTENT_OPS( MbExtrusionSurface )
//------------------------------------------------------------------------------
// \ru Проверить параметры. \en Check parameters.
// ---
inline void MbExtrusionSurface::CheckParam( double & u, double & v ) const
inline
void MbExtrusionSurface::CheckParam( double & u, double & v ) const
{
if ( u < umin ) {
if ( uclosed ) {
@@ -255,7 +256,6 @@ inline void MbExtrusionSurface::CheckParam( double & u, double & v ) const
else
u = umin;
}
if ( u > umax ) {
if ( uclosed ) {
double uRgn = ( umax - umin );
+2
View File
@@ -671,6 +671,8 @@ protected:
void InitFilletSurface ( const MbFilletSurface & init );
void CalculateCurve( double wmin, double wmax, bool insertPoints );
double CalculateVParam( const MbCartPoint3D & p, double u ) const; // \ru Нахождение параметра v проекции точки на вырожденную поверхность \en Searching of v parameter of point projection onto degenerate surface
bool IsSimilarToFillet( const MbFilletSurface & surf, VERSION version, double precision ) const; // \ru Подобные ли поверхности для объединения (слива). \en Whether the surfaces to union (joining) are similar.
protected:
// \ru Вычисление точки \en Calculation of a point
+1
View File
@@ -48,6 +48,7 @@ enum MbeMeshSurfaceVersion {
msv_Ver3, ///< \ru Третья версия. \en The third version.
msv_Ver4, ///< \ru Четвертая версия. \en The fourth version.
msv_Ver5, ///< \ru Пятая версия. \en The fifth version.
msv_Ver6, ///< \ru Шестая версия. \en The sixth version.
msv_Count ///< \ru Количество версий. \en Count of versions.
};
+1 -1
View File
@@ -329,7 +329,7 @@ public:
size_t GetVMeshCount() const override; // \ru Выдать количество полигонов по v. \en Get the count of polygons by v.
// \ru Определение параметрической области поверхности. \en Returns parametric region of surface.
void SetLimit( double u1, double v1, double u2, double v2 ) override;
bool SetLimit( double u1, double v1, double u2, double v2 ) override;
void IncludePoint ( double u, double v ) override; // \ru Включить точку в область определения. \en Include point into domain.
MbSplineSurface * NurbsSurface( double, double, double, double, bool bmatch = false ) const override; // \ru NURBS копия поверхности. \en NURBS copy of a surface.
+1 -1
View File
@@ -356,7 +356,7 @@ public:
void CalculateGabarit( MbCube &gab ) const override; // \ru Выдать габарит поверхности. \en Get bounding box of surface.
void CalculateLocalGabarit( const MbMatrix3D &, MbCube & ) const override; // \ru Рассчитать габарит относительно л.с.к. \en Calculate bounding box relative to the local coordinate system.
void SetLimit( double u1, double v1, double u2, double v2 ) override;
bool SetLimit( double u1, double v1, double u2, double v2 ) override;
void SetExtendedParamRegion( double u1, double v1, double u2, double v2 ) override;
void IncludePoint( double u, double v ) override; // \ru Включить точку в область определения. \en Include a point into domain.
+58 -32
View File
@@ -15,6 +15,7 @@
#include <templ_dptr.h>
#include <mb_placement3d.h>
#include <mb_matrix3d.h>
#include <curve3d.h>
#include <tool_multithreading.h>
@@ -43,16 +44,16 @@ class MATH_CLASS MbOffsetSurface;
*/ // ---
class MATH_CLASS MbRevolutionSurface : public MbSweptSurface {
private:
MbPlacement3D position; ///< \ru Местная система координат (position.axisZ - ось вращения). \en Local coordinate system ('position.axisZ' is rotation axis).
double uPoleMin; ///< \ru Значение параметра U в полюсе поверхности, если он есть. \en A value of U parameter in the pole of a surface if it exists.
double uPoleMax; ///< \ru Значение параметра U в полюсе поверхности, если он есть. \en A value of U parameter in the pole of a surface if it exists.
bool poleMin; ///< \ru Наличие полюса при umin. \en Existence of a pole at umin.
bool poleMax; ///< \ru Наличие полюса при umax. \en Existence of a pole at umax.
bool planeData; ///< \ru Кривая лежит в плоскости, содержащей ось вращения, (частный случай). \en A curve is located on a plane which contains the rotation axis (special case).
MbMatrix3D into; ///< \ru Матрица преобразования в систему position. \en Matrix of transformation to the system 'position'.
MbMatrix3D from; ///< \ru Матрица преобразования из системы position. \en Matrix of transformation from the system 'position'.
double uMinNormDelta; ///< \ru Величина отступа от минимального параметра u при подсчете нормали в полюсе. \en A value of indent from the minimum value of u in the calculation of normal vector in pole.
double uMaxNormDelta; ///< \ru Величина отступа от максимального параметра u при подсчете нормали в полюсе. \en A value of indent from the maximum value of u in the calculation of normal vector in pole.
MbPlacement3D position; ///< \ru Местная система координат (position.axisZ - ось вращения). \en Local coordinate system ('position.axisZ' is rotation axis).
double uPoleMin; ///< \ru Значение параметра U в полюсе поверхности, если он есть. \en A value of U parameter in the pole of a surface if it exists.
double uPoleMax; ///< \ru Значение параметра U в полюсе поверхности, если он есть. \en A value of U parameter in the pole of a surface if it exists.
bool poleMin; ///< \ru Наличие полюса при umin. \en Existence of a pole at umin.
bool poleMax; ///< \ru Наличие полюса при umax. \en Existence of a pole at umax.
bool planeData; ///< \ru Кривая лежит в плоскости, содержащей ось вращения, (частный случай). \en A curve is located on a plane which contains the rotation axis (special case).
MbMatrix3D into; ///< \ru Матрица преобразования в систему position. \en Matrix of transformation to the system 'position'.
MbMatrix3D from; ///< \ru Матрица преобразования из системы position. \en Matrix of transformation from the system 'position'.
double uMinNormDelta; ///< \ru Величина отступа от минимального параметра u при подсчете нормали в полюсе. \en A value of indent from the minimum value of u in the calculation of normal vector in pole.
double uMaxNormDelta; ///< \ru Величина отступа от максимального параметра u при подсчете нормали в полюсе. \en A value of indent from the maximum value of u in the calculation of normal vector in pole.
protected:
//------------------------------------------------------------------------------
@@ -126,7 +127,7 @@ public:
protected:
MbRevolutionSurface( const MbRevolutionSurface &, MbRegDuplicate * );
private:
// \ru Конструктор для создания эквидистанты \en Constructor for offset creation
// \ru Конструктор для создания эквидистанты. \en Constructor for offset creation.
MbRevolutionSurface( const MbRevolutionSurface &, MbCurve3D & offsetCurve, bool same );
public:
virtual ~MbRevolutionSurface();
@@ -262,7 +263,7 @@ public:
MbeParamDir GetFilletDirection( double accuracy = METRIC_REGION ) const override; // \ru Направление поверхности скругления. \en Direction of fillet surface.
ThreeStates Salient() const override; // \ru Выпуклая ли поверхность. \en Whether a surface is convex.
bool GetCylinderAxis( MbAxis3D & axis ) const override; // \ru Дать ось поверхности. \en Get the axis of a surface.
bool GetCenterLines( std::vector<MbCurve3D *> & clCurves ) const override; // \ru Дать осевые (центральные) линии для поверхности. \en Get center lines of a surface.
bool GetCenterLines( c3d::SpaceCurvesVector & clCurves ) const override; // \ru Дать осевые (центральные) линии для поверхности. \en Get center lines of a surface.
// \ru Определение разбивки параметрической области поверхности вертикалями и горизонталями. \en Determine a splitting of parametric region of a surface by verticals and horizontals.
void GetTesselation( const MbStepData & stepData,
double u1, double u2, double v1, double v2,
@@ -274,7 +275,7 @@ public:
bool IsRectangular() const override; // \ru Если true производные по u и v ортогональны. \en If true then derivatives with respect to u and v are orthogonal.
bool IsLineU() const override; // \ru Если true все производные по U выше первой равны нулю. \en If it equals true then all derivatives with respect to u which have more than first order are equal to null.
void SetLimit( double u1, double v1, double u2, double v2 ) override;
bool SetLimit( double u1, double v1, double u2, double v2 ) override;
/** \} */
/** \ru \name Функции поверхности вращения
\en \name Function of revolution surface.
@@ -333,8 +334,8 @@ private: // \ru Внутренние функции поверхности. \en
void InitPosition( const MbCartPoint3D & origin, const MbVector3D & axisZ );
void ExactNormal( double u, double v, const MbVector3D & derU, const MbVector3D & derV, MbVector3D & nor ) const; // \ru Нормаль. \en Normal.
void CheckPoles(); // \ru Проверить полюса. \en Check poles.
inline void CheckParam ( double &u, double &v ) const; // \ru Проверить параметры. \en Check parameters.
inline void CheckParam_( double &u ) const; // \ru Проверить параметр. \en Check parameter.
inline void CheckParam ( double & u, double & v ) const; // \ru Проверить параметры. \en Check parameters.
inline void CheckParam_( double & u ) const; // \ru Проверить параметр. \en Check parameter.
inline void RotateVector ( double sinV, double cosV, MbVector3D & v ) const;
inline void RotateDeriveV ( double sinV, double cosV, MbVector3D & v ) const;
inline void RotateDeriveVV ( double sinV, double cosV, MbVector3D & v ) const;
@@ -348,11 +349,12 @@ IMPL_PERSISTENT_OPS( MbRevolutionSurface )
//------------------------------------------------------------------------------
// \ru Проверить параметры \en Check parameters
// \ru Проверить параметры. \en Check parameters.
// ---
inline void MbRevolutionSurface::CheckParam ( double & u, double & v ) const
inline
void MbRevolutionSurface::CheckParam( double & u, double & v ) const
{
if (v < vmin) {
if ( v < vmin ) {
if ( vclosed )
v -= ( ::floor((v - vmin) * Math::invPI2) * M_PI2 );
else
@@ -364,17 +366,37 @@ inline void MbRevolutionSurface::CheckParam ( double & u, double & v ) const
else
v = vmax;
}
if ( poleMin && (u < umin) )
u = umin;
if ( poleMax && (u > umax) )
u = umax;
if ( u < umin ) { // KOMPAS-71035
if ( uclosed ) {
double uRgn = (umax - umin);
u -= (::floor( (u - umin) / uRgn ) * uRgn);
}
else
u = umin;
}
if ( u > umax ) { // KOMPAS-71035
if ( uclosed ) {
double uRgn = (umax - umin);
u -= (::floor( (u - umin) / uRgn ) * uRgn);
}
else
u = umax;
}
// KOMPAS-71035
// if ( poleMin && (u < umin) )
// u = umin;
// if ( poleMax && (u > umax) )
// u = umax;
}
//------------------------------------------------------------------------------
// \ru Проверить параметры \en Check parameters
// \ru Проверить параметр. \en Check parameter.
// ---
inline void MbRevolutionSurface::CheckParam_( double & u ) const
inline
void MbRevolutionSurface::CheckParam_( double & u ) const
{
if ( poleMin && (u < umin) )
u = umin;
@@ -394,9 +416,10 @@ inline void MbRevolutionSurface::CheckParam_( double & u ) const
//------------------------------------------------------------------------------
// \ru Поворот вектора вокруг оси спирали \en Rotation of vector around spiral axis
// \ru Поворот вектора вокруг оси спирали. \en Rotation of vector around spiral axis.
// ---
inline void MbRevolutionSurface::RotateVector( double sinV, double cosV, MbVector3D & _vector ) const
inline
void MbRevolutionSurface::RotateVector( double sinV, double cosV, MbVector3D & _vector ) const
{
// if ( planeData ) {
// double r = _vector * axisX;
@@ -415,9 +438,10 @@ inline void MbRevolutionSurface::RotateVector( double sinV, double cosV, MbVecto
//-------------------------------------------------------------------------------
// \ru Первая производная поворота вектора вокруг оси спирали \en First derivative of vector of rotation around the spiral axis
// \ru Первая производная поворота вектора вокруг оси спирали. \en First derivative of vector of rotation around the spiral axis.
// ---
inline void MbRevolutionSurface::RotateDeriveV( double sinV, double cosV, MbVector3D & _vector ) const
inline
void MbRevolutionSurface::RotateDeriveV( double sinV, double cosV, MbVector3D & _vector ) const
{
// if ( planeData ) {
// double r = _vector * axisX;
@@ -437,9 +461,10 @@ inline void MbRevolutionSurface::RotateDeriveV( double sinV, double cosV, MbVect
//-------------------------------------------------------------------------------
// \ru Вторая производная поворота вектора вокруг оси спирали \en Second derivative of vector of rotation around spiral axis
// \ru Вторая производная поворота вектора вокруг оси спирали. \en Second derivative of vector of rotation around spiral axis.
// ---
inline void MbRevolutionSurface::RotateDeriveVV( double sinV, double cosV, MbVector3D & _vector ) const
inline
void MbRevolutionSurface::RotateDeriveVV( double sinV, double cosV, MbVector3D & _vector ) const
{
// if ( planeData ) {
// double r = _vector * axisX;
@@ -459,9 +484,10 @@ inline void MbRevolutionSurface::RotateDeriveVV( double sinV, double cosV, MbVec
//-------------------------------------------------------------------------------
// \ru Третья производная поворота вектора вокруг оси спирали \en Third derivative of vector of rotation around spiral axis
// \ru Третья производная поворота вектора вокруг оси спирали. \en Third derivative of vector of rotation around spiral axis.
// ---
inline void MbRevolutionSurface::RotateDeriveVVV( double sinV, double cosV, MbVector3D & _vector ) const
inline
void MbRevolutionSurface::RotateDeriveVVV( double sinV, double cosV, MbVector3D & _vector ) const
{
// if ( planeData ) {
// double r = _vector * axisX;
+3
View File
@@ -381,6 +381,9 @@ public:
/// \ru Определить, выпуклая ли поверхность. \en Determine whether the surface is convex.
ThreeStates Salient() const override;
/// \ru Касается ли поверхность опорных граней? \en Does the surface tangent with its reference faces?
bool IsSurfaceTangent() const { return ( sform == st_Fillet || sform == st_Span ) && ( form == cs_Conic || form == cs_Cubic ); }
// \ru Определение разбивки параметрической области поверхности вертикалями и горизонталями. \en Determine splitting of parametric region of surface by vertical and horizontal lines.
void GetTesselation( const MbStepData & stepData,
double u1, double u2, double v1, double v2,
+1 -1
View File
@@ -242,7 +242,7 @@ public:
void CalculateGabarit( MbCube & ) const override; // \ru Выдать габарит. \en Get bounding box.
void CalculateLocalGabarit( const MbMatrix3D &, MbCube & ) const override; // \ru Рассчитать габарит относительно л.с.к. \en Calculate bounding box relative to the local coordinate system.
void SetLimit( double u1, double v1, double u2, double v2 ) override;
bool SetLimit( double u1, double v1, double u2, double v2 ) override;
void SetExtendedParamRegion( double u1, double v1, double u2, double v2 ) override;
void IncludePoint( double u, double v ) override; // \ru Включить точку в область определения. \en Include a point into domain.
// \ru Существует ли полюс на границе параметрической области. \en Whether a pole exists on parametric region boundary.
+1 -1
View File
@@ -468,7 +468,7 @@ public:
double u1, double u2, double v1, double v2,
SArray<double> & uu, SArray<double> & vv ) const override;
void SetLimit( double u1, double v1, double u2, double v2 ) override;
bool SetLimit( double u1, double v1, double u2, double v2 ) override;
/** \brief \ru Проверить параметры. Аналог глобальной функции _CheckParams, оптимизированный под использование кэшей.
\en Check parameters. Analogue of the global function _CheckParams, optimized for caches usage. \~
+1 -1
View File
@@ -259,7 +259,7 @@ public:
double u1, double u2, double v1, double v2,
SArray<double> & uu, SArray<double> & vv ) const override;
void SetLimit( double u1, double v1, double u2, double v2 ) override;
bool SetLimit( double u1, double v1, double u2, double v2 ) override;
void SetExtendedParamRegion( double u1, double v1, double u2, double v2 ) override;
void IncludePoint( double u, double v ) override; // \ru Включить точку в область определения. \en Include a point into domain.
+2 -2
View File
@@ -1588,9 +1588,9 @@ public:
MbCurve & MakeCurve( size_t number1, size_t number2 ) const;
/// \ru Установить пределы поверхности. Для внутреннего использования. \en Set surface limits. For internal use only.
virtual void SetLimit( double u1, double v1, double u2, double v2 );
virtual bool SetLimit( double u1, double v1, double u2, double v2 );
/// \ru Установить пределы поверхности. Для внутреннего использования. \en Set surface limits. For internal use only.
void SetLimit( const MbRect & );
bool SetLimit( const MbRect & );
/// \ru Установить расширенные пределы поверхности. Для внутреннего использования. \en Set extended limits of surface. For internal use only.
virtual void SetExtendedParamRegion( double u1, double v1, double u2, double v2 );
+3 -3
View File
@@ -59,7 +59,7 @@ typedef uint32 COLORREF;
// ---
inline uint8 GetRValue(COLORREF rgb_color)
{
return (uint8) (rgb_color);
return static_cast<uint8>(rgb_color);
}
@@ -68,7 +68,7 @@ inline uint8 GetRValue(COLORREF rgb_color)
// ---
inline uint8 GetGValue(COLORREF rgb_color)
{
return (uint8) (rgb_color >> 8);
return static_cast<uint8>(rgb_color >> 8);
}
@@ -77,7 +77,7 @@ inline uint8 GetGValue(COLORREF rgb_color)
// ---
inline uint8 GetBValue(COLORREF rgb_color)
{
return (uint8) (rgb_color >> 16);
return static_cast<uint8>(rgb_color >> 16);
}
+5 -5
View File
@@ -141,11 +141,11 @@ constexpr int32 SYS_MAX_INT32 = 0x7FFFFFFF; //-V
constexpr int64 SYS_MAX_INT64 = 0x7FFFFFFFFFFFFFFF; //-V112
/// \ru Минимальное значение int16. \en Minimum value of int16. \~ \ingroup Base_Tools
constexpr int16 SYS_MIN_INT16 = (int16)(uint16)0x8000; //-V112
constexpr int16 SYS_MIN_INT16 = static_cast<int16>( static_cast<uint16>(0x8000) );
/// \ru Минимальное значение int32. \en Minimum value of int32. \~ \ingroup Base_Tools
constexpr int32 SYS_MIN_INT32 = (int32)(uint32)0x80000000; //-V112
constexpr int32 SYS_MIN_INT32 = static_cast<int32>( static_cast<uint32>(0x80000000) );
/// \ru Минимальное значение int64. \en Minimum value of int64. \~ \ingroup Base_Tools
constexpr int64 SYS_MIN_INT64 = (int64)(uint64)0x8000000000000000; //-V112
constexpr int64 SYS_MIN_INT64 = static_cast<int64>( static_cast<uint64>(0x8000000000000000) );
//#endif // NOMINMAX
@@ -159,7 +159,7 @@ inline uint16 MkUint16( uint8 lo, uint8 hi ) { return uint16(lo | (uint16(hi)
/// \ru Создать uint32 на основе двух uint16. \en Create uint32 by two uint16. \~ \ingroup Base_Tools
inline uint32 MkUint32( uint16 lo, uint16 hi ) { return lo | (uint32(hi) << 16); } //-V112
/// \ru Создать uint64 на основе двух uint32. \en Create uint64 by two uint32. \~ \ingroup Base_Tools
inline uint64 MkUint64( uint32 lo, uint32 hi ) { return uint64((uint64)lo | (uint64(hi) << 32)); } //OV_x64 //-V112
inline uint64 MkUint64( uint32 lo, uint32 hi ) { return uint64(static_cast<uint64>(lo) | (uint64(hi) << 32)); } //OV_x64 //-V112
/// \ru Выделить младшее слово uint32 из uint64. \en Get lower uint32 word from uint64. \~ \ingroup Base_Tools
inline uint32 LoUint32( uint64 u64 ) { return uint32(u64); } //OV_x64
@@ -197,7 +197,7 @@ constexpr size_t NSIZE = SYS_MAX_T; //OV_x64 (size_t)-1;
//------------------------------------------------------------------------------
/// \ru Неопределенная позиция (для 32 битных данных). \en Undefined position (for 32-bit data). \~ \ingroup Base_Tools
//---
constexpr uint NPOS32 = (uint)SYS_MAX_UINT32; // \ru КВН x64 -1 для работы с таблицами \en КВН x64 -1 for dealing with tables
constexpr uint NPOS32 = static_cast<uint>(SYS_MAX_UINT32); // \ru КВН x64 -1 для работы с таблицами \en КВН x64 -1 for dealing with tables
//------------------------------------------------------------------------------
+3 -3
View File
@@ -219,7 +219,7 @@ inline Type* FDPArray<Type>::RemoveInd( size_t delIndex, DelType del ) {
if ( delIndex < RPArray<Type>::count ) {
const Type ** d = RPArray<Type>::GetAddr() + delIndex;
r = (Type *)*d;
r = const_cast<Type *>(*d);
// \ru сначала приведем в порядок массив ... \en put an array in order at first ...
memmove( d, d + 1, (RPArray<Type>::count - delIndex - 1) * SIZE_OF_POINTER );
@@ -264,7 +264,7 @@ inline Type* FDPArray<Type>::DestroyInd( size_t delIndex, typename FDPArray<Type
if ( delIndex < RPArray<Type>::count ) {
const Type ** d = RPArray<Type>::GetAddr() + delIndex;
r = (Type *)*d;
r = const_cast<Type *>(*d);
// \ru сначала приведем в порядок массив ... \en put an array in order at first ...
memmove( d, d + 1, (RPArray<Type>::count - delIndex - 1) * SIZE_OF_POINTER );
@@ -311,7 +311,7 @@ void destroy_array( FDPArray<Type> & arr )
size_t i = 0;
for ( const Type **parr = arr.GetAddr(); i < oldCount; i++, parr++ ) {
Type *del = (Type*)*parr;
Type *del = const_cast<Type*>(*parr);
*parr = 0; // \ru сначала обнулить... \en set to null at first...
PRECONDITION( !del || arr.nowDeletedElem != del ); // \ru Временно, для отладки \en Temporarily, for debugging.
+1 -1
View File
@@ -51,7 +51,7 @@ protected:
T * P;
private:
void * operator new( size_t ); // prohibit use of new
void operator delete( void * p ) { ((TPointerBase<T>*)p)->P = nullptr; }
void operator delete( void * p ) { (static_cast<TPointerBase<T>*>(p))->P = nullptr; }
// СМВ К15 MVS 2012
private:
+12 -12
View File
@@ -97,7 +97,7 @@ public:
size_t FindIt ( const Type * ) const; ///< \ru Найти элемент по указателю. \en Find an element by a pointer.
bool IsExist( const Type * ) const; ///< \ru Есть ли элемент в массиве. \en Whether an element belongs the array.
size_t Count() const { return count; } ///< \ru Получить количество элементов массива. \en Get the number of array elements.
ptrdiff_t MaxIndex() const { return ((ptrdiff_t)count - 1); } ///< \ru Получить индекс последнего объект в массиве. \en Get the index of the last element in the array.
ptrdiff_t MaxIndex() const { return ( static_cast<ptrdiff_t>(count) - 1); } ///< \ru Получить индекс последнего объект в массиве. \en Get the index of the last element in the array.
typedef int (*CompFunc)( const Type **, const Type ** ); ///< \ru Шаблон функции сортировки. \en A template of sorting function.
void Sort ( CompFunc comp ); ///< \ru Сортировать массив. \en Sort the array.
@@ -105,7 +105,7 @@ public:
/// \ru Оператор доступа по индексу. \en Access by index operator.
Type *& operator []( size_t loc ) const;
/// \ru Получить адрес последнего элемента в массиве. \en Get the address of the last element in the array.
Type * GetLast() const { return ((count > 0) ? parr[count-1] : (Type*)nullptr); }
Type * GetLast() const { return ((count > 0) ? parr[count-1] : static_cast<Type*>(nullptr)); }
public: // \ru унификация с вектором STL \en unification with STL vector
bool empty() const { return count == 0; }
@@ -138,7 +138,7 @@ public: // \ru унификация с вектором STL \en unification with
reference at( size_t idx );
protected:
const Type ** GetAddr() const { return (const Type **)parr; } ///< \ru Получить указатель на первый элемент массива. \en Get the pointer to the first array element.
const Type ** GetAddr() const { return const_cast<const Type **>(parr); } ///< \ru Получить указатель на первый элемент массива. \en Get the pointer to the first array element.
const TPtr * _Begin() const { return parr; } ///< \ru Получить указатель на первый элемент массива. \en Get the pointer to the first array element.
TPtr * _Begin() { return parr; } ///< \ru Получить указатель на первый элемент массива. \en Get the pointer to the first array element.
const TPtr * _End() const { return parr + count; } ///< \ru Получить указатель на участок памяти после массива. \en Get the pointer to the piece of memory after the array.
@@ -555,8 +555,8 @@ void RPArray<Type>::insert( Iterator pos, const Type * e )
pos = begin();
}
if ( begin() ) {
const ptrdiff_t k = std::distance( (Iterator)begin(), pos );
if ( k >= 0 && k <= (ptrdiff_t)count )
const ptrdiff_t k = std::distance( static_cast<Iterator>(begin()), pos );
if ( k >= 0 && k <= static_cast<ptrdiff_t>(count) )
Insert( k, const_cast<Type *>(e) );
}
}
@@ -570,8 +570,8 @@ template <class Iterator>
void RPArray<Type>::erase( Iterator pos )
{
if ( begin() ) {
const ptrdiff_t k = std::distance( (Iterator)begin(), pos );
if ( k >= 0 && k < (ptrdiff_t)count )
const ptrdiff_t k = std::distance( static_cast<Iterator>(begin()), pos );
if ( k >= 0 && k < static_cast<ptrdiff_t>(count) )
RemoveInd( k );
}
}
@@ -585,10 +585,10 @@ template <class Iterator>
void RPArray<Type>::erase( Iterator first, Iterator last )
{
if ( begin() ) {
const ptrdiff_t k1 = std::distance( (Iterator)begin(), first );
const ptrdiff_t k2 = std::distance( (Iterator)begin(), last );
const ptrdiff_t k1 = std::distance( static_cast<Iterator>(begin()), first );
const ptrdiff_t k2 = std::distance( static_cast<Iterator>(begin()), last );
if ( k1 >= 0 && k1 < k2 && k2 <= (ptrdiff_t)count ) {
if ( k1 >= 0 && k1 < k2 && k2 <= static_cast<ptrdiff_t>(count) ) {
for ( ptrdiff_t k = k2-1; k >= k1; k-- ) {
RemoveInd( k );
}
@@ -641,7 +641,7 @@ inline bool RPArray<Type>::CatchMemory() {
// --- !!!!!!!!!!
template <class Type>
inline void RPArray<Type>::Sort( CompFunc fcmp ) {
::KsQSort( (void *)parr, count, SIZE_OF_POINTER, (KsQSortCompFunc)fcmp );
::KsQSort( static_cast<void *>(parr), count, SIZE_OF_POINTER, reinterpret_cast<KsQSortCompFunc>(fcmp) );
}
@@ -741,7 +741,7 @@ size_t find_in_array( const RPArray<const Type> & arr, const Type * el ) {
inline uint16 CalcArrayDelta( size_t objsCount ) {
size_t delta = objsCount / 100;
delta = delta > 65000 ? 50000 : delta > 0 ? delta : 1;
return (uint16)delta;
return static_cast<uint16>(delta);
}
+18 -18
View File
@@ -116,7 +116,7 @@ public:
size_t FindIt ( const Type & ) const; ///< \ru Вернуть индекс элемента в массиве. \en Return an index of the element in the array.
bool IsExist ( const Type & ) const; ///< \ru true если элемент найден. \en true if the element is found.
size_t Count() const { return count; } ///< \ru Дать количество элементов массива. \en Get the number of elements in array.
ptrdiff_t MaxIndex() const { return ((ptrdiff_t)count - 1); } ///< \ru Дать количество элементов массива. \en Get the number of elements in array.
ptrdiff_t MaxIndex() const { return ( static_cast<ptrdiff_t>(count) - 1); } ///< \ru Дать количество элементов массива. \en Get the number of elements in array.
bool SetCArray( const Type * o, size_t count ); ///< \ru Присвоить значения из c-массива. \en Assign the value from the c-array.
@@ -459,7 +459,7 @@ inline Type * SArray<Type>::AddAfter( const Type & ent, size_t index ) {
memmove( parr + index + 2, parr + index + 1, sizeof(Type)*(count - index - 1) );
count++;
return (Type*)memcpy( parr + index + 1, &ent, sizeof(Type) );
return static_cast<Type*>( memcpy(parr + index + 1, &ent, sizeof(Type)) );
}
return nullptr;
}
@@ -481,7 +481,7 @@ inline Type * SArray<Type>::InsertInd( size_t index, const Type & ent ) {
}
count++;
return (Type*)memcpy( parr + index, &ent, sizeof(Type) ); // \ru записываем новый элемент \en writing new element
return static_cast<Type*>( memcpy(parr + index, &ent, sizeof(Type)) ); // \ru записываем новый элемент \en writing new element
}
return nullptr;
}
@@ -499,7 +499,7 @@ inline Type * SArray<Type>::InsertInd( size_t index ) {
memmove( parr + index + 1, parr + index, (count - index) * sizeof(Type) );
count++;
return (Type*)( parr + index ); // \ru записываем новый элемент \en writing new element
return static_cast<Type*>( parr + index ); // \ru записываем новый элемент \en writing new element
}
return nullptr;
}
@@ -572,8 +572,8 @@ void SArray<Type>::insert( Iterator pos, const Type & e )
pos = begin();
}
if ( begin() ) {
const ptrdiff_t k = std::distance( (Iterator)begin(), pos );
if ( k >= 0 && k <= (ptrdiff_t)count )
const ptrdiff_t k = std::distance( static_cast<Iterator>(begin()), pos );
if ( k >= 0 && k <= static_cast<ptrdiff_t>(count) )
InsertInd( k, e );
}
}
@@ -587,8 +587,8 @@ template <class Iterator>
void SArray<Type>::erase( Iterator pos )
{
if ( begin() ) {
const ptrdiff_t k = std::distance( (Iterator)begin(), pos );
if ( k >= 0 && k < (ptrdiff_t)count )
const ptrdiff_t k = std::distance( static_cast<Iterator>(begin()), pos );
if ( k >= 0 && k < static_cast<ptrdiff_t>(count) )
RemoveInd( k );
}
}
@@ -601,10 +601,10 @@ template <class Iterator>
void SArray<Type>::erase( Iterator first, Iterator last )
{
if ( begin() ) {
const ptrdiff_t k1 = std::distance( (Iterator)begin(), first );
const ptrdiff_t k2 = std::distance( (Iterator)begin(), last );
const ptrdiff_t k1 = std::distance( static_cast<Iterator>(begin()), first );
const ptrdiff_t k2 = std::distance( static_cast<Iterator>(begin()), last );
if ( k1 >= 0 && k1 < k2 && k2 <= (ptrdiff_t)count ) {
if ( k1 >= 0 && k1 < k2 && k2 <= static_cast<ptrdiff_t>(count) ) {
RemoveInd( k1, k2 );
}
}
@@ -627,7 +627,7 @@ inline void SArray<Type>::RemoveInd( size_t firstIdx, size_t lastIdx ) {
template <class Type>
inline void SArray<Type>::Remove( Type * firstItr, Type * lastItr )
{
PRECONDITION( firstItr >= parr && firstItr < lastItr && (lastItr - parr) <= (ptrdiff_t)count );
PRECONDITION( firstItr >= parr && firstItr < lastItr && (lastItr - parr) <= static_cast<ptrdiff_t>(count) );
if ( firstItr >= parr && firstItr < lastItr ) {
ptrdiff_t copyCount = ( parr + count ) - lastItr;
if ( copyCount >= 0 ) {
@@ -770,7 +770,7 @@ inline bool SArray<Type>::CatchMemory() {
// ---
template <class Type>
inline void SArray<Type>::Sort( CompFunc fcmp ) {
::KsQSort( (void *)parr, count, sizeof(Type), (KsQSortCompFunc)fcmp );
::KsQSort( static_cast<void *>(parr), count, sizeof(Type), reinterpret_cast<KsQSortCompFunc>(fcmp) );
}
@@ -784,7 +784,7 @@ void SArray<Type>::assign( Iterator first, Iterator last )
{
const ptrdiff_t newCount = std::distance( first, last );
if ( set_array_size(*this, newCount, true) ) {
PRECONDITION( newCount <= (ptrdiff_t)upper && count == 0 );
PRECONDITION( newCount <= static_cast<ptrdiff_t>(upper) && count == 0 );
for ( ; first != last; ++first, ++count ) {
parr[count] = *first; // SKIP_SA
}
@@ -825,9 +825,9 @@ bool set_array_size( SArray<Type> & arr, size_t newSize, bool clear )
#else
//YYK V15 #77319 Type * p_tmp = newSize ? (Type*)new char[ newSize * sizeOfType ] : 0;
#ifdef C3D_WINDOWS //_MSC_VER // win
Type * p_tmp = newSize ? (Type*)_aligned_malloc( newSize * sizeOfType, 16 ) : nullptr;
Type * p_tmp = newSize ? static_cast<Type*>( _aligned_malloc(newSize * sizeOfType, 16) ) : nullptr;
#else
Type * p_tmp = newSize ? (Type*)new char[newSize * sizeOfType] : 0;
Type * p_tmp = newSize ? reinterpret_cast<Type*>(new char[newSize * sizeOfType]) : 0;
#endif // win
if ( !clear && arr.parr && p_tmp )
@@ -838,7 +838,7 @@ bool set_array_size( SArray<Type> & arr, size_t newSize, bool clear )
#ifdef C3D_WINDOWS //_MSC_VER // win
_aligned_free( arr.parr );
#else
delete[](char *) arr.parr;
delete[]reinterpret_cast<char *>( arr.parr );
#endif // win
arr.parr = p_tmp;
@@ -994,7 +994,7 @@ bool fill_array_zero( SArray<Type> & arr, size_t fillCount, size_t startIndex )
bool res = arr.AddMemory( fillCount + startIndex ); // \ru обеспечить память на такое кол-во элементов \en allocate memory for the given number of elements
if ( res ) {
arr.count = fillCount + startIndex; // \ru установить размер массива \en set the size of the array
memset( (void*)&arr[startIndex], 0, fillCount * sizeof(Type) );
memset( static_cast<void*>(&arr[startIndex]), 0, fillCount * sizeof(Type) );
}
return res;
}
+4 -4
View File
@@ -597,7 +597,7 @@ inline void SFDPArray<Type>::Sort( size_t /*OV_x64 int*/ minInd /*= -1*/, size_t
do {
while( (*fCompare)(*((*this)[i]), *middle ) == -1 ) i++;
while( (*fCompare)( *middle, *(*this)[j]) == -1 ) j--;
if ( (ptrdiff_t)i <= (ptrdiff_t)j ) {
if ( static_cast<ptrdiff_t>(i) <= static_cast<ptrdiff_t>(j) ) {
if ( i != j ) {
Type * wi = (*this)[i];
(*this)[i] = (*this)[j];
@@ -606,12 +606,12 @@ inline void SFDPArray<Type>::Sort( size_t /*OV_x64 int*/ minInd /*= -1*/, size_t
i++;
j--;
}
} while( !((ptrdiff_t)i > (ptrdiff_t)j) );
} while( !(static_cast<ptrdiff_t>(i) > static_cast<ptrdiff_t>(j)) );
if ( (ptrdiff_t)minInd < (ptrdiff_t)j )
if ( static_cast<ptrdiff_t>(minInd) < static_cast<ptrdiff_t>(j) )
Sort( minInd, j );
if ( (ptrdiff_t)i < (ptrdiff_t)maxInd )
if ( static_cast<ptrdiff_t>(i) < static_cast<ptrdiff_t>(maxInd) )
Sort( i, maxInd );
}
+3 -3
View File
@@ -153,7 +153,7 @@ inline bool SSArray<Type>::operator < ( const SSArray<Type> & w ) const {
// \ru нам никчему, будем сравнивать содержимое массивов поэлементно (через оператор < объекта) \en we will compare the content of arrays element by element (using the operator < of an object)
for ( size_t i = 0, c = std_min(SArray<Type>::count, w.count); i < c; i++ ) {
if ( !((*this)[i] == w[i]) )
return (bool)((*this)[i] < w[i]);
return static_cast<bool>((*this)[i] < w[i]);
}
if ( SArray<Type>::count != w.count )
@@ -258,7 +258,7 @@ Type * add_to_array( SSArray<Type> & arr, const Type & el, size_t & indexEl )
}
mx = md;
}
else if ( mdE == (Type&)el ) {
else if ( mdE == const_cast<Type&>(el) ) {
indexEl = md;
return 0;
}
@@ -447,7 +447,7 @@ size_t find_from_array_spec( const SSArray<Type> & arr, const Type & el, bool &
mn = md;
else if ( el < arr/*.parr*/[md] )
mx = md;
else if ( arr/*.parr*/[md] == (Type&)el ) {
else if ( arr/*.parr*/[md] == const_cast<Type&>(el) ) {
isPresent = true;
return md;
}
+4 -4
View File
@@ -100,8 +100,8 @@ inline void KsQSort( void * base,
if (num < 2 || width == 0)
return;
lowElem = (char *)base;
hiElem = (char *)base + width * (num-1);
lowElem = static_cast<char *>( base );
hiElem = static_cast<char *>( base ) + width * (num-1);
if ( num == 2 ) {
if ( compareFunc( lowElem, hiElem ) >= 0 )
@@ -250,7 +250,7 @@ void InsertSort( Type * base,
return;
}
for ( ptrdiff_t i = 1; i < (ptrdiff_t)num; ++i ) {
for ( ptrdiff_t i = 1; i < static_cast<ptrdiff_t>(num); ++i ) {
for ( ptrdiff_t j = i; j > 0 && compareFunc( base + j - 1, base + j ) >= 0; j-- ) {
Swap<Type>( base, j - 1, j );
if ( base2 != nullptr ) {
@@ -439,7 +439,7 @@ inline int DoubleCompare( const double * first, const double * second ) {
//---
inline size_t KsAutoDelta( size_t count )
{
return std_min( (size_t)1024, std_max( (size_t)4, count / 8) ); //-V112
return std_min( static_cast<size_t>(1024), std_max( static_cast<size_t>(4), count / 8) ); //-V112
}
+1 -1
View File
@@ -416,7 +416,7 @@ inline uint16* Ucs4ToUtf16( uint32* source, size_t* calculateCountSymbol = nullp
if ( HiUint16( source[i] ) == 0 )
outBuf[i] = LoUint16( source[i] );
else
outBuf[i] = (uint16)'?';
outBuf[i] = static_cast<uint16>( '?' );
#else // __MOBILE_VERSION__
for ( size_t i = 0; i < count; ++i )
outBuf[i] = LoUint16( source[i] );
+1 -1
View File
@@ -105,7 +105,7 @@ public:
friend struct string_generator;
friend reader & CALL_DECLARATION operator >> ( reader & in, MbUuid & ref );
friend writer & CALL_DECLARATION operator << ( writer & out, const MbUuid & ref );
friend writer & CALL_DECLARATION operator << ( writer & out, MbUuid & ref ) { return operator << ( out, (const MbUuid &)ref ); }
friend writer & CALL_DECLARATION operator << ( writer & out, MbUuid & ref ) { return operator << ( out, const_cast<const MbUuid &>(ref) ); }
};
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.