81898eb5f93663c04b3306557888d75db747c851
[occt.git] / dox / user_guides / foundation_classes / foundation_classes.md
1 Foundation Classes  {#occt_user_guides__foundation_classes}
2 =================================
3
4 @tableofcontents
5
6 @section occt_fcug_1 Introduction
7
8 @subsection occt_fcug_1_1 Foundation Classes Overview
9
10 This manual explains how to use Open CASCADE Technology (**OCCT**)  Foundation Classes. It provides basic documentation on foundation classes. For  advanced information on foundation classes and their applications, see our  offerings on our web site at <a href="http://www.opencascade.org/support/training/">www.opencascade.org/support/training/</a>   
11 Foundation Classes provide a variety of general-purpose  services such as automated dynamic memory management (manipulation of objects  by handle), collections, exception handling, genericity by downcasting and  plug-in creation. 
12 Foundation Classes include the following: 
13
14 ### Root Classes
15 Root classes are the basic data types and classes on which all the  other classes are built. They provide: 
16   * fundamental types such as Boolean, Character, Integer or Real,
17   * safe handling of dynamically created objects, ensuring automatic  deletion of unreferenced objects (see the Standard_Transient class),
18   * configurable optimized memory manager increasing the performance  of applications that intensively use dynamically created objects,
19   * extended run-time type information (RTTI) mechanism facilitating  the creation of complex programs,
20   * management of exceptions,
21   * encapsulation of C++ streams.
22 Root classes are mainly implemented in the *Standard* and  *MMgt* packages. 
23
24 ### Strings
25 Strings are classes that handle dynamically sized sequences  of characters based on both ASCII (normal 8-bit character type) and Unicode  (16-bit character type).  
26 Strings may also be manipulated by handles, and consequently  be shared. 
27 Strings are implemented in the *TCollection* package. 
28
29 ### Collections
30 Collections are the classes that handle dynamically sized  aggregates of data.  
31 Collection classes are *generic*, 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 (similarly to C++ templates). When  you need to use a collection of a given type of object, you must *instantiate* it for this specific type of element. Once this declaration is compiled, all functions available on the generic collection are available on your *instantiated  class*. 
32
33 Collections include a wide range of generic classes such as  run-time sized arrays, lists, stacks, queues, sets and hash maps. 
34 Collections are implemented in the *TCollection* and *NCollection* packages. 
35
36 ### Collections of Standard Objects
37
38 The *TColStd* package provides frequently used  instantiations of generic classes from the *TCollection* package with  objects from the *Standard* package or strings from the *TCollection* package. 
39
40 ### Vectors and Matrices
41
42
43 These classes provide commonly used mathematical algorithms  and basic calculations (addition, multiplication, transposition, inversion,  etc.) involving vectors and matrices. 
44
45 ### Primitive Geometric Types
46
47 Open CASCADE Technology primitive geometric types are a  STEP-compliant implementation of basic geometric and algebraic entities.  
48 They provide: 
49   * Descriptions of elementary geometric shapes:
50   * Points,
51   * Vectors,
52   * Lines,
53   * Circles and conics,
54   * Planes and elementary surfaces,
55   * Positioning of these shapes in space or in a plane by means of an  axis or a coordinate system,
56   * Definition and application of geometric transformations to these  shapes:
57   * Translations
58   * Rotations
59   * Symmetries
60   * Scaling transformations
61   * Composed transformations
62   * Tools (coordinates and matrices) for algebraic computation.
63   
64 ### Common Math Algorithms
65
66 Open CASCADE Technology common math algorithms provide a C++  implementation of the most frequently used mathematical algorithms.  
67 These include: 
68   * Algorithms to solve a set of linear algebraic equations,
69   * Algorithms to find the minimum of a function of one or more  independent variables,
70   * Algorithms to find roots of one, or of a set, of non-linear  equations,
71   * Algorithms to find the eigen-values and eigen-vectors of a square  matrix.
72
73 ### Exceptions
74
75 A hierarchy of commonly used exception classes is provided,  all based on class Failure, the  root of exceptions. 
76 Exceptions describe exceptional situations, which can arise  during the execution of a function. With the raising of an exception, the  normal course of program execution is abandoned. The execution of actions in  response to this situation is called the treatment of the exception. 
77
78 ### Quantities
79
80 These are various classes supporting date and time  information and fundamental types representing most physical quantities such as  length, area, volume, mass, density, weight, temperature, pressure etc. 
81
82 ### Application services
83
84 Foundation Classes also include implementation of several  low-level services that facilitate the creation of customizable and  user-friendly applications with Open CASCADE Technology. These include: 
85   * 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 and so on (see package  *UnitsAPI*).
86   * Basic interpreter of expressions that facilitates the creation of  customized scripting tools, generic definition of expressions and so on (see  package *ExprIntrp*)
87   * 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
88   * 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.
89
90
91 @subsection occt_fcug_1_2 Fundamental Concepts
92 An object-oriented language structures a system around data  types rather than around the actions carried out on this data. In this context,  an **object** is an **instance** of a data type and its definition  determines how it can be used. Each data type is implemented by one or more  classes, which make up the basic elements of the system. 
93
94 In Open CASCADE Technology the  classes are usually defined using CDL (CASCADE Definition Language) that  provides a certain level of abstraction from pure C++ constructs and ensures a definite  level of similarity in the implementation of classes. See *CDL User’s Guide*  for more details. 
95
96 This chapter introduces some basic concepts most of which  are directly supported by CDL and used not only in Foundation Classes, but  throughout the whole OCCT library. 
97
98 @subsubsection occt_fcug_1_2_1 Modules  and toolkits
99 The whole OCCT library is organized in a set of modules. The  first module, providing most basic services and used by all other modules, is  called Foundation Classes and described by this manual. 
100
101 Every module consists primarily of one or several toolkits  (though it can also contain executables, resource units etc.). Physically a toolkit  is represented by a shared library (e.g. .so or .dll). The toolkit is built  from one or several packages. 
102
103 @subsubsection occt_fcug_1_2_2 Packages
104 A **package** groups together a number of classes which  have semantic links. For example, a geometry package would contain Point, Line,  and Circle classes. A package can also contain enumerations, exceptions and  package methods (functions). In practice, a class name is prefixed with the  name of its package e.g.  
105 *Geom_Circle*. 
106 Data types described in a package may include one or  more of the following data types: 
107   * Enumerations
108   * Object classes
109   * Exceptions
110   * Pointers to other object classes
111 Inside a package, two data types cannot bear the same  name. 
112
113 @image html /user_guides/foundation_classes/images/foundation_classes_image003.png  "Contents of a package"
114 @image latex /user_guides/foundation_classes/images/foundation_classes_image003.png  "Contents of a package"
115
116 **Methods** are either **functions** or **procedures**.  Functions return an object, whereas procedures only communicate by passing arguments.  In both cases, when the transmitted object is an instance manipulated by a  handle, its identifier is passed. There are three categories of methods: 
117 * **Object  constructor** Creates an instance of the described class. A class  will have one or more object constructors with various different arguments or none. 
118 * **Instance method** Operates on the  instance which owns it. 
119 * **Class  method** Does not work on individual  instances, only on the class itself. 
120
121 @subsubsection occt_fcug_1_2_3 Classes
122 The fundamental software component in object-oriented software  development is the class. A class is the implementation of a **data type**.  It defines its **behavior** (the services offered by its functions) and its **representation** (the data structure of the class – the fields, which store its data). 
123
124 #### Categories of Classes
125 Classes fall into three categories: 
126   * Ordinary classes.
127   * Deferred classes. A **deferred class** cannot be instantiated. 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. This is a way  of guaranteeing a certain base of inherited behavior common to all the classes  based on a particular deferred class. The C++ equivalent of a deferred CDL  class is an abstract class. 
128   * Generic classes. A **generic class** offers a set of functional behaviors  to manipulate other data types. Instantiation of a generic class requires that  a data type is given for its argument(s). The generic classes in CDL perform  the same mission as template classes in C++.
129   
130 @subsubsection occt_fcug_1_2_4 Genericity
131 Generic classes are implemented in two steps. First you  declare the generic class to establish the model, then you instantiate this  class by giving information about the generic types. 
132
133 #### Declaring a Generic  Class
134
135 The generic classes in Open CASCADE Technology are similar  by their intent to C++ templates with explicit instantiation. 
136 A generic class is declared in CDL as operating on data  items of non-fixed types which are declared as arguments of the generic class.  It is possible to put a restriction on these data types to be of subtype of  some definite class. Definition of the generic class does not create new class  type in C++ terms; it only defines a pattern for generation (instantiation) of  the real classes.
137  
138 #### Instantiation of a Generic Class
139
140 When a generic class is instantiated, its argument types are  substituted by actually existing data types (elementary types or classes). The  result of instantiation is a new C++ class with an arbitrary name (specified in  the instantiating declaration). By convention, the name of the instantiated class  is usually constructed from the name of the generic class and names of actual  argument types. As for any other class, the name of the class instantiating a generic  type is prefixed by the name of the package in which instantiation is declared. 
141 @code
142 class Array1OfReal instantiates Array1 from TCollection  (Real);
143 @endcode
144
145 This declaration located in a CDL file of the *TColStd*  package defines a new C++ class *TColStd_Array1OfReal* as the instantiation of  generic class *TCollection_Array1* for *Real* values. 
146 More than one class can be instantiated from the same  generic class with the same argument types. Such classes will be identical by  implementation, but considered as two different classes by C++.  
147 No class can inherit from a generic class. 
148 A generic class can be a deferred class. A generic class can  also accept a deferred class as its argument. In both these cases, any class  instantiated from it will also be deferred. The resulting class can then be  inherited by another class. 
149
150 #### Nested Generic Classes
151
152 It often happens that many classes are linked by a common  generic type. This is the case when a base structure furnishes an iterator. In  this context, it is necessary to make sure that the group of linked generic  classes is indeed instantiated for the same type of object. In order to group  the instantiation, you may declare certain classes as being nested. 
153 When generic class is instantiated, its nested classes are  instantiated as well. The name of the instantiation of the nested class is  constructed from the name of that nested class and name of the main generic  class, connected by ‘Of’. 
154 @code
155 class MapOfReal instantiates Map from TCollection  (Real,MapRealHasher);
156 @endcode
157 This declaration in *TColStd* defines not only class  *TColStd_MapOfReal*, but also class *TColStd_MapIteratorOfMapOfReal*, which is  instantiated from nested class *MapIterator* of the generic class  *TCollection_Map*. Note that instantiation of the nested class is separate class,  it is not nested class to the instantiation of the main class. 
158 **Nested classes**, even though they are described as  non-generic classes, are generic by construction being inside the class they  are a member of. 
159
160 @subsubsection occt_fcug_1_2_5 Inheritance
161 The purpose of inheritance is to reduce the development  workload. The inheritance mechanism allows a new class to be declared already  containing the characteristics of an existing class. This new class can then be  rapidly specialized for the task in hand. This avoids the necessity of  developing each component “from scratch”. 
162 For example, having already developed a class *BankAccount* you  could quickly specialize new classes: *SavingsAccount, LongTermDepositAccount,  MoneyMarketAccount, RevolvingCreditAccount*, etc.... 
163
164 The corollary of this is that when two or more classes  inherit from a parent (or ancestor) class, all these classes guarantee as a  minimum the behavior of their parent (or ancestor). For example, if the parent  class BankAccount contains the method Print which tells it to print itself out,  then all its descendent classes guarantee to offer the same service. 
165
166 One way of ensuring the use of inheritance is to declare  classes at the top of a hierarchy as being **deferred**. In such classes,  the methods are not implemented. This forces the user to create a new class  which redefines the methods. This is a way of guaranteeing a certain minimum of  behavior among descendent classes. 
167
168 @subsubsection occt_fcug_1_2_6 Categories  of Data Types
169 The data types in Open CASCADE Technology fall into two  categories: 
170   * Data types manipulated by handle (or reference)
171   * Data types manipulated by value
172   
173 @image html /user_guides/foundation_classes/images/foundation_classes_image004.png  "Manipulation of data types"
174 @image latex /user_guides/foundation_classes/images/foundation_classes_image004.png  "Manipulation of data types"
175   
176 A data type is implemented as a class. The class not only  defines its data representation and the methods available on instances, but it  also suggests how the instance will be manipulated. 
177   * A variable of a type manipulated by value contains the instance  itself.
178   * A variable of a type manipulated by handle contains a reference  to the instance.
179 The first examples of types manipulated by values are the  predefined **primitive types**: *Boolean, Character, Integer, Real*, etc. 
180
181 A variable of a type manipulated by handle which is not  attached to an object is said to be **null**. To reference an object, we  instantiate the class with one of its constructors. For example, in C++: 
182
183 ~~~~~
184 Handle(myClass)  m = new myClass; 
185 ~~~~~
186
187 In Open CASCADE Technology, the  Handles are specific classes that are used to safely manipulate objects  allocated in the dynamic memory by reference, providing reference counting  mechanism and automatic destruction of the object when it is not referenced. 
188
189 @subsubsection occt_fcug_1_2_7 Exceptions
190 The behavior of any object is implemented by the methods,  which were defined in its class declaration. The definition of these methods  includes not only their signature (their programming interface) but also their  domain of validity.  
191
192 This domain is expressed by **exceptions**. Exceptions  are raised under various error conditions. This mechanism is a safeguard of  software quality. 
193
194 @subsubsection occt_fcug_1_2_8 Persistence  and Data Schema
195 The data schema is the structure used by an application to  store its data. Data schemas consist of persistent classes. 
196
197 An object is called **persistent** if it can be  permanently stored. Thus, the object can be reused at a later date by the  application, which created it, or by another application.
198  
199 In order for an object to be persistent for CDL, its type  must be declared as inheriting from the class *Standard_Persistent* or have a  parent class inheriting from the *Standard_Persistent* class. Note that classes  inheriting from *Standard_Persistent* are handled by a reference. 
200
201 Objects instantiated from classes which inherit from the  Standard_Storable class cannot themselves be stored individually, but they can  be stored as fields of an object which inherits from *Standard_Persistent*. Note  that objects inheriting from *Standard_Storable* are handled by a value. 
202
203 @section occt_fcug_2 Basics
204 This chapter deals with basic services such as memory management,  programming with handles, primitive types, exception handling, genericity by  downcasting and plug-in creation. 
205 @subsection occt_fcug_2_1 Data Types
206 @subsubsection occt_fcug_2_1_1 Primitive Types
207 The primitive types are predefined in the language and they  are **manipulated by value**. 
208 Some of these primitives inherit from the **Storable** class.  This means they can be used in the implementation of persistent objects, either  contained in entities declared within the methods of the object, or they form  part of the internal representation of the object. 
209
210 The primitives inheriting from *Standard_Storable* are the  following: 
211 * **Boolean** is used to represent logical  data. It may have only two values: *Standard_True*  and *Standard_False*. 
212 * **Character** designates any ASCII  character. 
213 * **ExtCharacter** is an extended character. 
214 * **Integer** is a whole number. 
215 * **Real** denotes  a real number (i.e. one with whole and a fractional part, either of which may  be null). 
216 * **ShortReal** is a real with a smaller choice of  values and memory size. 
217 There are also non-Storable primitives. They are: 
218 * **CString** is used for literal  constants. 
219 * **ExtString** is an extended string. 
220 * **Address** represents a byte address of  undetermined size. 
221 The services offered by each of these types are described in  the **Standard** Package. 
222 The table below presents the equivalence existing between  C++ fundamental types and OCCT primitive types. 
223
224 **Table 1: Equivalence between C++ Types and OCCT Primitive  Types** 
225
226 | C++ Types     | OCCT Types |
227 | :--------- | :----------- |
228 | int   | Standard_Integer |
229 | double        | Standard_Real |
230 | float | Standard_ShortReal |
231 | unsigned int  | Standard_Boolean |
232 | char  | Standard_Character |
233 | short | Standard_ExtCharacter |
234 | char\*        | Standard_CString |
235 | void\*        | Standard_Address |
236 | short\*       | Standard_ExtString |
237
238 \* The types with asterisk are pointers. 
239
240
241 **Reminder of the classes listed above:** 
242
243 * **Standard_Integer** : fundamental type representing 32-bit integers yielding  negative, positive or null values. *Integer* is implemented as a *typedef* of the C++ *int* fundamental type. As such, the algebraic operations  +, -, *, / as well as the ordering and equivalence relations <, <=, ==, !=, >=, >  are defined on it. 
244 * **Standard_Real** : fundamental type representing real numbers with finite  precision and finite size. **Real** is implemented as a *typedef* of  the C++ *double* (double precision) fundamental type. As such, the  algebraic operations +, -, *, /, unary- and the ordering and equivalence  relations <, <=, ==, !=, >=, >  are defined on reals. 
245 * **Standard_ShortReal** : fundamental type representing real numbers with finite  precision and finite size. *ShortReal* is implemented as a *typedef* of  the C++ *float* (simple precision) fundamental type. As such, the  algebraic operations +, -, *, /, unary- and the ordering and equivalence  relations <, <=, ==, !=, >=, >  are defined on reals. 
246 * **Standard_Boolean** : fundamental type representing logical  expressions. It has two values: *false* and *true*. *Boolean* is implemented  as a *typedef* of the C++ *unsigned int* fundamental type. As such,  the algebraic operations *and, or, xor* and *not* as well as equivalence relations == and != are defined on Booleans. 
247 * **Standard_Character** : fundamental type representing the  normalized ASCII character set. It may be assigned the values of the 128 ASCII  characters. *Character* is implemented as a *typedef* of the C++ *char* fundamental type. As such, the ordering and equivalence relations <, <=, ==, !=, >=, >  are defined on characters using the order of the  ASCII chart (ex: A B). 
248 * **Standard_ExtCharacter** : fundamental type representing the  Unicode character set. It is a 16-bit character type. *ExtCharacter* is  implemented as a *typedef* of the C++ *short* fundamental type. 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. A string literal is a sequence of ASCII (8 bits) characters enclosed  in double quotes. *CString* is implemented as a *typedef* of the C++ *char* fundamental type. 
250 * **Standard_Address** : fundamental type representing a generic  pointer. *Address* is implemented as a *typedef* of the C++ *void* fundamental  type. 
251 * **Standard_ExtString** is a fundamental type representing string  literals as sequences of Unicode (16 bits) characters. *ExtString* is  implemented as a *typedef* of the C++ *short* fundamental type. 
252
253 @subsubsection occt_fcug_2_1_2 Types manipulated by value
254 There are three categories of types which are manipulated by  value: 
255   * Primitive types
256   * Enumerated types
257   * Types defined by classes not inheriting from *Standard_Persistent* or *Standard_Transient*, whether directly or not.
258 Types which are manipulated by value behave in a more direct  fashion than those manipulated by handle and thus can be expected to perform  operations faster, but they cannot be stored independently in a file. 
259
260 @image html /user_guides/foundation_classes/images/foundation_classes_image005.png   "Manipulation of a data type by value"
261 @image latex /user_guides/foundation_classes/images/foundation_classes_image005.png   "Manipulation of a data type by value"
262
263 Types that are known to the schema (i.e. they are either **primitives** or they inherit from *Storable*) and are manipulated by value, can be  stored inside a persistent object as part of the representation. Only in this  way can a “manipulated by value” object be stored in a file. 
264
265 @subsubsection occt_fcug_2_1_3 Types manipulated by reference (handle)
266 There are two categories of types which are manipulated by  handle: 
267   * Types defined by classes inheriting from the *Persistent* class,  which are therefore storable in a file.
268   * Types defined by classes inheriting from the *Transient* class.
269   
270 @image html /user_guides/foundation_classes/images/foundation_classes_image006.png   "Manipulation of a data type by reference"
271 @image latex /user_guides/foundation_classes/images/foundation_classes_image006.png   "Manipulation of a data type by reference"
272   
273 @subsubsection occt_fcug_2_1_4 Summary of properties
274
275 The following table summarizes how various data types are handled and stored.
276
277 | Type        | Manipulated by handle | Manipulated by value |
278 | :------- | :-------------------- | :-------------------- |
279 | storable |     Persistent     | Primitive, Storable (if nested in a persistent class)|
280 |temporary | Transient  | Other |
281
282
283 @subsection occt_fcug_2_2 Programming with Handles
284 @subsubsection occt_fcug_2_2_1 Handle Definition
285 A handle may be compared with a C++ pointer. Several handles  can reference the same object. Also, a single handle may reference several  objects, but only one at a time. To have access to the object it refers to, the  handle must be de-referenced just as with a C++ pointer. 
286
287 Transient and Persistent classes may be manipulated either  with handles or with values. Handles which reference non-persistent objects are  called non-storable handles; therefore, a persistent object cannot contain a  non-storable handle.  
288
289 #### Organization of Classes
290
291 Classes used with handles are persistent or transient. 
292
293 Classes that inherit from *Standard_Transient*  are transient while classes that inherit from *Standard_Persistent*  are persistent. 
294
295 In this chapter we will discuss only transient classes and  relevant handles. Persistent classes and their handles are organized in a similar  manner. 
296
297 Class *Standard_Transient* is a root of a big hierarchy of OCCT  classes that are said to be operable by handles. It provides a reference  counter field, inherited by all its descendant classes, that is used by  associated *Handle()* classes to track a number of handles pointing to this  instance of the object. 
298
299 For every class derived (directly or indirectly) from *Transient*, CDL extractor creates associated class *Handle()* whose name is the  same as the name of that class prefixed by *Handle_*. Open CASCADE Technology  provides preprocessor macro *Handle()* that produces a name of a *Handle()* class  for a given transient class name. 
300
301 #### Using a Handle
302
303
304 A handle is characterized by the object it references. 
305
306 Before performing any operation on a transient object, you  must declare the handle. For example, if Point and Line are two transient classes  from the Geom package, you  would write: 
307 ~~~~~
308 Handle(Geom_Point)  p1, p2; 
309 ~~~~~
310 Declaring a handle creates a null handle that does not refer  to any object. The handle may be checked to be null by its method *IsNull()*. To  nullify a handle, use method *Nullify()*. 
311
312 To initialize a handle, either a new object should be  created or the value of another handle can be assigned to it, on condition that  their types are compatible. 
313
314 **Note** that handles should only be used  for object sharing. For all local operations, it is advisable to use classes  manipulated by values. 
315
316 @subsubsection occt_fcug_2_2_2 Type Management
317
318 #### General
319
320
321 Open CASCADE Technology provides a means to describe the hierarchy  of data types in a generic way, with a possibility to check the exact type of  the given object at run-time (similarly to C++ RTTI). For every class type  derived from *Standard_Transient*, CDL extractor creates a code instantiating single  instance of the class *Standard_Type* (type descriptor) that holds information on  that type: its name and list of ancestor types. 
322 That instance (actually, a handle on it) is returned by the  virtual method *DynamicType()* of the class derived from *Standard_Transient*. The  other virtual method *IsKind()* provides a means to check whether a given object  has specified type or inherits it. 
323
324 In order to refer to the type descriptor object for a given  class type, use macros *STANDARD_TYPE()* with argument being a name of the class. 
325
326 #### Type Conformity
327
328 The type used in the declaration of a handle is the static  type of the object, the type seen by the compiler. A handle can reference an  object instantiated from a subclass of its static type. Thus, the dynamic type  of an object (also called the actual type of an object) can be a descendant of  the type which appears in the handle declaration through which it is  manipulated. 
329
330 Consider the persistent class *CartesianPoint*, a  sub-class of *Point*; the rule of type conformity can be illustrated as  follows: 
331
332 ~~~~~
333 Handle (Geom_Point) p1;
334 Handle (Geom_CartesianPoint) p2;
335 p2 = new Geom_CartesianPoint;
336 p1 = p2;  // OK,  the types are compatible
337 ~~~~~
338
339
340 The compiler sees p1 as a handle to *Point* though the  actual object referenced by *p1* is of the *CartesianPoint* type. 
341
342 #### Explicit Type Conversion
343
344
345 According to the rule of type conformity, it is always  possible to go up the class hierarchy through successive assignments of  handles. On the other hand, assignment does not authorize you to go down the  hierarchy. Consequently, an explicit type conversion of handles is required. 
346
347 A handle can be converted explicitly into one of its  sub-types if the actual type of the referenced object is a descendant of the  object used to cast the handle. If this is not the case, the handle is  nullified (explicit type conversion is sometimes called a “safe cast”).  Consider the example below. 
348
349 ~~~~~~
350 Handle (Geom_Point) p1;
351 Handle (Geom_CartesianPoint) p2, p3;
352 p2 = new Geom_CartesianPoint;
353 p1 = p2; // OK, standard assignment
354 p3 = Handle (Geom_CartesianPoint)::DownCast (p1);
355 // OK, the actual type of p1 is CartesianPoint, although the static type of the handle is Point
356 ~~~~~~
357
358 If conversion is not compatible with the actual type of the  referenced object, the handle which was “cast” becomes null (and no exception  is raised). So, if you require reliable services defined in a sub-class of the  type seen by the handle (static type), write as follows: 
359
360 ~~~~~~
361 void MyFunction (const Handle(A) & a)
362 {
363   Handle(B) b =  Handle(B)::Downcast(a);
364   if (! b.IsNull()) {
365     // we can use “b” if class B inherits from A
366   }
367   else {
368     // the types are incompatible
369   }
370 }
371 ~~~~~~
372 Downcasting is used particularly with collections of objects  of different types; however, these objects should inherit from the same root  class. 
373
374 For example, with a sequence of transient objects *SequenceOfTransient* and two classes  A and B that both inherit from *Standard_Transient*, you get the  following syntax: 
375
376 ~~~~~
377 Handle (A) a;
378 Handle (B) b;
379 Handle (Standard_Transient) t;
380 SequenceOfTransient s;
381 a = new A;
382 s.Append (a);
383 b = new B;
384 s.Append (b);
385 t = s.Value (1);
386 // here, you cannot write:
387 // a = t; // ERROR !
388 // so you downcast:
389 a = Handle (A)::Downcast (t)
390 if (! a.IsNull()) {
391         // types are compatible, you can use a
392 }
393 else {
394        // the types are incompatible
395 }
396 ~~~~~
397
398 @subsubsection occt_fcug_2_2_3 Using  Handles to Create Objects
399 To create an object which is manipulated by handle, declare  the handle and initialize it with the standard C++ **new** operator,  immediately followed by a call to the constructor. The constructor can be any  of those specified in the source of the class from which the object is  instanced. 
400
401 ~~~~~
402 Handle (Geom_CartesianPoint) p;
403 p = new Geom_CartesianPoint (0, 0, 0);
404 ~~~~~
405
406 Unlike for a pointer, the **delete** operator does not  work on a handle; the referenced object is automatically destroyed when no  longer in use. 
407
408 @subsubsection occt_fcug_2_2_4 Invoking Methods
409 Once you have a handle on a persistent or transient object,  you can use it like a pointer in C++. To invoke a method which acts on the  referenced object, you translate this method by the standard *arrow* operator, or  alternatively, by function call syntax when this is available. 
410
411 To test or to modify the state of the handle, the method is  translated by the *dot* operator. 
412 The example below illustrates how to access the coordinates  of an (optionally initialized) point object: 
413
414 ~~~~~
415 Handle (Geom_CartesianPoint) centre;
416 Standard_Real x, y, z;
417 if (centre.IsNull()) {
418   centre = new PGeom_CartesianPoint (0, 0, 0);
419 }
420 centre->Coord(x, y, z);
421 ~~~~~
422
423 The example below illustrates how to access the type object  of a Cartesian point: 
424
425 ~~~~~
426 Handle(Standard_Transient)  p = new Geom_CartesianPoint(0.,0.,0.);
427 if ( p->DynamicType() ==  STANDARD_TYPE(Geom_CartesianPoint) )
428   cout  << ;Type check OK;  << endl; 
429 else 
430   cout << ;Type check FAILED; <<  endl;   
431 ~~~~~
432
433 *NullObject* exception will be raised if  a field or a method of an object is accessed via a *Null* handle. 
434
435 #### Invoking Class Methods
436
437 A class method is called like a static C++ function, i.e. it  is called by the name of the class of which it is a member, followed by the “::” operator and the name of the  method. 
438
439 For example, we can find the maximum degree of a Bezier curve:
440
441 ~~~~~
442 Standard_Integer  n; 
443 n = Geom_BezierCurve::MaxDegree();
444 ~~~~~
445
446 @subsubsection occt_fcug_2_2_5 Handle deallocation
447 Before you delete an object, you must ensure it is no longer  referenced. To reduce the programming load related to this management of object  life, the delete function in Open CASCADE Technology is secured by a **reference  counter** of classes manipulated by handle. A handle automatically deletes an object when it is no  longer referenced. Normally you never call the delete operator explicitly on  instances of subclasses of *Standard_Transient*. 
448
449 When a new handle to the same object is created, the  reference counter is incremented. When the handle is destroyed, nullified, or  reassigned to another object, that counter is decremented. The object is  automatically deleted by the handle when reference counter becomes 0. 
450
451 The principle of allocation can be seen in the example  below. 
452
453 ~~~~~
454 ...
455 {
456 Handle (TColStd_HSequenceOfInteger) H1 = new TColStd_HSequenceOfInteger;
457   // H1 has one reference and corresponds to 48 bytes of  memory
458   {
459     Handle (TColStd_HSequenceOfInteger) H2;
460     H2 = H1; // H1 has two references
461     if (argc == 3) {
462       Handle (TColStd_HSequenceOfInteger) H3;
463       H3 = H1;
464       // Here, H1 has three references
465       ...
466     }
467     // Here, H1 has two references
468   }
469   // Here, H1 has 1 reference
470 }
471 // Here, H1 has no reference and the referred TColStd_HSequenceOfInteger object is deleted. 
472 ~~~~~
473
474 #### Cycles
475
476 Cycles appear if two or more objects reference each other by  handles (stored as fields). In this condition automatic destruction will not  work. 
477
478 Consider for example a graph, whose objects (primitives)  have to know the graph object to which they belong, i.e. a primitive must have  a reference to complete graph object. If both primitives and the graph are  manipulated by handle and they refer to each other by keeping a handle as a  field, the cycle appears.  
479 The graph object will not be deleted when the last handle to  it is destructed in the application, since there are handles to it stored  inside its own data structure (primitives). 
480
481 There are two approaches how to avoid such situation: 
482   * Use C++ pointer for one kind of references, e.g. from a primitive  to the graph
483   * Nullify one set of handles (e.g. handles to a graph in  primitives) when a graph object needs to be destroyed
484   
485 @subsubsection occt_fcug_2_2_6 Creating  Transient Classes without CDL
486
487 Though generation of Handle class and related C++ code is  normally performed by CDL extractor, it is also possible to define a class managed  by handle without CDL. To facilitate that, several macros are provided in the  file Standard_DefineHandle.hxx: 
488
489 * **DEFINE_STANDARD_HANDLE(class_name,ancestor_name)** - declares Handle class  for a class *class_name* that inherits class *ancestor_name* (for  instance, *Standard_Transient*). This macro should be put in a header file; the  declaration of the handle to a base class must be available (usually put before  or after the declaration of the class *class_name*, or into a separate  header file).  
490 * **IMPLEMENT_STANDARD_HANDLE(class_name,ancestor_name)** - implements method  *DownCast()* of the *Handle* class. Should be located in a C++ file (normally the  file where methods of the class *class_name* are implemented). 
491 * **DEFINE_STANDARD_RTTI(class_name)** - declares methods required for  RTTI in the class *class_name* declaration; should be in public: section. 
492 * **IMPLEMENT_STANDARD_RTTIEXT(class_name,ancestor_name)** - implements above methods. Usually  put into the C++ file implementing class class_name. 
493 Note that it is important to ensure correctness of macro  arguments, especially the ancestor name, otherwise the definition may be  inconsistent (no compiler warnings will be issued in case of mistake). 
494
495 In *Appli_ExtSurface.hxx* file:
496 ~~~~~
497 #include <Geom_Surface.hxx>
498 class Appli_ExtSurface : public Geom_Surface
499 {
500 . . .
501 public:
502   DEFINE_STANDARD_RTTI(Appli_ExtSurface)
503 }
504 DEFINE_STANDARD_HANDLE(Appli_ExtSurface,Geom_Surface)
505 ~~~~~
506
507 In *Appli_ExtSurface.cxx* file:
508 ~~~~~
509 #include <Appli_ExtSurface.hxx>
510 IMPLEMENT_STANDARD_HANDLE(Appli_ExtSurface,Geom_Surface)
511 IMPLEMENT_STANDARD_RTTIEXT(Appli_ExtSurface,Geom_Surface)
512 ~~~~~
513
514
515 @subsection occt_fcug_2_3 Memory  Management in Open CASCADE Technology
516 In the course of a work session, geometric modeling  applications create and delete a considerable number of C++ objects allocated  in the dynamic memory (heap). In this context, performance of standard  functions for allocating and deallocating memory may be not sufficient. For  this reason, Open CASCADE Technology employs a specialized memory manager  implemented in the Standard package. 
517
518 @subsubsection occt_fcug_2_3_1. Usage
519 To use the Open CASCADE Technology memory manager to  allocate memory in a C code, just use method *Standard::Allocate()* instead of  *malloc()* and method *Standard::Free()* instead of *free()*. In addition, method *Standard::Reallocate()* is provided to replace C function *realloc()*. 
520
521 In C++, operators *new()* and *delete()* for a class may be  defined so as to allocate memory using *Standard::Allocate()* and free it using  *Standard::Free()*. In that case all objects of that class and all inherited  classes will be allocated using the OCCT memory manager. 
522
523 CDL extractor defines *new()* and *delete()* in this way for all  classes declared with CDL. Thus all OCCT classes (apart from a few exceptions)  are allocated using the OCCT memory manager. 
524 Since operators *new()* and *delete()* are inherited, this is  also true for any class derived from an OCCT class, for instance, for all  classes derived from *Standard_Transient*. 
525
526 **Note** that it is possible (though not  recommended unless really unavoidable) to redefine *new()* and *delete()* functions  for some class inheriting Standard_Transient. If that is done, the method  *Delete()* should be also redefined to apply operator *delete* to *this*  pointer. This will ensure that appropriate *delete()* function will be called,  even if the object is manipulated by a handle to a base class.
527
528 @subsubsection occt_fcug_2_3_2 Configuring  the memory manager
529 The OCCT memory manager may be configured to apply different  optimization techniques to different memory blocks (depending on their size),  or even to avoid any optimization and use C functions *malloc()* and *free()*  directly. 
530 The configuration is defined by numeric values of the  following environment variables: 
531   * *MMGT_OPT*: if set to 0 (default) every memory block is allocated  in C memory heap directly (via *malloc()* and *free()* functions). In this case,  all other options except for *MMGT_CLEAR* are ignored; if set to 1 the memory manager  performs optimizations as described below; if set to 2, Intel ® TBB optimized  memory manager is used.
532   * *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.
533   * *MMGT_CELLSIZE*: defines the maximal size of blocks allocated in  large pools of memory. Default is 200.
534   * *MMGT_NBPAGES*: defines the size of memory chunks allocated for  small blocks in pages (operating-system dependent). Default is 1000.
535   * *MMGT_THRESHOLD*: defines the maximal size of blocks that are  recycled internally instead of being returned to the heap. Default is 40000.
536   * *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()*.
537
538 @subsubsection occt_fcug_2_3_3 Implementation  details
539 When *MMGT_OPT* is set to 1, the following optimization  techniques are used: 
540   * Small blocks with a size less than *MMGT_CELLSIZE*, are not  allocated separately. Instead, a large pools of memory are allocated (the size  of each pool is *MMGT_NBPAGES* pages). Every new memory block is arranged in a  spare place of the current pool. When the current memory pool is completely  occupied, the next one is allocated, and so on.
541   
542 In the current version memory  pools are never returned to the system (until the process finishes). However,  memory blocks that are released by the method *Standard::Free()* are remembered  in the free lists and later reused when the next block of the same size is  allocated (recycling). 
543
544   * 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()*). When such blocks are released by the method *Standard::Free()* they  are recycled just like small blocks.
545   
546 However, unlike small blocks, the  recycled medium blocks contained in the free lists (i.e. released by the  program but held by the memory manager) can be returned to the heap by method  *Standard::Purge()*. 
547
548   * 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*: 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. Large blocks are returned to the  system immediately when *Standard::Free()* is called. 
549
550 #### Benefits and drawbacks
551
552 The major benefit of the OCCT memory manager is explained  by its recycling of small and medium blocks that makes an application work much  faster when it constantly allocates and frees multiple memory blocks of similar  sizes. In practical situations, the real gain on the application performance  may be up to 50%. 
553
554 The associated drawback is that recycled memory is not  returned to the operating system during program execution. This may lead to  considerable memory consumption and even be misinterpreted as a memory leak. To  minimize this effect, the method Standard::Purge() shall be called after the completion  of memory-intensive operations. 
555 The overhead expenses induced by the OCCT memory manager  are: 
556   * size of every allocated memory block is rounded up to 8 bytes  (when MMGT_OPT is 0 (default), the rounding is defined by the CRT; the typical  value for 32-bit platforms is 4 bytes)
557   * additional 4 bytes (or 8 on 64-bit platforms) are allocated in  the beginning of every memory block to hold its size (or address of the next  free memory block when recycled in free list) only when MMGT_OPT is 1
558   
559   
560 Note that these overheads may be greater or less than  overheads induced by the C heap memory manager, so overall memory consumption  may be greater in either optimized or standard modes, depending on  circumstances. 
561
562 As a general rule, it is advisable to allocate memory  through significant blocks. In this way, you can work with blocks of contiguous  data, and processing is facilitated for the memory page manager. 
563
564 OCCT memory manager uses mutex to lock access to free lists, therefore it may have less  performance than non-optimized mode in situations when different threads often  make simultaneous calls to the memory manager.
565 The reason is that modern  implementations of *malloc()* and *free()* employ several allocation arenas and  thus avoid delays waiting mutex release, which are possible in such situations. 
566
567 @subsection occt_fcug_2_4 Exception  Handling
568 Exception handling provides a means of transferring control  from a given point in a program being executed to an **exception handler** associated  with another point previously executed. 
569
570 A method may raise an exception which interrupts its normal  execution and transfers control to the handler catching this exception. 
571
572 Open CASCADE Technology provides a hierarchy of exception  classes with a root class being class Standard_Failure from the Standard  package. The CDL extractor generates exception classes with standardized  interface. 
573
574 Open CASCADE Technology also provides  support for converting system signals (such as access violation or division by  zero) to exceptions, so that such situations can be safely handled with the  same uniform approach. 
575  
576 However, in order to support this functionality on various  platforms, some special methods and workarounds are used. Though the  implementation details are hidden and handling of OCCT exceptions is done  basically in the same way as with C++, some peculiarities of this approach  shall be taken into account and some rules must be respected. 
577
578 The following paragraphs describe recommended approaches for  using exceptions when working with Open CASCADE Technology.  
579
580 @subsubsection occt_fcug_2_4_1 Raising  an Exception
581
582 #### “C++ like” Syntax
583
584 To raise an exception of a definite type method Raise() of  the appropriate exception class shall be used. 
585 ~~~~~
586 DomainError::Raise(“Cannot cope with this condition”);
587 ~~~~~
588 raises an exception of *DomainError* type with the associated  message “Cannot cope with this condition”, the message being optional. This  exception may be caught by a handler of a *DomainError* type as follows: 
589 ~~~~~
590 try {
591   OCC_CATCH_SIGNALS
592   // try block
593 }
594 catch(DomainError) {
595 // handle DomainError exceptions here
596 }
597 ~~~~~
598
599 #### Regular usage
600
601 Exceptions should not be used as a programming technique, to  replace a “goto” statement for example, but as a way to protect methods against  misuse. The caller must make sure its condition is such that the method can  cope with it. 
602
603 Thus, 
604   * No exception should be raised during normal execution of an  application.
605   * A method which may raise an exception should be protected by  other methods allowing the caller to check on the validity of the call.
606   
607 For example, if you consider the *TCollection_Array1* class  used with: 
608   * *Value*  function to extract an element
609   * *Lower*  function to extract the lower bound of the array
610   * *Upper*  function  to extract the upper bound of the array. 
611   
612 then, the *Value*  function may be implemented as follows: 
613
614 ~~~~~
615 Item  TCollection_Array1::Value (const Standard_Integer&index) const
616 {
617   // where r1 and r2 are  the lower and upper bounds of the array
618   if(index  r1 || index > r2) {
619     OutOfRange::Raise(“Index  out of range in Array1::Value”);
620   }
621   return contents[index];
622 }
623 ~~~~~
624
625 Here validity of the index is first verified using the Lower and Upper functions in order to protect the call. 
626 Normally the caller ensures the index being in the valid  range before calling Value(). In this case the above implementation of Value is not optimal since the  test done in Value is  time-consuming and redundant. 
627  
628 It is a widely used practice to include that kind of  protections in a debug build of the program and exclude in release (optimized)  build. To support this practice, the macros Raise_if() are provided for every OCCT  exception class: 
629 ~~~~~
630 <ErrorTypeName>_Raise_if(condition,  “Error message”); 
631 ~~~~~
632 where ErrorTypeName  is the exception type, condition  is the logical expression leading to the raise of the exception, and Error message is the associated  message. 
633   
634 The entire call may be removed by defining one of the  pre-processor symbols No_Exception or No_<ErrorTypeName> at compile-time: 
635
636 ~~~~~
637 #define  No_Exception /* remove all raises */ 
638 ~~~~~
639
640 Using this syntax, the Value  function becomes: 
641
642 ~~~~~
643 Item  TCollection_Array1::Value (const Standard_Integer&index) const
644      { 
645   OutOfRange_Raise_if(index  r1 || index > r2,
646                       “index out of range in  Array1::Value”);
647   return contents[index];
648 }
649 ~~~~~
650
651 @subsubsection occt_fcug_2_4_2 Handling  an Exception
652
653 When an exception is raised, control is transferred to the  nearest handler of a given type in the call stack, that is: 
654   * the handler whose try block was most recently entered and not yet  exited,
655   * the handler whose type matches the raise expression.
656   
657 A handler of T exception type is a match for a raise  expression with an exception type of E if: 
658   * T and E are of the same type, or
659   * T is a supertype of E.
660   
661 In order to handle system signals as exceptions, make sure  to insert macro OCC_CATCH_SIGNALS somewhere in the beginning of the relevant  code. The recommended location for it is first statement after opening brace of  try {} block. 
662
663 As an example, consider the exceptions of type *NumericError, Overflow, Underflow* and *ZeroDivide*,  where *NumericError* is the parent type of the three others. 
664
665 ~~~~~
666 void f(1)
667  {
668   try {
669     OCC_CATCH_SIGNALS
670     // try block
671   }
672   catch(Standard_Overflow) { // first handler
673     // ...
674   }
675   catch(Standard_NumericError) { // second handler
676     // ...
677   }
678 }
679 ~~~~~
680
681 Here, the first handler will catch exceptions of *Overflow* type and the second one - exceptions of *NumericError* type and all exceptions derived from it, including *Underflow* and *ZeroDivide*. 
682
683 The handlers are checked in order of appearance, from the  nearest to the most distant try block, until one matches the raise expression.  For a try block, it would be a mistake to place a handler for a base exception  type ahead of a handler for its derived type since that would ensure that the  handler for the derived exception would never be invoked.  
684
685 ~~~~~
686 void f(1)
687 {
688   int i = 0;
689   {
690     try {
691       OCC_CATCH_SIGNALS
692       g(i);// i is accessible
693     }
694     // statement here will produce compile-time errors !
695     catch(Standard_NumericError) {
696       // fix up with possible reuse of i
697     }
698     // statement here may produce unexpected side effect 
699   }
700   . . .
701 }
702 ~~~~~
703
704 The exceptions form a hierarchy tree completely separated  from other user defined classes. One exception of type *Failure* is the root of the entire exception  hierarchy. Thus, using a handler with *Failure* type catches any OCCT exception. It is recommended to set up such a handler in  the main routine.  
705
706 The main routine of a program would look like this: 
707
708 ~~~~~
709 #include <Standard_ErrorHandler.hxx>
710 #include <Standard_Failure.hxx>
711 #include <iostream.h>
712 int main (int argc, char* argv[])
713 {
714   try {
715     OCC_CATCH_SIGNALS
716     // main block
717     return 0;
718   }
719   catch(Standard_Failure) {
720     Handle(Standard_Failure) error = Standard_Failure::Caught  ();
721     cout  error  end1;
722   }
723   return 1;
724 }
725 ~~~~~
726
727 In this example function *Caught* is a static member of *Failure* that  returns an exception object containing the error message built in the raise  expression. Note that this method of accessing a raised object is used in Open  CASCADE Technology instead of usual C++ syntax (receiving the exception in  catch argument). 
728
729 Though standard C++ scoping  rules and syntax apply to try block and handlers, note that on some platforms Open  CASCADE Technology may be compiled in compatibility mode when exceptions are  emulated by long jumps (see below). In this mode it is required that no  statement precedes or follows any handler. Thus it is highly recommended to  always include a try block into additional {} braces. Also this mode requires  that header file *Standard_ErrorHandler.hxx* be included in your program before a  try block, otherwise it may fail to handle Open CASCADE Technology exceptions;  furthermore *catch()* statement does not allow passing exception object as  argument. 
730
731 #### Catching signals
732
733 In order for the application to be able to catch system  signals (access violation, division by zero, etc.) in the same way as other  exceptions, the appropriate signal handler shall be installed in the runtime by  the method *OSD::SetSignal()*.
734  
735 Normally this method is called in the beginning of the  main() function. It installs a handler that will convert system signals into OCCT  exceptions. 
736
737 In order to actually convert signals to exceptions, macro *OCC_CATCH_SIGNALS* needs to be inserted in the source code. The typical place where  this macro is put is beginning of the *try{}* block which catches such exceptions.   
738
739 @subsubsection occt_fcug_2_4_3 Implementation  details
740
741 The exception handling mechanism in Open CASCADE Technology  is implemented in different ways depending on the preprocessor macros *NO_CXX_EXCEPTIONS*  and *OCC_CONVERT_SIGNALS*, which shall be consistently defined by compilation  procedures for both Open CASCADE Technology and user applications: 
742
743 1. On  Windows and DEC, these macros are not defined by default, and normal C++  exceptions are used in all cases, including throwing from signal handler. Thus the  behavior is as expected in C++. 
744
745 2. On  SUN and Linux, macro *OCC_CONVERT_SIGNALS* is defined by default. The C++  exception mechanism is used for catching exceptions and for throwing them from  normal code. 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. The macro *OCC_CATCH_SIGNALS* is defined in the  file *Standard_ErrorHandler.hxx*. Therefore, including this file is necessary for  successful compilation of a code containing this macro. 
746
747    This mode differs from standard  C++ exception handling only for signals:
748  
749    * macro *OCC_CATCH_SIGNALS* is necessary (besides call to  *OSD::SetSignal()* described above) for conversion of signals into exceptions;
750    * 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.
751
752 3. On  SUN and Linux Open CASCADE Technology can also be compiled in compatibility  mode (which was default till Open CASCADE Technology 6.1.0). In that case macro  *NO_CXX_EXCEPTIONS* is defined and the C++ exceptions are simulated with C long  jumps. As a consequence, the behavior is slightly different from that expected  in the C++ standard.  
753
754 While exception handling with  NO_CXX_EXCEPTIONS is very similar to C++ by syntax, it has a number of  peculiarities that should be taken into account: 
755
756 * try and catch are actually macros defined in the file *Standard_ErrorHandler.hxx*. Therefore, including this file is necessary for  handling OCCT exceptions;
757 * due to being a macro, catch cannot contain a declaration of the  exception object after its type; only type is allowed in the catch statement.  Use method *Standard_Failure::Caught()* to access an exception object;
758 * catch macro may conflict with some STL classes that might use  catch(...) statements in their header files. So STL headers should not be  included after *Standard_ErrorHandler.hxx*;
759 * Open CASCADE Technology try/catch block will not handle normal  C++ exceptions; however this can be achieved using special workarounds;
760 * the try macro defines a C++ object that holds an entry point in the  exception handler. Therefore if exception is raised by code located immediately  after the try/catch block but on the same nesting level as *try*, it may  be handled by that *catch*. This may lead to unexpected behavior,  including infinite loop. To avoid that, always surround the try/catch block in \{\} braces;
761 * the destructors of the C++ objects allocated on the stack after  handler initialization are not called by exception raising.
762
763 In general, for writing platform-independent code it is recommended  to insert macros *OCC_CATCH_SIGNALS* in try \{\} blocks or other code where signals  may happen. For compatibility with previous versions of Open CASCADE Technology  the limitations described above for *NO_CXX_EXCEPTIONS* shall be assumed. 
764
765 @subsection occt_fcug_2_5 Plug-In  Management
766
767 @subsubsection occt_fcug_2_5_1 Distribution by Plug-Ins
768
769 A plug-in is a component that can be loaded dynamically into  a client application, not requiring to be directly linked to it. The plug-in is  not bound to its client, i.e. the plug-in knows only how its connection  mechanism is defined and how to call the corresponding services. 
770
771 A plug-in can be used to: 
772   * 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),
773   * 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),
774   * 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).
775   
776 The plug-in is identified with the help of the global  universal identifier (GUID). The GUID includes lower case characters and cannot  end with a blank space. 
777
778 Once it has been loaded, the call to the services provided  by the plug-in is direct (the client is implemented in the same language as the  plug-in). 
779
780 #### C++ Plug-In  Implementation
781
782 The C++ plug-in implements a service as an object with  functions defined in an abstract class (this abstract class and its parent  classes with the GUID are the only information about the plug-in implemented in  the client application). The plug-in consists of a sharable library including a  method named Factory which  creates the C++ object (the client cannot instantiate this object because the  plug-in implementation is not visible). 
783 Foundation classes provide in the package **Plugin** a  method named Load(), which enables the client to access the required service  through a library.  
784
785 That method reads the information regarding available  plug-ins and their locations from the resource file Plugin found by environment  variable CSF_PluginDefaults:
786
787 ~~~~~ 
788 $CSF_PluginDefaults/.Plugin 
789 ~~~~~
790
791 The *Load* method looks for the library name in the resource file or registry  through its GUID, for example, on UNIX:
792 ~~~~~
793 ! METADATADRIVER whose value must be OS or DM.
794
795 ! FW
796 a148e300-5740-11d1-a904-080036aaa103.Location:
797  
798 libFWOSPlugin.so
799 a148e300-5740-11d1-a904-080036aaa103.CCL:
800 /adv_44/CAS/BAG/FW-K4C/inc/FWOS.ccl
801
802 ! FWDM
803 a148e301-5740-11d1-a904-080036aaa103.Location:
804 libFWDMPlugin.so
805 a148e301-5740-11d1-a904-080036aaa103.CCL:
806 /adv_44/CAS/BAG/DESIGNMANAGER-K4C/inc/DMAccess.ccl|/
807 adv_44/CAS/BAG/DATABASE-K4C/inc/FWDMCommands.ccl
808 a148e301-5740-11d1-a904-080036aaa103.Message:  /adv_44/CAS/
809 BAG/DESIGNMANAGER-K4C/etc/locale/DMAccess
810
811 ! Copy-Paste
812 5ff7dc00-8840-11d1-b5c2-00a0c9064368.Location:
813 libCDMShapeDriversPlugin.so
814 5ff7dc01-8840-11d1-b5c2-00a0c9064368.Location:
815 libCDMShapeDriversPlugin.so
816 5ff7dc02-8840-11d1-b5c2-00a0c9064368.Location:
817 libCDMShapeDriversPlugin.so
818 5ff7dc03-8840-11d1-b5c2-00a0c9064368.Location:
819 libCDMShapeDriversPlugin.so
820 5ff7dc04-8840-11d1-b5c2-00a0c9064368.Location:
821 libCDMShapeDriversPlugin.so
822
823 ! Plugs 2d plotters:
824 d0d722a2-b4c9-11d1-b561-0000f87a4710.location: FWOSPlugin
825 d0d722a2-b4c9-11d1-b561-0000f87a4710.CCL: /adv_44/CAS/BAG/
826 VIEWERS-K4C/inc/CCLPlotters.ccl
827 d0d722a2-b4c9-11d1-b561-0000f87a4710.Message: /adv_44/CAS/
828 BAG/VIEWERS-K4C/etc/locale/CCLPlotters
829
830 !SHAPES
831 e3708f72-b1a8-11d0-91c2-080036424703.Location:
832 libBRepExchangerPlugin.so
833 e3708f72-b1a8-11d0-91c2-080036424703.CCL: /adv_44/CAS/BAG/
834 FW-K4C/inc/BRep.ccl
835 ~~~~~
836
837
838 Then the *Load* method loads the library according to the rules of the operating system  of the host machine (for example, by using environment variables such as  *LD_LIBRARY_PATH* with Unix and *PATH* with Windows). After that it invokes the *Factory*  method to return the object which supports the required service.
839 The client may then call the functions supported by this  object. 
840
841 #### C++ Client Plug-In  Implementation
842
843 To invoke one of the services provided by the plug-in, you  may call the *Plugin::ServiceFactory* global function with the *Standard_GUID* of the requested service as follows: 
844
845 ~~~~~
846 Handle(FADriver_PartStorer)::DownCast 
847 (PlugIn::ServiceFactory 
848 (PlugIn_ServiceId(yourStandardGUID))) 
849 ~~~~~
850
851 Let us take *FAFactory.cxx* as an example:
852
853 ~~~~~
854 #include <FAFactory.ixx>
855
856 #include <FADriver_PartRetriever.hxx>
857 #include <FADriver_PartStorer.hxx>
858 #include <FirstAppSchema.hxx>
859 #include <Standard_GUID.hxx>
860 #include <Standard_Failure.hxx>
861 #include <FACDM_Application.hxx>
862 #include <Plugin_Macro.hxx>
863
864 PLUGIN(FAFactory)
865
866 static Standard_GUID 
867        StorageDriver(“45b3c690-22f3-11d2-b09e-0000f8791463”);
868 static Standard_GUID 
869        RetrievalDriver(“45b3c69c-22f3-11d2-b09e-0000f8791463”);
870 static Standard_GUID 
871        Schema(“45b3c6a2-22f3-11d2-b09e-0000f8791463”);
872
873 //======================================================
874 // function : Factory
875 // purpose :
876 //======================================================
877  
878 Handle(Standard_Transient)  FAFactory::Factory(const Standard_GUID& aGUID) 
879 {
880   if(aGUID == StorageDriver) {
881     cout  “FAFactory : Create store driver”   endl;
882     static  Handle(FADriver_PartStorer) sd = new FADriver_PartStorer();
883     return sd;
884   }
885
886   if(aGUID == RetrievalDriver) {
887     cout  “FAFactory : Create retrieve driver”   endl;
888     static Handle(FADriver_PartRetriever)
889     rd = new FADriver_PartRetriever();
890     return rd;
891   }
892
893   if(aGUID == Schema) {
894     cout  “FAFactory : Create schema”   endl;
895     static Handle(FirstAppSchema) s = new  FirstAppSchema();
896     return s;
897   }
898
899   Standard_Failure::Raise(“FAFactory: unknown GUID”);
900   Handle(Standard_Transient) t;
901   return t;
902 }
903 ~~~~~
904
905 #### Without using the Software  Factory
906
907 To create a factory without using the Software Factory,  define a *dll* project under Windows or a library under UNIX by using a  source file as specified above. The *FAFactory* class is implemented as  follows: 
908
909 ~~~~~
910 #include <Handle_Standard_Transient.hxx>
911 #include <Standard_Macro.hxx>
912 class Standard_Transient;
913 class Standard_GUID;
914 class FAFactory {
915 public:
916   Standard_EXPORT  static Handle_Standard_Transient
917                   Factory(const Standard_GUID& aGUID)  ;
918   . . .
919 };
920 ~~~~~
921
922
923 @section occt_fcug_3 Collections,  Strings and Unit Conversion
924
925 @subsection occt_fcug_3_1 Collections
926
927 @subsubsection occt_fcug_3_1_1 Overview
928
929 The **Collections** component contains the classes that  handle dynamically sized aggregates of data. They include a wide range of  collections such as arrays, lists and maps. 
930
931 Collections classes are *generic*, that is, they can  hold a variety of objects which do not necessarily inherit from a unique root  class. When you need to use a collection of a given type of object you must *instantiate* it for this specific type of element. Once this declaration is compiled,  all the functions available on the generic collection are available on your *instantiated  class*. 
932 However, note that: 
933   * Each collection directly used as an argument in OCCT public  syntax is instantiated in an OCCT component.
934   * 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.
935 The **Collections** component provides a wide range of  generic collections: 
936   * **Arrays** are generally used for a quick access to the item,  however an array is a fixed sized aggregate.
937   * **Sequences** are variable-sized structures, they avoid the  use of large and quasi-empty arrays. 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). Arrays and sequences are commonly  used as data structures for more complex objects.
938   * On the other hand, **maps** are dynamic structures where the  size is constantly adapted to the number of inserted items and the access time  for an item is effective. Maps structures are commonly used in cases of  numerous explorations: they are typically internal data structures for complex  algorithms. **Sets** generate the same results as maps but computation time  is considerable.
939   * **Lists, queues** and **stacks** are minor structures  similar to sequences but with other exploration algorithms.
940   
941 Most collections follow value semantics: their  instances are the actual collections, not **handles** to a collection. Only  arrays and sequences may also be manipulated by handle, and therefore shared. 
942
943 @subsubsection occt_fcug_3_1_2 Generic general-purpose Aggregates
944
945 #### TCollection_Array1
946
947 These are unidimensional arrays similar to C arrays, i.e. of fixed  size but dynamically dimensioned at construction time. 
948 As with a C array, the access time for an *Array1* indexed  item is constant and is independent of the array size. Arrays are commonly used  as elementary data structures for more complex objects. 
949
950 *Array1* is a generic class which depends on *Item*,  the type of element in the array. 
951
952 *Array1* indexes start and end at a user-defined  position. Thus, when accessing an item, you must base the index on the lower  and upper bounds of the array. 
953
954 #### TCollection_Array2
955
956 These are bi-dimensional arrays of fixed size but dynamically  dimensioned at construction time. 
957
958 As with a C array, the access time for an *Array2* indexed  item is constant and is independent of the array size. Arrays are commonly used  as elementary data structures for more complex objects. 
959
960 *Array2* is a generic class which depends on *Item*,  the type of element in the array. 
961
962 *Array2* indexes start and end at a user-defined  position. Thus, when accessing an item, you must base the index on the lower  and upper bounds of the array. 
963
964 #### TCollection_HArray1
965
966 These are unidimensional arrays similar to C arrays, i.e. of fixed  size but dynamically dimensioned at construction time. 
967 As with a C array, the access time for an *HArray1* or *HArray2* indexed item is constant and is independent of the array size. Arrays are  commonly used as elementary data structures for more complex objects. 
968
969 *HArray1* objects are **handles** to arrays. 
970   * *HArray1* arrays may be shared by several objects.
971   * You may use a *TCollection_Array1* structure to have the  actual array.
972   
973 *HArray1* is a generic class which depends on two parameters: 
974   * **Item**, the type of element in the array,
975   * **Array**, the actual type of array handled by *HArray1*.  This is an instantiation with **Item** of the *TCollection_Array1* generic  class.
976   
977 *HArray1* indexes start and end at a user-defined  position. Thus, when accessing an item, you must base the index on the lower  and upper bounds of the array. 
978
979 #### TCollection_HArray2
980
981 These are bi-dimensional arrays of fixed size but dynamically  dimensioned at construction time. 
982
983 As with a C array, the access time for an *HArray2* indexed  item is constant and is independent of the array size. Arrays are commonly used  as elementary data structures for more complex objects. 
984
985 *HArray2* objects are **handles** to arrays. 
986   * *HArray2* arrays may be shared by several objects.
987   * You may use a *TCollection_Array2* structure to have the  actual array.
988   
989 *HArray2* is a generic class which depends on two  parameters: 
990   * *Item*, the type of element in the array,
991   * *Array*, the actual type of array handled by *HArray2*.  This is an instantiation with *Item* of the *TCollection_Array2* generic  class.
992   
993 #### TCollection_HSequence
994
995 This is a sequence of items indexed by an integer. 
996
997 Sequences have about the same goal as unidimensional arrays  *TCollection_HArray1*: they are commonly used as elementary data  structures for more complex objects. But a sequence is a structure of *variable  size*: sequences avoid the use of large and quasi-empty arrays. Exploring a  sequence data structure is effective when the exploration is done in  sequence; elsewhere a sequence item is longer to read than an array item.  Note also that sequences are not effective when they have to support numerous  algorithmic explorations: a map is better for that. 
998
999 *HSequence* objects are **handles** to sequences. 
1000   * *HSequence* sequences may be shared by several objects.
1001   * You may use a *TCollection_Sequence* structure to have the  actual sequence.
1002   
1003 *HSequence* is a generic class which depends on two  parameters: 
1004   * *Item*, the type of element in the sequence,
1005   * *Seq*, the actual type of sequence handled by *HSequence*.  This is an instantiation with *Item* of the *TCollection_Sequence* generic  class.
1006   
1007 #### TCollection_HSet
1008
1009 This is a collection of non-ordered items without any duplicates. At  each transaction, the system checks if  there are no duplicates. 
1010 *HSet* objects are *handles* to sets. 
1011 *HSet* is a generic class which depends on two  parameters: 
1012   * *Item*, the type of element in the set,
1013   * *Set*, the actual type of set handled by *HSet*. This  is an instantiation with *TCollection_Set* generic class.
1014   
1015 #### TCollection_List
1016
1017 These are ordered lists of non-unique objects which can be accessed  sequentially using an iterator. 
1018 Item insertion in a list is very fast at any position. But  searching for items by value may be slow if the list is long, because it  requires a sequential search. 
1019
1020 *List* is a generic class, which depends on *Item*,  the type of element in the structure. 
1021 Use a *ListIterator* iterator to explore a *List* structure. 
1022
1023 An iterator class is automatically instantiated from the *TCollection_ListIterator* class at the time of instantiation of a *List* structure. 
1024
1025 A sequence is a better structure when searching for items by  value. 
1026
1027 Queues and stacks are other kinds of list with a different  access to data. 
1028
1029 #### TCollection_Queue
1030
1031 This is a structure, where items are added at the end and removed  from the front. The first item entered will be the first removed (**FIFO**  structure: First In First Out). *Queue* is a generic class which depends  on *Item*, the type of element in the structure. 
1032
1033 #### TCollection_Sequence
1034
1035 This is a sequence of items indexed by an integer. 
1036 Sequences have about the same goal as unidimensional arrays  (*TCollection_Array1*): they are commonly used as elementary data  structures for more complex objects. But a sequence is a structure of *variable  size*: sequences avoid the use of large and quasi-empty arrays. Exploring a  sequence data structure is effective when the exploration is done *in sequence*; elsewhere a sequence item is longer to read than an array item.  Note also that sequences are not effective when they have to support numerous  algorithmic explorations: a map is better for that. 
1037
1038 *Sequence* is a generic class which depends on *Item*,  the type of element in the sequence. 
1039
1040 #### TCollection_Set
1041
1042 This is a collection of non-ordered items without any duplicates. At  each transaction, the system checks if there are no duplicates. 
1043
1044 A set generates the same result as a map. A map is more  effective; so it is advisable to use maps instead of sets. 
1045
1046 *Set* is a generic class which depends on *Item*,  the type of element in the set. 
1047 Use *SetIterator* iterator to explore a *Set* structure. 
1048
1049 #### TCollection_Stack
1050
1051 This is a structure where items are added and removed from the top.  The last item entered will be the first removed. 
1052
1053 *Stack* is a generic class which depends on *Item*,  the type of element in the structure. 
1054 Use a *StackIterator* iterator to explore a *Stack* structure. 
1055
1056 @subsubsection occt_fcug_3_1_3 Generic Maps
1057
1058 Maps are dynamically extended data structures where data is  quickly accessed with a key. *TCollection_BasicMap* is a root class for maps. 
1059
1060 #### General properties of maps
1061
1062
1063 Map items may contain complex non-unitary data, thus it can be difficult to manage them with an array. The map allows a data structure to be  indexed by complex data. 
1064
1065 The size of a map is dynamically extended. So a map may be  first dimensioned for a little number of items. Maps avoid the use of large and  quasi-empty arrays. 
1066
1067 The access time for a map item is much better than the one  for a sequence, list, queue or stack item. It is  comparable with the  access time for an array item. It depends on the size of the map and on the quality of the user redefinable function (the *hashing  function*) to find quickly where is the item. 
1068
1069 The performance of a map exploration may be better of an array exploration because the size of the map is adapted to the  number of inserted items. 
1070
1071 That is why maps are commonly used as  internal data structures for algorithms. 
1072
1073 #### Definitions 
1074
1075 A map is a data structure for which data are addressed by *keys*. 
1076
1077 Once inserted in the map, a map item is referenced as an *entry* of the map. 
1078
1079 Each entry of the map is addressed by a key. Two different  keys address two different entries of the map. 
1080 The position of an entry in the map is called a *bucket*. 
1081
1082 A map is dimensioned by its number of buckets, i.e. the  maximum number of entries in the map. The performance of a map is conditioned  by the number of buckets. 
1083
1084 The *hashing function* transforms a key into a bucket  index. The number of values that can be computed by the hashing function is  equal to the number of buckets of the map. 
1085
1086 Both the hashing function and the equality test between two  keys are provided by a *hasher* object. 
1087
1088 A map may be explored by a *map iterator*. This  exploration provides only inserted entries in the map (i.e. non empty buckets). 
1089
1090 #### Collections of generic maps 
1091
1092 The *Collections* component provides numerous generic  derived maps. 
1093
1094 These maps include automatic management of the number of *buckets*:  they are automatically resized when the number of *keys* exceeds the  number of buckets. If you have a fair idea of the number of items in your map,  you can save on automatic resizing by specifying a number of buckets at the  time of construction, or by using a resizing function. This may be considered  for crucial optimization issues. 
1095
1096 *Keys, items* and *hashers* are parameters of  these generic derived maps. 
1097
1098 *TCollection_MapHasher* class describes the functions  required by any *hasher*, which is to be used with a map instantiated from  the **Collections** component. 
1099
1100 An iterator class is automatically instantiated at the time  of instantiation of a map provided by the *Collections* component if this  map is to be explored with an iterator. Note that some provided generic maps  are not to be explored with an iterator but with indexes (*indexed maps*). 
1101
1102 ##### TCollection_DataMap
1103
1104 This is a map used to store keys with associated items. An entry of **DataMap** is composed of both the key and the item. 
1105 The *DataMap* can be seen as an extended array where  the keys are the indexes.
1106  
1107 *DataMap* is a generic class which depends on three  parameters: 
1108   * *Key* is the type of key for an entry in the map,
1109   * *Item* is the type of element associated with a key in the  map,
1110   * *Hasher* is the type of hasher on keys.
1111   
1112 Use a *DataMapIterator* iterator to explore a *DataMap*  map. 
1113
1114 An iterator class is automatically instantiated from the *TCollection_DataMapIterator* generic class at the time  of instantiation of a *DataMap* map. 
1115
1116 *TCollection_MapHasher* class describes the functions required for a *Hasher* object. 
1117
1118 ##### TCollection_DoubleMap
1119
1120 This is a map used to bind pairs of keys (Key1,Key2) and retrieve them in linear time. 
1121
1122 *Key1* is  referenced as the first key of the *DoubleMap* and *Key2* as the second key. 
1123
1124 An entry of a *DoubleMap* is composed of a pair of two  keys: the first key and the second key. 
1125
1126 *DoubleMap* is a generic class which depends on four  parameters: 
1127   * *Key1* is the type of the first key for an entry in the map,
1128   * *Key2* is the type of the second key for an entry in the  map,
1129   * *Hasher1* is the type of hasher on first keys,
1130   * *Hasher2* is the type of hasher on second keys.
1131   
1132 Use *DoubleMapIterator* to explore a *DoubleMap* map. 
1133
1134 An iterator class is automatically instantiated from the *TCollection_DoubleMapIterator* class at the time of instantiation of a *DoubleMap* map. 
1135
1136 *TCollection_MapHasher* class describes the functions  required for a *Hasher1* or a *Hasher2* object. 
1137
1138 ##### TCollection_IndexedDataMap
1139
1140 This is  map to store keys with associated items and to bind an  index to them. 
1141
1142 Each new key stored in the map is assigned an index. Indexes  are incremented as keys (and items) stored in the map. A key can be found by  the index, and an index can be found by the key. No key but the last can be  removed, so the indexes are in the range 1...Upper,  where *Upper* is the number of  keys stored in the map. An item is stored with each key. 
1143
1144 An entry of an *IndexedDataMap* is composed of both the  key, the item and the index. An *IndexedDataMap* is an ordered map, which  allows a linear iteration on its contents. It combines the interest: 
1145   * of an array because data may be accessed with an index,
1146   * and of a map because data may also be accessed with a key.
1147
1148 *IndexedDataMap* is a generic class which depends on  three parameters: 
1149         * *Key* is the type of key for an entry in the map,
1150         * *Item* is the type of element associated with a key in the map,
1151         * *Hasher* is the type of hasher on keys.
1152
1153 ##### TCollection_IndexedMap
1154
1155 This is map used to store keys and to bind an index to them. 
1156
1157 Each new key stored in the map is assigned an index. Indexes  are incremented as keys stored in the map. A key can be found by the index, and  an index by the key. No key but the last can be removed, so the indexes are in  the range 1...Upper where Upper is the number of keys stored  in the map. 
1158
1159 An entry of an *IndexedMap* is composed of both the key  and the index. An *IndexedMap* is an ordered map, which allows a linear  iteration on its contents. But no data is attached to the key. An *IndexedMap* is typically used by an algorithm to know if some action is still performed  on components of a complex data structure. 
1160
1161 *IndexedMap* is a generic class which depends on two  parameters: 
1162   * *Key* is the type of key for an entry in the map,
1163   * *Hasher* is the type of hasher on keys.
1164
1165 ##### TCollection_Map
1166
1167 This is a basic hashed map, used to store and retrieve keys in  linear time. 
1168
1169 An entry of a *Map* is composed of the key only. No  data is attached to the key. A *Map* is typically used by an algorithm to  know if some action is still performed on components of a complex data  structure. 
1170
1171 *Map* is a generic class which depends on two  parameters: 
1172   * *Key* is the type of key in the map,
1173   * *Hasher* is the type of hasher on keys.
1174
1175 Use a *MapIterator* iterator to explore a *Map* map. 
1176
1177 ##### TCollection_MapHasher
1178
1179 This is a hasher on the *keys* of a map instantiated from the *Collections* component. 
1180
1181 A hasher provides two functions: 
1182 * *HashCode()* function transforms a key into a bucket index in the map. The number of values that can be  computed by the hashing function is equal to the number of buckets in the map.
1183 * *IsEqual* is the equality test between two keys. Hashers are  used as parameters in generic maps provided by the **Collections** component.
1184
1185 *MapHasher* is a generic class which depends on the  type of keys, providing that *Key* is a type from the *Standard* package.  In such cases *MapHasher* may be directly instantiated with *Key*.  Note that the package *TColStd* provides some of these instantiations. 
1186
1187 Elsewhere, if *Key* is not a type from the *Standard* package  you must consider *MapHasher* as a template and build a class which  includes its functions, in order to use it as a hasher in a map instantiated  from the *Collections* component. 
1188
1189 Note that *TCollection_AsciiString* and *TCollection_ExtendedString* classes correspond to these specifications, in consequence they may be used  as hashers: when *Key* is one of these two types you may just define the  hasher as the same type at the time of instantiation of your map. 
1190
1191 @subsubsection occt_fcug_3_1_4 Iterators
1192
1193 #### TCollection_BasicMapIterator
1194
1195 This is a root class for map iterators. A map iterator provides a step  by step exploration of all the entries of a map. 
1196
1197 #### TCollection_DataMapIterator
1198
1199 These are functions used for iterating the contents of a *DataMap* map. 
1200
1201 A map is a non-ordered data structure. The order in which  entries of a map are explored by the iterator depends on its contents and  change when the map is edited. It is not recommended to modify the contents of a map during  the iteration: the result is unpredictable. 
1202
1203 #### TCollection_DoubleMapIterator
1204
1205 These are functions used for iterating the contents of a *DoubleMap* map. 
1206
1207 #### TCollection_ListIterator
1208
1209 These are unctions used for iterating the contents of a *List* data  structure. 
1210
1211 A *ListIterator* object can be used to go through a  list sequentially, and as a bookmark to hold a position in a list. It is not an  index, however. Each step of the iteration gives the current position of  the iterator, to which corresponds the current item in the list. The current  position is not defined if the list is empty, or when the exploration  is finished. 
1212
1213 An iterator class is automatically instantiated from this  generic class at the time of instantiation of a *List* data structure. 
1214
1215 #### TCollection_MapIterator
1216
1217 These are functions used for iterating the contents of a *Map* map. 
1218 An iterator class is automatically instantiated from this  generic class at the time of instantiation of a *Map* map. 
1219
1220 #### TCollection_SetIterator
1221
1222 These are functions used for iterating the contents of a *Set* data  structure. 
1223 An iterator class is automatically instantiated from this  generic class at the time of instantiation of a *Set* structure. 
1224
1225 #### TCollection_StackIterator
1226
1227 These are functions used for iterating the contents of a **Stack** data  structure. 
1228
1229 An iterator class is automatically instantiated from this  generic class at the time of instantiation of a *Stack* structure. 
1230
1231 @subsection occt_fcug_3_2 Collections of Standard Objects
1232 @subsubsection occt_fcug_3_2_1 Overview
1233 While generic classes of the *TCollection* package are the  root classes that describe the generic purpose of every type of collection, classes effectively used are extracted from the *TColStd* package. 
1234 The *TColStd* and *TShort* packages provide  frequently used instantiations of generic classes with objects from the *Standard* package or strings from the *TCollection* package. 
1235
1236 @subsubsection occt_fcug_3_2_2 Description
1237 These instantiations are the following: 
1238   * Unidimensional arrays: instantiations of the *TCollection_Array1* generic class with *Standard* Objects and *TCollection* strings.
1239   * Bidimensional arrays: instantiations of the *TCollection_Array2* generic class with *Standard* Objects.
1240   * Unidimensional arrays manipulated by handles: instantiations of  the *TCollection_HArray1* generic class with *Standard* Objects and *TCollection* strings.
1241   * Bidimensional arrays manipulated by handles: instantiations of  the *TCollection_HArray2* generic class with *Standard* Objects.
1242   * Sequences: instantiations of the *TCollection_Sequence* generic  class with *Standard* objects and *TCollection* strings.
1243   * Sequences manipulated by handles: instantiations of the *TCollection_HSequence* generic class with *Standard* objects and *TCollection* strings.
1244   * Lists: instantiations of the *TCollection_List* generic  class with *Standard* objects.
1245   * Queues: instantiations of the *TCollection_Queue* generic  class with *Standard* objects.
1246   * Sets: instantiations of the *TCollection_Set* generic class  with *Standard* objects.
1247   * Sets manipulated by handles: instantiations of the *TCollection_HSet* generic class with *Standard* objects.
1248   * Stacks: instantiations of the *TCollection_Stack* generic  class with *Standard* objects.
1249   * Hashers on map keys: instantiations of the *TCollection_MapHasher* generic class with *Standard* objects.
1250   * Basic hashed maps: instantiations of the *TCollection_Map* generic  class with *Standard* objects.
1251   * Hashed maps with an additional item: instantiations of the *TCollection_DataMap* generic class with *Standard* objects.
1252   * Basic indexed maps: instantiations of the *TCollection_IndexedMap* generic class with *Standard* objects.
1253   * Indexed maps with an additional item: instantiations of the *TCollection_IndexedDataMap* generic class with *Standard_Transient* objects.
1254   * Class *TColStd_PackedMapOfInteger* provides alternative  implementation of map of integer numbers, optimized for both performance and  memory usage (it uses bit flags to encode integers, which results in spending  only 24 bytes per 32 integers stored in optimal case). This class also provides  Boolean operations with maps as sets of integers (union, intersection,  subtraction, difference, checks for equality and containment).
1255   
1256 @subsection occt_fcug_3_3 NCollections
1257 @subsubsection occt_fcug_3_3_1 Overview  
1258   
1259 *NCollection* package allows to not use WOK development environment in projects. Though it is quite natural to develop a code based on OCCT in any environment accepted in the industry, there is still one limitation: the so-called OCCT generic classes provided in TCollection package require compilation of the definitions in the CDL language and therefore can only be instantiated in WOK development environment.
1260
1261 The NCollection library provides a full replacement of all TCollection generic classes so that any OCCT collection could be instantiated via C++ template or macro definitions. It can be used in WOK as a package development unit, or in any other configuration, since it only uses the standard capabilities of C++ compiler.
1262
1263 Macro definitions of these classes are stored in *NCollection_Define\*.hxx* files. These definitions are now obsolete though still can be used, particularly for compatibility with the existing code. On the contrary, template classes in *NCollection_\*.hxx* files are recommended, they are supported by OPEN CASCADE Company and further developed according to various needs.
1264
1265 The technology used in this unit continues and complements the one offered in the header file *Standard_DefineHandle* – allowing to implement outside CDL the classes managed by Handle, also providing OCCT RTTI support.
1266
1267 @subsubsection occt_fcug_3_3_2 Instantiation of collection classes
1268
1269 Now we are going to implement the definitions from *NCollection* in the code, taking as an example a sequence of points (analogue of *TColgp_SequenceOfPnt*).
1270   
1271 #### Definition of a new collection class
1272
1273 Let the header file be *MyPackage_SequenceOfPnt.hxx* :
1274
1275 Template class instantiaton
1276 ~~~~~
1277 #include <NCollection_Sequence.hxx>
1278 #include <gp_Pnt.hxx>
1279 typedef NCollection_Sequence<gp_Pnt> MyPackage_SequenceOfPnt;
1280 ~~~~~
1281
1282 Macro instantiation
1283 ~~~~~
1284 #include <NCollection_DefineSequence.hxx>
1285 #include <gp_Pnt.hxx>
1286 ~~~~~
1287
1288 The following line defines the class "base collection of points"
1289 ~~~~~
1290 DEFINE_BASECOLLECTION(MyPackage_BaseCollPnt, gp_Pnt)
1291 ~~~~~
1292
1293 The following line defines the class *MyPackage_SequenceOfPnt*
1294
1295 ~~~~~
1296 DEFINE_SEQUENCE (MyPackage_SequenceOfPnt, MyPackage_BaseCollPnt , gp_Pnt)  
1297 ~~~~~
1298
1299 #### Definition of a new collection class managed by Handle
1300
1301 It is necessary to provide relevant statements both in the header ( .hxx file) and the C++ source ( .cxx file). 
1302
1303 Header file MyPackage_HSequenceOfPnt.hxx:
1304
1305 ~~~~~
1306 #include <NCollection_DefineHSequence.hxx>
1307 #include <gp_Pnt.hxx>
1308 ~~~~~
1309
1310 The following line defines the class "base collection of points"
1311
1312 ~~~~~
1313 DEFINE_BASECOLLECTION(MyPackage_BaseCollPnt, gp_Pnt)
1314 ~~~~~
1315
1316 The following line defines the class *MyPackage_SequenceOfPnt*
1317
1318 ~~~~~
1319 DEFINE_SEQUENCE (MyPackage_SequenceOfPnt, MyPackage_BaseCollPnt, gp_Pnt)
1320 ~~~~~
1321
1322 The following line defines the classes *MyPackage_HSequenceOfPnt* and *Handle(MyPackage_HSequenceOfPnt)*
1323
1324 ~~~~~
1325 DEFINE_HSEQUENCE (MyPackage_HSequenceOfPnt, MyPackage_SequenceOfPnt)
1326 ~~~~~
1327
1328 Source code file will be *MyPackage_HSequenceOfPnt.cxx* or any other .cxx file (once in the whole project):
1329
1330 ~~~~~
1331 IMPLEMENT_HSEQUENCE (MyPackage_HSequenceOfPnt)
1332 ~~~~~
1333
1334 @subsubsection occt_fcug_3_3_3 Class architecture
1335
1336
1337 To understand the basic architecture of the classes instantiated from *NCollection* macros, please refer to the documentation on *TCollection* package, particularly to CDL files. Almost all API described there is preserved in *NCollection*. Changes are described in corresponding *NCollection_Define\*.hxx* files. 
1338
1339 Nevertheless the internal structure of NCollection classes is more complex than that of *TCollection* ones, providing more capabilities. The advanced layer of architecture is described in the next chapter Features.
1340
1341 There are two principal changes:
1342 * In *TCollection* some classes ( Stack, List, Set, Map, DataMap, DoubleMap ) define the Iterator type, the name of Iterator being like *MyPackage_DoubleMapIteratorOfDoubleMapOfIntegerReal*. In *NCollection* each Iterator is always defined as subtype of the collection *MyPackage_DoubleMapOfIntegerReal::Iterator*. 
1343 * Hashed collections (of type Map\* ) require in *TCollection* that the special class *Map\*Hasher* is defined. In *NCollection* it is only required that the global functions *IsEqual* and *HashCode* are defined. 
1344
1345 #### Interface to classes defined in CDL
1346
1347 The classes defined above can be used as types for fields, parameters of methods and return values in CDL definitions. In our example, if MyPackage is a CDL package, you will need to create the file *MyPackage_SequenceOfPnt.hxx* containing or including the above definitions, and then to add the line: imported *SequenceOfPnt* to file *MyPackage.cdl*;
1348
1349 Then the new collection type can be used in any CDL definition under the name *SequenceOfPnt* from *MyPackage*.
1350
1351 @subsubsection occt_fcug_3_3_4 New collection types
1352
1353 There are 4 collection types provided as template classes:
1354 * *NCollection_Vector*
1355 * *NCollection_UBTree*
1356 * *NCollection_SparseArray*
1357 * *NCollection_CellFilter*
1358
1359 #### Vector
1360
1361 This type is implemented internally as a list of arrays of the same size. Its properties:
1362 * Direct (constant-time) access to members like in Array1 type; data are allocated in compact blocks, this provides faster iteration.
1363 * Can grow without limits, like List, Stack or Queue types.
1364 * Once having the size LEN, it cannot be reduced to any size less than LEN – there is no operation of removal of items.
1365
1366 Insertion in a Vector-type class is made by two methods:
1367 * _SetValue(ind, theValue)_ – array-type insertion, where ind is the index of the inserted item, can be any non-negative number. If it is greater than or equal to Length(), then the vector is enlarged (its Length() grows).
1368 * _Append(theValue)_ – list-type insertion equivalent to _myVec.SetValue(myVec.Length(), theValue)_ – incrementing the size of the collection.
1369
1370 Other essential properties coming from List and Array1 type collections:
1371 * Like in *List*, the method *Clear()* destroys all contained objects and releases the allocated memory.
1372 * Like in *Array1*, the methods *Value()* and *ChangeValue()* return a contained object by index. Also, these methods have the form of overloaded operator ().
1373
1374 #### UBTree
1375
1376 The name of this type stands for “Unbalanced Binary Tree”. It stores the members in a binary tree of overlapped bounding objects (boxes or else).
1377 Once the tree of boxes of geometric objects is constructed, the algorithm is capable of fast geometric selection of objects. The tree can be easily updated by adding to it a new object with bounding box. 
1378 The time of adding to the tree of one object is O(log(N)), where N is the total number of objects, so the time of building a tree of N objects is O(N(log(N)). The search time of one object is O(log(N)). 
1379
1380 Defining various classes inheriting *NCollection_UBTree::Selector* we can perform various kinds of selection over the same b-tree object.  
1381
1382 The object may be of any type allowing copying. Among the best suitable solutions there can be a pointer to an object, handled object or integer index of object inside some collection. The bounding object may have any dimension and geometry. The minimal interface of *TheBndType* (besides public empty and copy constructor and operator =) used in UBTree algorithm as follows: 
1383
1384 ~~~~~
1385    class MyBndType
1386    {
1387     public:
1388      inline void                   Add (const MyBndType& other);
1389      // Updates me with other bounding type instance
1390
1391      inline Standard_Boolean       IsOut (const MyBndType& other) const;
1392      // Classifies other bounding type instance relatively me
1393
1394      inline Standard_Real          SquareExtent() const;
1395      // Computes the squared maximal linear extent of me (for a box it is the squared diagonal of the box).
1396    };
1397 ~~~~~
1398    
1399
1400 This interface is implemented in types of Bnd package: *Bnd_Box, Bnd_Box2d, Bnd_B2x, Bnd_B3x*.
1401
1402 To select objects you need to define a class derived from *UBTree::Selector* that should redefine the necessary virtual methods to maintain the selection condition. Usually this class instance is also used to retrieve selected objects after search.
1403 The class *UBTreeFiller* is used to randomly populate a *UBTree* instance. The quality of a tree is better (considering the speed of searches) if objects are added to it in a random order trying to avoid the addition of a chain of nearby objects one following another. 
1404 Instantiation of *UBTreeFiller* collects objects to be added, and then adds them at once to the given UBTree instance in a random order using the Fisher-Yates algorithm.
1405 Below is the sample code that creates an instance of *NCollection_UBTree* indexed by 2D boxes (Bnd_B2f), then a selection is performed returning the objects whose bounding boxes contain the given 2D point.
1406
1407 ~~~~~
1408 typedef NCollection_UBTree<MyData, Bnd_B2f> UBTree;
1409 typedef NCollection_List<MyData> ListOfSelected;
1410 //! Tree Selector type
1411 class MyTreeSelector : public UBTree::Selector
1412 {
1413 public:
1414   // This constructor initializes the selection criterion (e.g., a point)
1415
1416   MyTreeSelector (const gp_XY& thePnt) : myPnt(thePnt) {}
1417   // Get the list of selected objects
1418
1419   const ListOfSelected& ListAccepted () const
1420   { return myList; }
1421   // Bounding box rejection - definition of virtual method.  @return True if theBox is outside the selection criterion.
1422
1423   Standard_Boolean Reject  (const Bnd_B2f& theBox) const
1424   { return theBox.IsOut(myPnt); }
1425   // Redefined from the base class. Called when the bounding of theData conforms to the selection criterion. This method updates myList.
1426
1427   Standard_Boolean Accept  (const MyData& theData)
1428   { myList.Append(theData); }
1429   private:
1430   gp_XY          myPnt;
1431   ListOfSelected myList;
1432 };
1433 . . .
1434 // Create a UBTree instance and fill it with data, each data item having the corresponding 2D box.
1435
1436 UBTree aTree;
1437 NCollection_UBTreeFiller <MyData, Bnd_B2f> aTreeFiller(aTree);
1438 for(;;) {
1439   const MyData& aData = …;
1440   const Bnd_B2d& aBox = aData.GetBox();
1441   aTreeFiller.Add(aData, aBox);
1442 }
1443 aTreeFiller.Fill();
1444 . . .
1445 // Perform selection based on ‘aPoint2d’
1446 MyTreeSelector aSel(aPoint2d);
1447 aTree.Select(aSel);
1448 const ListOfSelected = aSel.ListAccepted();
1449 ~~~~~
1450
1451
1452 #### SparseArray
1453
1454
1455 This type has almost the same features as Vector but it allows to store items having scattered indices. In Vector, if you set an item with index 1000000, the container will allocate memory for all items with indices in the range 0-1000000. In SparseArray, only one small block of items will be reserved that contains the item with index 1000000.
1456
1457 This class can be also seen as equivalence of *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). 
1458
1459 This type has both interfaces of DataMap and Vector to access items.
1460
1461 #### CellFilter
1462
1463 This class 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. It can be considered as a functional alternative to UBTree, as in the best case it provides the direct access to an object like in an n-dimensional array, while search with UBTree provides logarithmic law access time.
1464
1465 @subsubsection occt_fcug_3_3_5 Features
1466
1467 NCollection defines some specific features, in addition to the public API inherited from TCollection classes. 
1468
1469 #### Iterators
1470
1471 Every collection defines its Iterator class capable of iterating the members in some predefined order. Every Iterator is defined as a subtype of the particular collection type (e.g., MyPackage_StackOfPnt::Iterator ). The order of iteration is defined by a particular collection type. The methods of Iterator are: 
1472
1473 * _void Init (const MyCollection&)_ - initializes the iterator on the collection object;
1474 * _Standard_Boolean More () const_ - makes a query if there is another non-iterated member;
1475 * _void Next ()_ - increments the iterator; 
1476 * _const ItemType& Value () const_ - returns the current member; 
1477 * _ItemType& ChangeValue () const_ - returns the mutable current member
1478
1479 ~~~~~
1480 typedef Ncollection_Sequence<gp_Pnt>
1481 MyPackage_SequenceOfPnt
1482 void Perform (const MyPackage_SequenceOfPnt& theSequence)
1483 {
1484         MyPackage_SequenceOfPnt::Iterator anIter (theSequence);
1485         for (; anIter.More(); anIter.Next()) {
1486                 const gp_Pnt aPnt& = anIter.Value();
1487 ....
1488         }
1489 }
1490 ~~~~~
1491
1492 This feature is present only for some classes in *TCollection (Stack, List, Set, Map, DataMap, DoubleMap)*. In *NCollection* it is generalized. 
1493
1494
1495 #### Class BaseCollection
1496
1497 There is a common abstract base class for all collections for a given item type (e.g., gp_Pnt). Developer X can arbitrarily name this base class like *MyPackage_BaseCollPnt* in the examples above. This name is further used in the declarations of any (non-abstract) collection class to designate the C++ inheritance. 
1498
1499 This base class has the following public API:
1500 * abstract class Iterator as the base class for all Iterators descried above; 
1501 * _Iterator& CreateIterator () const_ - creates and returns the Iterator on this collection;
1502 * _Standard_Integer Size () const_ - returns the number of items in this collection;
1503 * *void Assign (const NCollection_BaseCollection& theOther)* - copies the contents of the Other to this collection object; 
1504
1505 These members enable accessing any collection without knowing its exact type. In particular, it makes possible to implement methods receiving objects of the abstract collection type: 
1506
1507 ~~~~~
1508 #include <NColection_Map.hxx>
1509 typedef NCollection_Map<gp_Pnt> MyPackage_MapOfPnt;
1510 typedef NCollection_BaseCollection<gp_Pnt> MyPackage_BaseCollPnt;
1511 MyPackage_MapOfPnt aMapPnt;
1512 ....
1513 gp_Pnt aResult = COG (aMapPnt);
1514 ....
1515 gp_Pnt COG(const MyPackage_BaseCollPnt& theColl)
1516 {
1517   gp_XYZ aCentreOfGravity(0., 0., 0.);
1518 // create type-independent iterator (it is abstract type instance)
1519   MyPackage_BaseCollString::Iterator& anIter = theColl.CreateIterator();
1520   for (; anIter.More(); anIter.Next()) {
1521     aCentreOfGravity += anIter.Value().XYZ();
1522   }
1523   return aCentreOfGravity / theColl.Size();
1524 }
1525 ~~~~~
1526
1527 Note that there are fundamental differences between the shown type-independent iterator and the iterator belonging to a particular non-abstract collection:
1528 * Type-independent iterator can only be obtained via the call CreateIterator(); the typed iterator - only via the explicit construction. 
1529 * Type-independent iterator is an abstract class, so it is impossible to copy it or to assign it to another collection object; the typed iterators can be copied and reassigned using the method Init() . 
1530 * Type-independent iterator is actually destroyed when its collection object is destroyed; the typed iterator is destroyed as any other C++ object in the corresponding C++ scope. 
1531
1532 The common point between them is that it is possible to create any number of both types of iterators on the same collection object. 
1533
1534 #### Heterogeneous Assign
1535
1536 The semantics of the method *Assign()* has been changed in comparison to *TCollection*. In *NCollection* classes the method *Assign()* is virtual and it receives the object of the abstract *BaseCollection* class (see the previous section). Therefore this method can be used to assign any collection type to any other if only these collections are instantiated on the same *ItemType*. 
1537
1538 For example, conversion of *Map* into *Array1* is performed like this:
1539
1540 ~~~~~
1541 #include <NCollection_Map.hxx>
1542 #include <NCollection_Array1.hxx>
1543 typedef NCollection_Map<gp_Pnt> MyPackage_MapOfPnt;
1544 typedef NCollection_Array1<gp_Pnt> MyPackage_Array1OfPnt;
1545 ....
1546 MyPackage_MapOfPnt aMapPnt;
1547 ....
1548 MyPackage_Array1OfPnt anArr1Pnt (1, aMapPnt.Size());
1549 anArr1Pnt.Assign (aMapPnt); // heterogeneous assignment
1550 ~~~~~
1551
1552 There are some aspects to mention:
1553 * Unlike in *TCollection*, in *NCollection* the methods *Assign* and operator= do not coincide. The former is a virtual method defined in the *BaseCollection* class. The latter is always defined in instance classes as a non-virtual inline method and it corresponds exactly to the method *Assign* in *TCollection* classes. Therefore it is always profitable to use operator= instead of *Assign* wherever the types on both sides of assignment are known. 
1554 * If the method *Assign* copies to *Array1* or *Array2* structure, it first checks if the size of the array is equal to the number of items in the copied collection object. If the sizes differ, an exception is thrown, as in *TCollection_Array1.gxx*. 
1555 * Copying to *Map, IndexedMap, DataMap* and *IndexedDataMap* can bring about a loss of data: when two or more copied data items have the same key value, only one item is copied and the others are discarded. It can lead to an error in the code like the following:
1556
1557 ~~~~~
1558 MyPackage_Array1OfPnt anArr1Pnt (1, 100); 
1559 MyPackage_MapOfPnt aMapPnt;
1560 ....
1561 aMapPnt.Assign(anArr1Pnt);
1562 anArr1Pnt.Assign(aMapPnt);
1563 ~~~~~
1564
1565 Objects of classes parameterised with two types (*DoubleMap, DataMap* and  *IndexedDataMap*) cannot be assigned. Their method *Assign* throws the exception *Standard_TypeMismatch* (because it is impossible to check if the passed *BaseCollection* parameter belongs to the same collection type).
1566
1567 #### Allocator
1568
1569 All constructors of *NCollection* classes receive the *Allocator* Object as the last parameter. This is an object of a type managed by Handle, inheriting *NCollection_BaseAllocator*, with the following (mandatory) methods redefined:
1570
1571 ~~~~~
1572 Standard_EXPORT virtual void* Allocate (const size_t size); 
1573 Standard_EXPORT virtual void Free (void * anAddress);
1574 ~~~~~
1575
1576 It is used internally every time when the collection allocates memory for its item(s) and releases this memory. The default value of this parameter (empty *Handle*) designates the use of *NCollection_BaseAllocator* X where the functions *Standard::Allocate* and *Standard::Free* are called. Therefore if the user of *NCollection* does not specify any allocator as a parameter to the constructor of his collection, the memory management will be identical to the one in *TCollection* and other Open CASCADE Technology classes.
1577
1578 Nevertheless, the it is possible to define a custom *Allocator* type to manage the memory in the most optimal or convenient way for his algorithms.
1579
1580 As one possible choice, the class *NCollection_IncAllocator* is included. Unlike *BaseAllocator*, it owns all memory it allocates from the system. Memory is allocated in big blocks (about 20kB) and the allocator keeps track of the amount of occupied memory. The method *Allocate* just increments the pointer to non-occupied memory and returns its previous value. Memory is only released in the destructor of *IncAllocator*, the method *Free* is empty. If used efficiently, this Allocator can greatly improve the performance of OCCT collections.
1581
1582
1583
1584 @subsection occt_fcug_3_4 Strings
1585
1586 The **Strings** component provides services to manipulate  character strings.  
1587 **Strings** are classes that handle dynamically sized  sequences of characters based on both ASCII (normal 8-bit character type) and  Unicode (16-bit character type). They provide editing operations with built-in  memory management which make the relative objects easier to use than ordinary  character arrays. 
1588 *Strings* may also be manipulated by *handle*, and  therefore shared. 
1589
1590 @subsubsection occt_fcug_3_4_1 Examples
1591
1592 #### TCollection_AsciiString
1593
1594 A variable-length sequence of ASCII characters (normal 8-bit  character type). It provides editing operations with built-in memory management  to make *AsciiString* objects easier to use than ordinary character  arrays. 
1595 *AsciiString* objects follow value  semantics;, that is, they are the actual strings, not handles to strings,  and are copied through assignment. You may use *HAsciiString* objects to  get handles to strings. 
1596
1597 #### TCollection_ExtendedString
1598
1599 A variable-length sequence of "extended" (UNICODE)  characters (16-bit character type). It provides editing operations with  built-in memory management to make *ExtendedString* objects easier to use  than ordinary extended character arrays. 
1600
1601 *ExtendedString* objects follow value  semantics;, that is, they are the actual strings, not handles to strings,  and are copied through assignment. You may use *HExtendedString* objects  to get handles to strings. 
1602
1603 #### TCollection_HAsciiString
1604
1605 A variable-length sequence of ASCII characters (normal 8-bit  character type). It provides editing operations with built-in memory management  to make *HAsciiString* objects easier to use than ordinary character  arrays. 
1606 *HAsciiString* objects are *handles* to strings. 
1607   * *HAsciiString* strings may be shared by several objects.
1608   * You may use an *AsciiString* object to get the actual  string.
1609 *HAsciiString* objects use an *AsciiString* string  as a field. 
1610
1611 #### TCollection_HExtendedString
1612
1613 A variable-length sequence of extended; (UNICODE)  characters (16-bit character type). It provides editing operations with  built-in memory management to make *ExtendedString* objects easier to use  than ordinary extended character arrays. 
1614 *HExtendedString* objects are *handles* to  strings. 
1615   * *HExtendedString* strings may be shared by several objects.
1616   * You may use an *ExtendedString* object to get the actual  string.
1617 *HExtendedString* objects use an *ExtendedString* string  as a field. 
1618
1619 @subsubsection occt_fcug_3_4_2 Conversion
1620
1621 *Resource_Unicode* provides functions to convert a non-ASCII *C string* given  in ANSI, EUC, GB or SJIS format, to a Unicode string of extended characters, and vice  versa. 
1622
1623 @subsection occt_fcug_3_5 Unit Conversion
1624
1625 The *UnitsAPI* global functions are used to convert a  value from any unit into another unit. Conversion is executed among three unit  systems: 
1626   * the **SI System**,
1627   * the user’s **Local System**,
1628   * the user’s **Current System**.
1629 The **SI System** is the standard international unit  system. It is indicated by *SI* in the signatures of the *UnitsAPI* functions. 
1630
1631 The OCCT (former MDTV) System corresponds to the SI  international standard but the length unit and all its derivatives use the millimeter instead of the meter.  
1632
1633 Both systems are proposed by Open CASCADE Technology; the SI  System is the standard option. By selecting one of these two systems, you  define your **Local System** through the *SetLocalSystem* function. The  **Local System** is indicated by *LS* in the signatures of the *UnitsAPI* functions. 
1634 The Local System units can be modified in the working  environment. You define your **Current System** by modifying its units  through the *SetCurrentUnit* function. The Current System is indicated by *Current* in the signatures of the *UnitsAPI* functions. 
1635 A physical quantity is defined by a string (example:  LENGTH). 
1636
1637
1638 @section occt_occt_fcug_4 Math Primitives and Algorithms
1639 @subsection occt_occt_fcug_4_1 Overview
1640 Math primitives and algorithms available in Open CASCADE  Technology include: 
1641   * Vectors and matrices
1642   * Geometric primitives
1643   * Math algorithms
1644   
1645 @subsection occt_occt_fcug_4_2 Vectors and Matrices
1646 The Vectors and Matrices component provides a C++  implementation of the fundamental types Matrix and Vector, currently used to  define more complex data structures. The Vector and Matrix classes support  vectors and matrices of real values with standard operations such as addition,  multiplication, transposition, inversion etc. 
1647 Vectors and matrices have arbitrary ranges which must be  defined at declaration time and cannot be changed after declaration. 
1648
1649 ~~~~~
1650 math_Vector  v(1, 3); 
1651 //  a vector of dimension 3 with range (1..3) 
1652 math_Matrix  m(0, 2, 0, 2); 
1653 //  a matrix of dimension 3x3 with range (0..2, 0..2) 
1654 math_Vector  v(N1, N2); 
1655 //  a vector of dimension N2-N1+1 with range (N1..N2)
1656 ~~~~~
1657
1658 Vector and Matrix objects use value semantics. In other  words, they cannot be shared and are copied through assignment. 
1659
1660 ~~~~~
1661 math_Vector  v1(1, 3), v2(0, 2); 
1662 v2  = v1; 
1663 //  v1 is copied into v2. a modification of v1 does not affect  v2 
1664 ~~~~~
1665
1666 Vector and Matrix values may be initialized and obtained  using indexes which must lie within the range definition of the vector or the  matrix. 
1667
1668 ~~~~~
1669 math_Vector v(1, 3);
1670 math_Matrix m(1, 3, 1, 3);
1671 Standard_Real value;
1672
1673 v(2) = 1.0;
1674 value = v(1);
1675 m(1, 3) = 1.0;
1676 value = m(2, 2);
1677 ~~~~~
1678
1679 Some operations on Vector and Matrix objects may not be  legal. In this case an exception is raised. Two standard exceptions are used: 
1680   * *Standard_DimensionError* exception is raised when two matrices or  vectors involved in an operation are of incompatible dimensions.
1681   * *Standard_RangeError* exception is raised if an access outside the  range definition of a vector or of a matrix is attempted.
1682   
1683 ~~~~~~
1684 math_Vector v1(1, 3), v2(1, 2), v3(0, 2);
1685 v1 = v2;
1686 // error: Standard_DimensionError is raised
1687
1688 v1 = v3;
1689 // OK: ranges are not equal but dimensions are
1690 // compatible
1691
1692 v1(0) = 2.0;
1693 // error: Standard_RangeError is raised
1694 ~~~~~~
1695
1696 @subsection occt_occt_fcug_4_3 Primitive Geometric Types
1697 Before creating a geometric object, you must decide whether  you are in a 2d or in a 3d context and how you want to handle the object. 
1698 The *gp* package offers classes for both 2d and 3d  objects which are handled by value rather than by reference. When this sort of  object is copied, it is copied entirely. Changes in one instance will not be  reflected in another. 
1699 The *gp* package defines the basic non-persistent  geometric entities used for algebraic calculation and basic analytical geometry  in 2d & 3d space. It also provides basic transformations such as identity,  rotation, translation, mirroring, scale transformations, combinations of  transformations, etc. Entities are handled by value.  
1700 The available geometric entities are: 
1701   * 2d & 3d Cartesian coordinates (x, y, z)
1702   * Matrices
1703   * Cartesian points
1704   * Vector
1705   * Direction
1706   * Axis
1707   * Line
1708   * Circle
1709   * Ellipse
1710   * Hyperbola
1711   * Parabola
1712   * Plane
1713   * Infinite cylindrical surface
1714   * Spherical surface
1715   * Toroidal surface
1716   * Conical surface.
1717   
1718 @subsection occt_occt_fcug_4_4 Collections of Primitive Geometric Types
1719
1720 Before creating a geometric object, you must decide whether  you are in a 2d or in a 3d context and how you want to handle the object. 
1721 If you do not need a single instance of a geometric  primitive but a set of them then the package which deals with collections of  this sort of object, *TColgp*, will provide the necessary functionality. 
1722 In particular, this package provides standard and frequently  used instantiations of generic classes with geometric objects, i.e. *XY*, *XYZ*,  *Pnt*, *Pnt2d*, *Vec*, *Vec2d*, *Lin*, *Lin2d*, *Circ*,  *Circ2d.* 
1723 These are non-persistent classes. 
1724
1725 @subsection occt_occt_fcug_4_5 Basic Geometric Libraries
1726 There are various library packages available which offer a  range of basic computations on curves and surfaces. 
1727 If you are dealing with objects created from the *gp* package,  the useful algorithms are in the elementary curves and surfaces libraries - the  *ElCLib* and *ElSLib* packages.
1728 * *EICLib* provides methods for analytic curves. This is a library of simple  computations on curves from the *gp* package (Lines, Circles and Conics).  It is possible to compute points with a given parameter or to compute the parameter for a point. 
1729 * *EISLib* provides methods for analytic surfaces. This is a library of simple  computations on surfaces from the package *gp* (Planes, Cylinders,  Spheres, Cones, Tori). It is possible to compute points with a given pair of parameters or to compute the parameter for a point. There is a library for calculating normals  on curves and surfaces. 
1730
1731 Additionally, *Bnd* package provides a set of classes and tools to operate  with bounding boxes of geometric objects in 2d and 3d space. 
1732
1733 @subsection occt_occt_fcug_4_6 Common Math Algorithms
1734 The common math algorithms library provides a C++  implementation of the most frequently used mathematical algorithms. These  include: 
1735   * Algorithms to solve a set of linear algebraic equations,
1736   * Algorithms to find the minimum of a function of one or more  independent variables,
1737   * Algorithms to find roots of one, or of a set, of non-linear  equations,
1738   * An algorithm to find the eigenvalues and eigenvectors of a square  matrix.
1739   
1740 All mathematical algorithms are implemented using the same  principles. They contain: 
1741 A constructor performing all, or most of, the calculation,  given the appropriate arguments. All relevant information is stored inside the  resulting object, so that all subsequent calculations or interrogations will be  solved in the most efficient way. 
1742
1743 A function *IsDone* returning the boolean true if the  calculation was successful. 
1744 A set of functions, specific to each algorithm, enabling all  the various results to be obtained. 
1745 Calling these functions is legal only if the function *IsDone*  answers **true**, otherwise the exception *StdFail_NotDone* is raised. 
1746
1747 The example below demonstrates the use of the Gauss class,  which implements the Gauss solution for a set of linear equations.The following  definition is an extract from the header file of the class *math_Gauss*: 
1748
1749 ~~~~~~
1750 class Gauss {
1751 public:
1752   Gauss (const math_Matrix& A);
1753   Standard_Boolean IsDone() const;
1754   void Solve (const math_Vector& B,
1755   math_Vector& X) const;
1756 };
1757 ~~~~~~
1758
1759 Now the main program uses the Gauss class to solve the  equations a*x1=b1 and a*x2=b2: 
1760
1761 ~~~~~
1762 #include <math_Vector.hxx> 
1763 #include <math_Matrix.hxx>
1764 main ()
1765 {
1766   math_Vector a(1, 3, 1, 3);
1767   math_Vector b1(1, 3), b2(1, 3);
1768   math_Vector x1(1, 3), x2(1, 3);
1769   // a, b1 and b2 are set here to the appropriate values
1770   math_Gauss sol(a);              // computation of the
1771   // LU decomposition of A
1772   if(sol.IsDone()) {              // is it OK ?
1773     sol.Solve(b1, x1);      // yes, so compute x1
1774     sol.Solve(b2, x2);      // then x2
1775     ...
1776   } 
1777   else {                    // it is not OK:
1778     // fix up
1779     sol.Solve(b1, x1);            // error:
1780     // StdFail_NotDone is raised
1781   }
1782 }
1783 ~~~~~
1784
1785 The next example demonstrates the use of the *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. The definition is an extract from the header file of the class *math_BissecNewton*: 
1786
1787 ~~~~~
1788 class  BissecNewton { 
1789         public: 
1790                 BissecNewton  (math_FunctionWithDerivative& f, 
1791                         const Standard_Real bound1, 
1792                         const Standard_Real bound2, 
1793                         const Standard_Real tolx); 
1794         Standard_Boolean IsDone() const; 
1795         Standard_Real Root(); 
1796 }; 
1797 ~~~~~
1798
1799 The abstract class  *math_FunctionWithDerivative* describes the services which have to be implemented  for the function f which is to be used by a *BissecNewton* algorithm. The  following definition corresponds to the header file of the abstract class  *math_FunctionWithDerivative*: 
1800
1801 ~~~~~
1802 class  math_FunctionWithDerivative { 
1803         public: 
1804                 virtual Standard_Boolean Value 
1805                         (const Standard_Real x, Standard_Real&  f) = 0; 
1806                 virtual Standard_Boolean Derivative 
1807                         (const Standard_Real x, Standard_Real&  d) = 0; 
1808                 virtual Standard_Boolean Values 
1809                         (const Standard_Real x, 
1810                         Standard_Real& f, 
1811                         Standard_Real& d) = 0; 
1812 }; 
1813 ~~~~~
1814
1815 Now the test sample uses the *BissecNewton* class to find the  root of the equation *f(x)=x**2-4* in the interval [1.5, 2.5]: the function to  solve is implemented in the class *myFunction* which inherits from the class *math_FunctionWithDerivative*, then the main program finds the required root. 
1816
1817 ~~~~~
1818 #include <math_BissecNewton.hxx> 
1819 #include <math_FunctionWithDerivative.hxx>
1820 class myFunction : public math_FunctionWithDerivative 
1821 {
1822   Standard_Real coefa, coefb, coefc;
1823
1824   public:
1825     myFunction (const  Standard_Real a, const Standard_Real b,
1826                 const Standard_Real c) :
1827       coefa(a), coefb(b), coefc(c)
1828     {}
1829
1830     virtual  Standard_Boolean Value (const Standard_Real x, 
1831                                     Standard_Real& f)
1832     {
1833       f = coefa * x * x + coefb * x + coefc;
1834     }
1835
1836     virtual  Standard_Boolean Derivative (const Standard_Real x,
1837                                          Standard_Real&  d)
1838     {
1839       d = coefa * x * 2.0 + coefb;
1840     }
1841
1842     virtual  Standard_Boolean Values (const Standard_Real x,
1843                                      Standard_Real& f, Standard_Real& d)
1844     {
1845       f = coefa * x * x + coefb * x + coefc;
1846       d = coefa * x *  2.0 + coefb;
1847     }
1848 };
1849
1850 main()
1851 {
1852   myFunction f(1.0, 0.0, 4.0);
1853   math_BissecNewton sol(F, 1.5, 2.5, 0.000001);
1854   if(Sol.IsDone()) { // is it OK ?
1855     Standard_Real x = sol.Root(); // yes.
1856   }
1857   else { // no
1858   }
1859 ~~~~~
1860
1861 @subsection occt_occt_fcug_4_7 Precision
1862
1863 On the OCCT platform, each object stored in the database  should carry its own precision value. This is important when dealing with  systems where objects are imported from other systems as well as with various  associated precision values. 
1864
1865 The *Precision* package addresses the daily problem of  the geometric algorithm developer: what precision setting to use to compare two  numbers. Real number equivalence is clearly a poor choice. The difference  between the numbers should be compared to a given precision setting. 
1866
1867 Do not write _if  (X1 == X2),_  instead write _if  (Abs(X1-X2) < Precision)._ 
1868
1869 Also, to order real numbers, keep in mind that _if  (X1 < X2 - Precision)_ is incorrect. 
1870 _if  (X2 - X1 > Precision)_ is far better when *X1* and *X2* are high numbers. 
1871
1872 This package proposes a set of methods providing precision  settings for the most commonly encountered situations. 
1873
1874 In Open CASCADE Technology, precision is usually not  implicit; low-level geometric algorithms accept precision settings as  arguments. Usually these should not refer directly to this package. 
1875
1876 High-level modeling algorithms have to provide a precision  setting to the low level geometric algorithms they call. One way is to use the  settings provided by this package. The high-level modeling algorithms can also  have their own strategy for managing precision. As an example the Topology Data  Structure stores precision values which are later used by algorithms. When a  new topology is created, it takes the stored value. 
1877 Different precision settings offered by this package cover  the most common needs of geometric algorithms such as *Intersection* and *Approximation*. 
1878 The choice of a precision value depends both on the algorithm  and on the geometric space. The geometric space may be either: 
1879   * a real space, 3d or 2d where the lengths are measured  in meters, micron, inches, etc.
1880   * a parametric space, 1d on a curve or 2d on a surface  where numbers have no dimension.
1881 The choice of precision value for parametric space depends  not only on the accuracy of the machine, but also on the dimensions of the  curve or the surface. 
1882 This is because it is desirable to link parametric precision  and real precision. If you are on a curve defined by the equation *P(t)*,  you would want to have equivalence between the following: 
1883
1884 ~~~~~
1885 Abs(t1-t2)  < ParametricPrecision 
1886 Distance  (P(t1),P(t2)) < RealPrecision. 
1887 ~~~~~
1888
1889 @subsubsection occt_occt_fcug_4_7_1 The Precision package
1890 The *Precision* package offers a number of package methods and  default precisions for use in dealing with angles, distances, intersections,  approximations, and parametric space. 
1891 It provides values to use in comparisons to test for real  number equalities. 
1892   * Angular precision compares angles.
1893   * Confusion precision compares distances.
1894   * Intersection precision is used by intersection algorithms.
1895   * Approximation precision is used by approximation algorithms.
1896   * Parametric precision gets a parametric space precision from a 3D  precision.
1897   * *Infinite* returns a high number that can be considered to  be infinite. Use <i>-Infinite</i> for a high negative number. 
1898   
1899 @subsubsection occt_occt_fcug_4_7_2 Standard Precision values
1900 This package provides a set of real space precision values  for algorithms. The real space precisions are designed for precision to *0.1*  nanometers. The only unit available is the millimeter. 
1901 The parametric precisions are derived from the real  precisions by the *Parametric* function. This applies a scaling factor which  is the length of a tangent to the curve or the surface. You, the user, provide  this length. There is a default value for a curve with <i>[0,1]</i> parameter  space and a length less than 100 meters. 
1902 The geometric packages provide Parametric precisions for the  different types of curves. 
1903 The *Precision* package provides methods to test whether a  real number can be considered to be infinite. 
1904
1905 #### Precision::Angular
1906
1907 This method is used to compare two angles. Its current value is *Epsilon(2 *  PI)* i.e. the smallest number *x* such that *2*PI + x* is  different of *2\*PI*. 
1908
1909 It can be used to check confusion  of two angles as follows:
1910 _Abs(Angle1  - Angle2) < Precision::Angular()_ 
1911
1912 It is also possible to check parallelism  of two vectors (_Vec_ from _gp_) as follows _V1.IsParallel(V2,Precision::Angular())_ 
1913
1914 Note that *Precision::Angular()* can be used on both  dot and cross products because for small angles the *Sine* and the *Angle* are equivalent. So to test if two directions of type *gp_Dir* are  perpendicular, it is legal to use the following code: 
1915 _Abs(D1 * D2) < Precision::Angular()_ 
1916
1917 #### Precision::Confusion
1918
1919 This method is used to test 3D distances. The current value is *1.e-7*, in other words, 1/10 micron if the unit used is the millimeter. 
1920
1921 It can be used to check confusion  of two points (_Pnt_ from _gp_) as follows: 
1922 _P1.IsEqual(P2,Precision::Confusion())_ 
1923
1924 It is also possible to find a  vector of null length (_Vec_ from _gp_) :
1925 _V.Magnitude() <  Precision::Confusion()_ 
1926
1927 #### Precision::Intersection
1928
1929 This is reasonable precision to pass to an Intersection process as  a limit of refinement of Intersection Points. *Intersection* is high  enough for the process to converge quickly. *Intersection* is lower than *Confusion* so that you still get a point on the intersected geometries. The current  value is *Confusion() / 100*. 
1930
1931 #### Precision::Approximation
1932
1933 This is a reasonable precision to pass to an approximation process  as a limit of refinement of fitting. The approximation is greater than the other  precisions because it is designed to be used when the time is at a premium. It has  been provided as a reasonable compromise by the designers of the Approximation  algorithm. The current value is *Confusion() * 10*. 
1934 Note that Approximation is greater than Confusion, so care  must be taken when using Confusion in an approximation process. 
1935
1936 @section occt_fcug_5 Data Storage
1937 @subsection occt_fcug_5_1 Saving and Opening Files
1938
1939 @image html /user_guides/foundation_classes/images/foundation_classes_image007.png "Example of Saving-Opening workflow"
1940 @image latex /user_guides/foundation_classes/images/foundation_classes_image007.png "Example of Saving-Opening workflow"
1941    
1942 In the example, the roots of the transferable transient objects *TopoDS_Shape, Geom_Geometry* and *Geom2d_Geometry* are used in algorithms, they contain data and temporary results. 
1943 The associated objects in the persistent domain are *PTopoDS_HShape, PGeom_Geometry* and *PGeom2d_Geometry*. They contain a real data  structure which is stored in a file. 
1944 Note that when an object is stored, if it contains another  stored object, the references to the contained object are also managed. 
1945 @image html /user_guides/foundation_classes/images/foundation_classes_image008.png "Saving-Opening mechanism"
1946 @image latex /user_guides/foundation_classes/images/foundation_classes_image008.png "Saving-Opening mechanism"
1947
1948
1949 @subsection occt_fcug_5_2 Basic Storage Procedures
1950
1951 @subsubsection occt_fcug_5_2_1 Saving
1952
1953 The storage procedure of a transient object follows five  main steps. 
1954 1. Create  an I/O driver for files. For example, *FSD_File f()*; 
1955 2. Instance the data schema, which will process your persistent information. The schema is  used for read/write operations. If ShapeSchema is the name of your schema: 
1956 ~~~~~
1957 Handle(ShapeSchema) s = new ShapeSchema; 
1958 ~~~~~
1959 3. Create a persistent shape from a transient shape. 
1960 ~~~~~
1961 TopoDS_Shape  aShape; 
1962 PTColStd_TransientPersistentMap  aMap; 
1963 Handle(PTopoDS_HShape)  aPShape = MgtBRep::Translate 
1964   (aShape, aMap, MgtBRep_WithoutTriangle); 
1965 ~~~~~
1966 4. Create  a new container and fill it using the *AddRoot()* method. 
1967 ~~~~~
1968 Handle(Storage_Data)  d = new Storage_Data; 
1969 d  -> AddRoot (“ObjectName”, aPShape); 
1970 ~~~~~
1971 You may add as  many objects as you want in this container. 
1972 5. Save  to the archive. 
1973 ~~~~~
1974 s -> Write (f,d); 
1975 ~~~~~
1976
1977 @subsubsection occt_fcug_5_2_2 Opening
1978 The retrieval mechanism is the opposite of the storage  mechanism. The procedure for retrieving an object is as follows:
1979  
1980 1. Create  an I/O driver and instance a data schema (if not done). 
1981 2. Read  the persistent object from the archive and get the list of objects using *Roots()* method. 
1982 ~~~~~
1983 Handle(Storage_Data)  d = s -> Read(f); 
1984 Handle(Storage_HSeqOfRoot)  roots = d-> Roots(); 
1985 ~~~~~
1986 3. Loop  on root objects to get *Standard_Persistent* objects (the following sequence only  gets the first root). 
1987 ~~~~~
1988 Handle(Standard_Persistent)  p; 
1989 Handle(Standard_Root)  r; 
1990 if(roots  -> Length() >= 1) { 
1991    r = roots -> Value(1); 
1992    p = r -> Object(); 
1993
1994 ~~~~~
1995 4. DownCast  the persistent object to a *PTopoDS_Hshape*. 
1996 ~~~~~
1997 Handle(PTopoDS_HShape) aPShape; 
1998 aPShape =  Handle(PTopoDS_HShape)::DownCast(p); 
1999 ~~~~~
2000 5. Create  the *TopoDS_Shape*. 
2001 ~~~~~
2002 TopoDS_Shape aShape; 
2003 PTColStd_PersistentTransientMap aMap;    
2004 MgtBRep::Translate (aPShape, aMap,  aShape, MgtBRep_WithoutTriangle); 
2005 ~~~~~
2006
2007
2008