1 Foundation Classes {#occt_user_guides__foundation_classes}
2 =================================
6 @section occt_fcug_1 Introduction
8 This manual explains how to use Open CASCADE Technology (**OCCT**) Foundation Classes.
9 It provides basic documentation on foundation classes.
11 Foundation Classes provide a variety of general-purpose services such as automated dynamic memory management (manipulation of objects by handle), collections, exception handling, genericity by down-casting and plug-in creation.
13 Foundation Classes include the following:
16 Root classes are the basic data types and classes on which all the other classes are built.
18 * fundamental types such as Boolean, Character, Integer or Real,
19 * safe handling of dynamically created objects, ensuring automatic deletion of unreferenced objects (see *Standard_Transient* class),
20 * standard and custom memory allocators,
21 * extended run-time type information (RTTI) mechanism facilitating the creation of complex programs,
22 * management of exceptions,
23 * encapsulation of C++ streams.
24 Root classes are mainly implemented in *Standard* package.
27 Strings are classes that handle dynamically sized sequences of characters based on UTF-8 and UTF-16 encodings.
28 Strings may also be manipulated by handles, and consequently be shared.
29 Strings are implemented in the *TCollection* package.
32 Collections are the classes that handle dynamically sized aggregates of data.
33 Collection classes are *generic* and rely on C++ templates.
35 Collections include a wide range of generic classes such as run-time sized arrays, lists, stacks, queues, sets and hash maps.
36 Collections are implemented in the *TCollection* and *NCollection* packages.
38 ### Collections of Standard Objects
40 The *TColStd* package provides frequently used instantiations of generic classes from the *TCollection* package with objects from the *Standard* package or strings from the *TCollection* package.
42 ### Vectors and Matrices
44 These classes provide commonly used mathematical algorithms and basic calculations (addition, multiplication, transposition, inversion, etc.) involving vectors and matrices.
46 ### Primitive Geometric Types
48 Open CASCADE Technology primitive geometric types are a STEP-compliant implementation of basic geometric and algebraic entities.
50 * Descriptions of elementary geometric shapes:
55 * Planes and elementary surfaces,
56 * Positioning of these shapes in space or in a plane by means of an axis or a coordinate system,
57 * Definition and application of geometric transformations to these shapes:
61 * Scaling transformations
62 * Composed transformations
63 * Tools (coordinates and matrices) for algebraic computation.
65 ### Common Math Algorithms
67 Open CASCADE Technology common math algorithms provide a C++ implementation of the most frequently used mathematical algorithms.
69 * Algorithms to solve a set of linear algebraic equations,
70 * Algorithms to find the minimum of a function of one or more independent variables,
71 * Algorithms to find roots of one, or of a set, of non-linear equations,
72 * Algorithms to find the eigen-values and eigen-vectors of a square matrix.
76 A hierarchy of commonly used exception classes is provided, all based on class Standard_Failure, the root of exceptions.
77 Exceptions describe exceptional situations, which can arise during the execution of a function.
78 With the raising of an exception, the normal course of program execution is abandoned.
79 The execution of actions in response to this situation is called the treatment of the exception.
83 These are various classes supporting date and time information.
85 ### Application services
87 Foundation Classes also include implementation of several low-level services that facilitate the creation of customizable and user-friendly applications with Open CASCADE Technology.
89 * Unit conversion tools, providing a uniform mechanism for dealing with quantities and associated physical units:
90 check unit compatibility, perform conversions of values between different units and so on (see package *UnitsAPI*);
91 * Basic interpreter of expressions that facilitates the creation of customized scripting tools, generic definition of expressions and so on (see package *ExprIntrp*);
92 * Tools for dealing with configuration resource files (see package *Resource*) and customizable message files (see package *Message*), making it easy to provide a multi-language support in applications;
93 * Progress indication and user break interfaces, giving a possibility even for low-level algorithms to communicate with the user in a universal and convenient way.
95 @section occt_fcug_2 Basics
96 This chapter deals with basic services such as library organization, persistence, data types, memory management, programming with handles, exception handling, genericity by downcasting and plug-in creation.
98 @subsection occt_fcug_2_a Library organization
100 This chapter introduces some basic concepts, which are used not only in Foundation Classes, but throughout the whole OCCT library.
102 @subsubsection occt_fcug_2_a_1 Modules and toolkits
104 The whole OCCT library is organized in a set of modules.
105 The first module, providing most basic services and used by all other modules, is called Foundation Classes and described by this manual.
107 Every module consists primarily of one or several toolkits (though it can also contain executables, resource units etc.).
108 Physically a toolkit is represented by a shared library (e.g. .so or .dll).
109 The toolkit is built from one or several packages.
111 @subsubsection occt_fcug_2_a_2 Packages
112 A **package** groups together a number of classes which have semantic links.
113 For example, a geometry package would contain Point, Line, and Circle classes.
114 A package can also contain enumerations, exceptions and package methods (functions).
115 In practice, a class name is prefixed with the name of its package e.g. *Geom_Circle*.
116 Data types described in a package may include one or more of the following data types:
120 * Pointers to other object classes
121 Inside a package, two data types cannot bear the same name.
123 @figure{/user_guides/foundation_classes/images/foundation_classes_image003.png,"Contents of a package",420}
125 **Methods** are either **functions** or **procedures**.
126 Functions return an object, whereas procedures only communicate by passing arguments.
127 In both cases, when the transmitted object is an instance manipulated by a handle, its identifier is passed.
128 There are three categories of methods:
129 * **Object constructor** Creates an instance of the described class.
130 A class will have one or more object constructors with various different arguments or none.
131 * **Instance method** Operates on the instance which owns it.
132 * **Class method** Does not work on individual instances, only on the class itself.
134 @subsubsection occt_fcug_2_a_3 Classes
135 The fundamental software component in object-oriented software development is the class.
136 A class is the implementation of a **data type**.
137 It defines its **behavior** (the services offered by its functions) and its **representation** (the data structure of the class -- the fields, which store its data).
139 Classes fall into three categories:
142 An **abstract class** cannot be instantiated.
143 The purpose of having such classes is to have a given behavior shared by a hierarchy of classes and dependent on the implementation of the descendants.
144 This is a way of guaranteeing a certain base of inherited behavior common to all the classes based on a particular deferred class.
146 A **template class** offers a set of functional behaviors to manipulate other data types.
147 Instantiation of a template class requires that a data type is given for its argument(s).
149 @subsubsection occt_fcug_2_a_5 Inheritance
150 The purpose of inheritance is to reduce the development workload.
151 The inheritance mechanism allows a new class to be declared already containing the characteristics of an existing class.
152 This new class can then be rapidly specialized for the task in hand.
153 This avoids the necessity of developing each component "from scratch".
154 For example, having already developed a class *BankAccount* you could quickly specialize new classes: *SavingsAccount, LongTermDepositAccount, MoneyMarketAccount, RevolvingCreditAccount*, etc....
156 The corollary of this is that when two or more classes inherit from a parent (or ancestor) class, all these classes guarantee as a minimum the behavior of their parent (or ancestor).
157 For example, if the parent class BankAccount contains the method Print which tells it to print itself out, then all its descendant classes guarantee to offer the same service.
159 One way of ensuring the use of inheritance is to declare classes at the top of a hierarchy as being **abstract**.
160 In such classes, the methods are not implemented.
161 This forces the user to create a new class which redefines the methods.
162 This is a way of guaranteeing a certain minimum of behavior among descendant classes.
164 @subsection occt_fcug_2_1 Data Types
166 An object-oriented language structures a system around data types rather than around the actions carried out on this data.
167 In this context, an **object** is an **instance** of a data type and its definition determines how it can be used.
168 Each data type is implemented by one or more classes, which make up the basic elements of the system.
170 The data types in Open CASCADE Technology fall into two categories:
171 * Data types manipulated by handle (or reference)
172 * Data types manipulated by value
174 @figure{/user_guides/foundation_classes/images/foundation_classes_image004.png,"Manipulation of data types",420}
176 A data type is implemented as a class.
177 The class not only defines its data representation and the methods available on instances, but it also suggests how the instance will be manipulated.
178 * A variable of a type manipulated by value contains the instance itself.
179 * A variable of a type manipulated by handle contains a reference to the instance.
180 The first examples of types manipulated by values are the predefined **primitive types**: *Boolean, Character, Integer, Real*, etc.
182 A variable of a type manipulated by handle which is not attached to an object is said to be **null**.
183 To reference an object, we instantiate the class with one of its constructors.
187 Handle(MyClass) anObject = new MyClass();
190 In Open CASCADE Technology, the Handles are specific classes that are used to safely manipulate objects allocated in the dynamic memory by reference,
191 providing reference counting mechanism and automatic destruction of the object when it is not referenced.
193 @subsubsection occt_fcug_2_1_1 Primitive Types
195 The primitive types are predefined in the language and they are **manipulated by value**.
197 * **Standard_Boolean** is used to represent logical data.
198 It may have only two values: *Standard_True* and *Standard_False*.
199 * **Standard_Character** designates any ASCII character.
200 * **Standard_ExtCharacter** is an extended character.
201 * **Standard_Integer** is a whole number.
202 * **Standard_Real** denotes a real number (i.e. one with whole and a fractional part, either of which may be null).
203 * **Standard_ShortReal** is a real with a smaller choice of values and memory size.
204 * **Standard_CString** is used for literal constants.
205 * **Standard_ExtString** is an extended string.
206 * **Standard_Address** represents a byte address of undetermined size.
208 The services offered by each of these types are described in the **Standard** Package.
209 The table below presents the equivalence existing between C++ fundamental types and OCCT primitive types.
211 **Table 1: Equivalence between C++ Types and OCCT Primitive Types**
213 | C++ Types | OCCT Types |
214 | :--------- | :----------- |
215 | int | Standard_Integer |
216 | double | Standard_Real |
217 | float | Standard_ShortReal |
218 | bool | Standard_Boolean |
219 | char | Standard_Character |
220 | char16_t | Standard_Utf16Char |
221 | char\* | Standard_CString |
222 | void\* | Standard_Address |
223 | char16_t\* | Standard_ExtString |
225 \* The types with asterisk are pointers.
227 **Reminder of the classes listed above:**
229 * **Standard_Integer**: fundamental type representing 32-bit integers yielding negative, positive or null values.
230 *Integer* is implemented as a *typedef* of the C++ *int* fundamental type.
231 As such, the algebraic operations +, -, *, / as well as the ordering and equivalence relations <, <=, ==, !=, >=, > are defined on it.
232 * **Standard_Real**: fundamental type representing real numbers with finite precision and finite size.
233 **Real** is implemented as a *typedef* of the C++ *double* (double precision) fundamental type.
234 As such, the algebraic operations +, -, *, /, unary- and the ordering and equivalence relations <, <=, ==, !=, >=, > are defined on reals.
235 * **Standard_ShortReal**: fundamental type representing real numbers with finite precision and finite size.
236 *ShortReal* is implemented as a *typedef* of the C++ *float* (single precision) fundamental type.
237 As such, the algebraic operations +, -, *, /, unary- and the ordering and equivalence relations <, <=, ==, !=, >=, > are defined on reals.
238 * **Standard_Boolean**: fundamental type representing logical expressions.
239 It has two values: *false* and *true*.
240 *Boolean* is implemented as a *typedef* of the C++ *bool* fundamental type.
241 As such, the algebraic operations *and, or, xor* and *not* as well as equivalence relations == and != are defined on Booleans.
242 * **Standard_Character**: fundamental type representing the UTF-8 character set.
243 *Character* is implemented as a *typedef* of the C++ *char* fundamental type.
244 As such, the ordering and equivalence relations <, <=, ==, !=, >=, > are defined on characters using the order of the ASCII chart (ex: A B).
245 * **Standard_ExtCharacter**: fundamental type representing the UTF-16 character set.
246 It is a 16-bit character type.
247 *ExtCharacter* is implemented as a *typedef* of the C++ *char16_t* fundamental type.
248 As such, the ordering and equivalence relations <, <=, ==, !=, >=, > are defined on extended characters using the order of the UNICODE chart (ex: A B).
249 * **Standard_CString**: fundamental type representing string literals.
250 A string literal is a sequence of UTF-8 (8 bits) code points enclosed in double quotes.
251 *CString* is implemented as a *typedef* of the C++ *char* fundamental type.
252 * **Standard_Address**: fundamental type representing a generic pointer.
253 *Address* is implemented as a *typedef* of the C++ *void* fundamental type.
254 * **Standard_ExtString**: fundamental type representing string literals as sequences of Unicode (16 bits) characters.
255 *ExtString* is implemented as a *typedef* of the C++ *char16_t* fundamental type.
257 @subsubsection occt_fcug_2_1_2 Types manipulated by value
258 There are three categories of types which are manipulated by value:
261 * Types defined by classes not inheriting from *Standard_Transient*, whether directly or not.
262 Types which are manipulated by value behave in a more direct fashion than those manipulated by handle and thus can be expected to perform operations faster, but they cannot be stored independently in a file.
264 @figure{/user_guides/foundation_classes/images/foundation_classes_image005.png,"Manipulation of a data type by value",420}
266 @subsubsection occt_fcug_2_1_3 Types manipulated by reference (handle)
268 These are types defined by classes inheriting from the *Standard_Transient* class.
270 @figure{/user_guides/foundation_classes/images/foundation_classes_image006.png,"Manipulation of a data type by reference",420}
272 @subsubsection occt_fcug_2_1_4 When is it necessary to use a handle?
274 When you design an object, it can be difficult to choose how to manipulate that object: by value or by handle.
275 The following ideas can help you to make up your mind:
276 * If your object may have a long lifetime within the application and you want to make multiple references to it,
277 it would be preferable to manipulate this object with a handle.
278 The memory for the object will be allocated on the heap.
279 The handle which points to that memory is a light object which can be rapidly passed in argument.
280 This avoids the penalty of copying a large object.
281 * If your object will have a limited lifetime, for example, used within a single algorithm,
282 it would be preferable to manipulate this object by value, non-regarding its size,
283 because this object is allocated on the stack and the allocation and de-allocation of memory is extremely rapid,
284 which avoids the implicit calls to *new* and *delete* occasioned by allocation on the heap.
285 * Finally, if an object will be created only once during, but will exist throughout the lifetime of the application,
286 the best choice may be a class manipulated by handle or a value declared as a global variable.
288 @subsection occt_fcug_2_2 Programming with Handles
290 @subsubsection occt_fcug_2_2_1 Handle Definition
292 A handle is OCCT implementation of a smart pointer.
293 Several handles can reference the same object.
294 Also, a single handle may reference several objects, but only one at a time.
295 To have access to the object it refers to, the handle must be de-referenced just as with a C++ pointer.
297 #### Organization of Classes
299 Class *Standard_Transient* is a root of a big hierarchy of OCCT classes that are said to be operable by handles.
300 It provides a reference counter field, inherited by all its descendant classes, that is used by associated *Handle()* classes to track a number of handles pointing to this instance of the object.
302 Objects of classes derived (directly or indirectly) from *Transient*, are normally allocated in dynamic memory using operator **new**, and manipulated by handle.
303 Handle is defined as template class *opencascade::handle<>*.
304 Open CASCADE Technology provides preprocessor macro *Handle()* that is historically used throughout OCCT code to name a handle:
306 Handle(Geom_Line) aLine; // "Handle(Geom_Line)" is expanded to "opencascade::handle<Geom_Line>"
309 In addition, for most OCCT classes additional *typedef* is defined for a handle, as the name of a class prefixed by *Handle_*.
310 For instance, the above example can be also coded as:
312 Handle_Geom_Line aLine; // "Handle_Geom_Line" is typedef to "opencascade::handle<Geom_Line>"
317 A handle is characterized by the object it references.
319 Before performing any operation on a transient object, you must declare the handle.
320 For example, if Point and Line are two transient classes from the Geom package, you would write:
322 Handle(Geom_Point) p1, p2;
324 Declaring a handle creates a null handle that does not refer to any object.
325 The handle may be checked to be null by its method *IsNull()*.
326 To nullify a handle, use method *Nullify()*.
328 To initialize a handle, either a new object should be created or the value of another handle can be assigned to it, on condition that their types are compatible.
330 **Note** that handles should only be used for object sharing.
331 For all local operations, it is advisable to use classes manipulated by values.
333 @subsubsection occt_fcug_2_2_2 Type Management
335 Open CASCADE Technology provides a means to describe the hierarchy of data types in a generic way, with a possibility to check the exact type of the given object at run-time (similarly to C++ RTTI).
337 To enable this feature, a class declaration should include the declaration of OCCT RTTI.
338 Header *Standard_Type.hxx* provides two variants of preprocessor macros facilitating this:
340 * Inline variant, which declares and defines RTTI methods by a single line of code:
342 #include <Geom_Surface.hxx>
343 class Appli_ExtSurface : public Geom_Surface
347 DEFINE_STANDARD_RTTIEXT(Appli_ExtSurface,Geom_Surface)
351 * Out-of line variant, which uses one macro in the declaration (normally in the header file), and another in the implementation (in C++ source):
353 In *Appli_ExtSurface.hxx* file:
355 #include <Geom_Surface.hxx>
356 class Appli_ExtSurface : public Geom_Surface
360 DEFINE_STANDARD_RTTIEXT(Appli_ExtSurface,Geom_Surface)
364 In *Appli_ExtSurface.cxx* file:
366 #include <Appli_ExtSurface.hxx>
367 IMPLEMENT_STANDARD_RTTIEXT(Appli_ExtSurface,Geom_Surface)
370 These macros define method *DynamicType()* that returns a type descriptor - handle to singleton instance of the class *Standard_Type* describing the class.
371 The type descriptor stores the name of the class and the descriptor of its parent class.
373 Note that while inline version is easier to use, for widely used classes this method may lead to bloating of binary code of dependent libraries, due to multiple instantiations of inline method.
375 To get the type descriptor for a given class type, use macro *STANDARD_TYPE()* with the name of the class as argument.
379 if (aCurve->IsKind(STANDARD_TYPE(Geom_Line))) // equivalent to "if (dynamic_cast<Geom_Line>(aCurve.get()) != 0)"
387 The type used in the declaration of a handle is the static type of the object, the type seen by the compiler.
388 A handle can reference an object instantiated from a subclass of its static type.
389 Thus, the dynamic type of an object (also called the actual type of an object) can be a descendant of the type which appears in the handle declaration through which it is manipulated.
391 Consider the class *Geom_CartesianPoint*, a sub-class of *Geom_Point*; the rule of type conformity can be illustrated as follows:
394 Handle(Geom_Point) aPnt1;
395 Handle(Geom_CartesianPoint) aPnt2;
396 aPnt2 = new Geom_CartesianPoint();
397 aPnt1 = aPnt2; // OK, the types are compatible
400 The compiler sees *aPnt1* as a handle to *Geom_Point* though the actual object referenced by *aPnt1* is of the *Geom_CartesianPoint* type.
402 #### Explicit Type Conversion
404 According to the rule of type conformity, it is always possible to go up the class hierarchy through successive assignments of handles.
405 On the other hand, assignment does not authorize you to go down the hierarchy.
406 Consequently, an explicit type conversion of handles is required.
408 A handle can be converted explicitly into one of its sub-types if the actual type of the referenced object is a descendant of the object used to cast the handle.
409 If this is not the case, the handle is nullified (explicit type conversion is sometimes called a "safe cast").
410 Consider the example below.
413 Handle(Geom_Point) aPnt1;
414 Handle(Geom_CartesianPoint) aPnt2, aPnt3;
415 aPnt2 = new Geom_CartesianPoint();
416 aPnt1 = aPnt2; // OK, standard assignment
417 aPnt3 = Handle(Geom_CartesianPoint)::DownCast (aPnt1);
418 // OK, the actual type of aPnt1 is Geom_CartesianPoint, although the static type of the handle is Geom_Point
421 If conversion is not compatible with the actual type of the referenced object, the handle which was "cast" becomes null (and no exception is raised).
422 So, if you require reliable services defined in a sub-class of the type seen by the handle (static type), write as follows:
425 void MyFunction (const Handle(A) & a)
427 Handle(B) b = Handle(B)::DownCast(a);
429 // we can use “b” if class B inherits from A
432 // the types are incompatible
436 Downcasting is used particularly with collections of objects of different types; however, these objects should inherit from the same root class.
438 For example, with a sequence of transient objects *TColStd_SequenceOfTransient* and two classes A and B that both inherit from *Standard_Transient*, you get the following syntax:
443 Handle(Standard_Transient) t;
444 TColStd_SequenceOfTransient aSeq;
450 // here, you cannot write:
453 a = Handle (A)::Downcast (t)
456 // types are compatible, you can use a
460 // the types are incompatible
464 @subsubsection occt_fcug_2_2_3 Using Handles to Create Objects
466 To create an object which is manipulated by handle, declare the handle and initialize it with the standard C++ **new** operator, immediately followed by a call to the constructor.
467 The constructor can be any of those specified in the source of the class from which the object is instanced.
470 Handle(Geom_CartesianPoint) aPnt;
471 aPnt = new Geom_CartesianPoint (0, 0, 0);
474 Unlike for a pointer, the **delete** operator does not work on a handle; the referenced object is automatically destroyed when no longer in use.
476 @subsubsection occt_fcug_2_2_4 Invoking Methods
477 Once you have a handle to an object, you can use it like a pointer in C++.
478 To invoke a method which acts on the referenced object, you translate this method by the standard *arrow* operator, or alternatively, by function call syntax when this is available.
480 To test or to modify the state of the handle, the method is translated by the *dot* operator.
481 The example below illustrates how to access the coordinates of an (optionally initialized) point object:
484 Handle(Geom_CartesianPoint) aCentre;
485 Standard_Real x, y, z;
486 if (aCentre.IsNull())
488 aCentre = new PGeom_CartesianPoint (0, 0, 0);
490 aCentre->Coord (x, y, z);
493 The example below illustrates how to access the type object of a Cartesian point:
496 Handle(Standard_Transient) aPnt = new Geom_CartesianPoint (0., 0., 0.);
497 if (aPnt->DynamicType() == STANDARD_TYPE(Geom_CartesianPoint))
499 std::cout << "Type check OK\n";
503 std::cout << "Type check FAILED\n";
507 *Standard_NullObject* exception will be raised if a field or a method of an object is accessed via a *Null* handle.
509 #### Invoking Class Methods
511 A class method is called like a static C++ function, i.e. it is called by the name of the class of which it is a member, followed by the “::” operator and the name of the method.
513 For example, we can find the maximum degree of a Bezier curve:
516 Standard_Integer aDegree = Geom_BezierCurve::MaxDegree();
519 @subsubsection occt_fcug_2_2_5 Handle deallocation
521 Before you delete an object, you must ensure it is no longer referenced.
522 To reduce the programming load related to this management of object life, the delete function in Open CASCADE Technology is secured by a **reference counter** of classes manipulated by handle.
523 A handle automatically deletes an object when it is no longer referenced.
524 Normally you never call the delete operator explicitly on instances of subclasses of *Standard_Transient*.
526 When a new handle to the same object is created, the reference counter is incremented.
527 When the handle is destroyed, nullified, or reassigned to another object, that counter is decremented.
528 The object is automatically deleted by the handle when reference counter becomes 0.
530 The principle of allocation can be seen in the example below.
535 Handle(TColStd_HSequenceOfInteger) H1 = new TColStd_HSequenceOfInteger();
536 // H1 has one reference and corresponds to 48 bytes of memory
538 Handle(TColStd_HSequenceOfInteger) H2;
539 H2 = H1; // H1 has two references
542 Handle(TColStd_HSequenceOfInteger) H3;
544 // Here, H1 has three references
547 // Here, H1 has two references
549 // Here, H1 has 1 reference
551 // Here, H1 has no reference and the referred TColStd_HSequenceOfInteger object is deleted.
554 You can easily cast a reference to the handle object to <i> void* </i> by defining the following:
558 Handle(Some_Class) aHandle;
559 // Here only a pointer will be copied
561 // Here the Handle object will be copied
562 aHandle = *(Handle(Some_Class)*)aPointer;
565 @subsubsection occt_fcug_2_2_6 Cycles
567 Cycles appear if two or more objects reference each other by handles (stored as fields).
568 In this condition automatic destruction will not work.
570 Consider for example a graph, whose objects (primitives) have to know the graph object to which they belong, i.e. a primitive must have a reference to complete graph object.
571 If both primitives and the graph are manipulated by handle and they refer to each other by keeping a handle as a field, the cycle appears.
573 The graph object will not be deleted when the last handle to it is destructed in the application, since there are handles to it stored inside its own data structure (primitives).
575 There are two approaches how to avoid such situation:
576 * Use C++ pointer for one kind of references, e.g. from a primitive to the graph
577 * Nullify one set of handles (e.g. handles to a graph in primitives) when a graph object needs to be destroyed
579 @subsection occt_fcug_2_3 Memory Management
581 In a work session, geometric modeling applications create and delete a considerable number of C++ objects allocated in the dynamic memory (heap).
582 In this context, performance of standard functions for allocating and deallocating memory may be not sufficient.
583 For this reason, Open CASCADE Technology employs a specialized memory manager implemented in the *Standard* package.
585 The Memory Manager is based on the following principles:
587 * small memory arrays are grouped into clusters and then recycled (clusters are never released to the system),
588 * large arrays are allocated and de-allocated through the standard functions of the system (the arrays are released to system when they are no longer used).
590 As a general rule, it is advisable to allocate memory through significant blocks.
591 In this way, the user can work with blocks of contiguous data and it facilitates memory page manager processing.
593 @subsubsection occt_fcug_2_3_1 Usage of Memory Manager
595 To allocate memory in a C code with Open CASCADE Technology memory manager, simply use method *Standard::Allocate()* instead of *malloc()* and method *Standard::Free()* instead of *free()*.
596 In addition, method *Standard::Reallocate()* is provided to replace C function *realloc()*.
598 In C++, operators *new()* and *delete()* for a class may be defined so as to allocate memory using *Standard::Allocate()* and free it using *Standard::Free()*.
599 In that case all objects of that class and all inherited classes will be allocated using the OCCT memory manager.
601 Preprocessor macro *DEFINE_STANDARD_ALLOC* provided by header *Standard_DefineAlloc.hxx* defines *new()* and *delete()* in this way.
602 It is used for all OCCT classes (apart from a few exceptions) which thus are allocated using the OCCT memory manager.
603 Since operators *new()* and *delete()* are inherited, this is also true for any class derived from an OCCT class, for instance, for all classes derived from *Standard_Transient*.
605 **Note** that it is possible (though not recommended unless really unavoidable) to redefine *new()* and *delete()* functions for a class inheriting *Standard_Transient*.
606 If that is done, the method *Delete()* should be also redefined to apply operator *delete* to this pointer.
607 This will ensure that appropriate *delete()* function will be called, even if the object is manipulated by a handle to a base class.
609 @subsubsection occt_fcug_2_3_2 How to configure the Memory Manager
611 The OCCT memory manager may be configured to apply different optimization techniques to different memory blocks (depending on their size),
612 or even to avoid any optimization and use C functions *malloc()* and *free()* directly.
613 The configuration is defined by numeric values of the following environment variables:
615 - if set to 0 (default) every memory block is allocated in C memory heap directly (via *malloc()* and *free()* functions).
616 In this case, all other options except for *MMGT_CLEAR* are ignored;
617 - if set to 1 the memory manager performs optimizations as described below;
618 - if set to 2, Intel ® TBB optimized memory manager is used.
619 * *MMGT_CLEAR*: if set to 1 (default), every allocated memory block is cleared by zeros; if set to 0, memory block is returned as it is.
620 * *MMGT_CELLSIZE*: defines the maximal size of blocks allocated in large pools of memory. Default is 200.
621 * *MMGT_NBPAGES*: defines the size of memory chunks allocated for small blocks in pages (operating-system dependent). Default is 1000.
622 * *MMGT_THRESHOLD*: defines the maximal size of blocks that are recycled internally instead of being returned to the heap. Default is 40000.
623 * *MMGT_MMAP*: when set to 1 (default), large memory blocks are allocated using memory mapping functions of the operating system; if set to 0, they will be allocated in the C heap by *malloc()*.
625 @subsubsection occt_fcug_2_3_3 Optimization Techniques
627 When *MMGT_OPT* is set to 1, the following optimization techniques are used:
628 * Small blocks with a size less than *MMGT_CELLSIZE*, are not allocated separately.
629 Instead, a large pools of memory are allocated (the size of each pool is *MMGT_NBPAGES* pages).
630 Every new memory block is arranged in a spare place of the current pool.
631 When the current memory pool is completely occupied, the next one is allocated, and so on.
633 In the current version memory pools are never returned to the system (until the process finishes).
634 However, memory blocks that are released by the method *Standard::Free()* are remembered in the free lists and later reused when the next block of the same size is allocated (recycling).
636 * Medium-sized blocks, with a size greater than *MMGT_CELLSIZE* but less than *MMGT_THRESHOLD*, are allocated directly in the C heap (using *malloc()* and *free()*).
637 When such blocks are released by the method *Standard::Free()* they are recycled just like small blocks.
639 However, unlike small blocks, the recycled medium blocks contained in the free lists (i.e. released by the program but held by the memory manager) can be returned to the heap by method *Standard::Purge()*.
641 * Large blocks with a size greater than *MMGT_THRESHOLD*, including memory pools used for small blocks, are allocated depending on the value of *MMGT_MMAP*:
642 if it is 0, these blocks are allocated in the C heap; otherwise they are allocated using operating-system specific functions managing memory mapped files.
643 Large blocks are returned to the system immediately when *Standard::Free()* is called.
645 @subsubsection occt_fcug_2_3_4 Benefits and drawbacks
647 The major benefit of the OCCT memory manager is explained by its recycling of small and medium blocks that makes an application work much faster
648 when it constantly allocates and frees multiple memory blocks of similar sizes.
649 In practical situations, the real gain on the application performance may be up to 50%.
651 The associated drawback is that recycled memory is not returned to the operating system during program execution.
652 This may lead to considerable memory consumption and even be misinterpreted as a memory leak.
653 To minimize this effect it is necessary to call the method *Standard::Purge* after the completion of memory-intensive operations.
655 The overhead expenses induced by the OCCT memory manager are:
656 * size of every allocated memory block is rounded up to 8 bytes
657 (when *MMGT_OPT* is 0 (default), the rounding is defined by the CRT; the typical value for 32-bit platforms is 4 bytes)
658 * additional 4 bytes (or 8 on 64-bit platforms) are allocated in the beginning of every memory block to hold its size
659 (or address of the next free memory block when recycled in free list) only when *MMGT_OPT* is 1.
661 Note that these overheads may be greater or less than overheads induced by the C heap memory manager,
662 so overall memory consumption may be greater in either optimized or standard modes, depending on circumstances.
664 As a general rule, it is advisable to allocate memory through significant blocks.
665 In this way, you can work with blocks of contiguous data, and processing is facilitated for the memory page manager.
667 OCCT memory manager uses mutex to lock access to free lists, therefore it may have less performance than non-optimized mode in situations
668 when different threads often make simultaneous calls to the memory manager.
669 The reason is that modern implementations of *malloc()* and *free()* employ several allocation arenas and thus avoid delays waiting mutex release, which are possible in such situations.
671 @subsection occt_fcug_2_4 Exceptions
673 @subsubsection occt_fcug_2_4_1 Introduction
675 The behavior of any object is implemented by the methods, which were defined in its class declaration.
676 The definition of these methods includes not only their signature (their programming interface) but also their domain of validity.
678 This domain is expressed by **exceptions**.
679 Exceptions are raised under various error conditions to protect software quality.
681 Exception handling provides a means of transferring control from a given point in a program being executed to an **exception handler** associated with another point previously executed.
683 A method may raise an exception which interrupts its normal execution and transfers control to the handler catching this exception.
685 A hierarchy of commonly used exception classes is provided.
686 The root class is *Standard_Failure* from the *Standard* package.
687 So each exception inherits from *Standard_Failure* either directly or by inheriting from another exception.
688 Exception classes list all exceptions, which can be raised by any OCCT function.
690 Open CASCADE Technology also provides support for converting system signals (such as access violation or division by zero) to exceptions,
691 so that such situations can be safely handled with the same uniform approach.
693 However, in order to support this functionality on various platforms, some special methods and workarounds are used.
694 Though the implementation details are hidden and handling of OCCT exceptions is done basically in the same way as with C++,
695 some peculiarities of this approach shall be taken into account and some rules must be respected.
697 The following paragraphs describe recommended approaches for using exceptions when working with Open CASCADE Technology.
699 @subsubsection occt_fcug_2_4_2 Raising an Exception
701 #### "C++ like" Syntax
703 The following example:
705 throw Standard_DomainError ("Cannot cope with this condition");
707 raises an exception of *Standard_DomainError* type with the associated message "Cannot cope with this condition", the message being optional.
708 This exception may be caught by a handler of a *Standard_DomainError* type as follows:
715 catch (const Standard_DomainError& )
717 // handle Standard_DomainError exceptions here
723 Exceptions should not be used as a programming technique, to replace a "goto" statement for example, but as a way to protect methods against misuse.
724 The caller must make sure its condition is such that the method can cope with it.
727 * No exception should be raised during normal execution of an application.
728 * A method which may raise an exception should be protected by other methods allowing the caller to check on the validity of the call.
730 For example, if you consider the *TCollection_Array1* class used with:
731 * *Value* function to extract an element;
732 * *Lower* function to extract the lower bound of the array;
733 * *Upper* function to extract the upper bound of the array.
735 then, the *Value* function may be implemented as follows:
738 Item TCollection_Array1::Value (Standard_Integer theIndex) const
740 // where myR1 and myR2 are the lower and upper bounds of the array
741 if (theIndex < myR1 || theIndex > myR2)
743 throw Standard_OutOfRange ("Index out of range in TCollection_Array1::Value");
745 return myContents[theIndex];
749 Here validity of the index is first verified using the Lower and Upper functions in order to protect the call.
750 Normally the caller ensures the index being in the valid range before calling <i>Value()</i>.
751 In this case the above implementation of *Value* is not optimal since the test done in *Value* is time-consuming and redundant.
753 It is a widely used practice to include that kind of protections in a debug build of the program and exclude in release (optimized) build.
754 To support this practice, the macros <i>Raise_if()</i> are provided for every OCCT exception class:
756 <ErrorTypeName>_Raise_if(condition, "Error message");
758 where *ErrorTypeName* is the exception type, *condition* is the logical expression leading to the raise of the exception, and *Error message* is the associated message.
760 The entire call may be removed by defining one of the preprocessor symbols *No_Exception* or <i>No_<ErrorTypeName></i> at compile-time:
763 #define No_Exception // remove all raises
766 Using this syntax, the *Value* function becomes:
769 Item TCollection_Array1::Value (Standard_Integer theIndex) const
771 Standard_OutOfRange_Raise_if(theIndex < myR1 || theIndex > myR2, "index out of range in TCollection_Array1::Value");
772 return myContents[theIndex];
776 @subsubsection occt_fcug_2_4_3 Handling an Exception
778 When an exception is raised, control is transferred to the nearest handler of a given type in the call stack, that is:
779 * the handler whose try block was most recently entered and not yet exited,
780 * the handler whose type matches the raise expression.
782 A handler of T exception type is a match for a raise expression with an exception type of E if:
783 * T and E are of the same type, or
784 * T is a supertype of E.
786 In order to handle system signals as exceptions, make sure to insert macro *OCC_CATCH_SIGNALS* somewhere in the beginning of the relevant code.
787 The recommended location for it is first statement after opening brace of <i>try {}</i> block.
789 As an example, consider the exceptions of type *Standard_NumericError, Standard_Overflow, Standard_Underflow* and *Standard_DivideByZero*, where *Standard_NumericError* is the parent type of the three others.
799 catch (const Standard_Overflow& ) // first handler
803 catch (const Standard_NumericError& ) // second handler
810 Here, the first handler will catch exceptions of *Standard_Overflow* type
811 and the second one -- exceptions of *Standard_NumericError* type and all exceptions derived from it, including *Standard_Underflow* and *Standard_DivideByZero*.
813 The handlers are checked in order of appearance, from the nearest to the try block to the most distant from it, until one matches the raise expression.
814 For a try block, it would be a mistake to place a handler for a base exception type ahead of a handler for its derived type since that would ensure that the handler for the derived exception would never be invoked.
824 g(i);// i is accessible
826 // statement here will produce compile-time errors !
827 catch (const Standard_NumericError& )
829 // fix up with possible reuse of i
831 // statement here may produce unexpected side effect
837 The exceptions form a hierarchy tree completely separated from other user defined classes.
838 One exception of type *Standard_Failure* is the root of the entire exception hierarchy.
839 Thus, using a handler with *Standard_Failure* type catches any OCCT exception.
840 It is recommended to set up such a handler in the main routine.
842 The main routine of a program would look like this:
845 #include <Standard_ErrorHandler.hxx>
846 #include <Standard_Failure.hxx>
848 int main (int argc, char* argv[])
856 catch (const Standard_Failure& theFailure)
858 std::cerr << "Error " + theFailure.DynamicType()->Name() << " [" << theFailure.GetMessageString() << "]\n";
864 Though standard C++ scoping rules and syntax apply to try block and handlers, note that on some platforms Open CASCADE Technology may be compiled in compatibility mode when exceptions are emulated by long jumps (see below).
865 In this mode it is required that no statement precedes or follows any handler.
866 Thus it is highly recommended to always include a try block into additional {} braces.
867 Also this mode requires that header file *Standard_ErrorHandler.hxx* be included in your program before a try block, otherwise it may fail to handle Open CASCADE Technology exceptions.
869 #### Catching signals
871 In order for the application to be able to catch system signals (access violation, division by zero, etc.) in the same way as other exceptions, the appropriate signal handler shall be installed in the runtime by the method *OSD::SetSignal()*.
873 Normally this method is called in the beginning of the main() function.
874 It installs a handler that will convert system signals into OCCT exceptions.
876 In order to actually convert signals to exceptions, macro *OCC_CATCH_SIGNALS* needs to be inserted in the source code.
877 The typical place where this macro is put is beginning of the *try{}* block which catches such exceptions.
879 @subsubsection occt_fcug_2_4_4 Implementation on various platforms
881 The exception handling mechanism in Open CASCADE Technology is implemented in different ways depending on the preprocessor macro *OCC_CONVERT_SIGNALS*, which shall be consistently defined by compilation procedures for both Open CASCADE Technology and user applications:
883 1. On Windows, these macros are not defined by default, and normal C++ exceptions are used in all cases, including throwing from signal handler.
884 Thus the behavior is as expected in C++.
886 2. On Linux, macro *OCC_CONVERT_SIGNALS* is defined by default.
887 The C++ exception mechanism is used for catching exceptions and for throwing them from normal code.
888 Since it is not possible to throw C++ exception from system signal handler function, that function makes a long jump to the nearest (in the execution stack) invocation of macro *OCC_CATCH_SIGNALS*, and only there the C++ exception gets actually thrown.
889 The macro *OCC_CATCH_SIGNALS* is defined in the file *Standard_ErrorHandler.hxx*.
890 Therefore, including this file is necessary for successful compilation of a code containing this macro.
892 This mode differs from standard C++ exception handling only for signals:
894 * macro *OCC_CATCH_SIGNALS* is necessary (besides call to *OSD::SetSignal()* described above) for conversion of signals into exceptions;
895 * the destructors for automatic C++ objects created in the code after that macro and till the place where signal is raised will not be called in case of signal, since no C++ stack unwinding is performed by long jump.
897 In general, for writing platform-independent code it is recommended to insert macros *OCC_CATCH_SIGNALS* in try {} blocks or other code where signals may happen.
899 @subsection occt_fcug_2_5 Plug-In Management
901 @subsubsection occt_fcug_2_5_1 Distribution by Plug-Ins
903 A plug-in is a component that can be loaded dynamically into a client application, not requiring to be directly linked to it.
904 The plug-in is not bound to its client, i.e. the plug-in knows only how its connection mechanism is defined and how to call the corresponding services.
906 A plug-in can be used to:
907 * implement the mechanism of a *driver*, i.e dynamically changing a driver implementation according to the current transactions (for example, retrieving a document stored in another version of an application),
908 * restrict processing resources to the minimum required (for example, it does not load any application services at run-time as long as the user does not need them),
909 * facilitate modular development (an application can be delivered with base functions while some advanced capabilities will be added as plug-ins when they are available).
911 The plug-in is identified with the help of the global universal identifier (GUID).
912 The GUID includes lower case characters and cannot end with a blank space.
914 Once it has been loaded, the call to the services provided by the plug-in is direct (the client is implemented in the same language as the plug-in).
916 #### C++ Plug-In Implementation
918 The C++ plug-in implements a service as an object with functions defined in an abstract class (this abstract class and its parent classes with the GUID are the only information about the plug-in implemented in the client application).
919 The plug-in consists of a sharable library including a method named Factory which creates the C++ object (the client cannot instantiate this object because the plug-in implementation is not visible).
920 Foundation classes provide in the package *Plugin* a method named *Load()*, which enables the client to access the required service through a library.
922 That method reads the information regarding available plug-ins and their locations from the resource file *Plugin* found by environment variable *CSF_PluginDefaults*:
925 $CSF_PluginDefaults/Plugin
928 The *Load* method looks for the library name in the resource file or registry through its GUID, for example, on UNIX:
930 ! METADATADRIVER whose value must be OS or DM.
933 a148e300-5740-11d1-a904-080036aaa103.Location: libFWOSPlugin.so
936 Then the *Load* method loads the library according to the rules of the operating system of the host machine (for example, by using environment variables such as *LD_LIBRARY_PATH* with Unix and *PATH* with Windows).
937 After that it invokes the *PLUGINFACTORY* method to return the object, which supports the required service.
938 The client may then call the functions supported by this object.
940 #### C++ Client Plug-In Implementation
942 To invoke one of the services provided by the plug-in, you may call the *Plugin::Load()* global function with the *Standard_GUID* of the requested service as follows:
945 Handle(FADriver_PartStorer)::DownCast(PlugIn::Load (yourStandardGUID));
948 Let us take *FAFactory.hxx* and *FAFactory.cxx* as an example:
951 #include <Standard_Macro.hxx>
952 #include <Standard_GUID.hxx>
953 #include <Standard_Transient.hxx>
958 Standard_EXPORT static Handle(Standard_Transient) Factory (const Standard_GUID& theGUID);
963 #include <FAFactory.hxx>
965 #include <FADriver_PartRetriever.hxx>
966 #include <FADriver_PartStorer.hxx>
967 #include <FirstAppSchema.hxx>
968 #include <Standard_Failure.hxx>
969 #include <FACDM_Application.hxx>
970 #include <Plugin_Macro.hxx>
972 static Standard_GUID StorageDriver ("45b3c690-22f3-11d2-b09e-0000f8791463");
973 static Standard_GUID RetrievalDriver("45b3c69c-22f3-11d2-b09e-0000f8791463");
974 static Standard_GUID Schema ("45b3c6a2-22f3-11d2-b09e-0000f8791463");
976 //======================================================
977 // function : Factory
979 //======================================================
980 Handle(Standard_Transient) FAFactory::Factory (const Standard_GUID& theGUID)
982 if (theGUID == StorageDriver)
984 std::cout << "FAFactory : Create store driver\n";
985 static Handle(FADriver_PartStorer) sd = new FADriver_PartStorer();
988 if (theGUID == RetrievalDriver)
990 std::cout << "FAFactory : Create retrieve driver\n";
991 static Handle(FADriver_PartRetriever) rd = new FADriver_PartRetriever();
994 if (theGUID == Schema)
996 std::cout << "FAFactory : Create schema\n";
997 static Handle(FirstAppSchema) s = new FirstAppSchema();
1001 throw Standard_Failure ("FAFactory: unknown GUID");
1002 return Handle(Standard_Transient)();
1005 // export plugin function "PLUGINFACTORY"
1009 Application might also instantiate a factory by linking to the library and calling *FAFactory::Factory()* directly.
1011 @section occt_fcug_3 Collections, Strings, Quantities and Unit Conversion
1013 @subsection occt_fcug_3_1 Collections
1015 @subsubsection occt_fcug_3_1_1 Overview
1017 The **Collections** component contains the classes that handle dynamically sized aggregates of data.
1018 They include a wide range of collections such as arrays, lists and maps.
1020 Some OCCT collections have close friends in modern STL (standard templates collection), but define a little bit different properties or behavior.
1021 OCCT gives user a wider choice, but it is up to user to decide which particular OCCT or STL collection is most suitable for specific algorithm (including performance and usage convenience).
1022 OCCT itself highly relies on its own collections for historical reasons - many features implemented by OCCT were unavailable in earlier versions of STL.
1024 Collections classes are *generic* (C++ templates), that is, they define a structure and algorithms allowing to hold a variety of objects which do not necessarily inherit from a unique root class.
1027 * Each collection directly used as an argument in OCCT public syntax is instantiated in an OCCT component.
1028 * The *TColStd* package (**Collections of Standard Objects** component) provides numerous instantiations of these generic collections with objects from the **Standard** package or from the **Strings** component.
1030 The **Collections** component provides a wide range of generic collections:
1031 * **Arrays** are generally used for a quick access to the item, however an array is a fixed sized aggregate.
1032 * **Sequences** are variable-sized structures, they avoid the use of large and quasi-empty arrays.
1033 A sequence item is longer to access than an array item: only an exploration in sequence is effective (but sequences are not adapted for numerous explorations).
1034 Arrays and sequences are commonly used as data structures for more complex objects.
1035 * **Maps** are dynamic structures, where the size is constantly adapted to the number of inserted items and access to an item is the fastest.
1036 Maps structures are commonly used in cases of numerous explorations: they are typically internal data structures for complex algorithms.
1037 * **Lists** are similar to sequences but have different algorithms to explore them.
1038 * **Acceleration structures** are trees or other structures optimized for fast traverse based on locality criteria (like picking objects by ray in 3D).
1040 Macro definitions of these classes are stored in *NCollection_Define\*.hxx* files.
1041 These definitions are now obsolete though still can be used, particularly for compatibility with the existing code.
1043 Let see an example of NCollection template class instantiation for a sequence of points in the header file *MyPackage_SequenceOfPnt.hxx* (analogue of *TColgp_SequenceOfPnt*):
1046 #include <NCollection_Sequence.hxx>
1047 #include <gp_Pnt.hxx>
1048 typedef NCollection_Sequence<gp_Pnt> MyPackage_SequenceOfPnt;
1051 For the case, when sequence itself should be managed by handle, auxiliary macros *DEFINE_HSEQUENCE* can be used:
1053 #include <NCollection_Sequence.hxx>
1054 #include <NCollection_DefineHSequence.hxx>
1055 #include <gp_Pnt.hxx>
1056 typedef NCollection_Sequence<gp_Pnt> MyPackage_SequenceOfPnt;
1057 DEFINE_HSEQUENCE(MyPackage_HSequenceOfPnt, MyPackage_SequenceOfPnt)
1059 Handle(MyPackage_HSequenceOfPnt) aSeq = new MyPackage_HSequenceOfPnt();
1062 See more details about available collections in following sections.
1064 @subsubsection occt_fcug_3_1_2 Arrays and sequences
1066 Standard collections provided by OCCT are:
1067 * *NCollection_Array1* -- fixed-size (at initialization) one-dimensional array; note that the index can start at any value, usually 1;
1068 * *NCollection_Array2* -- fixed-size (at initialization) two-dimensional array; note that the index can start at any value, usually 1;
1069 * *NCollection_List* -- plain list;
1070 * *NCollection_Sequence* -- double-connected list with access by index; note that the index starts at 1;
1071 * *NCollection_Vector* -- two-step indexed array, expandable in size, but not shrinkable;
1072 * *NCollection_SparseArray* -- array-alike structure with sparse memory allocation for sequences with discontinuities.
1074 These classes provide STL-style iterators (methods begin() and end()) and thus can be used in STL algorithms.
1076 ##### NCollection_Array1
1078 These are unidimensional arrays similar to C arrays, i.e. of fixed size but dynamically dimensioned at construction time.
1079 As with a C array, the access time for an *NCollection_Array1* indexed item is constant and is independent of the array size.
1080 Arrays are commonly used as elementary data structures for more complex objects.
1082 This template class depends on *Item*, the type of element in the array.
1083 Array indexation starts and ends at a position given to class constructor.
1084 Thus, when accessing an item, you must base the index on the lower and upper bounds of the array.
1086 ##### NCollection_Array2
1088 These are bi-dimensional arrays of fixed size but dynamically dimensioned at construction time.
1090 As with a C array, the access time for an *NCollection_Array2* indexed item is constant and is independent of the array size.
1091 Arrays are commonly used as elementary data structures for more complex objects.
1093 This template class depends on *Item*, the type of element in the array.
1094 Array indexation starts and ends at a position given to class constructor.
1095 Thus, when accessing an item, you must base the index on the lower and upper bounds of the array.
1097 ##### NCollection_List
1099 These are ordered lists of non-unique objects which can be accessed sequentially using an NCollection_List::Iterator.
1100 Item insertion in a list is very fast at any position.
1101 But searching for items by value may be slow if the list is long, because it requires a sequential search.
1103 This template class depends on *Item*, the type of element in the structure.
1104 A sequence is a better structure when searching for items by value.
1105 Queues and stacks are other kinds of list with a different access to data.
1107 ##### NCollection_Sequence
1109 This is a sequence of items indexed by an integer.
1110 Sequences have about the same goal as unidimensional arrays (*NCollection_Array1*): they are commonly used as elementary data structures for more complex objects.
1111 But a sequence is a structure of *variable size*: sequences avoid the use of large and quasi-empty arrays.
1112 Exploring a sequence data structure is effective when the exploration is done *in sequence*; elsewhere a sequence item is longer to read than an array item.
1113 Note also that sequences are not effective when they have to support numerous algorithmic explorations: a map is better for that.
1115 This template class depends on *Item*, the type of element in the sequence.
1116 The first element in sequence has index equal to 1.
1118 ##### NCollection_Vector
1120 Class *NCollection_Vector* is implemented internally as a list of arrays of the same size.
1122 * Direct (constant-time) access to members like in NCollection_Array1 type.
1123 Data are allocated in compact blocks, this provides faster iteration.
1124 * Can grow without limits, like NCollection_List or NCollection_Sequence types.
1125 * Once having the size LEN, it cannot be reduced to any size less than LEN -- there is no operation of removal of items.
1127 Insertion in a Vector-type class is made by two methods:
1128 * _SetValue(ind, theValue)_ -- array-type insertion, where ind is the index of the inserted item, can be any non-negative number.
1129 If it is greater than or equal to Length(), then the vector is enlarged (its Length() grows).
1130 * _Append(theValue)_ -- list-type insertion equivalent to _myVec.SetValue(myVec.Length(), theValue)_, incrementing the size of the collection.
1132 Other essential properties coming from NCollection_List and NCollection_Array1 type collections:
1133 * Like in *NCollection_List*, the method *Clear()* destroys all contained objects and releases the allocated memory.
1134 * Like in *NCollection_Array1*, the methods *Value()* and *ChangeValue()* return a contained object by index.
1135 Also, these methods have the form of overloaded operator().
1137 The first element in vector has index equal to 0.
1139 ##### NCollection_SparseArray
1141 Class *NCollection_SparseArray* has almost the same features as *NCollection_Vector*, but it allows to store items having scattered indices.
1142 In NCollection_Vector, if you set an item with index 1000000, the container will allocate memory for all items with indices in the range 0-1000000.
1143 In NCollection_SparseArray, only one small block of items will be reserved that contains the item with index 1000000.
1145 This class can be also seen as equivalence of *NCollection_DataMap<int,TheItemType>* with the only one practical difference: it can be much less memory-expensive if items are small (e.g. Integer or Handle).
1147 This type has both interfaces of NCollection_DataMap and NCollection_Vector to access items.
1149 @subsubsection occt_fcug_3_1_3 Maps
1151 OCCT provides several classes for storage of objects by value, providing fast search due to use of hash:
1152 * *NCollection_Map* -- hash set;
1153 * *NCollection_IndexedMap* -- set with a prefixed order of elements, allowing fast access by index or by value (hash-based);
1154 * *NCollection_DataMap* -- hash map;
1155 * *NCollection_IndexedDataMap* -- map with a prefixed order of elements, allowing fast access by index or by value (hash-based);
1156 * *NCollection_DoubleMap* -- two-side hash map (with two keys).
1158 Maps are dynamically extended data structures where data is quickly accessed with a *key*.
1159 Once inserted in the map, a map item is referenced as an *entry* of the map.
1160 Maps avoid the use of large and quasi-empty arrays.
1162 Each entry of the map is addressed by a key.
1163 Two different keys address two different entries of the map.
1164 The position of an entry in the map is called a *bucket*.
1166 A map is dimensioned by its number of buckets, i.e. the maximum number of entries in the map.
1167 The *hashing function* transforms a key into a bucket index.
1168 The number of values that can be computed by the hashing function is equal to the number of buckets of the map.
1170 Both the hashing function and the equality test between two keys are provided by a *hasher* object.
1172 The access time for a map item is much better than the one for a sequence, list, queue or stack item.
1173 It is comparable with the access time for an array item.
1174 It depends on the size of the map (number of buckets) and on the quality of the user redefinable *hashing function*.
1176 *Keys, items* and *hashers* are parameters of these OCCT map templates.
1177 *NCollection_DefaultHasher* class describes the functions required by any *hasher*, which is to be used with a map instantiated from the **NCollection** component.
1179 A map may be explored by a *map iterator*.
1180 This exploration provides only inserted entries in the map (i.e. non empty buckets).
1182 ##### NCollection_DataMap
1184 This is a map used to store keys with associated items.
1185 An entry of **NCollection_DataMap** is composed of both the key and the item.
1186 The *NCollection_DataMap* can be seen as an extended array where the keys are the indexes.
1188 *NCollection_DataMap* is a template class which depends on three parameters:
1189 * *Key* is the type of key for an entry in the map,
1190 * *Item* is the type of element associated with a key in the map,
1191 * *Hasher* is the type of hasher on keys.
1193 Use a *NCollection_DataMap::Iterator* to explore a *NCollection_DataMap* map.
1194 *NCollection_DefaultHasher* class describes the functions required for a *Hasher* object.
1196 ##### NCollection_DoubleMap
1198 This is a map used to bind pairs of keys (Key1,Key2) and retrieve them in linear time.
1200 *Key1* is referenced as the first key of the *NCollection_DoubleMap* and *Key2* as the second key.
1202 An entry of a *NCollection_DoubleMap* is composed of a pair of two keys: the first key and the second key.
1204 *NCollection_DoubleMap* is a teamplate class which depends on four parameters:
1205 * *Key1* is the type of the first key for an entry in the map,
1206 * *Key2* is the type of the second key for an entry in the map,
1207 * *Hasher1* is the type of hasher on first keys,
1208 * *Hasher2* is the type of hasher on second keys.
1210 Use *NCollection_DoubleMap::Iterator* to explore a *NCollection_DoubleMap* map.
1211 *NCollection_DefaultHasher* class describes the functions required for a *Hasher1* or a *Hasher2* object.
1213 ##### NCollection_IndexedDataMap
1215 This is map to store keys with associated items and to bind an index to them.
1217 Each new key stored in the map is assigned an index.
1218 Indexes are incremented as keys (and items) stored in the map.
1219 A key can be found by the index, and an index can be found by the key.
1220 No key but the last can be removed, so the indexes are in the range 1...Upper, where *Upper* is the number of keys stored in the map.
1221 An item is stored with each key.
1223 An entry of an *NCollection_IndexedDataMap* is composed of both the key, the item and the index.
1224 An *NCollection_IndexedDataMap* is an ordered map, which allows a linear iteration on its contents.
1225 It combines the interest:
1226 * of an array because data may be accessed with an index,
1227 * and of a map because data may also be accessed with a key.
1229 *NCollection_IndexedDataMap* is a template class which depends on three parameters:
1230 * *Key* is the type of key for an entry in the map,
1231 * *Item* is the type of element associated with a key in the map,
1232 * *Hasher* is the type of hasher on keys.
1234 ##### NCollection_IndexedMap
1236 This is map used to store keys and to bind an index to them.
1238 Each new key stored in the map is assigned an index.
1239 Indexes are incremented as keys stored in the map.
1240 A key can be found by the index, and an index by the key.
1241 No key but the last can be removed, so the indexes are in the range 1...Upper where Upper is the number of keys stored in the map.
1243 An entry of an *NCollection_IndexedMap* is composed of both the key and the index.
1244 An *NCollection_IndexedMap* is an ordered map, which allows a linear iteration on its contents.
1245 But no data is attached to the key.
1246 An *NCollection_IndexedMap* is typically used by an algorithm to know if some action is still performed on components of a complex data structure.
1248 *NCollection_IndexedMap* is a template class which depends on two parameters:
1249 * *Key* is the type of key for an entry in the map,
1250 * *Hasher* is the type of hasher on keys.
1252 ##### NCollection_Map
1254 This is a basic hashed map, used to store and retrieve keys in linear time.
1256 An entry of a *NCollection_Map* is composed of the key only.
1257 No data is attached to the key.
1258 An *NCollection_Map* is typically used by an algorithm to know if some action is still performed on components of a complex data structure.
1260 *NCollection_Map* is a generic class which depends on two parameters:
1261 * *Key* is the type of key in the map,
1262 * *Hasher* is the type of hasher on keys.
1264 Use a *NCollection_Map::Iterator* to explore a *NCollection_Map* map.
1266 ##### NCollection_DefaultHasher
1268 This is a default hasher on the *keys* of a map instantiated from the *NCollection* component.
1270 A hasher provides two functions:
1271 * *HashCode()* function transforms a key into a bucket index in the map.
1272 The number of values that can be computed by the hashing function is equal to the number of buckets in the map.
1273 * *IsEqual* is the equality test between two keys.
1275 Hashers are used as parameters in template maps provided by the **NCollection** component.
1277 *NCollection_DefaultHasher* is a template class which depends on the type of keys, providing that *Key* is a type from the *Standard* package.
1278 In such cases *NCollection_DefaultHasher* may be directly instantiated with *Key*.
1279 Note that the package *TColStd* provides some of these instantiations.
1281 Elsewhere, if *Key* is not a type from the *Standard* package you must consider *NCollection_DefaultHasher* as a template
1282 and build a class which includes its functions, in order to use it as a hasher in a map instantiated from the *NCollection* component.
1284 Note that *TCollection_AsciiString* and *TCollection_ExtendedString* classes correspond to these specifications, in consequence they may be used as hashers:
1285 when *Key* is one of these two types you may just define the hasher as the same type at the time of instantiation of your map.
1287 @subsubsection occt_fcug_3_1_4 Iterators
1289 Every collection defines its *Iterator* class capable of iterating the members in some predefined order.
1290 Every Iterator is defined as a subtype of the particular collection type (e.g., MyPackage_StackOfPnt::Iterator).
1291 The order of iteration is defined by a particular collection type.
1293 The common methods of Iterator are:
1295 | Name | Method | Description |
1296 | :---------------- | :--------------------------- | :----------- |
1297 | **Init()** | _void Init (MyCollection& )_ | Initializes the iterator on the collection object |
1298 | **More()** | _bool More()_ | Makes a query if there is another non-iterated member |
1299 | **Next()** | _void Next()_ | Increments the iterator |
1300 | **Value()** | _const ItemType& Value()_ | Returns the current member |
1301 | **ChangeValue()** | _ItemType& ChangeValue()_ | Returns the mutable current member |
1306 typedef Ncollection_Sequence<gp_Pnt> MyPackage_SequenceOfPnt;
1307 void Perform (const MyPackage_SequenceOfPnt& theSequence)
1309 for (MyPackage_SequenceOfPnt::Iterator anIter (theSequence); anIter.More(); anIter.Next())
1311 const gp_Pnt aPnt& = anIter.Value();
1317 @subsubsection occt_fcug_3_1_5 Allocators
1319 All constructors of *NCollection* classes receive the *Allocator* object as the last parameter.
1320 This is an object of a type managed by Handle, inheriting *NCollection_BaseAllocator*, with the following (mandatory) methods redefined:
1323 virtual void* Allocate (const size_t theSize) override;
1324 virtual void Free (void* theAddress) override;
1327 It is used internally every time when the collection allocates memory for its item(s) and releases this memory.
1328 The default value of this parameter (empty *Handle*) designates the use of *NCollection_BaseAllocator*, where the functions *Standard::Allocate* and *Standard::Free* are called.
1329 Therefore if the user of *NCollection* does not specify any allocator as a parameter to the constructor of his collection, the memory management will be identical to other Open CASCADE Technology classes.
1331 Nevertheless, it is possible to define a custom *Allocator* type to manage the memory in the most optimal or convenient way for this algorithm.
1333 As one possible choice, the class *NCollection_IncAllocator* is included.
1334 Unlike *NCollection_BaseAllocator*, the memory is allocated in big blocks (about 20kB) and the allocator keeps track of the amount of occupied memory.
1335 The method *Allocate* just increments the pointer to non-occupied memory and returns its previous value.
1336 Memory is only released in the destructor of *NCollection_IncAllocator*, the method *Free* is empty.
1337 If used properly, this Allocator can greatly improve the performance of specific algorithms.
1339 @subsubsection occt_fcug_3_1_6 Acceleration structures
1341 OCCT provides several data structures for optimized traverse of large collection of objects based on their locality (in 3D space).
1342 * *NCollection_UBTree* -- Unbalanced Binary Tree;
1343 * *NCollection_CellFilter* -- array of 2D/3D cells;
1344 * *BVH_Tree* -- boundary volume hierarchy.
1346 ##### NCollection_UBTree
1348 The class name NCollection_UBTree stands for "Unbalanced Binary Tree".
1349 It stores the members in a binary tree of overlapped bounding objects (boxes or else).
1350 Once the tree of boxes of geometric objects is constructed, the algorithm is capable of fast geometric selection of objects.
1351 The tree can be easily updated by adding to it a new object with bounding box.
1352 The time of adding to the tree of one object is O(log(N)), where N is the total number of objects, so the time of building a tree of N objects is O(N(log(N)).
1353 The search time of one object is O(log(N)).
1355 Defining various classes inheriting *NCollection_UBTree::Selector* we can perform various kinds of selection over the same b-tree object.
1357 The object may be of any type allowing copying.
1358 Among the best suitable solutions there can be a pointer to an object, handled object or integer index of object inside some collection.
1360 The bounding object may have any dimension and geometry.
1361 The minimal interface of *TheBndType* (besides public empty and copy constructor and operator=) used in NCollection_UBTree algorithm as follows:
1367 //! Updates me with other bounding type instance
1368 void Add (const MyBndType& theOther);
1370 //! Classifies other bounding type instance relatively me
1371 Standard_Boolean IsOut (const MyBndType& theOther) const;
1373 //! Computes the squared maximal linear extent of me (for a box it is the squared diagonal of the box).
1374 Standard_Real SquareExtent() const;
1378 This interface is implemented in types of Bnd package: *Bnd_Box, Bnd_Box2d, Bnd_B2x, Bnd_B3x*.
1380 To select objects you need to define a class derived from *NCollection_UBTree::Selector* that should redefine the necessary virtual methods to maintain the selection condition.
1381 Usually this class instance is also used to retrieve selected objects after search.
1382 The class *NCollection_UBTreeFiller* is used to randomly populate a *NCollection_UBTree* instance.
1383 The quality of a tree is better (considering the speed of searches) if objects are added to it in a random order trying to avoid the addition of a chain of nearby objects one following another.
1384 Instantiation of *NCollection_UBTreeFiller* collects objects to be added, and then adds them at once to the given NCollection_UBTree instance in a random order using the Fisher-Yates algorithm.
1385 Below is the sample code that creates an instance of *NCollection_UBTree* indexed by 2D boxes (Bnd_B2f), then a selection is performed returning the objects whose bounding boxes contain the given 2D point.
1388 typedef NCollection_UBTree<MyData, Bnd_B2f> UBTree;
1389 typedef NCollection_List<MyData> ListOfSelected;
1390 //! Tree Selector type
1391 class MyTreeSelector : public UBTree::Selector
1394 //! This constructor initializes the selection criterion (e.g., a point)
1395 MyTreeSelector (const gp_XY& thePnt) : myPnt(thePnt) {}
1397 //! Get the list of selected objects
1398 const ListOfSelected& ListAccepted() const { return myList; }
1400 //! Bounding box rejection - definition of virtual method.
1401 //! @return True if theBox is outside the selection criterion.
1402 virtual Standard_Boolean Reject (const Bnd_B2f& theBox) const override { return theBox.IsOut (myPnt); }
1404 //! Redefined from the base class.
1405 //! Called when the bounding of theData conforms to the selection criterion.
1406 //! This method updates myList.
1407 virtual Standard_Boolean Accept (const MyData& theData) override { myList.Append (theData); }
1411 ListOfSelected myList;
1414 // Create a UBTree instance and fill it with data, each data item having the corresponding 2D box.
1416 NCollection_UBTreeFiller <MyData, Bnd_B2f> aTreeFiller (aTree);
1419 const MyData& aData = ...;
1420 const Bnd_B2d& aBox = aData.GetBox();
1421 aTreeFiller.Add (aData, aBox);
1425 // Perform selection based on "aPoint2d"
1426 MyTreeSelector aSel (aPoint2d);
1427 aTree.Select (aSel);
1428 const ListOfSelected& aSelected = aSel.ListAccepted();
1431 ##### NCollection_CellFilter
1433 Class *NCollection_CellFilter* represents a data structure for sorting geometric objects in n-dimensional space into cells, with associated algorithm for fast checking of coincidence (overlapping, intersection, etc.) with other objects.
1434 It can be considered as a functional alternative to *NCollection_UBTree*, as in the best case it provides the direct access to an object like in an n-dimensional array,
1435 while search with NCollection_UBTree provides logarithmic law access time.
1437 @subsection occt_fcug_3_2 Collections of Standard Objects
1439 Packages *TShort*, *TColGeom*, *TColGeom2d*, *TColStd*, *TColgp* provide template instantiations (typedefs) of *NCollection* templates to standard OCCT types.
1440 Classes with *H* prefix in name are handle-based variants and inherit Standard_Transient.
1442 typedef NCollection_Array1<gp_Vec> TColgp_Array1OfVec;
1443 typedef NCollection_Array1<TCollection_AsciiString> TColStd_Array1OfAsciiString;
1446 Packages like *TopTools* also include definitions of collections and hash functions for complex types like shapes -- *TopTools_ShapeMapHasher*, *TopTools_MapOfShape*.
1448 Apart from that class *TColStd_PackedMapOfInteger* provides an alternative implementation of map of integer numbers,
1449 optimized for both performance and memory usage (it uses bit flags to encode integers, which results in spending only 24 bytes per 32 integers stored in optimal case).
1450 This class also provides Boolean operations with maps as sets of integers (union, intersection, subtraction, difference, checks for equality and containment).
1452 @subsection occt_fcug_3_4 Strings
1454 *TCollection_AsciiString* defines a variable-length sequence of UTF-8 code points (normal 8-bit character type), while *TCollection_ExtendedString* stores UTF-16/UCS-2 code points (16-bit character type).
1455 Both follow value semantics - that is, they are the actual strings, not handles to strings, and are copied through assignment.
1456 *TCollection_HAsciiString* / *TCollection_HExtendedString* are handle wrappers over *TCollection_AsciiString* / *TCollection_ExtendedString*.
1458 String classes provide the following services to manipulate character strings:
1459 * Editing operations on string objects, using a built-in string manager
1460 * Handling of dynamically-sized sequences of characters
1461 * Conversion from/to ASCII and UTF-8 strings.
1463 *TCollection_AsciiString* and *TCollection_ExtendedString* provide UTF-8 <-> UTF-16 conversion constructors, making these string classes interchangeable.
1464 *Resource_Unicode* provides functions to convert strings given in ANSI, EUC, GB or SJIS format, to a Unicode string and vice versa.
1465 *NCollection_UtfIterator* class implements an iterator over multibyte UTF-8/UTF-16 strings as a sequence of UTF-32 Unicode symbols.
1467 @subsection occt_fcug_3_5 Quantities
1469 Quantities are various classes supporting date and time information and color.
1471 Quantity classes provide the following services:
1472 * Unit conversion tools providing a uniform mechanism for dealing with quantities and associated physical units: check unit compatibility, perform conversions of values between different units, etc. (see package *UnitsAPI*)
1473 * Resources to manage time information such as dates and time periods
1474 * Resources to manage color definition
1476 A mathematical quantity is characterized by the name and the value (real).
1478 A physical quantity is characterized by the name, the value (real) and the unit.
1479 The unit may be either an international unit complying with the International Unit System (SI) or a user defined unit.
1480 The unit is managed by the physical quantity user.
1482 @subsection occt_fcug_3_6 Unit Conversion
1484 The *UnitsAPI* global functions are used to convert a value from any unit into another unit.
1485 Conversion is executed among three unit systems:
1486 * the **SI System**,
1487 * the user's **Local System**,
1488 * the user's **Current System**.
1490 The **SI System** is the standard international unit system.
1491 It is indicated by *SI* in the signatures of the *UnitsAPI* functions.
1493 The OCCT (former MDTV) System corresponds to the SI international standard but the length unit and all its derivatives use the millimeter instead of the meter.
1495 Both systems are proposed by Open CASCADE Technology; the SI System is the standard option.
1496 By selecting one of these two systems, you define your **Local System** through the *SetLocalSystem* function.
1497 The **Local System** is indicated by *LS* in the signatures of the *UnitsAPI* functions.
1498 The Local System units can be modified in the working environment.
1499 You define your **Current System** by modifying its units through the *SetCurrentUnit* function.
1500 The Current System is indicated by *Current* in the signatures of the *UnitsAPI* functions.
1501 A physical quantity is defined by a string (example: LENGTH).
1503 @section occt_occt_fcug_4 Math Primitives and Algorithms
1505 @subsection occt_occt_fcug_4_1 Overview
1507 Math primitives and algorithms available in Open CASCADE Technology include:
1508 * Vectors and matrices
1509 * Geometric primitives
1512 @subsection occt_occt_fcug_4_2 Vectors and Matrices
1514 The Vectors and Matrices component provides a C++ implementation of the fundamental types *math_Vector* and *math_Matrix*, which are regularly used to define more complex data structures.
1516 The <i>math_Vector</i> and <i>math_Matrix</i> classes provide commonly used mathematical algorithms which include:
1518 * Basic calculations involving vectors and matrices;
1519 * Computation of eigenvalues and eigenvectors of a square matrix;
1520 * Solvers for a set of linear algebraic equations;
1521 * Algorithms to find the roots of a set of non-linear equations;
1522 * Algorithms to find the minimum function of one or more independent variables.
1524 These classes also provide a data structure to represent any expression, relation, or function used in mathematics, including the assignment of variables.
1526 Vectors and matrices have arbitrary ranges which must be defined at declaration time and cannot be changed after declaration.
1529 math_Vector aVec (1, 3);
1530 // a vector of dimension 3 with range (1..3)
1531 math_Matrix aMat (0, 2, 0, 2);
1532 // a matrix of dimension 3x3 with range (0..2, 0..2)
1533 math_Vector aVec (N1, N2);
1534 // a vector of dimension N2-N1+1 with range (N1..N2)
1537 Vector and Matrix objects use value semantics.
1538 In other words, they cannot be shared and are copied through assignment.
1541 math_Vector aVec1 (1, 3), aVec2 (0, 2);
1543 // aVec1 is copied into aVec2; a modification of aVec1 does not affect aVec2
1546 Vector and Matrix values may be initialized and obtained using indexes which must lie within the range definition of the vector or the matrix.
1549 math_Vector aVec (1, 3);
1550 math_Matrix aMat (1, 3, 1, 3);
1551 Standard_Real aValue;
1556 aValue = aMat (2, 2);
1559 Some operations on Vector and Matrix objects may not be legal.
1560 In this case an exception is raised.
1561 Two standard exceptions are used:
1562 * *Standard_DimensionError* exception is raised when two matrices or vectors involved in an operation are of incompatible dimensions.
1563 * *Standard_RangeError* exception is raised if an access outside the range definition of a vector or of a matrix is attempted.
1566 math_Vector aVec1 (1, 3), aVec2 (1, 2), aVec3 (0, 2);
1567 aVec1 = aVec2; // error: Standard_DimensionError is raised
1568 aVec1 = aVec3; // OK: ranges are not equal but dimensions are compatible
1569 aVec1 (0) = 2.0; // error: Standard_RangeError is raised
1572 @subsection occt_occt_fcug_4_3 Primitive Geometric Types
1574 Open CASCADE Technology primitive geometric types are a STEP-compliant implementation of basic geometric and algebraic entities.
1576 * Descriptions of primitive geometric shapes, such as:
1580 * Circles and conics;
1581 * Planes and elementary surfaces;
1582 * Positioning of these shapes in space or in a plane by means of an axis or a coordinate system;
1583 * Definition and application of geometric transformations to these shapes:
1587 * Scaling transformations;
1588 * Composed transformations;
1589 * Tools (coordinates and matrices) for algebraic computation.
1591 All these functions are provided by geometric processor package <i>gp</i>.
1592 Its classes for 2d and 3d objects are handled by value rather than by reference.
1593 When this sort of object is copied, it is copied entirely.
1594 Changes in one instance will not be reflected in another.
1596 The *gp* package defines the basic geometric entities used for algebraic calculation and basic analytical geometry in 2d & 3d space.
1597 It also provides basic transformations such as identity, rotation, translation, mirroring, scale transformations, combinations of transformations, etc.
1598 Entities are handled by value.
1600 Note that <i>gp</i> curves and surfaces are analytic: there is no parameterization and no orientation on <i>gp</i> entities, i.e. these entities do not provide functions which work with these properties.
1602 If you need, you may use more evolved data structures provided by <i>Geom</i> (in 3D space) and <i>Geom2d</i> (in the plane).
1603 However, the definition of <i>gp</i> entities is identical to the one of equivalent <i>Geom</i> and <i>Geom2d</i> entities, and they are located in the plane or in space with the same kind of positioning systems.
1604 They implicitly contain the orientation, which they express on the <i>Geom </i> and <i>Geom2d</i> entities, and they induce the definition of their parameterization.
1606 Therefore, it is easy to give an implicit parameterization to <i>gp</i> curves and surfaces, which is the parametrization of the equivalent <i>Geom</i> or <i>Geom2d</i> entity.
1607 This property is particularly useful when computing projections or intersections, or for operations involving complex algorithms where it is particularly important to manipulate the simplest data structures, i.e. those of <i>gp</i>.
1608 Thus, <i>ElCLib</i> and <i>ElSLib</i> packages provide functions to compute:
1609 * the point of parameter u on a 2D or 3D gp curve,
1610 * the point of parameter (u,v) on a gp elementary surface, and
1611 * any derivative vector at this point.
1613 Note: the <i>gp</i> entities cannot be shared when they are inside more complex data structures.
1615 @subsection occt_occt_fcug_4_4 Collections of Primitive Geometric Types
1617 Before creating a geometric object, you must decide whether you are in a 2d or in a 3d context and how you want to handle the object.
1618 If you do not need a single instance of a geometric primitive but a set of them then the package which deals with collections of this sort of object, *TColgp*, will provide the necessary functionality.
1619 In particular, this package provides standard and frequently used instantiations of generic classes with geometric objects, i.e. *gp_XY*, *gp_XYZ*, *gp_Pnt*, *gp_Pnt2d*, *gp_Vec*, *gp_Vec2d*, *gp_Lin*, *gp_Lin2d*, *gp_Circ*, *gp_Circ2d*.
1621 @subsection occt_occt_fcug_4_5 Basic Geometric Libraries
1622 There are various library packages available which offer a range of basic computations on curves and surfaces.
1623 If you are dealing with objects created from the *gp* package, the useful algorithms are in the elementary curves and surfaces libraries -- the *ElCLib* and *ElSLib* packages.
1624 * *EICLib* provides methods for analytic curves.
1625 This is a library of simple computations on curves from the *gp* package (Lines, Circles and Conics).
1626 It is possible to compute points with a given parameter or to compute the parameter for a point.
1627 * *EISLib* provides methods for analytic surfaces.
1628 This is a library of simple computations on surfaces from the package *gp* (Planes, Cylinders, Spheres, Cones, Tori).
1629 It is possible to compute points with a given pair of parameters or to compute the parameter for a point.
1630 There is a library for calculating normals on curves and surfaces.
1632 Additionally, *Bnd* package provides a set of classes and tools to operate with bounding boxes of geometric objects in 2d and 3d space.
1634 @subsection occt_occt_fcug_4_6 Common Math Algorithms
1635 The common math algorithms library provides a C++ implementation of the most frequently used mathematical algorithms. These include:
1636 * Algorithms to solve a set of linear algebraic equations,
1637 * Algorithms to find the minimum of a function of one or more independent variables,
1638 * Algorithms to find roots of one, or of a set, of non-linear equations,
1639 * An algorithm to find the eigenvalues and eigenvectors of a square matrix.
1641 All mathematical algorithms are implemented using the same principles.
1643 * A constructor performing all, or most of, the calculation, given the appropriate arguments.
1644 All relevant information is stored inside the resulting object, so that all subsequent calculations or interrogations will be solved in the most efficient way.
1645 * A function *IsDone* returning the boolean true if the calculation was successful.
1646 * A set of functions, specific to each algorithm, enabling all the various results to be obtained.
1647 Calling these functions is legal only if the function *IsDone* answers **true**, otherwise the exception *StdFail_NotDone* is raised.
1649 The example below demonstrates the use of the math_Gauss class, which implements the Gauss solution for a set of linear equations.
1650 The following definition is an extract from the header file of the class *math_Gauss*:
1656 math_Gauss (const math_Matrix& A);
1657 Standard_Boolean IsDone() const;
1658 void Solve (const math_Vector& B, math_Vector& X) const;
1662 Now the main program uses the math_Gauss class to solve the equations _a*x1=b1_ and _a*x2=b2_:
1665 #include <math_Vector.hxx>
1666 #include <math_Matrix.hxx>
1669 math_Vector a(1, 3, 1, 3);
1670 math_Vector b1(1, 3), b2(1, 3);
1671 math_Vector x1(1, 3), x2(1, 3);
1672 // a, b1 and b2 are set here to the appropriate values
1675 math_Gauss aSol(a); // computation of the LU decomposition of A
1676 if (aSol.IsDone()) // is it OK ?
1678 aSol.Solve(b1, x1); // yes, so compute x1
1679 aSol.Solve(b2, x2); // then x2
1682 else // it is not OK:
1685 aSol.Solve(b1, x1); // error:
1686 // StdFail_NotDone is raised
1691 The next example demonstrates the use of the *math_BissecNewton* class, which implements a combination of the Newton and Bissection algorithms to find the root of a function known to lie between two bounds.
1692 The definition is an extract from the header file of the class *math_BissecNewton*:
1695 class math_BissecNewton
1698 math_BissecNewton (math_FunctionWithDerivative& f,
1699 const Standard_Real bound1,
1700 const Standard_Real bound2,
1701 const Standard_Real tolx);
1702 Standard_Boolean IsDone() const;
1703 Standard_Real Root();
1707 The abstract class *math_FunctionWithDerivative* describes the services which have to be implemented for the function _f_ which is to be used by a *math_BissecNewton* algorithm.
1708 The following definition corresponds to the header file of the abstract class *math_FunctionWithDerivative*:
1711 class math_FunctionWithDerivative
1714 virtual Standard_Boolean Value (const Standard_Real x, Standard_Real& f) = 0;
1715 virtual Standard_Boolean Derivative (const Standard_Real x, Standard_Real& d) = 0;
1716 virtual Standard_Boolean Values (const Standard_Real x, Standard_Real& f, Standard_Real& d) = 0;
1720 Now the test sample uses the *math_BissecNewton* class to find the root of the equation _f(x)=x**2-4_ in the interval [1.5, 2.5].
1721 The function to solve is implemented in the class *myFunction* which inherits from the class *math_FunctionWithDerivative*, then the main program finds the required root.
1724 #include <math_BissecNewton.hxx>
1725 #include <math_FunctionWithDerivative.hxx>
1726 class myFunction : public math_FunctionWithDerivative
1728 Standard_Real myCoefA, myCoefB, myCoefC;
1731 myFunction (const Standard_Real theA, const Standard_Real theB, const Standard_Real theC)
1732 : myCoefA(a), myCoefB(b), myCoefC(c) {}
1734 virtual Standard_Boolean Value (const Standard_Real x, Standard_Real& f) override
1736 f = myCoefA * x * x + myCoefB * x + myCoefC;
1739 virtual Standard_Boolean Derivative (const Standard_Real x, Standard_Real& d) override
1741 d = myCoefA * x * 2.0 + myCoefB;
1744 virtual Standard_Boolean Values (const Standard_Real x, Standard_Real& f, Standard_Real& d) override
1746 f = myCoefA * x * x + myCoefB * x + myCoefC;
1747 d = myCoefA * x * 2.0 + myCoefB;
1753 myFunction aFunc (1.0, 0.0, 4.0);
1754 math_BissecNewton aSol (aFunc, 1.5, 2.5, 0.000001);
1755 if (aSol.IsDone()) // is it OK ?
1757 Standard_Real x = aSol.Root(); // yes
1764 @subsection occt_occt_fcug_4_7 Precision
1766 On the OCCT platform, each object stored in the database should carry its own precision value.
1767 This is important when dealing with systems where objects are imported from other systems as well as with various associated precision values.
1769 The *Precision* package addresses the daily problem of the geometric algorithm developer: what precision setting to use to compare two numbers.
1770 Real number equivalence is clearly a poor choice.
1771 The difference between the numbers should be compared to a given precision setting.
1773 Do not write _if (X1 == X2)_, instead write _if (Abs(X1-X2) < Precision)_.
1775 Also, to order real numbers, keep in mind that _if (X1 < X2 - Precision)_ is incorrect.
1776 _if (X2 - X1 > Precision)_ is far better when *X1* and *X2* are high numbers.
1778 This package proposes a set of methods providing precision settings for the most commonly encountered situations.
1780 In Open CASCADE Technology, precision is usually not implicit; low-level geometric algorithms accept precision settings as arguments.
1781 Usually these should not refer directly to this package.
1783 High-level modeling algorithms have to provide a precision setting to the low level geometric algorithms they call.
1784 One way is to use the settings provided by this package.
1785 The high-level modeling algorithms can also have their own strategy for managing precision.
1786 As an example the Topology Data Structure stores precision values which are later used by algorithms.
1787 When a new topology is created, it takes the stored value.
1789 Different precision settings offered by this package cover the most common needs of geometric algorithms such as *Intersection* and *Approximation*.
1790 The choice of a precision value depends both on the algorithm and on the geometric space.
1791 The geometric space may be either:
1792 * a real space, 3d or 2d where the lengths are measured in meters, micron, inches, etc.
1793 * a parametric space, 1d on a curve or 2d on a surface where numbers have no dimension.
1795 The choice of precision value for parametric space depends not only on the accuracy of the machine, but also on the dimensions of the curve or the surface.
1796 This is because it is desirable to link parametric precision and real precision.
1797 If you are on a curve defined by the equation *P(t)*, you would want to have equivalence between the following:
1800 Abs (t1 - t2) < ParametricPrecision
1801 Distance (P(t1), P(t2)) < RealPrecision
1804 @subsubsection occt_occt_fcug_4_7_1 The Precision package
1806 The *Precision* package offers a number of package methods and default precisions for use in dealing with angles, distances, intersections, approximations, and parametric space.
1807 It provides values to use in comparisons to test for real number equalities.
1808 * **Angular** precision compares angles.
1809 * **Confusion** precision compares distances.
1810 * **Intersection** precision is used by intersection algorithms.
1811 * **Approximation** precision is used by approximation algorithms.
1812 * **Parametric** precision gets a parametric space precision from a 3D precision.
1813 * **Infinite** returns a high number that can be considered to be infinite.
1814 Use <i>-Infinite</i> for a high negative number.
1816 @subsubsection occt_occt_fcug_4_7_2 Standard Precision values
1818 This package provides a set of real space precision values for algorithms.
1819 The real space precisions are designed for precision to *0.1* nanometers (in case if model is defined in millimeters).
1821 The parametric precisions are derived from the real precisions by the *Parametric* function.
1822 This applies a scaling factor which is the length of a tangent to the curve or the surface.
1823 You, the user, provide this length.
1824 There is a default value for a curve with <i>[0,1]</i> parameter space and a length less than 100 meters.
1826 The geometric packages provide Parametric precisions for the different types of curves.
1827 The *Precision* package provides methods to test whether a real number can be considered to be infinite.
1829 #### Precision::Angular
1831 This method is used to compare two angles.
1832 Its current value is *Epsilon(2 * PI)* i.e. the smallest number *x* such that *2*PI + x* is different of *2\*PI*.
1834 It can be used to check confusion of two angles as follows:
1836 bool areEqualAngles (double theAngle1, double theAngle2)
1838 return Abs(theAngle1 - theAngle2) < Precision::Angular();
1842 It is also possible to check parallelism of two vectors as follows:
1844 bool areParallelVectors (const gp_Vec& theVec1, const gp_Vec& theVec2)
1846 return theVec1.IsParallel (theVec2, Precision::Angular());
1850 Note that *Precision::Angular()* can be used on both dot and cross products because for small angles the *Sine* and the *Angle* are equivalent.
1851 So to test if two directions of type *gp_Dir* are perpendicular, it is legal to use the following code:
1853 bool arePerpendicular (const gp_Dir& theDir1, const gp_Dir& theDir2)
1855 return Abs(theDir1 * theDir2) < Precision::Angular();
1859 #### Precision::Confusion
1861 This method is used to test 3D distances.
1862 The current value is *1.e-7*, in other words, 1/10 micron if the unit used is the millimeter.
1864 It can be used to check confusion of two points as follows:
1866 bool areEqualPoints (const gp_Pnt& thePnt1, const gp_Pnt& thePnt2)
1868 return thePnt1.IsEqual (thePnt2, Precision::Confusion());
1872 It is also possible to find a vector of null length:
1874 bool isNullVector (const gp_Vec& theVec)
1876 return theVec.Magnitude() < Precision::Confusion();
1880 #### Precision::Intersection
1882 This is reasonable precision to pass to an Intersection process as a limit of refinement of Intersection Points.
1883 *Intersection* is high enough for the process to converge quickly.
1884 *Intersection* is lower than *Confusion* so that you still get a point on the intersected geometries.
1885 The current value is *Confusion() / 100*.
1887 #### Precision::Approximation
1889 This is a reasonable precision to pass to an approximation process as a limit of refinement of fitting.
1890 The approximation is greater than the other precisions because it is designed to be used when the time is at a premium.
1891 It has been provided as a reasonable compromise by the designers of the Approximation algorithm.
1892 The current value is *Confusion() * 10*.
1893 Note that Approximation is greater than Confusion, so care must be taken when using Confusion in an approximation process.