0031939: Coding - correction of spelling errors in comments [part 3]
[occt.git] / dox / user_guides / foundation_classes / foundation_classes.md
CommitLineData
ba06f8bb 1Foundation Classes {#occt_user_guides__foundation_classes}
72b7576f 2=================================
3
e5bd0d98 4@tableofcontents
5
72b7576f 6@section occt_fcug_1 Introduction
7
8b742dc1 8This manual explains how to use Open CASCADE Technology (**OCCT**) Foundation Classes.
9It provides basic documentation on foundation classes.
e2b55410 10
8b742dc1 11Foundation 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.
72b7576f 12
72b7576f 13Foundation Classes include the following:
14
dba69de2 15### Root Classes
8b742dc1 16Root classes are the basic data types and classes on which all the other classes are built.
17They provide:
72b7576f 18 * fundamental types such as Boolean, Character, Integer or Real,
8b742dc1 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,
72b7576f 22 * management of exceptions,
23 * encapsulation of C++ streams.
8b742dc1 24Root classes are mainly implemented in *Standard* package.
72b7576f 25
dba69de2 26### Strings
8b742dc1 27Strings are classes that handle dynamically sized sequences of characters based on UTF-8 and UTF-16 encodings.
28Strings may also be manipulated by handles, and consequently be shared.
29Strings are implemented in the *TCollection* package.
72b7576f 30
dba69de2 31### Collections
8b742dc1 32Collections are the classes that handle dynamically sized aggregates of data.
33Collection classes are *generic* and rely on C++ templates.
72b7576f 34
8b742dc1 35Collections include a wide range of generic classes such as run-time sized arrays, lists, stacks, queues, sets and hash maps.
36Collections are implemented in the *TCollection* and *NCollection* packages.
72b7576f 37
dba69de2 38### Collections of Standard Objects
39
8b742dc1 40The *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.
72b7576f 41
dba69de2 42### Vectors and Matrices
43
8b742dc1 44These classes provide commonly used mathematical algorithms and basic calculations (addition, multiplication, transposition, inversion, etc.) involving vectors and matrices.
72b7576f 45
dba69de2 46### Primitive Geometric Types
47
8b742dc1 48Open CASCADE Technology primitive geometric types are a STEP-compliant implementation of basic geometric and algebraic entities.
49They provide:
50 * Descriptions of elementary geometric shapes:
51 * Points,
52 * Vectors,
53 * Lines,
54 * Circles and conics,
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:
58 * Translations
59 * Rotations
60 * Symmetries
61 * Scaling transformations
62 * Composed transformations
63 * Tools (coordinates and matrices) for algebraic computation.
64
dba69de2 65### Common Math Algorithms
72b7576f 66
8b742dc1 67Open CASCADE Technology common math algorithms provide a C++ implementation of the most frequently used mathematical algorithms.
68These include:
72b7576f 69 * Algorithms to solve a set of linear algebraic equations,
8b742dc1 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.
72b7576f 73
dba69de2 74### Exceptions
75
8b742dc1 76A hierarchy of commonly used exception classes is provided, all based on class Standard_Failure, the root of exceptions.
77Exceptions describe exceptional situations, which can arise during the execution of a function.
78With the raising of an exception, the normal course of program execution is abandoned.
79The execution of actions in response to this situation is called the treatment of the exception.
dba69de2 80
81### Quantities
82
8b742dc1 83These are various classes supporting date and time information.
72b7576f 84
dba69de2 85### Application services
86
8b742dc1 87Foundation Classes also include implementation of several low-level services that facilitate the creation of customizable and user-friendly applications with Open CASCADE Technology.
88These include:
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.
72b7576f 94
e2b55410 95@section occt_fcug_2 Basics
8b742dc1 96This 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.
dba69de2 97
e2b55410 98@subsection occt_fcug_2_a Library organization
dba69de2 99
e2b55410 100This chapter introduces some basic concepts, which are used not only in Foundation Classes, but throughout the whole OCCT library.
101
8b742dc1 102@subsubsection occt_fcug_2_a_1 Modules and toolkits
72b7576f 103
8b742dc1 104The whole OCCT library is organized in a set of modules.
105The first module, providing most basic services and used by all other modules, is called Foundation Classes and described by this manual.
dba69de2 106
8b742dc1 107Every module consists primarily of one or several toolkits (though it can also contain executables, resource units etc.).
108Physically a toolkit is represented by a shared library (e.g. .so or .dll).
109The toolkit is built from one or several packages.
dba69de2 110
e2b55410 111@subsubsection occt_fcug_2_a_2 Packages
8b742dc1 112A **package** groups together a number of classes which have semantic links.
113For example, a geometry package would contain Point, Line, and Circle classes.
114A package can also contain enumerations, exceptions and package methods (functions).
115In practice, a class name is prefixed with the name of its package e.g. *Geom_Circle*.
116Data types described in a package may include one or more of the following data types:
72b7576f 117 * Enumerations
118 * Object classes
119 * Exceptions
120 * Pointers to other object classes
8b742dc1 121Inside a package, two data types cannot bear the same name.
72b7576f 122
d6b4d3d0 123@figure{/user_guides/foundation_classes/images/foundation_classes_image003.png,"Contents of a package",420}
72b7576f 124
8b742dc1 125**Methods** are either **functions** or **procedures**.
126Functions return an object, whereas procedures only communicate by passing arguments.
127In both cases, when the transmitted object is an instance manipulated by a handle, its identifier is passed.
128There 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.
72b7576f 133
e2b55410 134@subsubsection occt_fcug_2_a_3 Classes
8b742dc1 135The fundamental software component in object-oriented software development is the class.
136A class is the implementation of a **data type**.
137It defines its **behavior** (the services offered by its functions) and its **representation** (the data structure of the class -- the fields, which store its data).
72b7576f 138
8b742dc1 139Classes fall into three categories:
e2b55410 140* Ordinary classes.
8b742dc1 141* Abstract classes.
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.
145* Template classes.
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).
dba69de2 148
e2b55410 149@subsubsection occt_fcug_2_a_5 Inheritance
8b742dc1 150The purpose of inheritance is to reduce the development workload.
151The inheritance mechanism allows a new class to be declared already containing the characteristics of an existing class.
152This new class can then be rapidly specialized for the task in hand.
153This avoids the necessity of developing each component "from scratch".
154For example, having already developed a class *BankAccount* you could quickly specialize new classes: *SavingsAccount, LongTermDepositAccount, MoneyMarketAccount, RevolvingCreditAccount*, etc....
dba69de2 155
8b742dc1 156The 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).
157For 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.
e2b55410 158
8b742dc1 159One way of ensuring the use of inheritance is to declare classes at the top of a hierarchy as being **abstract**.
160In such classes, the methods are not implemented.
161This forces the user to create a new class which redefines the methods.
162This is a way of guaranteeing a certain minimum of behavior among descendant classes.
e2b55410 163
164@subsection occt_fcug_2_1 Data Types
dba69de2 165
8b742dc1 166An object-oriented language structures a system around data types rather than around the actions carried out on this data.
167In this context, an **object** is an **instance** of a data type and its definition determines how it can be used.
168Each data type is implemented by one or more classes, which make up the basic elements of the system.
72b7576f 169
8b742dc1 170The data types in Open CASCADE Technology fall into two categories:
72b7576f 171 * Data types manipulated by handle (or reference)
172 * Data types manipulated by value
8b742dc1 173
d6b4d3d0 174@figure{/user_guides/foundation_classes/images/foundation_classes_image004.png,"Manipulation of data types",420}
dba69de2 175
8b742dc1 176A data type is implemented as a class.
177The 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.
180The first examples of types manipulated by values are the predefined **primitive types**: *Boolean, Character, Integer, Real*, etc.
181
182A variable of a type manipulated by handle which is not attached to an object is said to be **null**.
183To reference an object, we instantiate the class with one of its constructors.
184For example, in C++:
72b7576f 185
186~~~~~
8b742dc1 187Handle(MyClass) anObject = new MyClass();
72b7576f 188~~~~~
189
8b742dc1 190In Open CASCADE Technology, the Handles are specific classes that are used to safely manipulate objects allocated in the dynamic memory by reference,
191providing reference counting mechanism and automatic destruction of the object when it is not referenced.
72b7576f 192
72b7576f 193@subsubsection occt_fcug_2_1_1 Primitive Types
e2b55410 194
8b742dc1 195The primitive types are predefined in the language and they are **manipulated by value**.
dba69de2 196
8b742dc1 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.
d3013f55 207
8b742dc1 208The services offered by each of these types are described in the **Standard** Package.
209The table below presents the equivalence existing between C++ fundamental types and OCCT primitive types.
72b7576f 210
8b742dc1 211**Table 1: Equivalence between C++ Types and OCCT Primitive Types**
e5bd0d98 212
213| C++ Types | OCCT Types |
214| :--------- | :----------- |
215| int | Standard_Integer |
72b7576f 216| double | Standard_Real |
e5bd0d98 217| float | Standard_ShortReal |
7863dabb 218| bool | Standard_Boolean |
e5bd0d98 219| char | Standard_Character |
8b742dc1 220| char16_t | Standard_Utf16Char |
dba69de2 221| char\* | Standard_CString |
222| void\* | Standard_Address |
7863dabb 223| char16_t\* | Standard_ExtString |
72b7576f 224
8b742dc1 225\* The types with asterisk are pointers.
226
227**Reminder of the classes listed above:**
228
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.
72b7576f 256
257@subsubsection occt_fcug_2_1_2 Types manipulated by value
8b742dc1 258There are three categories of types which are manipulated by value:
72b7576f 259 * Primitive types
260 * Enumerated types
d3013f55 261 * Types defined by classes not inheriting from *Standard_Transient*, whether directly or not.
8b742dc1 262Types 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.
72b7576f 263
d6b4d3d0 264@figure{/user_guides/foundation_classes/images/foundation_classes_image005.png,"Manipulation of a data type by value",420}
72b7576f 265
72b7576f 266@subsubsection occt_fcug_2_1_3 Types manipulated by reference (handle)
d3013f55 267
8b742dc1 268These are types defined by classes inheriting from the *Standard_Transient* class.
269
d6b4d3d0 270@figure{/user_guides/foundation_classes/images/foundation_classes_image006.png,"Manipulation of a data type by reference",420}
72b7576f 271
e2b55410 272@subsubsection occt_fcug_2_1_4 When is it necessary to use a handle?
72b7576f 273
8b742dc1 274When you design an object, it can be difficult to choose how to manipulate that object: by value or by handle.
275The 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.
72b7576f 287
288@subsection occt_fcug_2_2 Programming with Handles
e2b55410 289
72b7576f 290@subsubsection occt_fcug_2_2_1 Handle Definition
e2b55410 291
d3013f55 292A handle is OCCT implementation of a smart pointer.
293Several handles can reference the same object.
8b742dc1 294Also, a single handle may reference several objects, but only one at a time.
295To have access to the object it refers to, the handle must be de-referenced just as with a C++ pointer.
72b7576f 296
4ee1bdf4 297#### Organization of Classes
298
8b742dc1 299Class *Standard_Transient* is a root of a big hierarchy of OCCT classes that are said to be operable by handles.
300It 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.
dba69de2 301
d3013f55 302Objects of classes derived (directly or indirectly) from *Transient*, are normally allocated in dynamic memory using operator **new**, and manipulated by handle.
303Handle is defined as template class *opencascade::handle<>*.
8b742dc1 304Open CASCADE Technology provides preprocessor macro *Handle()* that is historically used throughout OCCT code to name a handle:
d3013f55 305~~~~~{.cpp}
7863dabb 306Handle(Geom_Line) aLine; // "Handle(Geom_Line)" is expanded to "opencascade::handle<Geom_Line>"
d3013f55 307~~~~~
308
8b742dc1 309In addition, for most OCCT classes additional *typedef* is defined for a handle, as the name of a class prefixed by *Handle_*.
04c2daa4 310For instance, the above example can be also coded as:
d3013f55 311~~~~~{.cpp}
7863dabb 312Handle_Geom_Line aLine; // "Handle_Geom_Line" is typedef to "opencascade::handle<Geom_Line>"
d3013f55 313~~~~~
4ee1bdf4 314
315#### Using a Handle
72b7576f 316
8b742dc1 317A handle is characterized by the object it references.
72b7576f 318
8b742dc1 319Before performing any operation on a transient object, you must declare the handle.
320For example, if Point and Line are two transient classes from the Geom package, you would write:
72b7576f 321~~~~~
8b742dc1 322Handle(Geom_Point) p1, p2;
72b7576f 323~~~~~
8b742dc1 324Declaring a handle creates a null handle that does not refer to any object.
325The handle may be checked to be null by its method *IsNull()*.
326To nullify a handle, use method *Nullify()*.
dba69de2 327
8b742dc1 328To 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.
dba69de2 329
8b742dc1 330**Note** that handles should only be used for object sharing.
331For all local operations, it is advisable to use classes manipulated by values.
72b7576f 332
333@subsubsection occt_fcug_2_2_2 Type Management
334
8b742dc1 335Open 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).
d3013f55 336
04c2daa4 337To enable this feature, a class declaration should include the declaration of OCCT RTTI.
d3013f55 338Header *Standard_Type.hxx* provides two variants of preprocessor macros facilitating this:
339
04c2daa4 340* Inline variant, which declares and defines RTTI methods by a single line of code:
d3013f55 341~~~~~{.cpp}
342#include <Geom_Surface.hxx>
343class Appli_ExtSurface : public Geom_Surface
344{
345. . .
346public:
347 DEFINE_STANDARD_RTTIEXT(Appli_ExtSurface,Geom_Surface)
348};
349~~~~~
350
04c2daa4 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):
d3013f55 352
353 In *Appli_ExtSurface.hxx* file:
354~~~~~{.cpp}
355#include <Geom_Surface.hxx>
356class Appli_ExtSurface : public Geom_Surface
357{
358. . .
359public:
360 DEFINE_STANDARD_RTTIEXT(Appli_ExtSurface,Geom_Surface)
361};
362~~~~~
363
364 In *Appli_ExtSurface.cxx* file:
365~~~~~{.cpp}
366#include <Appli_ExtSurface.hxx>
367IMPLEMENT_STANDARD_RTTIEXT(Appli_ExtSurface,Geom_Surface)
368~~~~~
369
370These macros define method *DynamicType()* that returns a type descriptor - handle to singleton instance of the class *Standard_Type* describing the class.
04c2daa4 371The type descriptor stores the name of the class and the descriptor of its parent class.
e2b55410 372
d3013f55 373Note 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.
dba69de2 374
04c2daa4 375To get the type descriptor for a given class type, use macro *STANDARD_TYPE()* with the name of the class as argument.
d3013f55 376
377Example of usage:
378~~~~~{.cpp}
379if (aCurve->IsKind(STANDARD_TYPE(Geom_Line))) // equivalent to "if (dynamic_cast<Geom_Line>(aCurve.get()) != 0)"
380{
381...
382}
383~~~~~
72b7576f 384
4ee1bdf4 385#### Type Conformity
386
8b742dc1 387The type used in the declaration of a handle is the static type of the object, the type seen by the compiler.
388A handle can reference an object instantiated from a subclass of its static type.
389Thus, 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.
dba69de2 390
8b742dc1 391Consider the class *Geom_CartesianPoint*, a sub-class of *Geom_Point*; the rule of type conformity can be illustrated as follows:
72b7576f 392
393~~~~~
8b742dc1 394Handle(Geom_Point) aPnt1;
395Handle(Geom_CartesianPoint) aPnt2;
396aPnt2 = new Geom_CartesianPoint();
397aPnt1 = aPnt2; // OK, the types are compatible
72b7576f 398~~~~~
399
8b742dc1 400The compiler sees *aPnt1* as a handle to *Geom_Point* though the actual object referenced by *aPnt1* is of the *Geom_CartesianPoint* type.
72b7576f 401
4ee1bdf4 402#### Explicit Type Conversion
403
8b742dc1 404According to the rule of type conformity, it is always possible to go up the class hierarchy through successive assignments of handles.
405On the other hand, assignment does not authorize you to go down the hierarchy.
406Consequently, an explicit type conversion of handles is required.
dba69de2 407
8b742dc1 408A 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.
409If this is not the case, the handle is nullified (explicit type conversion is sometimes called a "safe cast").
410Consider the example below.
72b7576f 411
412~~~~~~
8b742dc1 413Handle(Geom_Point) aPnt1;
414Handle(Geom_CartesianPoint) aPnt2, aPnt3;
415aPnt2 = new Geom_CartesianPoint();
416aPnt1 = aPnt2; // OK, standard assignment
417aPnt3 = 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
72b7576f 419~~~~~~
420
8b742dc1 421If conversion is not compatible with the actual type of the referenced object, the handle which was "cast" becomes null (and no exception is raised).
422So, if you require reliable services defined in a sub-class of the type seen by the handle (static type), write as follows:
72b7576f 423
424~~~~~~
e5bd0d98 425void MyFunction (const Handle(A) & a)
72b7576f 426{
04c2daa4 427 Handle(B) b = Handle(B)::DownCast(a);
dba69de2 428 if (! b.IsNull()) {
429 // we can use “b” if class B inherits from A
430 }
431 else {
432 // the types are incompatible
433 }
72b7576f 434}
435~~~~~~
8b742dc1 436Downcasting is used particularly with collections of objects of different types; however, these objects should inherit from the same root class.
dba69de2 437
8b742dc1 438For 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:
72b7576f 439
440~~~~~
8b742dc1 441Handle(A) a;
442Handle(B) b;
443Handle(Standard_Transient) t;
444TColStd_SequenceOfTransient aSeq;
445a = new A();
446aSeq.Append (a);
447b = new B();
448aSeq.Append (b);
449t = aSeq.Value (1);
72b7576f 450// here, you cannot write:
451// a = t; // ERROR !
452// so you downcast:
453a = Handle (A)::Downcast (t)
8b742dc1 454if (!a.IsNull())
455{
456 // types are compatible, you can use a
72b7576f 457}
8b742dc1 458else
459{
460 // the types are incompatible
72b7576f 461}
462~~~~~
463
8b742dc1 464@subsubsection occt_fcug_2_2_3 Using Handles to Create Objects
e2b55410 465
8b742dc1 466To 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.
467The constructor can be any of those specified in the source of the class from which the object is instanced.
72b7576f 468
469~~~~~
8b742dc1 470Handle(Geom_CartesianPoint) aPnt;
471aPnt = new Geom_CartesianPoint (0, 0, 0);
72b7576f 472~~~~~
473
8b742dc1 474Unlike for a pointer, the **delete** operator does not work on a handle; the referenced object is automatically destroyed when no longer in use.
72b7576f 475
476@subsubsection occt_fcug_2_2_4 Invoking Methods
8b742dc1 477Once you have a handle to an object, you can use it like a pointer in C++.
478To 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.
dba69de2 479
8b742dc1 480To test or to modify the state of the handle, the method is translated by the *dot* operator.
481The example below illustrates how to access the coordinates of an (optionally initialized) point object:
72b7576f 482
483~~~~~
8b742dc1 484Handle(Geom_CartesianPoint) aCentre;
72b7576f 485Standard_Real x, y, z;
8b742dc1 486if (aCentre.IsNull())
487{
488 aCentre = new PGeom_CartesianPoint (0, 0, 0);
72b7576f 489}
8b742dc1 490aCentre->Coord (x, y, z);
72b7576f 491~~~~~
492
8b742dc1 493The example below illustrates how to access the type object of a Cartesian point:
72b7576f 494
495~~~~~
8b742dc1 496Handle(Standard_Transient) aPnt = new Geom_CartesianPoint (0., 0., 0.);
497if (aPnt->DynamicType() == STANDARD_TYPE(Geom_CartesianPoint))
498{
499 std::cout << "Type check OK\n";
500}
501else
502{
503 std::cout << "Type check FAILED\n";
504}
72b7576f 505~~~~~
506
8b742dc1 507*Standard_NullObject* exception will be raised if a field or a method of an object is accessed via a *Null* handle.
72b7576f 508
4ee1bdf4 509#### Invoking Class Methods
510
8b742dc1 511A 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.
72b7576f 512
513For example, we can find the maximum degree of a Bezier curve:
514
515~~~~~
8b742dc1 516Standard_Integer aDegree = Geom_BezierCurve::MaxDegree();
72b7576f 517~~~~~
518
4ee1bdf4 519@subsubsection occt_fcug_2_2_5 Handle deallocation
e2b55410 520
8b742dc1 521Before you delete an object, you must ensure it is no longer referenced.
522To 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.
523A handle automatically deletes an object when it is no longer referenced.
524Normally you never call the delete operator explicitly on instances of subclasses of *Standard_Transient*.
dba69de2 525
8b742dc1 526When a new handle to the same object is created, the reference counter is incremented.
527When the handle is destroyed, nullified, or reassigned to another object, that counter is decremented.
528The object is automatically deleted by the handle when reference counter becomes 0.
dba69de2 529
8b742dc1 530The principle of allocation can be seen in the example below.
72b7576f 531
532~~~~~
533...
534{
8b742dc1 535 Handle(TColStd_HSequenceOfInteger) H1 = new TColStd_HSequenceOfInteger();
dba69de2 536 // H1 has one reference and corresponds to 48 bytes of memory
537 {
8b742dc1 538 Handle(TColStd_HSequenceOfInteger) H2;
dba69de2 539 H2 = H1; // H1 has two references
8b742dc1 540 if (argc == 3)
541 {
542 Handle(TColStd_HSequenceOfInteger) H3;
dba69de2 543 H3 = H1;
544 // Here, H1 has three references
545 ...
546 }
547 // Here, H1 has two references
548 }
549 // Here, H1 has 1 reference
72b7576f 550}
8b742dc1 551// Here, H1 has no reference and the referred TColStd_HSequenceOfInteger object is deleted.
72b7576f 552~~~~~
553
e2b55410 554You can easily cast a reference to the handle object to <i> void* </i> by defining the following:
555
556~~~~
8b742dc1 557 void* aPointer;
558 Handle(Some_Class) aHandle;
559 // Here only a pointer will be copied
560 aPointer = &aHandle;
561 // Here the Handle object will be copied
562 aHandle = *(Handle(Some_Class)*)aPointer;
e2b55410 563~~~~
4ee1bdf4 564
8b742dc1 565@subsubsection occt_fcug_2_2_6 Cycles
e2b55410 566
8b742dc1 567Cycles appear if two or more objects reference each other by handles (stored as fields).
568In this condition automatic destruction will not work.
dba69de2 569
8b742dc1 570Consider 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.
571If 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.
e2b55410 572
8b742dc1 573The 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).
dba69de2 574
8b742dc1 575There 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
72b7576f 578
e2b55410 579@subsection occt_fcug_2_3 Memory Management
580
8b742dc1 581In a work session, geometric modeling applications create and delete a considerable number of C++ objects allocated in the dynamic memory (heap).
582In this context, performance of standard functions for allocating and deallocating memory may be not sufficient.
583For this reason, Open CASCADE Technology employs a specialized memory manager implemented in the *Standard* package.
e2b55410 584
585The Memory Manager is based on the following principles:
586
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).
589
8b742dc1 590As a general rule, it is advisable to allocate memory through significant blocks.
591In this way, the user can work with blocks of contiguous data and it facilitates memory page manager processing.
e2b55410 592
593@subsubsection occt_fcug_2_3_1 Usage of Memory Manager
594
8b742dc1 595To 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()*.
596In addition, method *Standard::Reallocate()* is provided to replace C function *realloc()*.
dba69de2 597
8b742dc1 598In 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()*.
599In that case all objects of that class and all inherited classes will be allocated using the OCCT memory manager.
dba69de2 600
d3013f55 601Preprocessor macro *DEFINE_STANDARD_ALLOC* provided by header *Standard_DefineAlloc.hxx* defines *new()* and *delete()* in this way.
8b742dc1 602It is used for all OCCT classes (apart from a few exceptions) which thus are allocated using the OCCT memory manager.
603Since 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*.
dba69de2 604
8b742dc1 605**Note** that it is possible (though not recommended unless really unavoidable) to redefine *new()* and *delete()* functions for a class inheriting *Standard_Transient*.
606If that is done, the method *Delete()* should be also redefined to apply operator *delete* to this pointer.
607This will ensure that appropriate *delete()* function will be called, even if the object is manipulated by a handle to a base class.
e2b55410 608
609@subsubsection occt_fcug_2_3_2 How to configure the Memory Manager
72b7576f 610
8b742dc1 611The OCCT memory manager may be configured to apply different optimization techniques to different memory blocks (depending on their size),
612or even to avoid any optimization and use C functions *malloc()* and *free()* directly.
613The configuration is defined by numeric values of the following environment variables:
614 * *MMGT_OPT*:
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()*.
7277133a 624
e2b55410 625@subsubsection occt_fcug_2_3_3 Optimization Techniques
626
8b742dc1 627When *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.
dba69de2 632
8b742dc1 633In the current version memory pools are never returned to the system (until the process finishes).
634However, 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).
635
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.
dba69de2 638
8b742dc1 639However, 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()*.
640
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.
dba69de2 644
e2b55410 645@subsubsection occt_fcug_2_3_4 Benefits and drawbacks
dba69de2 646
8b742dc1 647The major benefit of the OCCT memory manager is explained by its recycling of small and medium blocks that makes an application work much faster
648when it constantly allocates and frees multiple memory blocks of similar sizes.
649In practical situations, the real gain on the application performance may be up to 50%.
dba69de2 650
8b742dc1 651The associated drawback is that recycled memory is not returned to the operating system during program execution.
652This may lead to considerable memory consumption and even be misinterpreted as a memory leak.
653To minimize this effect it is necessary to call the method *Standard::Purge* after the completion of memory-intensive operations.
e2b55410 654
8b742dc1 655The 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.
dba69de2 660
8b742dc1 661Note that these overheads may be greater or less than overheads induced by the C heap memory manager,
662so overall memory consumption may be greater in either optimized or standard modes, depending on circumstances.
dba69de2 663
8b742dc1 664As a general rule, it is advisable to allocate memory through significant blocks.
665In this way, you can work with blocks of contiguous data, and processing is facilitated for the memory page manager.
72b7576f 666
8b742dc1 667OCCT memory manager uses mutex to lock access to free lists, therefore it may have less performance than non-optimized mode in situations
668when different threads often make simultaneous calls to the memory manager.
669The 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.
e2b55410 670
8b742dc1 671@subsection occt_fcug_2_4 Exceptions
e2b55410 672
8b742dc1 673@subsubsection occt_fcug_2_4_1 Introduction
e2b55410 674
8b742dc1 675The behavior of any object is implemented by the methods, which were defined in its class declaration.
676The definition of these methods includes not only their signature (their programming interface) but also their domain of validity.
e2b55410 677
8b742dc1 678This domain is expressed by **exceptions**.
679Exceptions are raised under various error conditions to protect software quality.
dba69de2 680
8b742dc1 681Exception 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.
dba69de2 682
8b742dc1 683A method may raise an exception which interrupts its normal execution and transfers control to the handler catching this exception.
dba69de2 684
8b742dc1 685A hierarchy of commonly used exception classes is provided.
686The root class is *Standard_Failure* from the *Standard* package.
687So each exception inherits from *Standard_Failure* either directly or by inheriting from another exception.
688Exception classes list all exceptions, which can be raised by any OCCT function.
689
690Open CASCADE Technology also provides support for converting system signals (such as access violation or division by zero) to exceptions,
691so that such situations can be safely handled with the same uniform approach.
dba69de2 692
8b742dc1 693However, in order to support this functionality on various platforms, some special methods and workarounds are used.
694Though the implementation details are hidden and handling of OCCT exceptions is done basically in the same way as with C++,
695some peculiarities of this approach shall be taken into account and some rules must be respected.
dba69de2 696
8b742dc1 697The following paragraphs describe recommended approaches for using exceptions when working with Open CASCADE Technology.
dba69de2 698
8b742dc1 699@subsubsection occt_fcug_2_4_2 Raising an Exception
72b7576f 700
8b742dc1 701#### "C++ like" Syntax
dba69de2 702
8b742dc1 703The following example:
72b7576f 704~~~~~
8b742dc1 705throw Standard_DomainError ("Cannot cope with this condition");
72b7576f 706~~~~~
8b742dc1 707raises an exception of *Standard_DomainError* type with the associated message "Cannot cope with this condition", the message being optional.
708This exception may be caught by a handler of a *Standard_DomainError* type as follows:
72b7576f 709~~~~~
8b742dc1 710try
711{
dba69de2 712 OCC_CATCH_SIGNALS
713 // try block
72b7576f 714}
8b742dc1 715catch (const Standard_DomainError& )
716{
717 // handle Standard_DomainError exceptions here
72b7576f 718}
719~~~~~
720
dba69de2 721#### Regular usage
722
8b742dc1 723Exceptions should not be used as a programming technique, to replace a "goto" statement for example, but as a way to protect methods against misuse.
724The caller must make sure its condition is such that the method can cope with it.
dba69de2 725
8b742dc1 726Thus,
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.
729
730For 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.
734
735then, the *Value* function may be implemented as follows:
72b7576f 736
737~~~~~
8b742dc1 738Item TCollection_Array1::Value (Standard_Integer theIndex) const
72b7576f 739{
8b742dc1 740 // where myR1 and myR2 are the lower and upper bounds of the array
741 if (theIndex < myR1 || theIndex > myR2)
742 {
743 throw Standard_OutOfRange ("Index out of range in TCollection_Array1::Value");
dba69de2 744 }
8b742dc1 745 return myContents[theIndex];
72b7576f 746}
747~~~~~
748
8b742dc1 749Here validity of the index is first verified using the Lower and Upper functions in order to protect the call.
750Normally the caller ensures the index being in the valid range before calling <i>Value()</i>.
751In this case the above implementation of *Value* is not optimal since the test done in *Value* is time-consuming and redundant.
dba69de2 752
8b742dc1 753It is a widely used practice to include that kind of protections in a debug build of the program and exclude in release (optimized) build.
754To support this practice, the macros <i>Raise_if()</i> are provided for every OCCT exception class:
72b7576f 755~~~~~
8b742dc1 756<ErrorTypeName>_Raise_if(condition, "Error message");
72b7576f 757~~~~~
8b742dc1 758where *ErrorTypeName* is the exception type, *condition* is the logical expression leading to the raise of the exception, and *Error message* is the associated message.
dba69de2 759
8b742dc1 760The entire call may be removed by defining one of the preprocessor symbols *No_Exception* or <i>No_<ErrorTypeName></i> at compile-time:
72b7576f 761
762~~~~~
8b742dc1 763#define No_Exception // remove all raises
72b7576f 764~~~~~
765
8b742dc1 766Using this syntax, the *Value* function becomes:
72b7576f 767
768~~~~~
8b742dc1 769Item TCollection_Array1::Value (Standard_Integer theIndex) const
770{
771 Standard_OutOfRange_Raise_if(theIndex < myR1 || theIndex > myR2, "index out of range in TCollection_Array1::Value");
772 return myContents[theIndex];
72b7576f 773}
774~~~~~
775
8b742dc1 776@subsubsection occt_fcug_2_4_3 Handling an Exception
ba06f8bb 777
8b742dc1 778When 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,
72b7576f 780 * the handler whose type matches the raise expression.
dba69de2 781
8b742dc1 782A handler of T exception type is a match for a raise expression with an exception type of E if:
72b7576f 783 * T and E are of the same type, or
784 * T is a supertype of E.
dba69de2 785
8b742dc1 786In order to handle system signals as exceptions, make sure to insert macro *OCC_CATCH_SIGNALS* somewhere in the beginning of the relevant code.
787The recommended location for it is first statement after opening brace of <i>try {}</i> block.
788
789As 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.
72b7576f 790
791~~~~~
792void f(1)
8b742dc1 793{
794 try
795 {
dba69de2 796 OCC_CATCH_SIGNALS
797 // try block
798 }
8b742dc1 799 catch (const Standard_Overflow& ) // first handler
800 {
dba69de2 801 // ...
802 }
8b742dc1 803 catch (const Standard_NumericError& ) // second handler
804 {
dba69de2 805 // ...
806 }
72b7576f 807}
808~~~~~
809
8b742dc1 810Here, the first handler will catch exceptions of *Standard_Overflow* type
811and the second one -- exceptions of *Standard_NumericError* type and all exceptions derived from it, including *Standard_Underflow* and *Standard_DivideByZero*.
dba69de2 812
8b742dc1 813The 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.
814For 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.
72b7576f 815
816~~~~~
817void f(1)
818{
dba69de2 819 int i = 0;
820 {
8b742dc1 821 try
822 {
dba69de2 823 OCC_CATCH_SIGNALS
824 g(i);// i is accessible
825 }
826 // statement here will produce compile-time errors !
8b742dc1 827 catch (const Standard_NumericError& )
828 {
dba69de2 829 // fix up with possible reuse of i
830 }
831 // statement here may produce unexpected side effect
832 }
833 . . .
72b7576f 834}
835~~~~~
836
8b742dc1 837The exceptions form a hierarchy tree completely separated from other user defined classes.
838One exception of type *Standard_Failure* is the root of the entire exception hierarchy.
839Thus, using a handler with *Standard_Failure* type catches any OCCT exception.
840It is recommended to set up such a handler in the main routine.
dba69de2 841
8b742dc1 842The main routine of a program would look like this:
72b7576f 843
844~~~~~
845#include <Standard_ErrorHandler.hxx>
846#include <Standard_Failure.hxx>
8b742dc1 847#include <iostream>
72b7576f 848int main (int argc, char* argv[])
849{
8b742dc1 850 try
851 {
dba69de2 852 OCC_CATCH_SIGNALS
853 // main block
854 return 0;
855 }
8b742dc1 856 catch (const Standard_Failure& theFailure)
857 {
858 std::cerr << "Error " + theFailure.DynamicType()->Name() << " [" << theFailure.GetMessageString() << "]\n";
dba69de2 859 }
860 return 1;
72b7576f 861}
862~~~~~
863
8b742dc1 864Though 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).
865In this mode it is required that no statement precedes or follows any handler.
866Thus it is highly recommended to always include a try block into additional {} braces.
867Also 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.
72b7576f 868
dba69de2 869#### Catching signals
870
8b742dc1 871In 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()*.
dba69de2 872
8b742dc1 873Normally this method is called in the beginning of the main() function.
874It installs a handler that will convert system signals into OCCT exceptions.
dba69de2 875
8b742dc1 876In order to actually convert signals to exceptions, macro *OCC_CATCH_SIGNALS* needs to be inserted in the source code.
877The typical place where this macro is put is beginning of the *try{}* block which catches such exceptions.
72b7576f 878
8b742dc1 879@subsubsection occt_fcug_2_4_4 Implementation on various platforms
dba69de2 880
8b742dc1 881The 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:
ba06f8bb 882
8b742dc1 8831. 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++.
ba06f8bb 885
8b742dc1 8862. 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.
dba69de2 891
8b742dc1 892 This mode differs from standard C++ exception handling only for signals:
893
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.
ba06f8bb 896
8b742dc1 897In 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.
72b7576f 898
8b742dc1 899@subsection occt_fcug_2_5 Plug-In Management
ba06f8bb 900
72b7576f 901@subsubsection occt_fcug_2_5_1 Distribution by Plug-Ins
ba06f8bb 902
8b742dc1 903A plug-in is a component that can be loaded dynamically into a client application, not requiring to be directly linked to it.
904The 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.
dba69de2 905
8b742dc1 906A 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).
910
911The plug-in is identified with the help of the global universal identifier (GUID).
912The GUID includes lower case characters and cannot end with a blank space.
dba69de2 913
8b742dc1 914Once 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).
72b7576f 915
8b742dc1 916#### C++ Plug-In Implementation
4ee1bdf4 917
8b742dc1 918The 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).
a25d5aaa 919The plug-in consists of a shareable 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).
8b742dc1 920Foundation classes provide in the package *Plugin* a method named *Load()*, which enables the client to access the required service through a library.
dba69de2 921
8b742dc1 922That method reads the information regarding available plug-ins and their locations from the resource file *Plugin* found by environment variable *CSF_PluginDefaults*:
72b7576f 923
924~~~~~
8b742dc1 925$CSF_PluginDefaults/Plugin
72b7576f 926~~~~~
927
8b742dc1 928The *Load* method looks for the library name in the resource file or registry through its GUID, for example, on UNIX:
72b7576f 929~~~~~
930! METADATADRIVER whose value must be OS or DM.
931
932! FW
d5265175 933a148e300-5740-11d1-a904-080036aaa103.Location: libFWOSPlugin.so
934~~~~~
935
8b742dc1 936Then 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).
937After that it invokes the *PLUGINFACTORY* method to return the object, which supports the required service.
938The client may then call the functions supported by this object.
72b7576f 939
8b742dc1 940#### C++ Client Plug-In Implementation
4ee1bdf4 941
8b742dc1 942To 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:
72b7576f 943
d5265175 944~~~~~{.cpp}
945Handle(FADriver_PartStorer)::DownCast(PlugIn::Load (yourStandardGUID));
72b7576f 946~~~~~
947
d5265175 948Let us take *FAFactory.hxx* and *FAFactory.cxx* as an example:
72b7576f 949
d5265175 950~~~~~{.cpp}
951#include <Standard_Macro.hxx>
952#include <Standard_GUID.hxx>
953#include <Standard_Transient.hxx>
954
955class FAFactory
956{
957public:
958 Standard_EXPORT static Handle(Standard_Transient) Factory (const Standard_GUID& theGUID);
959};
72b7576f 960~~~~~
d5265175 961
962~~~~~{.cpp}
963#include <FAFactory.hxx>
72b7576f 964
965#include <FADriver_PartRetriever.hxx>
966#include <FADriver_PartStorer.hxx>
967#include <FirstAppSchema.hxx>
72b7576f 968#include <Standard_Failure.hxx>
969#include <FACDM_Application.hxx>
970#include <Plugin_Macro.hxx>
971
d5265175 972static Standard_GUID StorageDriver ("45b3c690-22f3-11d2-b09e-0000f8791463");
973static Standard_GUID RetrievalDriver("45b3c69c-22f3-11d2-b09e-0000f8791463");
974static Standard_GUID Schema ("45b3c6a2-22f3-11d2-b09e-0000f8791463");
72b7576f 975
976//======================================================
977// function : Factory
978// purpose :
979//======================================================
d5265175 980Handle(Standard_Transient) FAFactory::Factory (const Standard_GUID& theGUID)
72b7576f 981{
d5265175 982 if (theGUID == StorageDriver)
983 {
984 std::cout << "FAFactory : Create store driver\n";
985 static Handle(FADriver_PartStorer) sd = new FADriver_PartStorer();
dba69de2 986 return sd;
987 }
d5265175 988 if (theGUID == RetrievalDriver)
989 {
990 std::cout << "FAFactory : Create retrieve driver\n";
991 static Handle(FADriver_PartRetriever) rd = new FADriver_PartRetriever();
dba69de2 992 return rd;
993 }
d5265175 994 if (theGUID == Schema)
995 {
996 std::cout << "FAFactory : Create schema\n";
997 static Handle(FirstAppSchema) s = new FirstAppSchema();
dba69de2 998 return s;
999 }
1000
8b742dc1 1001 throw Standard_Failure ("FAFactory: unknown GUID");
d5265175 1002 return Handle(Standard_Transient)();
72b7576f 1003}
72b7576f 1004
d5265175 1005// export plugin function "PLUGINFACTORY"
1006PLUGIN(FAFactory)
72b7576f 1007~~~~~
1008
80223385 1009Application might also instantiate a factory by linking to the library and calling *FAFactory::Factory()* directly.
72b7576f 1010
8b742dc1 1011@section occt_fcug_3 Collections, Strings, Quantities and Unit Conversion
ba06f8bb 1012
dba69de2 1013@subsection occt_fcug_3_1 Collections
ba06f8bb 1014
72b7576f 1015@subsubsection occt_fcug_3_1_1 Overview
ba06f8bb 1016
8b742dc1 1017The **Collections** component contains the classes that handle dynamically sized aggregates of data.
1018They include a wide range of collections such as arrays, lists and maps.
dba69de2 1019
8b742dc1 1020Some OCCT collections have close friends in modern STL (standard templates collection), but define a little bit different properties or behavior.
1021OCCT 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).
1022OCCT itself highly relies on its own collections for historical reasons - many features implemented by OCCT were unavailable in earlier versions of STL.
e2b55410 1023
8b742dc1 1024Collections 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.
e2b55410 1025
8b742dc1 1026Note that:
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.
72b7576f 1029
8b742dc1 1030The **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).
dba69de2 1039
8b742dc1 1040Macro definitions of these classes are stored in *NCollection_Define\*.hxx* files.
1041These definitions are now obsolete though still can be used, particularly for compatibility with the existing code.
dba69de2 1042
8b742dc1 1043Let see an example of NCollection template class instantiation for a sequence of points in the header file *MyPackage_SequenceOfPnt.hxx* (analogue of *TColgp_SequenceOfPnt*):
dba69de2 1044
8b742dc1 1045~~~~~{.cpp}
1046#include <NCollection_Sequence.hxx>
1047#include <gp_Pnt.hxx>
1048typedef NCollection_Sequence<gp_Pnt> MyPackage_SequenceOfPnt;
1049~~~~~
dba69de2 1050
8b742dc1 1051For the case, when sequence itself should be managed by handle, auxiliary macros *DEFINE_HSEQUENCE* can be used:
1052~~~~~{.cpp}
1053#include <NCollection_Sequence.hxx>
1054#include <NCollection_DefineHSequence.hxx>
1055#include <gp_Pnt.hxx>
1056typedef NCollection_Sequence<gp_Pnt> MyPackage_SequenceOfPnt;
1057DEFINE_HSEQUENCE(MyPackage_HSequenceOfPnt, MyPackage_SequenceOfPnt)
1058...
1059Handle(MyPackage_HSequenceOfPnt) aSeq = new MyPackage_HSequenceOfPnt();
1060~~~~~
dba69de2 1061
8b742dc1 1062See more details about available collections in following sections.
dba69de2 1063
8b742dc1 1064@subsubsection occt_fcug_3_1_2 Arrays and sequences
dba69de2 1065
8b742dc1 1066Standard 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.
dba69de2 1073
8b742dc1 1074These classes provide STL-style iterators (methods begin() and end()) and thus can be used in STL algorithms.
dba69de2 1075
8b742dc1 1076##### NCollection_Array1
dba69de2 1077
8b742dc1 1078These are unidimensional arrays similar to C arrays, i.e. of fixed size but dynamically dimensioned at construction time.
1079As with a C array, the access time for an *NCollection_Array1* indexed item is constant and is independent of the array size.
1080Arrays are commonly used as elementary data structures for more complex objects.
dba69de2 1081
8b742dc1 1082This template class depends on *Item*, the type of element in the array.
1083Array indexation starts and ends at a position given to class constructor.
1084Thus, when accessing an item, you must base the index on the lower and upper bounds of the array.
dba69de2 1085
8b742dc1 1086##### NCollection_Array2
dba69de2 1087
8b742dc1 1088These are bi-dimensional arrays of fixed size but dynamically dimensioned at construction time.
dba69de2 1089
8b742dc1 1090As with a C array, the access time for an *NCollection_Array2* indexed item is constant and is independent of the array size.
1091Arrays are commonly used as elementary data structures for more complex objects.
dba69de2 1092
8b742dc1 1093This template class depends on *Item*, the type of element in the array.
1094Array indexation starts and ends at a position given to class constructor.
1095Thus, when accessing an item, you must base the index on the lower and upper bounds of the array.
dba69de2 1096
8b742dc1 1097##### NCollection_List
dba69de2 1098
8b742dc1 1099These are ordered lists of non-unique objects which can be accessed sequentially using an NCollection_List::Iterator.
1100Item insertion in a list is very fast at any position.
1101But searching for items by value may be slow if the list is long, because it requires a sequential search.
dba69de2 1102
8b742dc1 1103This template class depends on *Item*, the type of element in the structure.
1104A sequence is a better structure when searching for items by value.
1105Queues and stacks are other kinds of list with a different access to data.
dba69de2 1106
8b742dc1 1107##### NCollection_Sequence
dba69de2 1108
8b742dc1 1109This is a sequence of items indexed by an integer.
1110Sequences have about the same goal as unidimensional arrays (*NCollection_Array1*): they are commonly used as elementary data structures for more complex objects.
1111But a sequence is a structure of *variable size*: sequences avoid the use of large and quasi-empty arrays.
1112Exploring 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.
1113Note also that sequences are not effective when they have to support numerous algorithmic explorations: a map is better for that.
72b7576f 1114
8b742dc1 1115This template class depends on *Item*, the type of element in the sequence.
1116The first element in sequence has index equal to 1.
dba69de2 1117
8b742dc1 1118##### NCollection_Vector
dba69de2 1119
8b742dc1 1120Class *NCollection_Vector* is implemented internally as a list of arrays of the same size.
1121Its properties:
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.
dba69de2 1126
8b742dc1 1127Insertion 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.
72b7576f 1131
8b742dc1 1132Other 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().
dba69de2 1136
8b742dc1 1137The first element in vector has index equal to 0.
72b7576f 1138
8b742dc1 1139##### NCollection_SparseArray
dba69de2 1140
8b742dc1 1141Class *NCollection_SparseArray* has almost the same features as *NCollection_Vector*, but it allows to store items having scattered indices.
1142In 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.
1143In NCollection_SparseArray, only one small block of items will be reserved that contains the item with index 1000000.
dba69de2 1144
8b742dc1 1145This 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).
dba69de2 1146
8b742dc1 1147This type has both interfaces of NCollection_DataMap and NCollection_Vector to access items.
dba69de2 1148
8b742dc1 1149@subsubsection occt_fcug_3_1_3 Maps
dba69de2 1150
8b742dc1 1151OCCT 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).
dba69de2 1157
8b742dc1 1158Maps are dynamically extended data structures where data is quickly accessed with a *key*.
1159Once inserted in the map, a map item is referenced as an *entry* of the map.
1160Maps avoid the use of large and quasi-empty arrays.
dba69de2 1161
8b742dc1 1162Each entry of the map is addressed by a key.
1163Two different keys address two different entries of the map.
1164The position of an entry in the map is called a *bucket*.
72b7576f 1165
8b742dc1 1166A map is dimensioned by its number of buckets, i.e. the maximum number of entries in the map.
1167The *hashing function* transforms a key into a bucket index.
1168The number of values that can be computed by the hashing function is equal to the number of buckets of the map.
dba69de2 1169
8b742dc1 1170Both the hashing function and the equality test between two keys are provided by a *hasher* object.
dba69de2 1171
8b742dc1 1172The access time for a map item is much better than the one for a sequence, list, queue or stack item.
1173It is comparable with the access time for an array item.
1174It depends on the size of the map (number of buckets) and on the quality of the user redefinable *hashing function*.
dba69de2 1175
8b742dc1 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.
dba69de2 1178
8b742dc1 1179A map may be explored by a *map iterator*.
1180This exploration provides only inserted entries in the map (i.e. non empty buckets).
dba69de2 1181
8b742dc1 1182##### NCollection_DataMap
dba69de2 1183
8b742dc1 1184This is a map used to store keys with associated items.
1185An entry of **NCollection_DataMap** is composed of both the key and the item.
1186The *NCollection_DataMap* can be seen as an extended array where the keys are the indexes.
dba69de2 1187
8b742dc1 1188*NCollection_DataMap* is a template class which depends on three parameters:
4ee1bdf4 1189 * *Key* is the type of key for an entry in the map,
8b742dc1 1190 * *Item* is the type of element associated with a key in the map,
4ee1bdf4 1191 * *Hasher* is the type of hasher on keys.
dba69de2 1192
8b742dc1 1193Use a *NCollection_DataMap::Iterator* to explore a *NCollection_DataMap* map.
1194*NCollection_DefaultHasher* class describes the functions required for a *Hasher* object.
dba69de2 1195
8b742dc1 1196##### NCollection_DoubleMap
dba69de2 1197
8b742dc1 1198This is a map used to bind pairs of keys (Key1,Key2) and retrieve them in linear time.
dba69de2 1199
8b742dc1 1200*Key1* is referenced as the first key of the *NCollection_DoubleMap* and *Key2* as the second key.
dba69de2 1201
8b742dc1 1202An entry of a *NCollection_DoubleMap* is composed of a pair of two keys: the first key and the second key.
dba69de2 1203
a25d5aaa 1204*NCollection_DoubleMap* is a template class which depends on four parameters:
dba69de2 1205 * *Key1* is the type of the first key for an entry in the map,
8b742dc1 1206 * *Key2* is the type of the second key for an entry in the map,
dba69de2 1207 * *Hasher1* is the type of hasher on first keys,
1208 * *Hasher2* is the type of hasher on second keys.
dba69de2 1209
8b742dc1 1210Use *NCollection_DoubleMap::Iterator* to explore a *NCollection_DoubleMap* map.
1211*NCollection_DefaultHasher* class describes the functions required for a *Hasher1* or a *Hasher2* object.
dba69de2 1212
8b742dc1 1213##### NCollection_IndexedDataMap
dba69de2 1214
8b742dc1 1215This is map to store keys with associated items and to bind an index to them.
dba69de2 1216
8b742dc1 1217Each new key stored in the map is assigned an index.
1218Indexes are incremented as keys (and items) stored in the map.
1219A key can be found by the index, and an index can be found by the key.
1220No 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.
1221An item is stored with each key.
dba69de2 1222
8b742dc1 1223An entry of an *NCollection_IndexedDataMap* is composed of both the key, the item and the index.
1224An *NCollection_IndexedDataMap* is an ordered map, which allows a linear iteration on its contents.
1225It combines the interest:
72b7576f 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.
1228
8b742dc1 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.
dba69de2 1233
8b742dc1 1234##### NCollection_IndexedMap
dba69de2 1235
8b742dc1 1236This is map used to store keys and to bind an index to them.
72b7576f 1237
8b742dc1 1238Each new key stored in the map is assigned an index.
1239Indexes are incremented as keys stored in the map.
1240A key can be found by the index, and an index by the key.
1241No 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.
72b7576f 1242
8b742dc1 1243An entry of an *NCollection_IndexedMap* is composed of both the key and the index.
1244An *NCollection_IndexedMap* is an ordered map, which allows a linear iteration on its contents.
1245But no data is attached to the key.
1246An *NCollection_IndexedMap* is typically used by an algorithm to know if some action is still performed on components of a complex data structure.
dba69de2 1247
8b742dc1 1248*NCollection_IndexedMap* is a template class which depends on two parameters:
dba69de2 1249 * *Key* is the type of key for an entry in the map,
1250 * *Hasher* is the type of hasher on keys.
1251
8b742dc1 1252##### NCollection_Map
dba69de2 1253
8b742dc1 1254This is a basic hashed map, used to store and retrieve keys in linear time.
dba69de2 1255
8b742dc1 1256An entry of a *NCollection_Map* is composed of the key only.
1257No data is attached to the key.
1258An *NCollection_Map* is typically used by an algorithm to know if some action is still performed on components of a complex data structure.
dba69de2 1259
8b742dc1 1260*NCollection_Map* is a generic class which depends on two parameters:
dba69de2 1261 * *Key* is the type of key in the map,
1262 * *Hasher* is the type of hasher on keys.
1263
8b742dc1 1264Use a *NCollection_Map::Iterator* to explore a *NCollection_Map* map.
72b7576f 1265
8b742dc1 1266##### NCollection_DefaultHasher
dba69de2 1267
8b742dc1 1268This is a default hasher on the *keys* of a map instantiated from the *NCollection* component.
dba69de2 1269
8b742dc1 1270A 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.
dba69de2 1274
8b742dc1 1275Hashers are used as parameters in template maps provided by the **NCollection** component.
72b7576f 1276
8b742dc1 1277*NCollection_DefaultHasher* is a template class which depends on the type of keys, providing that *Key* is a type from the *Standard* package.
1278In such cases *NCollection_DefaultHasher* may be directly instantiated with *Key*.
1279Note that the package *TColStd* provides some of these instantiations.
dba69de2 1280
8b742dc1 1281Elsewhere, if *Key* is not a type from the *Standard* package you must consider *NCollection_DefaultHasher* as a template
1282and build a class which includes its functions, in order to use it as a hasher in a map instantiated from the *NCollection* component.
72b7576f 1283
8b742dc1 1284Note that *TCollection_AsciiString* and *TCollection_ExtendedString* classes correspond to these specifications, in consequence they may be used as hashers:
1285when *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.
72b7576f 1286
8b742dc1 1287@subsubsection occt_fcug_3_1_4 Iterators
72b7576f 1288
8b742dc1 1289Every collection defines its *Iterator* class capable of iterating the members in some predefined order.
1290Every Iterator is defined as a subtype of the particular collection type (e.g., MyPackage_StackOfPnt::Iterator).
1291The order of iteration is defined by a particular collection type.
72b7576f 1292
8b742dc1 1293The common methods of Iterator are:
72b7576f 1294
8b742dc1 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 |
72b7576f 1302
8b742dc1 1303Usage sample:
72b7576f 1304
8b742dc1 1305~~~~~{.cpp}
1306typedef Ncollection_Sequence<gp_Pnt> MyPackage_SequenceOfPnt;
1307void Perform (const MyPackage_SequenceOfPnt& theSequence)
1308{
1309 for (MyPackage_SequenceOfPnt::Iterator anIter (theSequence); anIter.More(); anIter.Next())
1310 {
1311 const gp_Pnt aPnt& = anIter.Value();
1312 ...
1313 }
1314}
72b7576f 1315~~~~~
1316
8b742dc1 1317@subsubsection occt_fcug_3_1_5 Allocators
72b7576f 1318
8b742dc1 1319All constructors of *NCollection* classes receive the *Allocator* object as the last parameter.
1320This is an object of a type managed by Handle, inheriting *NCollection_BaseAllocator*, with the following (mandatory) methods redefined:
72b7576f 1321
8b742dc1 1322~~~~~{.cpp}
1323 virtual void* Allocate (const size_t theSize) override;
1324 virtual void Free (void* theAddress) override;
72b7576f 1325~~~~~
1326
8b742dc1 1327It is used internally every time when the collection allocates memory for its item(s) and releases this memory.
1328The default value of this parameter (empty *Handle*) designates the use of *NCollection_BaseAllocator*, where the functions *Standard::Allocate* and *Standard::Free* are called.
1329Therefore 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.
72b7576f 1330
8b742dc1 1331Nevertheless, it is possible to define a custom *Allocator* type to manage the memory in the most optimal or convenient way for this algorithm.
72b7576f 1332
8b742dc1 1333As one possible choice, the class *NCollection_IncAllocator* is included.
1334Unlike *NCollection_BaseAllocator*, the memory is allocated in big blocks (about 20kB) and the allocator keeps track of the amount of occupied memory.
1335The method *Allocate* just increments the pointer to non-occupied memory and returns its previous value.
1336Memory is only released in the destructor of *NCollection_IncAllocator*, the method *Free* is empty.
1337If used properly, this Allocator can greatly improve the performance of specific algorithms.
72b7576f 1338
8b742dc1 1339@subsubsection occt_fcug_3_1_6 Acceleration structures
72b7576f 1340
8b742dc1 1341OCCT 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.
72b7576f 1345
8b742dc1 1346##### NCollection_UBTree
72b7576f 1347
8b742dc1 1348The class name NCollection_UBTree stands for "Unbalanced Binary Tree".
1349It stores the members in a binary tree of overlapped bounding objects (boxes or else).
1350Once the tree of boxes of geometric objects is constructed, the algorithm is capable of fast geometric selection of objects.
1351The tree can be easily updated by adding to it a new object with bounding box.
1352The 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)).
1353The search time of one object is O(log(N)).
72b7576f 1354
8b742dc1 1355Defining various classes inheriting *NCollection_UBTree::Selector* we can perform various kinds of selection over the same b-tree object.
dba69de2 1356
8b742dc1 1357The object may be of any type allowing copying.
1358Among the best suitable solutions there can be a pointer to an object, handled object or integer index of object inside some collection.
72b7576f 1359
8b742dc1 1360The bounding object may have any dimension and geometry.
1361The minimal interface of *TheBndType* (besides public empty and copy constructor and operator=) used in NCollection_UBTree algorithm as follows:
72b7576f 1362
8b742dc1 1363~~~~~{.cpp}
1364class MyBndType
1365{
1366public:
1367 //! Updates me with other bounding type instance
1368 void Add (const MyBndType& theOther);
72b7576f 1369
8b742dc1 1370 //! Classifies other bounding type instance relatively me
1371 Standard_Boolean IsOut (const MyBndType& theOther) const;
72b7576f 1372
8b742dc1 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;
1375};
dba69de2 1376~~~~~
1377
dba69de2 1378This interface is implemented in types of Bnd package: *Bnd_Box, Bnd_Box2d, Bnd_B2x, Bnd_B3x*.
72b7576f 1379
8b742dc1 1380To 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.
1381Usually this class instance is also used to retrieve selected objects after search.
1382The class *NCollection_UBTreeFiller* is used to randomly populate a *NCollection_UBTree* instance.
1383The 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.
1384Instantiation 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.
dba69de2 1385Below 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.
72b7576f 1386
8b742dc1 1387~~~~~{.cpp}
72b7576f 1388typedef NCollection_UBTree<MyData, Bnd_B2f> UBTree;
1389typedef NCollection_List<MyData> ListOfSelected;
1390//! Tree Selector type
1391class MyTreeSelector : public UBTree::Selector
1392{
1393public:
8b742dc1 1394 //! This constructor initializes the selection criterion (e.g., a point)
72b7576f 1395 MyTreeSelector (const gp_XY& thePnt) : myPnt(thePnt) {}
72b7576f 1396
8b742dc1 1397 //! Get the list of selected objects
1398 const ListOfSelected& ListAccepted() const { return myList; }
1399
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); }
72b7576f 1403
8b742dc1 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); }
72b7576f 1408
8b742dc1 1409private:
72b7576f 1410 gp_XY myPnt;
1411 ListOfSelected myList;
1412};
1413. . .
1414// Create a UBTree instance and fill it with data, each data item having the corresponding 2D box.
72b7576f 1415UBTree aTree;
8b742dc1 1416NCollection_UBTreeFiller <MyData, Bnd_B2f> aTreeFiller (aTree);
1417for(;;)
1418{
1419 const MyData& aData = ...;
72b7576f 1420 const Bnd_B2d& aBox = aData.GetBox();
8b742dc1 1421 aTreeFiller.Add (aData, aBox);
72b7576f 1422}
1423aTreeFiller.Fill();
1424. . .
8b742dc1 1425// Perform selection based on "aPoint2d"
1426MyTreeSelector aSel (aPoint2d);
1427aTree.Select (aSel);
1428const ListOfSelected& aSelected = aSel.ListAccepted();
72b7576f 1429~~~~~
1430
8b742dc1 1431##### NCollection_CellFilter
72b7576f 1432
8b742dc1 1433Class *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.
1434It 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,
1435while search with NCollection_UBTree provides logarithmic law access time.
72b7576f 1436
8b742dc1 1437@subsection occt_fcug_3_2 Collections of Standard Objects
72b7576f 1438
8b742dc1 1439Packages *TShort*, *TColGeom*, *TColGeom2d*, *TColStd*, *TColgp* provide template instantiations (typedefs) of *NCollection* templates to standard OCCT types.
1440Classes with *H* prefix in name are handle-based variants and inherit Standard_Transient.
1441~~~~~{.cpp}
1442typedef NCollection_Array1<gp_Vec> TColgp_Array1OfVec;
1443typedef NCollection_Array1<TCollection_AsciiString> TColStd_Array1OfAsciiString;
72b7576f 1444~~~~~
72b7576f 1445
8b742dc1 1446Packages like *TopTools* also include definitions of collections and hash functions for complex types like shapes -- *TopTools_ShapeMapHasher*, *TopTools_MapOfShape*.
72b7576f 1447
8b742dc1 1448Apart from that class *TColStd_PackedMapOfInteger* provides an alternative implementation of map of integer numbers,
1449optimized 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).
1450This class also provides Boolean operations with maps as sets of integers (union, intersection, subtraction, difference, checks for equality and containment).
72b7576f 1451
1452@subsection occt_fcug_3_4 Strings
1453
8b742dc1 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).
1455Both 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*.
e2b55410 1457
1458String classes provide the following services to manipulate character strings:
8b742dc1 1459 * Editing operations on string objects, using a built-in string manager
1460 * Handling of dynamically-sized sequences of characters
e2b55410 1461 * Conversion from/to ASCII and UTF-8 strings.
1462
8b742dc1 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.
72b7576f 1466
e2b55410 1467@subsection occt_fcug_3_5 Quantities
1468
8b742dc1 1469Quantities are various classes supporting date and time information and color.
e2b55410 1470
1471Quantity classes provide the following services:
8b742dc1 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
e2b55410 1475
1476A mathematical quantity is characterized by the name and the value (real).
1477
8b742dc1 1478A physical quantity is characterized by the name, the value (real) and the unit.
1479The unit may be either an international unit complying with the International Unit System (SI) or a user defined unit.
1480The unit is managed by the physical quantity user.
e2b55410 1481
1482@subsection occt_fcug_3_6 Unit Conversion
72b7576f 1483
8b742dc1 1484The *UnitsAPI* global functions are used to convert a value from any unit into another unit.
1485Conversion is executed among three unit systems:
72b7576f 1486 * the **SI System**,
8b742dc1 1487 * the user's **Local System**,
1488 * the user's **Current System**.
dba69de2 1489
8b742dc1 1490The **SI System** is the standard international unit system.
1491It is indicated by *SI* in the signatures of the *UnitsAPI* functions.
dba69de2 1492
8b742dc1 1493The 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.
72b7576f 1494
8b742dc1 1495Both systems are proposed by Open CASCADE Technology; the SI System is the standard option.
1496By selecting one of these two systems, you define your **Local System** through the *SetLocalSystem* function.
1497The **Local System** is indicated by *LS* in the signatures of the *UnitsAPI* functions.
1498The Local System units can be modified in the working environment.
1499You define your **Current System** by modifying its units through the *SetCurrentUnit* function.
1500The Current System is indicated by *Current* in the signatures of the *UnitsAPI* functions.
1501A physical quantity is defined by a string (example: LENGTH).
72b7576f 1502
1503@section occt_occt_fcug_4 Math Primitives and Algorithms
e2b55410 1504
72b7576f 1505@subsection occt_occt_fcug_4_1 Overview
e2b55410 1506
8b742dc1 1507Math primitives and algorithms available in Open CASCADE Technology include:
72b7576f 1508 * Vectors and matrices
1509 * Geometric primitives
1510 * Math algorithms
e2b55410 1511
8b742dc1 1512@subsection occt_occt_fcug_4_2 Vectors and Matrices
e2b55410 1513
8b742dc1 1514The 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.
e2b55410 1515
8b742dc1 1516The <i>math_Vector</i> and <i>math_Matrix</i> classes provide commonly used mathematical algorithms which include:
e2b55410 1517
8b742dc1 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.
72b7576f 1523
8b742dc1 1524These classes also provide a data structure to represent any expression, relation, or function used in mathematics, including the assignment of variables.
72b7576f 1525
8b742dc1 1526Vectors and matrices have arbitrary ranges which must be defined at declaration time and cannot be changed after declaration.
72b7576f 1527
8b742dc1 1528~~~~~{.cpp}
1529math_Vector aVec (1, 3);
1530// a vector of dimension 3 with range (1..3)
1531math_Matrix aMat (0, 2, 0, 2);
1532// a matrix of dimension 3x3 with range (0..2, 0..2)
1533math_Vector aVec (N1, N2);
1534// a vector of dimension N2-N1+1 with range (N1..N2)
72b7576f 1535~~~~~
1536
8b742dc1 1537Vector and Matrix objects use value semantics.
1538In other words, they cannot be shared and are copied through assignment.
72b7576f 1539
8b742dc1 1540~~~~~{.cpp}
1541math_Vector aVec1 (1, 3), aVec2 (0, 2);
1542aVec2 = aVec1;
1543// aVec1 is copied into aVec2; a modification of aVec1 does not affect aVec2
72b7576f 1544~~~~~
72b7576f 1545
8b742dc1 1546Vector and Matrix values may be initialized and obtained using indexes which must lie within the range definition of the vector or the matrix.
72b7576f 1547
8b742dc1 1548~~~~~{.cpp}
1549math_Vector aVec (1, 3);
1550math_Matrix aMat (1, 3, 1, 3);
1551Standard_Real aValue;
1552
1553aVec (2) = 1.0;
1554aValue = aVec(1);
1555aMat (1, 3) = 1.0;
1556aValue = aMat (2, 2);
1557~~~~~
1558
1559Some operations on Vector and Matrix objects may not be legal.
1560In this case an exception is raised.
1561Two 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.
1564
1565~~~~~~{.cpp}
1566math_Vector aVec1 (1, 3), aVec2 (1, 2), aVec3 (0, 2);
1567aVec1 = aVec2; // error: Standard_DimensionError is raised
1568aVec1 = aVec3; // OK: ranges are not equal but dimensions are compatible
1569aVec1 (0) = 2.0; // error: Standard_RangeError is raised
72b7576f 1570~~~~~~
1571
1572@subsection occt_occt_fcug_4_3 Primitive Geometric Types
e2b55410 1573
8b742dc1 1574Open CASCADE Technology primitive geometric types are a STEP-compliant implementation of basic geometric and algebraic entities.
1575They provide:
e2b55410 1576 * Descriptions of primitive geometric shapes, such as:
8b742dc1 1577 * Points;
1578 * Vectors;
1579 * Lines;
1580 * Circles and conics;
1581 * Planes and elementary surfaces;
e2b55410 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:
8b742dc1 1584 * Translations;
1585 * Rotations;
1586 * Symmetries;
1587 * Scaling transformations;
1588 * Composed transformations;
e2b55410 1589 * Tools (coordinates and matrices) for algebraic computation.
e2b55410 1590
8b742dc1 1591All these functions are provided by geometric processor package <i>gp</i>.
1592Its classes for 2d and 3d objects are handled by value rather than by reference.
1593When this sort of object is copied, it is copied entirely.
1594Changes in one instance will not be reflected in another.
e2b55410 1595
8b742dc1 1596The *gp* package defines the basic geometric entities used for algebraic calculation and basic analytical geometry in 2d & 3d space.
1597It also provides basic transformations such as identity, rotation, translation, mirroring, scale transformations, combinations of transformations, etc.
1598Entities are handled by value.
e2b55410 1599
8b742dc1 1600Note 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.
e2b55410 1601
8b742dc1 1602If you need, you may use more evolved data structures provided by <i>Geom</i> (in 3D space) and <i>Geom2d</i> (in the plane).
1603However, 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.
1604They 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.
1605
1606Therefore, 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.
1607This 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>.
1608Thus, <i>ElCLib</i> and <i>ElSLib</i> packages provide functions to compute:
e2b55410 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.
1612
8b742dc1 1613Note: the <i>gp</i> entities cannot be shared when they are inside more complex data structures.
1614
72b7576f 1615@subsection occt_occt_fcug_4_4 Collections of Primitive Geometric Types
dba69de2 1616
8b742dc1 1617Before 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.
1618If 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.
1619In 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*.
dba69de2 1620
72b7576f 1621@subsection occt_occt_fcug_4_5 Basic Geometric Libraries
8b742dc1 1622There are various library packages available which offer a range of basic computations on curves and surfaces.
1623If 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.
1631
1632Additionally, *Bnd* package provides a set of classes and tools to operate with bounding boxes of geometric objects in 2d and 3d space.
dba69de2 1633
72b7576f 1634@subsection occt_occt_fcug_4_6 Common Math Algorithms
1635The 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,
8b742dc1 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.
1640
1641All mathematical algorithms are implemented using the same principles.
1642They contain:
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.
1648
1649The example below demonstrates the use of the math_Gauss class, which implements the Gauss solution for a set of linear equations.
1650The following definition is an extract from the header file of the class *math_Gauss*:
1651
1652~~~~~~{.cpp}
1653class math_Gauss
1654{
72b7576f 1655public:
8b742dc1 1656 math_Gauss (const math_Matrix& A);
dba69de2 1657 Standard_Boolean IsDone() const;
8b742dc1 1658 void Solve (const math_Vector& B, math_Vector& X) const;
72b7576f 1659};
1660~~~~~~
1661
8b742dc1 1662Now the main program uses the math_Gauss class to solve the equations _a*x1=b1_ and _a*x2=b2_:
72b7576f 1663
8b742dc1 1664~~~~~{.cpp}
72b7576f 1665#include <math_Vector.hxx>
1666#include <math_Matrix.hxx>
8b742dc1 1667main()
72b7576f 1668{
dba69de2 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
8b742dc1 1673 ...
1674
1675 math_Gauss aSol(a); // computation of the LU decomposition of A
1676 if (aSol.IsDone()) // is it OK ?
1677 {
1678 aSol.Solve(b1, x1); // yes, so compute x1
1679 aSol.Solve(b2, x2); // then x2
dba69de2 1680 ...
7e3451c7 1681 }
8b742dc1 1682 else // it is not OK:
1683 {
dba69de2 1684 // fix up
8b742dc1 1685 aSol.Solve(b1, x1); // error:
dba69de2 1686 // StdFail_NotDone is raised
1687 }
72b7576f 1688}
1689~~~~~
1690
8b742dc1 1691The 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.
1692The definition is an extract from the header file of the class *math_BissecNewton*:
72b7576f 1693
8b742dc1 1694~~~~~{.cpp}
1695class math_BissecNewton
1696{
1697public:
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();
72b7576f 1704};
1705~~~~~
1706
8b742dc1 1707The 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.
1708The following definition corresponds to the header file of the abstract class *math_FunctionWithDerivative*:
72b7576f 1709
8b742dc1 1710~~~~~{.cpp}
1711class math_FunctionWithDerivative
1712{
1713public:
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;
1717};
72b7576f 1718~~~~~
1719
8b742dc1 1720Now 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].
1721The function to solve is implemented in the class *myFunction* which inherits from the class *math_FunctionWithDerivative*, then the main program finds the required root.
72b7576f 1722
8b742dc1 1723~~~~~{.cpp}
1724#include <math_BissecNewton.hxx>
72b7576f 1725#include <math_FunctionWithDerivative.hxx>
8b742dc1 1726class myFunction : public math_FunctionWithDerivative
72b7576f 1727{
8b742dc1 1728 Standard_Real myCoefA, myCoefB, myCoefC;
dba69de2 1729
8b742dc1 1730public:
1731 myFunction (const Standard_Real theA, const Standard_Real theB, const Standard_Real theC)
1732 : myCoefA(a), myCoefB(b), myCoefC(c) {}
dba69de2 1733
8b742dc1 1734 virtual Standard_Boolean Value (const Standard_Real x, Standard_Real& f) override
1735 {
1736 f = myCoefA * x * x + myCoefB * x + myCoefC;
1737 }
dba69de2 1738
8b742dc1 1739 virtual Standard_Boolean Derivative (const Standard_Real x, Standard_Real& d) override
1740 {
1741 d = myCoefA * x * 2.0 + myCoefB;
1742 }
dba69de2 1743
8b742dc1 1744 virtual Standard_Boolean Values (const Standard_Real x, Standard_Real& f, Standard_Real& d) override
1745 {
1746 f = myCoefA * x * x + myCoefB * x + myCoefC;
1747 d = myCoefA * x * 2.0 + myCoefB;
1748 }
72b7576f 1749};
1750
1751main()
1752{
8b742dc1 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 ?
1756 {
1757 Standard_Real x = aSol.Root(); // yes
dba69de2 1758 }
8b742dc1 1759 else // no
1760 {
dba69de2 1761 }
72b7576f 1762~~~~~
1763
1764@subsection occt_occt_fcug_4_7 Precision
1765
8b742dc1 1766On the OCCT platform, each object stored in the database should carry its own precision value.
1767This is important when dealing with systems where objects are imported from other systems as well as with various associated precision values.
1768
1769The *Precision* package addresses the daily problem of the geometric algorithm developer: what precision setting to use to compare two numbers.
1770Real number equivalence is clearly a poor choice.
1771The difference between the numbers should be compared to a given precision setting.
1772
1773Do not write _if (X1 == X2)_, instead write _if (Abs(X1-X2) < Precision)_.
dba69de2 1774
8b742dc1 1775Also, 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.
dba69de2 1777
8b742dc1 1778This package proposes a set of methods providing precision settings for the most commonly encountered situations.
dba69de2 1779
8b742dc1 1780In Open CASCADE Technology, precision is usually not implicit; low-level geometric algorithms accept precision settings as arguments.
1781Usually these should not refer directly to this package.
dba69de2 1782
8b742dc1 1783High-level modeling algorithms have to provide a precision setting to the low level geometric algorithms they call.
1784One way is to use the settings provided by this package.
1785The high-level modeling algorithms can also have their own strategy for managing precision.
1786As an example the Topology Data Structure stores precision values which are later used by algorithms.
1787When a new topology is created, it takes the stored value.
dba69de2 1788
8b742dc1 1789Different precision settings offered by this package cover the most common needs of geometric algorithms such as *Intersection* and *Approximation*.
1790The choice of a precision value depends both on the algorithm and on the geometric space.
1791The 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.
dba69de2 1794
8b742dc1 1795The 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.
1796This is because it is desirable to link parametric precision and real precision.
1797If you are on a curve defined by the equation *P(t)*, you would want to have equivalence between the following:
72b7576f 1798
1799~~~~~
8b742dc1 1800 Abs (t1 - t2) < ParametricPrecision
1801 Distance (P(t1), P(t2)) < RealPrecision
72b7576f 1802~~~~~
1803
1804@subsubsection occt_occt_fcug_4_7_1 The Precision package
8b742dc1 1805
1806The *Precision* package offers a number of package methods and default precisions for use in dealing with angles, distances, intersections, approximations, and parametric space.
1807It 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.
1815
72b7576f 1816@subsubsection occt_occt_fcug_4_7_2 Standard Precision values
8b742dc1 1817
1818This package provides a set of real space precision values for algorithms.
1819The real space precisions are designed for precision to *0.1* nanometers (in case if model is defined in millimeters).
1820
1821The parametric precisions are derived from the real precisions by the *Parametric* function.
1822This applies a scaling factor which is the length of a tangent to the curve or the surface.
1823You, the user, provide this length.
1824There is a default value for a curve with <i>[0,1]</i> parameter space and a length less than 100 meters.
1825
1826The geometric packages provide Parametric precisions for the different types of curves.
1827The *Precision* package provides methods to test whether a real number can be considered to be infinite.
dba69de2 1828
1829#### Precision::Angular
72b7576f 1830
8b742dc1 1831This method is used to compare two angles.
1832Its current value is *Epsilon(2 * PI)* i.e. the smallest number *x* such that *2*PI + x* is different of *2\*PI*.
72b7576f 1833
8b742dc1 1834It can be used to check confusion of two angles as follows:
1835~~~{.cpp}
1836bool areEqualAngles (double theAngle1, double theAngle2)
1837{
1838 return Abs(theAngle1 - theAngle2) < Precision::Angular();
1839}
1840~~~
72b7576f 1841
8b742dc1 1842It is also possible to check parallelism of two vectors as follows:
1843~~~{.cpp}
1844bool areParallelVectors (const gp_Vec& theVec1, const gp_Vec& theVec2)
1845{
1846 return theVec1.IsParallel (theVec2, Precision::Angular());
1847}
1848~~~
72b7576f 1849
8b742dc1 1850Note that *Precision::Angular()* can be used on both dot and cross products because for small angles the *Sine* and the *Angle* are equivalent.
1851So to test if two directions of type *gp_Dir* are perpendicular, it is legal to use the following code:
1852~~~{.cpp}
1853bool arePerpendicular (const gp_Dir& theDir1, const gp_Dir& theDir2)
1854{
1855 return Abs(theDir1 * theDir2) < Precision::Angular();
1856}
1857~~~
72b7576f 1858
dba69de2 1859#### Precision::Confusion
1860
8b742dc1 1861This method is used to test 3D distances.
1862The current value is *1.e-7*, in other words, 1/10 micron if the unit used is the millimeter.
72b7576f 1863
8b742dc1 1864It can be used to check confusion of two points as follows:
1865~~~{.cpp}
1866bool areEqualPoints (const gp_Pnt& thePnt1, const gp_Pnt& thePnt2)
1867{
1868 return thePnt1.IsEqual (thePnt2, Precision::Confusion());
1869}
1870~~~
72b7576f 1871
8b742dc1 1872It is also possible to find a vector of null length:
1873~~~{.cpp}
1874bool isNullVector (const gp_Vec& theVec)
1875{
1876 return theVec.Magnitude() < Precision::Confusion();
1877}
1878~~~
72b7576f 1879
dba69de2 1880#### Precision::Intersection
1881
8b742dc1 1882This 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.
1885The current value is *Confusion() / 100*.
72b7576f 1886
dba69de2 1887#### Precision::Approximation
1888
8b742dc1 1889This is a reasonable precision to pass to an approximation process as a limit of refinement of fitting.
1890The approximation is greater than the other precisions because it is designed to be used when the time is at a premium.
1891It has been provided as a reasonable compromise by the designers of the Approximation algorithm.
1892The current value is *Confusion() * 10*.
1893Note that Approximation is greater than Confusion, so care must be taken when using Confusion in an approximation process.