0027231: Obsolete OCCT features still mentioned in the documentation
[occt.git] / dox / user_guides / ocaf / ocaf.md
1 OCAF  {#occt_user_guides__ocaf}
2 ========================
3
4 @tableofcontents
5
6 @section occt_ocaf_1 Introduction
7
8 This manual explains how to use the Open CASCADE Application Framework (OCAF).
9 It provides basic documentation on using OCAF. For advanced information on OCAF 
10 and its applications, see our <a href="http://www.opencascade.com/content/tutorial-learning">E-learning & Training</a> offerings.
11
12 @subsection occt_ocaf_1_1 Purpose of OCAF
13
14 OCAF (the Open CASCADE Application Framework) is an  easy-to-use platform for rapidly developing
15   sophisticated domain-specific  design applications. 
16   A typical application developed using OCAF deals with two or three-dimensional (2D or 3D) geometric modeling 
17   in trade-specific Computer Aided Design (CAD) systems, manufacturing or analysis applications, 
18   simulation  applications or illustration tools. 
19   
20   Developing a design application requires addressing many technical aspects. 
21   In particular, given the functional specification of your application, you must at least:  
22   
23   * Design the  architecture of the application— definition of the software components and the way they cooperate;
24   * Define the  data model able to support the functionality required — a design application  operates on data maintained during the whole end-user working session;
25   * Structure  the software in order to:
26     * synchronize the display with the  data — commands modifying objects must update the views;  
27     * support generalized undo-redo  commands — this feature has to be taken into account very early in the design  process;  
28   * Implement  the function for saving the data — if the application has a long life cycle,  the compatibility of data between versions of the application has to be  addressed;
29   * Build the  application user interface.
30  
31 Architectural guidance and ready-to-use solutions provided by OCAF offer you the following benefits:
32   * You can concentrate on the functionality specific for your application;  
33   * The underlying mechanisms required to support the application are already provided; 
34   * The application can be rapidly be prototyped thanks to the coupling the other Open CASCADE Technology modules;
35   * The final application can be developed by industrializing the prototype — you don't need to restart the development from scratch. 
36   * The Open Source nature of the platform guarantees the long-term usefulness of your development.   
37
38 OCAF is much more than just one toolkit among many in the CAS.CADE Object Libraries. Since it can handle any data and algorithms in these libraries -- be it modeling algorithms, topology or geometry -- OCAF is their logical supplement. 
39
40 The table below contrasts the design of a modeling application using object libraries alone and using OCAF. 
41
42 **Table 1: Services provided by OCAF** 
43
44 |Development tasks      |Comments | Without OCAF        | With OCAF |
45 |------------------:|---------:|---------------:|-----------:|
46 |Creation of geometry| Algorithm Calling the modeling libraries |       To be created by the user       | To be created by the user| 
47 | Data organization | Including specific attributes and modeling process | To be created by the user |  Simplified| 
48 | Saving data in a file | Notion of document | To be created by the user | Provided |
49 | Document-view management |    |  To be created by the user | Provided |
50 | Application infrastructure | New, Open, Close, Save and Save As File menus | To be created by the user | Provided | 
51 | Undo-Redo | Robust, multi-level       | To be created by the user     | Provided |
52 | Application-specific dialog boxes     |    | To be created by the user  |     To be created by the user |
53
54 OCAF uses other modules of Open CASCADE Technology — the Shape  is implemented with the geometry supported by the <a href="#user_guides__modeling_data">Modeling Data</a> module and the viewer is the one provided with the <a href="#user_guides__visualization">Visualization</a> module. Modeling functions can be implemented using the <a href="#user_guides__modeling_algos">Modeling Algorithms</a> module.
55
56 The relationship between OCAF and the Open CASCADE Technology (**OCCT**) Object Libraries can be seen in the image below. 
57
58 @figure{/user_guides/ocaf/images/ocaf_image003.svg, "OCCT Architecture"}
59
60 In the image, the OCAF (Open CASCADE Application Framework) is shown with black rectangles and OCCT Object Libraries required by OCAF are shown with white rectangles. 
61  
62 The subsequent chapters of this document explain the concepts and show how to use the services of OCAF.
63
64 @subsection occt_ocaf_1_2 Architecture Overview
65
66 OCAF provides you with an object-oriented Application-Document-Attribute model consisting of C++ class libraries. 
67
68 @image html ocaf_wp_image003.png "The Application-Document-Attribute model"
69 @image latex ocaf_wp_image003.png "The Application-Document-Attribute model"
70
71 @subsubsection occt_ocaf_1_2_1 Application
72
73 The *Application* is an abstract class in charge of handling documents during the working session, namely:  
74   * Creating new  documents;
75   * Saving documents and opening them;
76   * Initializing document views.
77   
78 @subsubsection occt_ocaf_1_2_2 Document   
79  
80   The document, implemented by the concrete class  *Document*, is the container for the application data. Documents offer access to the data framework and serve the following purposes: 
81
82   * Manage the notification of changes
83   * Update external links
84   * Manage the saving and restoring of data
85   * Store the names of software extensions.
86   * Manage command transactions
87   * Manage Undo and Redo options. 
88   
89   Each  document is saved in a single flat ASCII file defined by its format and  extension (a ready-to-use format is provided with  OCAF).  
90
91   Apart from their role as a container of application data, documents can refer to each other; Document A, for example, can refer to a specific label in Document B. This functionality is made possible by means of the reference key.   
92   
93 @subsubsection occt_ocaf_1_2_3 Attribute
94
95   Application data is described by **Attributes**, which are instances of  classes derived from the *Attribute* abstract class, organized according to the OCAF Data  Framework. 
96   
97   The @ref occt_ocaf_3 "OCAF Data Framework" references aggregations of attributes using  persistent identifiers in a single hierarchy. A wide range of  attributes come with OCAF, including:    
98   
99   * @ref occt_ocaf_6 "Standard attributes" allow operating with simple common data in the data framework (for example: integer, real, string, array kinds of data), realize auxiliary functions (for example: tag sources attribute for the children of the label counter), create dependencies (for example: reference, tree node)....;
100   * @ref occt_ocaf_5 "Shape attributes" contain the geometry of the whole model or its elements including reference to the shapes and tracking of shape evolution;
101   * Other  geometric attributes such as **Datums** (points, axis and plane) and **Constraints** (*tangent-to, at-a-given-distance, from-a-given-angle, concentric,* etc.)
102   * User  attributes, that is, attributes typed by the application  
103   * @ref occt_ocaf_7 "Visualization attributes" allow placing viewer information to the data framework, visual representation of objects and other auxiliary visual information, which is needed for graphical data representation.
104   * @ref occt_ocaf_8 "Function services" — the purpose of these attributes is to rebuild  objects after they have been modified (parameterization of models). While the document manages the notification of changes, a function manages propagation of these changes. The function mechanism provides links between functions and calls to various algorithms. 
105   
106 In addition,  application-specific data can be added by defining new attribute classes; naturally, this changes the standard file format. The only functions that have to be implemented are:
107     * Copying the  attribute
108     * Converting  it from and persistent data storage
109         
110 @subsection occt_ocaf_1_3  Reference-key model
111
112   In most existing geometric modeling systems, the data are topology driven. 
113   They usually use a boundary representation (BRep), where geometric models 
114   are defined by a collection of faces, edges and vertices, 
115   to which application data are attached. Examples of data include:  
116  
117   * a color;
118   * a material;
119   * information that a particular edge is blended.
120  
121   When the geometric model is parameterized, that is, when you can change 
122   the value of parameters used to build the model (the radius of a  blend, the thickness of a rib, etc.), 
123   the geometry is highly subject to change. 
124   In order to maintain the attachment of application data, the geometry must be  distinguished from other data.  
125    
126   In OCAF, the data are reference-key driven. It is a  uniform model in which reference-keys 
127   are the persistent identification of  data. All **accessible** data, including the geometry, 
128   are implemented as attributes attached to reference-keys. 
129   The geometry becomes the  value of the Shape attribute, just as a number is the value 
130   of the Integer and  Real attributes and a string that of the Name attribute.  
131    
132   On a single reference-key, many attributes can be  aggregated; 
133   the application can ask at runtime which attributes are available. 
134   For example, to associate a texture to a face in a geometric model, 
135   both the face and the texture are attached to the same reference-key.  
136  
137 @image html ocaf_image004.png "Topology driven versus reference-key driven approaches" 
138 @image latex ocaf_image004.png "Topology driven versus reference-key driven approaches" 
139
140  Reference-keys can be created in two ways:   
141  
142   * At  programming time, by the application
143   * At runtime,  by the end-user of the application (providing that you include this capability  in the application)
144  
145   As an application developer, you generate reference-keys in order to give semantics to the data. 
146   For example, a function building a  prism may create three reference-keys: 
147   one for the base of the prism, a second  for the lateral faces and a third for the top face. 
148   This makes up a semantic  built-in the application's prism feature.
149   On the other hand, in a command  allowing the end-user to set a texture to a face he/she selects, 
150   you must create  a reference-key to the selected face 
151   if it has not previously been referenced in any feature 
152   (as in the case of one of the lateral faces of the prism).  
153  
154   When you create a reference-key to selected topological  elements (faces, edges or vertices), 
155   OCAF attaches to the reference-key  information defining the selected topology — the Naming attribute. 
156   For example,  it may be the faces to which a selected edge is common to. 
157   This information, as  well as information about the evolution of the topology at each modeling step 
158   (the modified, updated and deleted faces), is used by the naming algorithm to  maintain the topology 
159   attached to the reference-key. As such, on a  parametrized model, 
160   after modifying the value of a parameter, the reference-keys still address the appropriate faces, 
161   even if their geometry has  changed. 
162   Consequently, you change the size of the cube shown in the figure above, 
163   the user texture stay attached to the right face.  
164  
165   <b>Note</b> As Topological naming is based on the reference-key and attributes such as Naming 
166   (selection information) and Shape (topology evolution  information), 
167   OCAF is not coupled to the underlying modeling libraries. 
168   The  only modeling services required by OCAF are the following:  
169
170   * Each  algorithm must provide information about the evolution of the topology 
171    (the  list of faces modified, updated and deleted by the algorithm)
172   * Exploration  of the geometric model must be available 
173    (a 3D model is made of faces bounded  by close wires, 
174    themselves composed by a sequence of edges connected by their  vertices)
175  
176   Currently, OCAF uses the Open CASCADE Technology  modeling libraries.   
177  
178   To design an OCAF-based data model, the application  developer is encouraged to aggregate 
179   ready-to-use attributes instead of defining new attributes by inheriting from an abstract root class.  
180   There are two major advantages in using aggregation  rather than inheritance:
181   
182   * As you don't  implement data by defining new classes, the format of saved data 
183     provided with OCAF doesn't change; so you don't have to write the Save and Open functions
184   * The application can query the data at runtime if a particular attribute is  available
185   
186 **Summary**
187
188   * OCAF is  based on a uniform reference-key model in which:
189     * Reference-keys provide  persistent identification of data;  
190     * Data, including geometry, are  implemented as attributes attached to reference-keys;  
191     * Topological naming maintains the  selected geometry attached to reference-keys in parametrized models; 
192   * In many  applications, the data format provided with OCAF doesn't need to be extended;
193   * OCAF is not  coupled to the underlying modeling libraries.
194   
195   
196 @section occt_ocaf_3 The Data  Framework
197  
198 @subsection occt_ocaf_3_1 Data Structure
199  
200   The OCAF Data Framework is the Open CASCADE Technology  realization 
201   of the reference-key model in a tree structure. It offers a single environment where data from different application components can be handled. This allows exchanging and modifying data simply, consistently, with a maximum level of information and stable semantics.
202   
203
204 The building blocks of this approach are: 
205
206   * The tag
207   * The label
208   * The attribute
209
210 As it has been mentioned earlier, the first label in a framework is the root label of the tree. Each label has a tag expressed as an integer value, and a label is uniquely defined by an entry expressed as a list of tags from the root, 0:1:2:1, for example. 
211
212 Each label can have a list of attributes, which contain data, and several attributes can be attached to a label. Each attribute is identified by a GUID, and although a label may have several attributes attached to it, it must not have more than one attribute of a single GUID. 
213
214 The sub-labels of a label are called its children. Conversely, each label, which is not the root, has a father. Brother labels cannot share the same tag. 
215
216 The most important property is that a label’s entry is its persistent address in the data framework. 
217   
218 @image html /user_guides/ocaf/images/ocaf_image005.png "A simple framework model"
219 @image latex /user_guides/ocaf/images/ocaf_image005.png "A simple framework model"
220
221 In this image the circles contain tags of the corresponding labels.  The lists of tags are located under the circles. The root label always has a zero tag. 
222
223 The children of a root label are middle-level labels with tags 1 and 3. These labels are brothers. 
224
225 List of tags of the right-bottom label is "0:3:4": this label has tag 4, its father (with entry "0:3") has tag 3, father of father has tag 0 (the root label always has "0" entry). 
226
227 @subsection occt_ocaf_3_2 Examples of a Data Structure
228
229 Let's have a look at the example:
230   
231 @image html ocaf_wp_image007.png "The coffee machine"  
232 @image latex ocaf_wp_image007.png "The coffee machine"    
233   
234    In the image the application for designing coffee  machines first allocates 
235   a label for the machine unit. It then adds sub-labels  for the main features 
236   (glass coffee pot, water receptacle and filter) which it  refines as needed 
237   (handle and reservoir of the coffee pot and spout of the  reservoir). 
238   
239   You now attach technical data describing the handle — its geometry and color — 
240   and the reservoir — its geometry and material. 
241   Later on, you can  modify the handle's geometry without changing its color — 
242   both remain attached  to the same label.  
243   
244 @image html ocaf_wp_image005.png "The data structure of the coffee machine"  
245 @image latex ocaf_wp_image005.png "The data structure of the coffee machine"  
246  
247   The nesting of labels is key to OCAF. This allows a  label to have its own structure 
248   with its local addressing scheme which can be  reused in a more complex structure. 
249   Take, for example, the coffee machine.  Given that the coffee pot's handle has a label of tag [1], 
250   the entry for the handle in  the context of the coffee pot only (without the machine unit) is [0:1:1]. 
251   If you now model a coffee  machine with two coffee pots, one at the label [1], 
252   the second at the label [4] in the machine unit, 
253   the handle  of the first pot would have the entry [0:1:1:1] 
254   whereas the handle of the second pot would be [0:1:4:1]. 
255   This way, we avoid any  confusion between coffee pot handles.
256
257 Another example is the application for designing table lamps. The first label is allocated to the lamp unit. 
258
259 @image html /user_guides/ocaf/images/ocaf_image006.png
260 @image latex /user_guides/ocaf/images/ocaf_image006.png
261
262 The root label cannot have brother labels. Consequently, various lamps in the framework allocation correspond to the sub-labels of the root label. This allows avoiding any confusion between table lamps in the data framework. Different lamp parts have different material, color and other attributes, so a child label of the lamp with the specified tags is allocated for each sub-unit of the lamp: 
263
264   * a lamp-shade label with tag 1
265   * a bulb label with tag 2
266   * a stem label with tag 3
267
268 Label tags are chosen at will. They are only identifiers of the lamp parts. Now you can refine all units: by setting geometry, color, material and other information about the lamp or its parts to the specified label. This information is placed into special attributes of the label: the pure label contains no data -- it is only a key to access data. 
269
270 Remember that tags are private addresses without any meaning outside the data framework. It would, for instance, be an error to use part names as tags. These might change or be removed from production in next versions of the application, whereas the exact form of that part might be reused in your design, the part name could be integrated into the framework as an attribute. 
271
272 So, after the user changes the lamp design, only corresponding attributes are changed, but the label structure is maintained. The lamp shape must be recreated by new attribute values and attributes of the lamp shape must refer to a new shape. 
273
274 @image html /user_guides/ocaf/images/ocaf_image007.png
275 @image latex /user_guides/ocaf/images/ocaf_image007.png
276
277
278 The previous figure shows the table-lamps document structure: each child of the root label contains a lamp shape attribute and refers to the sub-labels, which contain some design information about corresponding sub-units. 
279
280 The data framework structure allows to create more complex structures: each lamp label sub-label may have children labels with more detailed information about parts of the table lamp and its components. 
281
282 Note that the root label can have attributes too, usually global attributes: the name of the document, for example. 
283
284 @subsection occt_ocaf_3_3 Tag
285
286 A tag is an integer, which identifies a label in two ways: 
287
288   * Relative identification
289   * Absolute identification.
290
291 In relative identification, a label’s tag has a meaning relative to the father label only. For a specific label, you might, for example, have four child labels identified by the tags 2, 7, 18, 100. In using relative identification, you ensure that you have a safe scope for setting attributes. 
292
293 In absolute identification, a label’s place in the data framework is specified unambiguously by a colon-separated list of tags of all the labels from the one in question to the root of the data framework. This list is called an entry. *TDF_Tool::TagList* allows retrieving the entry for a specific label. 
294
295 In both relative and absolute identification, it is important to remember that the value of an integer has no intrinsic semantics whatsoever. In other words, the natural sequence that integers suggest, i.e. 0, 1, 2, 3, 4 ... -- has no importance here. The integer value of a tag is simply a key. 
296
297 The tag can be created in two ways: 
298
299   * Random delivery
300   * User-defined delivery
301
302 As the names suggest, in random delivery, the tag value is generated by the system in a random manner. In user-defined delivery, you assign it by passing the tag as an argument to a method. 
303
304 @subsubsection occt_ocaf_3_3_1 Creating child labels using random delivery of tags
305
306 To append and return a new child label, you use *TDF_TagSource::NewChild*. In the example below, the argument *level2*, which is passed to *NewChild,* is a *TDF_Label*. 
307
308
309 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
310 TDF_Label child1 = TDF_TagSource::NewChild (level2); 
311 TDF_Label child2 = TDF_TagSource::NewChild (level2); 
312 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
313
314 @subsubsection occt_ocaf_3_3_2 Creation of a child label by user delivery from a tag
315
316 The other way to create a child label from a tag is by user delivery. In other words, you specify the tag, which you want your child label to have. 
317
318 To retrieve a child label from a tag which you have specified yourself, you need to use *TDF_Label::FindChild* and *TDF_Label::Tag* as in the example below. Here, the integer 3 designates the tag of the label you are interested in, and the Boolean false is the value for the argument *create*. When this argument is set to *false*, no new child label is created. 
319
320
321 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
322 TDF_Label achild = root.FindChild(3,Standard_False); 
323 if (!achild.IsNull()) { 
324 Standard_Integer tag = achild.Tag(); 
325
326 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
327
328 @subsection occt_ocaf_3_4 Label
329
330 The tag gives a persistent address to a label. The label -- the semantics of the tag -- is a place in the data framework where attributes, which contain data, are attached. The data framework is, in fact, a tree of labels with a root as the ultimate father label.
331
332 Label can not be deleted from the data framework, so, the structure of the data framework that has been created can not be removed while the document is opened. Hence any kind of reference to an existing label will be actual while an application is working with the document. 
333
334 @subsubsection occt_ocaf_3_4_1 Label creation
335
336 Labels can be created on any labels, compared with brother labels and retrieved. You can also find their depth in the data framework (depth of the root label is 0, depth of child labels of the root is 1 and so on), whether they have children or not, relative placement of labels, data framework of this label. The class *TDF_Label* offers the above services. 
337
338 @subsubsection occt_ocaf_3_4_2 Creating child labels
339
340 To create a new child label in the data framework using explicit delivery of tags, use *TDF_Label::FindChild*. 
341
342
343 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
344 //creating a label with tag 10 at Root 
345 TDF_Label lab1 = aDF->Root().FindChild(10); 
346
347 //creating labels 7 and 2 on label 10 
348 TDF_Label lab2 = lab1.FindChild(7); 
349
350 TDF_Label lab3 = lab1.FindChild(2); 
351 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
352 You could also use the same syntax but add the Boolean *true* as a value of the argument **create**. This ensures that a new child label will be created if none is found. Note that in the previous syntax, this was also the case since **create** is *true* by default. 
353
354
355 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
356 TDF_Label level1 = root.FindChild(3,Standard_True); 
357 TDF_Label level2 = level1.FindChild(1,Standard_True); 
358 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
359 @subsubsection occt_ocaf_3_4_3 Retrieving child labels
360
361 You can retrieve child labels of your current label by iteration on the first level in the scope of this label. 
362
363
364 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
365 TDF_Label current; 
366 // 
367 for (TDF_ChildIterator it1 (current,Standard_False); it1.More(); it1.Next()) { 
368 achild = it1.Value(); 
369 // 
370 // do something on a child (level 1) 
371 // 
372
373 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
374 You can also retrieve all child labels in every descendant generation of your current label by iteration on all levels in the scope of this label. 
375 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
376 for (TDF_ChildIterator itall (current,Standard_True); itall.More(); itall.Next()) { 
377 achild = itall.Value(); 
378 // 
379 // do something on a child (all levels) 
380 // 
381
382 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
383 Using *TDF_Tool::Entry* with *TDF_ChildIterator* you can retrieve the entries of your current label’s child labels as well. 
384
385  
386 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
387 void DumpChildren(const TDF_Label& aLabel) 
388
389   TDF_ChildIterator it; 
390   TCollection_AsciiString es; 
391   for (it.Initialize(aLabel,Standard_True); it.More(); it.Next()){ 
392     TDF_Tool::Entry(it.Value(),es); 
393     cout  <<  as.ToCString()  <<  endl; 
394   } 
395
396 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
397 @subsubsection occt_ocaf_3_4_4 Retrieving the father label
398
399 Retrieving the father label of a current label. 
400
401
402 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
403 TDF_Label father = achild.Father(); 
404 isroot = father.IsRoot(); 
405 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
406
407 @subsection occt_ocaf_3_5 Attribute
408
409 The label itself contains no data. All data of any type whatsoever -- application or non-application -- is contained in attributes. These are attached to labels, and there are different types for different types of data. OCAF provides many ready-to-use standard attributes such as integer, real, constraint, axis and plane. There are also attributes for topological naming, functions and visualization. Each type of attribute is identified by a GUID. 
410
411 The advantage of OCAF is that all of the above attribute types are handled in the same way. Whatever the attribute type is, you can create new instances of them, retrieve them, attach them to and remove them from labels, "forget" and "remember" the attributes of a particular label. 
412
413 @subsubsection occt_ocaf_3_5_1 Retrieving an attribute from a label
414
415 To retrieve an attribute from a label, you use *TDF_Label::FindAttribute*. In the example below, the GUID for integer attributes, and *INT*, a handle to an attribute are passed as arguments to *FindAttribute* for the current label. 
416
417
418 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
419 if(current.FindAttribute(TDataStd_Integer::GetID(),INT)) 
420
421   // the attribute is found 
422
423 else 
424
425   // the attribute is not found 
426
427 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
428 @subsubsection occt_ocaf_3_5_2 Identifying an attribute using a GUID
429
430 You can create a new instance of an attribute and retrieve its GUID. In the example below, a new integer attribute is created, and its GUID is passed to the variable *guid* by the method ID inherited from *TDF_Attribute*. 
431
432
433 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
434 Handle(TDataStd_Integer) INT = new TDataStd_Integer(); 
435 Standard_GUID guid = INT->ID(); 
436 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
437
438 @subsubsection occt_ocaf_3_5_3 Attaching an attribute to a label
439
440 To attach an attribute to a label, you use *TDF_Label::Add*. Repetition of this syntax raises an error message because there is already an attribute with the same GUID attached to the current label. 
441
442 *TDF_Attribute::Label* for *INT* then returns the label *attach* to which *INT* is attached. 
443
444
445 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
446 current.Add (INT); // INT is now attached to current 
447 current.Add (INT); // causes failure 
448 TDF_Label attach = INT->Label(); 
449 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
450 @subsubsection occt_ocaf_3_5_4 Testing the attachment to a label
451
452 You can test whether an attribute is attached to a label or not by using *TDF_Attribute::IsA* with the GUID of the attribute as an argument. In the example below, you test whether the current label has an integer attribute, and then, if that is so, how many attributes are attached to it. *TDataStd_Integer::GetID* provides the GUID argument needed by the method IsAttribute. 
453
454 *TDF_Attribute::HasAttribute* tests whether there is an attached attribute, and *TDF_Tool::NbAttributes* returns the number of attributes attached to the label in question, e.g. *current*. 
455
456
457 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
458 // Testing of attribute attachment 
459 // 
460 if (current.IsA(TDataStd_Integer::GetID())) { 
461 // the label has an Integer attribute attached 
462
463 if (current.HasAttribute()) { 
464 // the label has at least one attribute attached 
465 Standard_Integer nbatt = current.NbAttributes(); 
466 // the label has nbatt attributes attached 
467
468 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
469 @subsubsection occt_ocaf_3_5_5 Removing an attribute from a label
470
471 To remove an attribute from a label, you use *TDF_Label::Forget* with the GUID of the deleted attribute. To remove all attributes of a label, *TDF_Label::ForgetAll*. 
472
473
474 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
475 current.Forget(TDataStd_Integer::GetID()); 
476 // integer attribute is now not attached to current label 
477 current.ForgetAll(); 
478 // current has now 0 attributes attached 
479 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
480 @subsubsection occt_ocaf_3_5_6 Specific attribute creation
481
482 If the set of existing and ready to use attributes implementing standard data types does  not cover the needs of a specific data presentation task, the user can build his own data type and the corresponding new specific attribute implementing this new data type. 
483
484 There are two ways to implement a new data type: create a new attribute (standard approach), or use the notion of User Attribute by means of a combination of standard attributes  (alternative way) 
485
486 In order to create a new attribute in the standard way, create a class inherited from *TDF_Attribute* and implement all purely virtual and necessary virtual methods:
487 * **ID()** -- returns a unique GUID of a given attribute 
488 * **Restore(attribute)** -- sets fields of this attribute equal to the fields of a given attribute of the same type 
489 * **Paste(attribute, relocation_table)** -- sets fields of a given attribute equal to the field values of this attribute ; if the attribute has references to some objects of the data framework  and relocation_table has this element, then the given attribute must also refer to this object . 
490 * **NewEmpty()** -- returns a new attribute of this class with empty fields 
491 * **Dump(stream)** --  outputs information about a given attribute to a given stream debug (usually outputs an attribute of type string only) 
492
493 Methods *NewEmpty, Restore* and *Paste* are used for the common transactions mechanism (Undo/Redo commands). If you don’t need this attribute to react to undo/redo commands, you can write only stubs of these methods, else you must call the Backup method of the *TDF_Attribute* class every time attribute fields are changed. 
494
495 To enable possibility to save / restore the new attribute in XML format, do the following: 
496   1. Create a new package with the name Xml[package name] (for example *XmlMyAttributePackage*) containing  class *XmlMyAttributePackage_MyAttributeDriver*. The new class inherits *XmlMDF_ADriver* class and contains the translation functionality: from transient to persistent and vice versa (see the realization of the standard attributes in the packages *XmlMDataStd*, for example). Add package method AddDrivers which adds your class to a driver table (see below).
497   2. Create a new package (or do it in the current one) with two package methods: 
498           * *Factory*, which loads the document storage and retrieval drivers; and 
499           * *AttributeDrivers*, which calls the methods AddDrivers for all packages responsible for persistence of the document.
500   3. Create a plug-in implemented as an executable (see example *XmlPlugin*). It calls a macro PLUGIN with the package name where you implemented the method Factory.
501
502 To enable possibility to save / restore the new attribute in binary format, do the following: 
503   1. Create a new package with name <i> Bin[package name] </i> (for example *BinMyAttributePackage*) containing a class *BinMyAttributePackage_MyAttributeDriver*. The new class inherits *BinMDF_ADriver* class and contains the translation functionality: from transient to persistent and vice versa (see the realization of the standard attributes in the packages *BinMDataStd*, for example). Add package method *AddDrivers*, which adds your class to a driver table.
504   2. Create a new package (or do it in the current one) with two package methods: 
505           * Factory, which loads the document storage and retrieval drivers; and 
506           * AttributeDrivers, which calls the methods AddDrivers for all packages responsible for persistence of the document.
507   3. Create a plug-in implemented as an executable (see example *BinPlugin*). It calls a macro PLUGIN with the package name where you implemented the method Factory.
508 See @ref occt_ocaf_4_3_3 "Saving the document" and @ref occt_ocaf_4_3_4 "Opening the document from a file" for the description of document save/open mechanisms. 
509
510 If you decided to use the alternative way (create a new attribute by means of *UAttribute* and a combination of other standard attributes), do the following: 
511   1. Set a *TDataStd_UAttribute* with a unique GUID attached to a label. This attribute defines the semantics of the data type (identifies the data type).
512   2. Create child labels and allocate all necessary data through standard attributes at the child labels.
513   3. Define an interface class for access to the data of the child labels.
514
515 Choosing the alternative way of implementation of new data types allows to forget about creating persistence classes for your new data type. Standard persistence classes will be used instead. Besides, this way allows separating the data and the methods for access to the data (interfaces). It can be used for rapid development in all cases when requirements to application performance are not very high. 
516
517 Let’s study the implementation of the same data type in both ways by the example of transformation represented by *gp_Trsf* class. The class *gp_Trsf* defines the transformation according to the type (*gp_TrsfForm*) and a set of parameters of the particular type of transformation (two points or a vector for translation, an axis and an angle for rotation, and so on). 
518
519 1. The first way: creation of a new attribute. The implementation of the transformation by creation of a new attribute is represented in the @ref occt_ocaf_11 "Samples". 
520
521 2. The second way: creation of a new data type by means of combination of standard attributes. Depending on the type of transformation it may be kept in data framework by different standard attributes. For example, a translation is defined by two points. Therefore the data tree for translation looks like this: 
522   * Type of transformation <i>(gp_Translation)</i> as *TDataStd_Integer*;
523   * First point as *TDataStd_RealArray* (three values: X1, Y1 and Z1);
524   * Second point as *TDataStd_RealArray* (three values: X2, Y2 and Z2).
525
526 @image html /user_guides/ocaf/images/ocaf_image010.png "Data tree for translation"
527 @image latex /user_guides/ocaf/images/ocaf_image010.png "Data tree for translation"
528
529 If the type of transformation is changed to rotation, the data tree looks like this: 
530   * Type of transformation <i>(gp_Rotation)</i> as *TDataStd_Integer*;
531   * Point of axis of rotation as *TDataStd_RealArray* (three values: X, Y and Z);
532   * Axis of rotation as *TDataStd_RealArray* (three values: DX, DY and DZ);
533   * Angle of rotation as *TDataStd_Real*.
534
535 @image html /user_guides/ocaf/images/ocaf_image011.png "Data tree for rotation"
536 @image latex /user_guides/ocaf/images/ocaf_image011.png "Data tree for rotation"
537
538 The attribute *TDataStd_UAttribute* with the chosen unique GUID identifies the data type. The interface class initialized by the label of this attribute allows access to the data container (type of transformation and the data of transformation according to the type). 
539   
540 @subsection occt_ocaf_3_6 Compound documents
541  
542   As the identification of data is persistent, one document can reference data contained in another document, 
543   the referencing and  referenced documents being saved in two separate files.  
544  
545   Lets look at the coffee machine application again. The  coffee pot can be placed in one document. 
546   The coffee machine document then  includes an *occurrence* — a positioned copy — of the coffee pot. 
547   This occurrence is defined by an XLink attribute (the external Link) 
548   which references the coffee pot of the first document 
549   (the XLink contains the relative path of the coffee pot document and the entry of the coffee pot data [0:1] ).  
550
551 @image html ocaf_wp_image006.png "The coffee machine compound document"
552 @image latex ocaf_wp_image006.png "The coffee machine compound document"
553  
554   In this context, the end-user of the coffee machine application can open the coffee pot document, 
555   modify the geometry of, for  example, the reservoir, and overwrite the document without worrying 
556   about the impact of the modification in the coffee machine document. 
557   To deal with this  situation, OCAF provides a service which allows the application to check 
558   whether a document is up-to-date. This service is based on a modification counter included in each document: 
559   when an external link is created, a copy of  the referenced document counter is associated to the XLink 
560   in the referencing  document. Providing that each modification of the referenced document increments its own counter,   
561   we can detect that the referencing document has to  be updated by comparing the two counters 
562   (an update function importing the data  referenced by an XLink into the referencing document is also provided).  
563  
564  @subsection occt_ocaf_3_7 Transaction mechanism
565  
566   The Data Framework also provides a transaction mechanism inspired from database management systems: 
567   the data are modified within a transaction which is terminated either by a Commit 
568   if the modifications are validated  or by an Abort if the modifications are abandoned — 
569   the data are then restored  to the state it was in prior to the transaction. 
570   This mechanism is extremely useful for:
571
572   * Securing  editing operations (if an error occurs, the transaction is abandoned and the  structure retains its integrity)
573   * Simplifying  the implementation of the **Cancel** function (when the end-user begins a command, 
574   the application may launch a transaction and operate directly in the data structure; 
575   abandoning the action causes the transaction to Abort)
576   * Executing  **Undo** (at commit time, the modifications are recorded in order to be able to  restore the data to their previous state)
577  
578   The transaction mechanism simply manages a  backup copy of attributes. 
579   During a transaction, attributes are copied before  their first modification. 
580   If the transaction is validated, the copy is  destroyed. 
581   If the transaction is abandoned, the attribute is restored to its initial value 
582   (when attributes are added or deleted, the operation is simply  reversed).
583
584   Transactions are document-centered, that is, the application starts a transaction on a document. 
585   So, modifying a referenced  document and updating one of its referencing documents requires 
586   two transactions, even if both operations are done in the same working session.
587
588   
589 @section occt_ocaf_4_ Standard Document Services
590
591 @subsection occt_ocaf_4_1 Overview
592
593 Standard documents offer ready-to-use documents containing a TDF-based data framework. Each document can contain only one framework. 
594
595 The documents themselves are contained in the instantiation of a class inheriting from *TDocStd_Application*. This application manages the creation, storage and retrieval of documents. 
596
597 You can implement undo and redo in your document, and refer from the data framework of one document to that of another one. This is done by means of external link attributes, which store the path and the entry of external links. 
598
599 To sum up, standard documents alone provide access to the data framework. They also allow you to: 
600
601   * Update external links
602   * Manage the saving and opening of data
603   * Manage the undo/redo functionality.
604
605
606 @subsection occt_ocaf_4_2 The Application
607
608 As a container for your data framework, you need a document, and your document must be contained in your application. This application will be a class inheriting from *TDocStd_Application*. 
609
610 @subsubsection occt_ocaf_4_2_1 Creating an application
611
612 To create an application, use the following syntax. 
613
614 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
615 Handle(TDocStd_Application) app 
616 = new MyApplication_Application (); 
617 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
618 Note that *MyApplication_Application* is a class, which you have to create and which will inherit from *TDocStd_Application*. 
619
620 @subsubsection occt_ocaf_4_2_2 Creating a new document
621
622 To the application which you declared in the previous example (4.2.1), you must add the document *doc* as an argument of *TDocStd_Application::NewDocument*. 
623
624 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
625 Handle(TDocStd_Document) doc; 
626 app->NewDocument("NewDocumentFormat", doc); 
627 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
628
629 @subsubsection occt_ocaf_4_2_3 Retrieving the application to which the document belongs
630
631 To retrieve the application containing your document, you use the syntax below. 
632
633 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
634 app = Handle(TDocStd_Application)::DownCast 
635 (doc->Application()); 
636 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
637 @subsection occt_ocaf_4_3 The Document
638
639 The document contains your data framework, and allows you to retrieve this framework, recover its main label, save it in a file, and open or close this file. 
640
641 @subsubsection occt_ocaf_4_3_1 Accessing the main label of the framework
642
643 To access the main label in the data framework, you use *TDocStd_Document::Main* as in the example below. The main label is the first child of the root label in the data framework, and has the entry 0:1. 
644
645 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
646 TDF_Label label = doc->Main(); 
647 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
648 @subsubsection occt_ocaf_4_3_2 Retrieving the document from a label in its framework
649
650 To retrieve the document from a label in its data framework, you use *TDocStd_Document::Get* as in the example below. The argument *label* passed to this method is an instantiation of *TDF_Label*. 
651 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
652 doc = TDocStd_Document::Get(label); 
653 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
654
655 @subsubsection occt_ocaf_4_3_3 Saving the document
656
657 If in your document you use only standard attributes (from the packages *TDF, TDataStd, TNaming, TFunction, TPrsStd* and *TDocStd*), you just do the following steps: 
658
659 * In your application class (which inherits class *TDocStd_Application*) implement two methods:
660         + Formats (TColStd_SequenceOfExtendedString& theFormats), which append to a given sequence <i>\<theFormats\></i> your document format string, for example, "NewDocumentFormat" -- this string is also set in the document creation command 
661         + ResourcesName(), which returns a string with a name of resources file (this file contains a description about the extension of the document, storage/retrieval drivers GUIDs...), for example, "NewFormat" 
662 * Create the resource file (with name, for example, "NewFormat") with the following strings:
663
664 ~~~~~
665 formatlist:NewDocumentFormat 
666 NewDocumentFormat: New Document Format Version 1.0 
667 NewDocumentFormat.FileExtension: ndf 
668 NewDocumentFormat.StoragePlugin: bd696000-5b34-11d1-b5ba-00a0c9064368 
669 NewDocumentFormat.RetrievalPlugin: bd696001-5b34-11d1-b5ba-00a0c9064368 
670 NewDocumentFormatSchema: bd696002-5b34-11d1-b5ba-00a0c9064368 
671 NewDocumentFormat.AttributeStoragePlugin:57b0b826-d931-11d1-b5da-00a0c9064368 
672 NewDocumentFormat.AttributeRetrievalPlugin:57b0b827-d931-11d1-b5da-00a0c9064368 
673 ~~~~~
674
675 * Copy the resource file "Plugin" from $CASROOT/src/StdResource
676
677 In order to set the paths for these files it is necessary to set the environments: *CSF_PluginDefaults* and *CSF_NewFormatDefaults*. For example, set the files in the directory *MyApplicationPath/MyResources*: 
678
679 ~~~~~
680 setenv CSF_PluginDefaults MyApplicationPath/MyResources 
681 setenv CSF_NewFormatDefaults MyApplicationPath/MyResources 
682 ~~~~~
683
684 Once these steps are taken you may run your application, create documents and Save/Open them.
685
686 @subsubsection occt_ocaf_4_3_4 Opening the document from a file
687
688 To open the document from a file where it has been previously saved, you can use *TDocStd_Application::Open* as in the example below. The arguments are the path of the file and the document saved in this file. 
689
690 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
691 app->Open("/tmp/example.caf", doc); 
692 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
693
694 @subsubsection occt_ocaf_4_3_5 Cutting, copying and pasting inside a document
695
696 To cut, copy and paste inside a document, use the class *TDF_CopyLabel*.
697
698 In fact, you must define a *Label*, which contains the temporary value of a cut or 
699 copy operation (say, in <i> Lab_Clipboard</i>). You must also define two other labels:
700
701 * The data container (e.g. <i> Lab_source</i>)
702 * The destination of the copy (e.g. <i> Lab_ Target</i> )
703
704 ~~~~
705     Copy = copy (Lab_Source => Lab_Clipboard)
706     Cut = copy + Lab_Source.ForgetAll() // command clear the contents of LabelSource.
707     Paste = copy (Lab_Clipboard => Lab_target)
708 ~~~~
709
710 So we need a tool to copy all (or a part) of the content of a label and its sub-label,
711 to another place defined by a label.
712
713 ~~~~
714     TDF_CopyLabel aCopy;
715     TDF_IDFilter aFilter (Standard_False);
716
717     //Don't copy TDataStd_TreeNode attribute
718
719      aFilter.Ignore(TDataStd_TreeNode::GetDefaultTreeID());
720      aCopy.Load(aSource, aTarget); aCopy.UseFilter(aFilter); aCopy.Perform();
721
722     // copy the data structure to clipboard 
723
724     return aCopy.IsDone(); }
725 ~~~~
726
727 The filter is used to forbid copying a specified type of attribute. 
728
729 You can also have a look at the class *TDF_Closure*, which can be useful to determine the dependencies of the part you want to cut from the document.
730
731 @subsection occt_ocaf_4_4 External Links
732
733 External links refer from one document to another. They allow you to update the copy of data  framework later on. 
734
735 @image html /user_guides/ocaf/images/ocaf_image012.png  "External links between documents"
736 @image latex /user_guides/ocaf/images/ocaf_image012.png  "External links between documents"
737
738 Note that documents can be copied with or without a possibility of updating an external link. 
739
740 @subsubsection occt_ocaf_4_4_1 Copying the document
741
742 #### With the possibility of updating it later
743
744 To copy a document with a possibility of updating it later, you use *TDocStd_XLinkTool::CopyWithLink*. 
745
746 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
747 Handle(TDocStd_Document) doc1; 
748 Handle(TDocStd_Document) doc2; 
749
750 TDF_Label source = doc1->GetData()->Root(); 
751 TDF_Label target = doc2->GetData()->Root(); 
752 TDocStd_XLinkTool XLinkTool; 
753
754 XLinkTool.CopyWithLink(target,source); 
755 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
756
757 Now the target document has a copy of the source document. The copy also has a link in order to update the content of the copy if the original changes. 
758
759 In the example below, something has changed in the source document. As a result, you need to update the copy in the target document. This copy is passed to *TDocStd_XLinkTool::UpdateLink* as the argument *target*. 
760
761 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
762 XLinkTool.UpdateLink(target); 
763 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
764
765 #### Without any link between the copy and the original
766
767 You can also create a copy of the document with no link between the original and the copy. The syntax to use this option is *TDocStd_XLinkTool::Copy*. The copied document is again represented by the argument *target*, and the original -- by *source.* 
768
769 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
770 XLinkTool.Copy(target, source); 
771
772 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
773
774
775 @section occt_ocaf_5 OCAF Shape Attributes
776 @subsection occt_ocaf_5_1 Overview
777
778 A topological attribute can be seen as a hook into the topological structure. It is possible to attach data to define references to it.
779
780 OCAF shape attributes are used for topology objects and their evolution access. All topological objects are stored in one *TNaming_UsedShapes* attribute at the root label of the data framework. This attribute contains a map with all topological shapes used in a given document. 
781
782 The user can add the *TNaming_NamedShape* attribute to other labels. This attribute contains references (hooks) to shapes from the *TNaming_UsedShapes* attribute and an evolution of these shapes. The *TNaming_NamedShape* attribute contains a set of pairs of hooks: to the *Old* shape and to a *New* shape (see the following figure). It allows not only to get the topological shapes by the labels, but also to trace the evolution of the shapes and to correctly update dependent shapes by the changed one. 
783
784 If a shape is newly created, then the old shape of a corresponding named shape is an empty shape. If a shape is deleted, then the new shape in this named shape is empty. 
785
786 @image html /user_guides/ocaf/images/ocaf_image013.png
787 @image latex /user_guides/ocaf/images/ocaf_image013.png
788
789 @subsection occt_ocaf_5_2 Shape attributes in data framework. 
790
791 Different algorithms may dispose sub-shapes of the result shape at the individual labels depending on whether it is necessary to do so: 
792
793 * If a sub-shape must have some extra attributes (material of each face or color of each edge). In this case a specific sub-shape is placed to a separate label (usually to a sub-label of the result shape label) with all attributes of this sub-shape.
794 * If the topological naming algorithm is needed, a necessary and sufficient set of sub-shapes is placed to child labels of the result shape label. As usual, for a basic solid and closed shells, all faces of the shape are disposed.
795
796 *TNaming_NamedShape* may contain a few pairs of hooks with the same evolution. In this case the topology shape, which belongs to the named shape is a compound of new shapes. 
797
798 Consider the following example. Two boxes (solids) are fused into one solid (the result one). Initially each box was placed to the result label as a named shape, which has evolution PRIMITIVE and refers to the corresponding shape of the *TNaming_UsedShapes* map. The box result label has a material attribute and six child labels containing named shapes of Box faces. 
799
800 @image html /user_guides/ocaf/images/ocaf_image014.png "Resulting box"
801 @image latex /user_guides/ocaf/images/ocaf_image014.png "Resulting box"
802
803 After the fuse operation a modified result is placed to a separate label as a named shape, which refers to the old shape (one of the boxes) and to the new shape resulting from the fuse operation, and has evolution MODIFY (see the following figure). 
804
805 Named shapes, which contain information about modified faces, belong to the fuse result sub-labels: 
806 * sub-label with tag 1 -- modified faces from box 1, 
807 * sub-label with tag 2 -- modified faces from box 2. 
808
809 @image html /user_guides/ocaf/images/ocaf_image015.png
810 @image latex /user_guides/ocaf/images/ocaf_image015.png
811
812 This is necessary and sufficient information for the functionality of the right naming mechanism: any sub-shape of the result can be identified unambiguously by name type and set of labels, which contain named shapes: 
813
814   * face F1’ as a modification of face F11  
815   * face F1’’ as generation of face F12 
816   * edges as an intersection of two contiguous faces
817   * vertices as an intersection of three contiguous faces
818
819 After any modification of source boxes the application must automatically rebuild the naming entities: recompute the named shapes of the boxes (solids and faces) and fuse the resulting named shapes (solids and faces) that reference to the new named shapes. 
820
821 @subsection occt_ocaf_5_3 Registering shapes and their evolution
822
823 When using TNaming_NamedShape to create attributes, the following fields of an attribute are filled: 
824
825 * A list of shapes called the "old" and the "new" shapes A new shape is recomputed as the value of the named shape. The meaning of this pair depends on the type of evolution.
826 * The type of evolution, which is a term of the *TNaming_Evolution* enumeration used for the selected shapes that are placed to the separate label: 
827         * PRIMITIVE -- newly created topology, with no previous history;
828         * GENERATED -- as usual, this evolution of a  named shape means, that the new shape is created from a low-level old shape ( a prism face from an edge, for example );
829         * MODIFY -- the new shape is a modified old shape;
830         * DELETE -- the new shape is empty; the named shape with this evolution just indicates that the old shape topology is deleted from the model;
831         * SELECTED -- a named shape with this evolution has no effect on the history of the topology.
832
833 Only pairs of shapes with equal evolution can be stored in one named shape. 
834
835 @subsection occt_ocaf_5_4 Using naming resources
836
837 The class *TNaming_Builder* allows creating a named shape attribute. It has a label of a future attribute as an argument of the constructor. Respective methods are used for the evolution and setting of shape pairs. If for the same TNaming_Builder object a lot of pairs of shapes with the same evolution are given, then these pairs would be placed in the resulting named shape. After the creation of a new object of the TNaming_Builder class, an empty named shape is created at the given label. 
838
839 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
840 // a new empty named shape is created at "label" 
841 TNaming_Builder builder(label); 
842 // set a pair of shapes with evolution GENERATED 
843 builder.Generated(oldshape1,newshape1); 
844 // set another pair of shapes with the same evolution 
845 builder.Generated(oldshape2,newshape2); 
846 // get the result - TNaming_NamedShape attribute 
847 Handle(TNaming_NamedShape) ns = builder.NamedShape(); 
848 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
849
850 @subsection occt_ocaf_5_5 Reading the contents of a named shape attribute
851
852 You can use the method <i>TNaming_NamedShape::Evolution()</i> to get the evolution of this named shape and the method <i>TNaming_NamedShape::Get()</i> to get a compound of new shapes of all pairs of this named shape.
853   
854 More detailed information about the contents of the named shape or about the modification history of a topology can be obtained with the following: 
855 * *TNaming_Tool* provides a common high-level functionality for access to the named shapes contents:
856         * The method <i>GetShape(Handle(TNaming_NamedShape)) </i>  returns a compound of new shapes of the given named shape;
857         * The method <i>CurrentShape(Handle(TNaming_NamedShape))</i>  returns a compound of the shapes, which are latest versions of the shapes from the given named shape;
858         * The method <i>NamedShape(TopoDS_Shape,TDF_Label) </i> returns a named shape, which contains a given shape as a new shape. A given label is any label from the data framework -- it just gives access to it.
859 * *TNaming_Iterator* gives access to the named shape and hooks pairs.
860
861 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
862 // create an iterator for a named shape 
863 TNaming_Iterator iter(namedshape); 
864 // iterate while some pairs are not iterated 
865 while(iter.More()) { 
866 // get the new shape from the current pair 
867 TopoDS_Shape newshape = iter.NewShape(); 
868 // get the old shape from the current pair 
869 TopoDS_Shape oldshape = iter.OldShape(); 
870 // do something... 
871
872 // go to the next pair 
873 iter.Next(); 
874
875 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
876
877
878 @subsection occt_ocaf_5_6 Topological naming
879
880 The Topological Naming mechanism is based on 3 components:
881 * History of the used modeling operation algorithm;
882 * Registering of the built result in Data Framework (i.e. loading the necessary elements of the extracted history in OCAF document);
883 * Selection / Recomputation of a "selected" sub-shape of the algorithm result.
884
885 To get the expected result the work of the three components should be synchronized and the rules of each component should be respected.
886
887 @subsubsection occt_ocaf_5_6_1 Algorithm history
888
889 The "correct" history of a used modeling operation serves the basis of naming mechanism. It should be provided by the algorithm supporting the operation. The history content depends on the type of the topological result. The purpose of the history is to provide all entities for consistent and correct work of the Selection / Recomputation mechanism. The table below presents expected types of entities depending on the result type.
890
891 | Result type | Type of sub-shapes to be returned by history of algorithm | Comments |
892 | :---------- | :-------------------------------------------------------- | :------- |
893 | Solid or closed shell | Faces | All faces |
894 | Open shell or single face | Faces and edges of opened boundaries only | All faces plus all edges of opened boundaries |
895 | Closed wire | Edges | All edges |
896 | Opened wire | Edges and ending vertexes | All edges plus ending vertexes of the wire |
897 | Edge | Vertexes |     Two vertexes are expected |
898 | Compound or CompSolid | To be used consequentially the above declared rule applied to all sub-shapes of the first level | Compound/CompSolid to be explored level by level until any the mentioned above types will be met | 
899
900 The history should return (and track) only elementary types of sub-shapes, i.e. Faces, Edges and Vertexes, while other so-called aggregation types: Compounds, Shells, Wires, are calculated by Selection mechanism automatically.
901
902 There are some simple exceptions for several cases. For example, if the Result contains a seam edge -- in conical, cylindrical or spherical surfaces -- this seam edge should be tracked by the history and in addition should be defined before the types. All degenerated entities should be filtered and excluded from consideration.
903
904 @subsubsection occt_ocaf_5_6_2 Loading history in data framework
905
906 All elements returned by the used algorithm according to the aforementioned rules should be put in the Data Framework (or OCAF document in other words) consequently in linear order under the so-called **Result Label**. 
907
908 The "Result Label" is *TDF_label* used to keep the algorithm result *Shape* from *TopoDS* in *NamedShape* attribute. During loading sub-shapes of the result in Data Framework should be used the rules of chapter @ref occt_ocaf_5_3.  These rules are also applicable for loading the main shape, i.e. the resulting shape produced by the modeling algorithm.
909
910 @subsubsection occt_ocaf_5_6_3 Selection / re-computation mechanism
911
912 When the Data Framework is filled with all impacted entities (including the data structures resulting from the current modeling operation and the data structures resulting from the previous modeling operations, on which the current operation depends) any sub-shape of the current result can be **selected**, i.e. the corresponding new naming data structures, which support this functionality, can be produced and kept in the Data Framework.
913
914 One of the user interfaces for topological naming is the class *TNaming_Selector*. It implements the above mentioned sub-shape "selection" functionality as an additional one. I.e. it can be used for:
915 * Storing the selected shape on a label -- its **Selection**;
916 * Accessing the named shape -- check the kept value of the shape
917 * Update of this naming -- recomputation of an earlier selected shape.
918
919 The selector places a new named shape with evolution **SELECTED** to the given label. The selector creates a **name** of the selected shape, which is a unique description (data structure) of how to find the selected topology using as resources:
920 * the given context shape, i.e. the main shape kept on **Result Label**, which contains a selected sub-shape, 
921 * its evolution and
922 * naming structure.
923
924 After any modification of a context shape and update of the corresponding naming structure, it is necessary to call method *TNaming_Selector::Solve*. If the naming structure, i.e. the above mentioned **name**, is correct, the selector automatically updates the selected sub-shape in the corresponding named shape, else it fails.
925
926 @subsection occt_ocaf_5_7 Exploring shape evolution
927
928 The class *TNaming_Tool* provides a toolkit to read current data contained in the attribute. 
929
930 If you need to create a topological attribute for existing data, use the method *NamedShape*. 
931
932 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
933 class MyPkg_MyClass 
934
935 public: Standard_Boolean SameEdge (const Handle(CafTest_Line)& L1, const Handle(CafTest_Line)& L2); 
936 }; 
937
938 Standard_Boolean CafTest_MyClass::SameEdge (const Handle(CafTest_Line)& L1, const Handle(CafTest_Line)& L2) 
939
940   Handle(TNaming_NamedShape) NS1 = L1->NamedShape(); 
941   Handle(TNaming_NamedShape) NS2 = L2->NamedShape(); 
942   return BRepTools::Compare(NS1,NS2); 
943
944 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
945
946
947 @subsection occt_ocaf_5_8 Example of topological naming usage
948
949 **Topological naming** is a mechanism of Open CASCADE aimed to keep reference to the selected shape. If, for example, we select a vertex of a solid shape and “ask” the topological naming to keep reference to this vertex, it will refer to the vertex whatever happens with the shape (translations, scaling, fusion with another shape, etc.).
950
951 Let us consider an example: imagine a wooden plate. The job is to drive several nails in it:
952
953 @figure{/user_guides/ocaf/images/ocaf_image020.png, "A nail driven in a wooden plate"}
954
955 There may be several nails with different size and position. A **Hammer** should push each **Nail** exactly in the center point of the top surface. For this the user does the following:
956 *       Makes several Nails of different height and diameter (according to the need),
957 *       Chooses (selects) the upper surface of each Nail for the Hammer.
958
959 The job is done. The application should do the rest -- the Hammer calculates a center point for each selected surface of the Nail and “strikes” each Nail driving it into the wooden plate.
960
961 What happens if the user changes the position of some Nails? How will the Hammer know about it? It keeps reference to the surface of each Nail. However, if a Nail is relocated, the Hammer should know the new position of the selected surface. Otherwise, it will “strike” at the old position (keep the fingers away!)…
962
963 Topological naming mechanism should help the Hammer to obtain the relocated surfaces. The Hammer “asks” the mechanism to “resolve” the selected shapes by calling method *TNaming_Selection::Solve()* and the mechanism “returns” the modified surfaces located at the new position by calling  *TNaming_Selector::NamedShape()*.
964
965 The topological naming is represented as a “black box” in the example above. Now it is time to make the box a little more “transparent”.
966
967 The application contains 3 functions:
968 * **Nail** -- produces a shape representing a nail,
969 * **Translator** -- translates a shape along the wooden plate,
970 * **Hammer** -- drives the nail in the wooden plate.
971
972 Each function gives the topological naming some hints how to “re-solve” the selected sub-shapes:
973 * The Nail constructs a solid shape and puts each face of the shape into sub-labels: 
974
975 @figure{/user_guides/ocaf/images/ocaf_image021.png, "Distribution of faces through sub-labels of the Nail"}
976
977 * The **Translator** moves a shape and registers modification for each face: it puts a pair: “old” shape -- “new” shape at a sub-label of each moving Nail. The “old” shape represents a face of the Nail at the initial position. The “new” shape -- is the same face, but at a new position:
978
979 @figure{/user_guides/ocaf/images/ocaf_image022.png, "Registration of relocation of faces of a Nail"}
980
981 How does it work?
982 * The Hammer selects a face of a Nail calling *TNaming_Selector::Select()*. This call makes a unique name for the selected shape. In our example, it will be a direct reference to the label of the top face of the Nail (Face 1).
983 * When the user moves a Nail along the wooden plate, the Translator registers this modification by putting the pairs: “old” face of the Nail -- new face of the Nail into its sub-labels. 
984 * When the Hammer calls *TNaming::Solve()*, the topological naming “looks” at the unique name of the selected shape and tries to re-solve it:
985         * It finds the 1st appearance of the selected shape in the data tree -- it is a label under the Nail function *Face 1*.
986         * It follows the evolution of this face. In our case, there is only one evolution -- the translation: *Face 1* (top face) -- <i>Face 1’</i> (relocated top face). So, the last evolution is the relocated top face.
987 * Calling the method *TNaming_Selector::NamedShape()* the Hammer obtains the last evolution of the selected face -- the relocated top face.
988
989 The job is done.
990
991 P.S. Let us say a few words about a little more complicated case -- selection of a wire of the top face. Its topological name is an “intersection” of two faces. We remember that the **Nail** puts only faces under its label. So, the selected wire will represent an “intersection” of the top face and the conic face keeping the “head” of the nail. Another example is a selected vertex. Its unique name may be represented as an “intersection” of three or even more faces (depends on the shape).
992
993
994 @section occt_ocaf_6 Standard Attributes
995
996 @subsection occt_ocaf_6_1 Overview
997
998 Standard attributes are ready-to-use attributes, which allow creating and modifying attributes for many basic data types. They are available in the packages *TDataStd, TDataXtd* and *TDF*. Each attribute belongs to one of four types: 
999
1000   * Geometric attributes;
1001   * General attributes;
1002   * Relationship attributes;
1003   * Auxiliary attributes.
1004   
1005    
1006
1007 ### Geometric attributes
1008
1009   * **Axis** -- simply identifies, that the concerned *TNaming_NamedShape* attribute with an axis shape inside belongs to the same label; 
1010   * **Constraint** -- contains information about a constraint between geometries: used geometry attributes, type, value (if exists), plane (if exists), "is reversed", "is inverted" and "is verified" flags;
1011   * **Geometry** -- simply identifies, that the concerned *TNaming_NamedShape* attribute with a specified-type geometry belongs to the same label; 
1012   * **Plane** -- simply identifies, that the concerned *TNaming_NamedShape* attribute with a plane shape inside belongs to the same label;
1013   * **Point** -- simply identifies, that the concerned *TNaming_NamedShape* attribute with a  point shape inside belongs to the same label;
1014   * **Shape** -- simply identifies, that the concerned *TNaming_NamedShape* attribute belongs to the same label;
1015   * **PatternStd**  -- identifies one of five available pattern models (linear, circular, rectangular, circular rectangular and mirror);
1016   * **Position** -- identifies the position in 3d global space.
1017
1018 ### General attributes
1019
1020   * **AsciiString** -- contains AsciiString value;
1021   * **BooleanArray** -- contains an array of Boolean;
1022   * **BooleanList** -- contains a list of Boolean;
1023   * **ByteArray** -- contains an array of Byte (unsigned char) values;
1024   * **Comment** -- contains a string -- the comment for a given label (or attribute);
1025   * **Expression** -- contains an expression string and a list of used variables attributes;
1026   * **ExtStringArray** -- contains an array of *ExtendedString* values;
1027   * **ExtStringList** -- contains a list of *ExtendedString* values;
1028   * **Integer** -- contains an integer value;
1029   * **IntegerArray** -- contains an array of integer values;
1030   * **IntegerList** -- contains a list of integer values;
1031   * **IntPackedMap** -- contains a packed map of integers;
1032   * **Name** -- contains a string -- the name of a given label (or attribute);
1033   * **NamedData** -- may contain up to 6 of the following named data sets (vocabularies): *DataMapOfStringInteger, DataMapOfStringReal, DataMapOfStringString, DataMapOfStringByte, DataMapOfStringHArray1OfInteger* or *DataMapOfStringHArray1OfReal*;
1034   * **NoteBook** -- contains a *NoteBook* object attribute;
1035   * **Real** -- contains a real value;
1036   * **RealArray** -- contains an array of  real values;
1037   * **RealList** -- contains a list of real values;
1038   * **Relation** -- contains a relation string and a list of used variables attributes;
1039   * **Tick** -- defines a boolean attribute;
1040   * **Variable** -- simply identifies, that a variable belongs to this label; contains the flag *is constraint* and a string of used units ("mm", "m"...);
1041   * **UAttribute** -- attribute with a user-defined GUID. As a rule, this attribute is used as a marker, which is independent of attributes at the same label (note, that attributes with the same GUIDs can not belong to the same label).
1042   
1043 ### Relationship attributes 
1044
1045   * **Reference** -- contains reference to the label of its own data framework;
1046   * **ReferenceArray** -- contains an array of references;
1047   * **ReferenceList** -- contains a list of references;
1048   * **TreeNode** -- this attribute allows to create an internal tree in the data framework; this tree consists of nodes with the specified tree ID; each node contains references to the father, previous brother, next brother, first child nodes and tree ID.
1049
1050 ### Auxiliary attributes
1051
1052   * **Directory** -- high-level tool attribute for sub-labels management;
1053   * **TagSource** -- this attribute is used for creation of new children: it stores the tag of the last-created child of the label and gives access to the new child label creation functionality.
1054
1055 All attributes inherit class *TDF_Attribute*, so, each attribute has its own GUID and standard methods for attribute creation, manipulation, getting access to the data framework. 
1056
1057
1058 @subsection occt_ocaf_6_2 Services common to all attributes
1059
1060 @subsubsection occt_ocaf_6_2_1 Accessing GUIDs
1061
1062 To access the GUID of an attribute, you can use two methods: 
1063   * Method *GetID* is the static method of a class. It returns the GUID of any attribute, which is an object of a specified class (for example, *TDataStd_Integer* returns the GUID of an integer attribute). Only two classes from the list of standard attributes do not support these methods: *TDataStd_TreeNode* and *TDataStd_Uattribute*, because the GUIDs of these attributes are variable.
1064   * Method *ID* is the method of an object of an attribute class. It returns the GUID of this attribute. Absolutely all attributes have this method: only by this identifier you can discern the type of an attribute.
1065   
1066 To find an attribute attached to a specific label, you use the GUID of the attribute type you are looking for. This information can be found using the method  <i> GetID</i> and the method <i> Find</i> for the label as follows:
1067
1068 ~~~~
1069     Standard_GUID anID = MyAttributeClass::GetID();
1070     Standard_Boolean HasAttribute = aLabel.Find(anID,anAttribute);
1071 ~~~~
1072
1073 @subsubsection occt_ocaf_6_2_2 Conventional Interface of Standard Attributes
1074
1075 It is usual to create standard named methods for the attributes: 
1076
1077   * Method *Set(label, [value])* is the static method, which allows to add an attribute to a given label.  If an attribute is characterized by one value this method may set it.
1078   * Method *Get()* returns the value of an attribute if it is characterized by one value.
1079   * Method *Dump(Standard_OStream)* outputs debug information about a given attribute to a given stream.
1080   
1081 @subsection occt_ocaf_6_3 The choice between standard and custom attributes
1082
1083 When you start to design an application  based on OCAF, usually it is necessary to choose, which attribute will be used for allocation of data in the OCAF document: standard or newly-created?
1084
1085 It is possible to describe any model by means of standard OCAF attributes. 
1086   However, it is still a question if  this description will be  efficient in terms of memory and speed, and, at the same time, convenient to use.
1087   
1088   This depends on a particular model.  
1089    
1090   OCAF imposes the restriction that only one attribute type may be allocated to one label. 
1091   It is necessary to take into  account the design of the application data tree. 
1092   For example, if a label should  possess several double values, 
1093   it is necessary to distribute them through several child sub-labels or use an array of double values.   
1094    
1095   Let us consider several boundary implementations of the same model in OCAF tree and analyze the advantages and disadvantages of each approach.  
1096
1097   
1098 @subsubsection occt_ocaf_6_2_3 Comparison  and analysis of approaches
1099
1100   Below are described two different model implementations: 
1101   one is based on standard OCAF attributes and the other is based 
1102   on the creation of a new attribute possessing all data of the model.  
1103    
1104   A load is distributed through the shape. The measurements are taken at particular points defined by (x, y and z) co-ordinates. The load is represented as a projection onto X, Y and Z axes of the local co-ordinate system at each point of measurement. A matrix of transformation is needed 
1105   to convert the local co-ordinate system to the global one, but this is optional.   
1106    
1107   So, we have 15 double values at each point  of measurement. 
1108   If the number of such points is 100 000, for example, it means 
1109   that we have to store 1 500 000 double values in the OCAF document.  
1110    
1111   The first  approach consists in using standard OCAF attributes. 
1112   Besides, there are several  variants of how the standard attributes may be used:  
1113   * Allocation of all 1 500 000 double values as one array of double values attached to one label;
1114   * Allocation of values of one measure of load (15 values) as one array of double values and attachment of one point of measure to one label;
1115   * Allocation of each point of measure as an array of 3 double values attached to one label, the projection of load onto the local co-ordinate system  axes as another array of 3 double values attached to a sub-label, and the matrix of projection (9 values) as the third array also attached to a sub-label.  
1116   
1117   Certainly, other variants are also  possible.   
1118  
1119 @image html ocaf_tree_wp_image003.png "Allocation of all data as one  array of double values"
1120 @image latex ocaf_tree_wp_image003.png "Allocation of all data as one  array of double values"
1121  
1122   The first approach to allocation of all  data represented as one array of double values 
1123   saves initial memory and is easy to implement. 
1124   But access to the data is difficult because the values are stored in a flat array. 
1125   It will be necessary to implement a class with several methods giving access 
1126   to particular fields like the measurement points, loads and so  on.  
1127    
1128   If the values may be edited in the  application, 
1129   it means that the whole array will be backed-up on each edition. 
1130   The memory usage will increase very fast! 
1131   So, this approach may be considered only in case of non-editable data.  
1132    
1133   Let’s consider the allocation of data of  each measurement point per label (the second case). 
1134   In this case we create 100  000 labels -- one label for each measurement point 
1135   and attach an array of double  values to these labels:  
1136  
1137 @image html ocaf_tree_wp_image004.png "Allocation of data of each  measurement point as arrays of double values"
1138 @image latex ocaf_tree_wp_image004.png "Allocation of data of each  measurement point as arrays of double values"
1139  
1140   Now edition of data is safer as far as  memory usage is concerned. 
1141   Change of value for one measurement point (any  value: point co-ordinates, load, and so on) 
1142   backs-up only one small array of double values. 
1143   But this structure (tree) requires more memory space (additional  labels and attributes).  
1144    
1145   Besides, access to the values is still difficult and it is necessary 
1146   to have a class with methods of access to the  array fields.  
1147    
1148   The third case of allocation of data  through OCAF tree is represented below:  
1149
1150 @image html ocaf_tree_wp_image005.png "Allocation of data into separate arrays of double values"
1151 @image latex ocaf_tree_wp_image005.png "Allocation of data into separate arrays of double values"
1152
1153   In this case sub-labels are involved and we  can easily access the values of each measurement point, 
1154   load or matrix. We don’t need an interface class with methods of access to the data 
1155   (if it exists, it would help to use the data structure, but this is optional).  
1156
1157   On the one hand, this approach requires more  memory for allocation of the attributes (arrays of double values). 
1158   On the other  hand, it saves memory during the edition of data 
1159   by backing-up only the small array containing the modified data. 
1160   So, if the data is fully modifiable, this  approach is more preferable.  
1161
1162   Before making a conclusion, let’s consider the same model implemented through a newly created OCAF attribute.  
1163
1164   For example, we might allocate all data  belonging to one measurement point as one OCAF attribute. 
1165   In this case we  implement the third variant of using the standard attributes (see picture 3), 
1166   but we use less memory (because we use only one attribute instead of three):  
1167  
1168 @image html ocaf_tree_wp_image006.png "Allocation of data into newly  created OCAF attribute"
1169 @image latex ocaf_tree_wp_image006.png "Allocation of data into newly  created OCAF attribute"
1170
1171   The second variant of using standard OCAF attributes still has drawbacks: 
1172   when data is edited, OCAF backs-up all values  of the measurement point.   
1173    
1174   Let’s imagine that we have some  non-editable data. 
1175   It would be better for us to allocate this data separately from editable data. 
1176   Back-up will not affect non-editable data and memory will not increase so much during data edition.  
1177   
1178  @subsubsection occt_ocaf_6_2_4 Conclusion
1179
1180   When deciding which variant of data model implementation to choose, 
1181   it is necessary to take into account the application  response time, 
1182   memory allocation and memory usage in transactions.   
1183    
1184   Most of the models may be implemented using only standard OCAF attributes. 
1185   Some other models need special treatment and require implementation of new OCAF attributes.
1186
1187     
1188 @section occt_ocaf_7 Visualization Attributes
1189
1190 @subsection occt_ocaf_7_1 Overview
1191
1192 Standard visualization attributes implement the Application Interactive Services (see @ref occt_user_guides__visualization "Visualization User's Guide"). in the context of Open CASCADE Technology Application Framework. Standard visualization attributes are AISViewer and Presentation and belong to the TPrsStd package. 
1193
1194 @subsection occt_ocaf_7_2 Services provided
1195
1196 @subsubsection occt_ocaf_7_2_1 Defining an interactive viewer attribute
1197
1198 The class *TPrsStd_AISViewer* allows you to define an interactive viewer attribute. There may be only one such attribute per one data framework and it is always placed to the root label. So, it could be set or found by any label ("access label") of the data framework. Nevertheless the default architecture can be easily extended and the user can manage several Viewers per one framework by himself. 
1199
1200 To initialize the AIS viewer as in the example below, use method *Find*. 
1201
1202 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
1203 // "access" is any label of the data framework 
1204 Handle(TPrsStd_AISViewer) viewer = TPrsStd_AISViewer::Find(access) 
1205 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1206
1207 @subsection occt_ocaf_7_2_2 Defining a presentation attribute
1208
1209 The class *TPrsStd_AISPresentation* allows you to define the visual presentation of document labels contents. In addition to various visual fields (color, material, transparency, *isDisplayed*, etc.), this attribute contains its driver GUID. This GUID defines the functionality, which will update the presentation every time when needed. 
1210
1211 @subsubsection occt_ocaf_7_2_3 Creating your own driver
1212
1213 The abstract class TPrsStd_Driver allows you to define your own driver classes. Simply redefine the Update method in your new class, which will rebuild the presentation. 
1214
1215 If your driver is placed to the driver table with the unique driver GUID, then every time the viewer updates presentations with a GUID identical to your driver’s GUID, the *Update* method of your driver for these presentations must be called: 
1216 @image html /user_guides/ocaf/images/ocaf_image016.png
1217 @image latex /user_guides/ocaf/images/ocaf_image016.png
1218
1219 As usual, the GUID of a driver and the GUID of a displayed attribute are the same. 
1220
1221 @subsubsection occt_ocaf_7_2_4 Using a container for drivers
1222
1223 You frequently need a container for different presentation drivers. The class *TPrsStd_DriverTable* provides this service. You can add a driver to the table, see if one is successfully added, and fill it with standard drivers. 
1224
1225 To fill a driver table with standard drivers, first initialize the AIS viewer as in the example above, and then pass the return value of the method *InitStandardDrivers* to the driver table returned by the method *Get*. Then attach a *TNaming_NamedShape* to a label and set the named shape in the presentation attribute using the method *Set*. Then attach the presentation attribute to the named shape attribute, and the *AIS_InteractiveObject*, which the presentation attribute contains, will initialize its drivers for the named shape. This can be seen in the example below. 
1226
1227 **Example** 
1228 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
1229 DriverTable::Get() -> InitStandardDrivers(); 
1230 // next, attach your named shape to a label 
1231 TPrsStd_AISPresentation::Set(NS}; 
1232 // here, attach the AISPresentation to NS. 
1233 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1234
1235
1236 @section occt_ocaf_8 Function Services
1237
1238 Function services aggregate data necessary for regeneration of a model. The function mechanism -- available in the package *TFunction* -- provides links between functions and any execution algorithms, which take their arguments from the data framework, and write their results inside the same framework. 
1239
1240 When you edit any application model, you have to regenerate the model by propagating the modifications. Each propagation step calls various algorithms. To make these algorithms independent of your application model, you need to use function services. 
1241
1242 @image html /user_guides/ocaf/images/ocaf_image008.png "Document structure"
1243 @image latex /user_guides/ocaf/images/ocaf_image008.png "Document structure"
1244
1245 Take, for example, the case of a modeling sequence made up of a box with the application of a fillet on one of its edges. If you change the height of the box, the fillet will need to be regenerated as well. 
1246
1247 @subsection occt_ocaf_8_1 Finding functions, their owners and roots
1248
1249 The class *TFunction_Function* is an attribute, which stores a link to a function driver in the data framework. In the static table *TFunction_DriverTable* correspondence links between function attributes and drivers are stored. 
1250
1251 You can write your function attribute, a driver for such attribute, which updates the function result in accordance to a given map of changed labels, and set your driver with the GUID to the driver table. 
1252
1253 Then the solver algorithm of a data model can find the *Function* attribute on a corresponding label and call the *Execute* driver method to update the result of the function. 
1254
1255 @subsection occt_ocaf_8_2 Storing and accessing information about function status
1256
1257 For updating algorithm optimization, each function driver has access to the *TFunction_Logbook* object that is a container for a set of touched, impacted and valid labels. Using this object a driver gets to know which arguments of the function were modified. 
1258
1259 @subsection occt_ocaf_8_3 Propagating modifications
1260
1261 An application must implement its functions, function drivers and the common solver for parametric model creation. For example, check the following model: 
1262
1263 @image html /user_guides/ocaf/images/ocaf_image017.png
1264 @image latex /user_guides/ocaf/images/ocaf_image017.png
1265
1266 The procedure of its creation is as follows:
1267   * create a rectangular planar face *F* with height 100 and width 200;
1268   * create prism *P* using face *F* as a basis;
1269   * create fillet *L* at the edge of the prism;
1270   * change the width of *F* from 200 to 300;
1271   * the solver for the function of face *F* starts;
1272   * the solver detects that an argument of the face *F* function has been modified;
1273   * the solver calls the driver of the face *F* function for a  regeneration of the face;
1274   * the driver rebuilds face *F* and adds the label of the face *width* argument to the logbook as touched and the label of the function of face *F* as impacted;
1275
1276   * the solver detects the function of *P* -- it depends on the function of *F*;
1277   * the solver calls the driver of the prism *P* function;
1278   * the driver rebuilds prism *P* and adds the label of this prism to the logbook as  impacted;
1279   * the solver detects the function of *L*  -- it depends on the function of *P*;
1280   * the solver calls the *L* function driver;
1281   * the driver rebuilds fillet *L* and adds the label of the fillet to the logbook as impacted.
1282   
1283  @section occt_ocaf_8a Example of Function Mechanism Usage
1284  
1285  @subsection occt_ocaf_8a_1 Introduction
1286
1287   Let us describe the usage of the Function Mechanism of Open CASCADE Application Framework on a simple example.  
1288   This example represents a "nail" composed by a cone and two cylinders of different radius and height:  
1289
1290 @image html ocaf_functionmechanism_wp_image003.png "A nail"
1291 @image latex ocaf_functionmechanism_wp_image003.png " A nail"
1292
1293   These three objects (a cone and two cylinders) are  independent, 
1294   but the Function Mechanism makes them connected to each other and representing one object -- a nail.  
1295   The object "nail" has the following parameters:  
1296   
1297   * The position of the nail is defined by the apex point of the  cone. 
1298    The cylinders are built on the cone and therefore they depend on the position  of the cone. 
1299    In this way we define a dependency of the cylinders on the cone.  
1300   * The height of the nail is defined by the height of the cone.  
1301    Let’s consider that the long cylinder has 3 heights of the cone 
1302    and the header cylinder has a half of the height of the cone.  
1303   * The radius of the nail is defined by the radius of the cone. 
1304   The radius of the long cylinder coincides with this value. 
1305   Let’s consider that the  header cylinder has one and a half radiuses of the cone.  
1306   
1307   So, the cylinders depend on the cone and the cone  parameters define the size of the nail.  
1308   
1309   It means that re-positioning the cone (changing its  apex point) moves the nail, 
1310   the change of the radius of the cone produces a thinner or thicker nail, 
1311   and the change of the height of the cone shortens or  prolongates the nail.  
1312    It is suggested to examine the programming steps needed to create a 3D parametric model of the "nail".  
1313   
1314 @subsection occt_ocaf_8a_2 Step 1: Data Tree
1315
1316   The first step consists in model data allocation in the OCAF tree. 
1317   In other words, it is necessary to decide where to put the data.  
1318   
1319   In this case, the data can be organized into a simple tree 
1320   using references for definition of dependent parameters:  
1321
1322 * Nail
1323         * Cone
1324                 + Position (x,y,z)
1325                 + Radius 
1326                 + Height
1327         * Cylinder (stem)
1328                 + Position = "Cone" position translated for "Cone" height along Z;
1329                 + Radius = "Cone" radius;
1330                 + Height = "Cone" height multiplied by 3;
1331         * Cylinder (head)  
1332                 + Position = "Long cylinder" position translated for "Long cylinder" height along Z;
1333                 + Radius = "Long cylinder" radius multiplied by 1.5;
1334                 + Height = "Cone" height divided by 2. 
1335
1336   The "nail" object has three sub-leaves in the tree:  the cone and two cylinders.   
1337   
1338   The cone object is independent.  
1339   
1340   The long cylinder representing a "stem" of the nail  refers to the corresponding parameters 
1341   of the cone to define its own data  (position, radius and height). It means that the long cylinder depends on the  cone.  
1342   
1343   The parameters of the head cylinder may be expressed  through the cone parameters 
1344   only or through the cone and the long cylinder  parameters. 
1345   It is suggested to express the position and the radius of the head cylinder 
1346   through the position and the radius of the long cylinder, and the height 
1347   of the head cylinder through the height of the cone. 
1348   It means that the head cylinder depends on the cone and the long cylinder.  
1349
1350 @subsection occt_ocaf_8a_3 Step 2: Interfaces
1351
1352   The interfaces of the data model are responsible for dynamic creation 
1353   of the data tree of the represented at the previous step, data  modification and deletion.  
1354   
1355   The interface called *INail*  should contain the methods for creation 
1356   of the data tree for the nail, setting  and getting of its parameters, computation, visualization and removal.  
1357
1358 @subsubsection occt_ocaf_8a_3_1 Creation of the nail
1359
1360   This method of the interface creates a data tree for the nail  at a given leaf of OCAF data tree.  
1361   
1362   It creates three sub-leaves for the cone and two cylinders  and allocates the necessary data (references at the sub-leaves of the long and the  head cylinders).  
1363   
1364   It sets the default values of position, radius and height of  the nail.  
1365   
1366   The nail has the following user parameters:  
1367   * The position -- coincides with the position of the cone  
1368   * The radius of the stem part of the nail -- coincides with the radius  of the cone  
1369   * The height of the nail -- a sum of heights of the cone and both  cylinders  
1370   
1371   The values of the position and the radius of the  nail are defined for the cone object data. 
1372   The height of the cone is recomputed  as 2 * heights of nail and divided by 9.  
1373
1374 @subsubsection occt_ocaf_8a_3_2 Computation
1375
1376   The Function Mechanism is responsible for re-computation of  the nail. 
1377   It will be described in detail later in this document.  
1378   
1379   A data leaf consists of the reference  to the location of the  real data 
1380   and a real value defining a coefficient of multiplication of the  referenced data.  
1381   
1382   For example, the height of the long cylinder is defined as a  reference to the height of the cone 
1383   with coefficient 3. The data  leaf of the height of the long cylinder 
1384   should contain two attributes: a  reference to the height of cone and a real value equal to 3.  
1385
1386 @subsubsection occt_ocaf_8a_3_3 Visualization
1387
1388  The shape resulting of the nail function can be displayed using the standard OCAF visualization mechanism.  
1389
1390 @subsubsection occt_ocaf_8a_3_4 Removal of the nail
1391
1392 To automatically erase the nail from the viewer and the data  tree it is enough to clean the nail leaf from attributes.  
1393
1394 @subsection occt_ocaf_8a_4 Step 3: Functions
1395
1396   The nail is defined by four functions: the cone, the two cylinders  and the nail function.  
1397   The function of the cone is independent. The functions of the cylinders depend on the cone function. 
1398   The nail function depends on the  results of all functions:  
1399
1400 @image html ocaf_functionmechanism_wp_image005.png "A graph of dependencies between functions"
1401 @image latex ocaf_functionmechanism_wp_image005.png "A graph of dependencies between functions"
1402
1403   Computation of the model starts with the cone function, then the long cylinder, 
1404   after that the header cylinder and, finally, the result is generated  by the nail function at the end of function chain.  
1405
1406   The Function Mechanism of Open CASCADE Technology creates this  graph of dependencies 
1407   and allows iterating it following the dependencies. 
1408   The  only thing the Function Mechanism requires from its user 
1409   is the implementation  of pure virtual methods of *TFunction_Driver*:  
1410   
1411   * <i>\::Arguments()</i> -- returns a list of arguments for the  function  
1412   * <i>\::Results()</i> -- returns a list of results of the function  
1413   
1414   These methods give the Function Mechanism the information on the location of arguments 
1415   and results of the function and allow building a  graph of functions. 
1416   The class *TFunction_Iterator* iterates the functions of the graph in the execution order.  
1417   
1418   The pure virtual method *TFunction_Driver::Execute()* calculating the function should be overridden.  
1419   
1420   The method <i>\::MustExecute()</i> calls the method <i>\::Arguments()</i>  of the function driver 
1421   and ideally this information (knowledge of modification  of arguments of the function) is enough
1422   to make a decision whether the function  should be executed or not. Therefore, this method usually shouldn’t be  overridden.  
1423
1424   The cone and cylinder functions differ only in geometrical construction algorithms. 
1425   Other parameters are the same (position, radius and height).  
1426   
1427   It means that it is possible to create a base class -- function driver for the three functions, 
1428   and two descendant classes producing:  a cone or a cylinder.  
1429   
1430   For the base function driver the methods <i>\::Arguments()</i>  and <i>\::Results()</i> will be overridden. 
1431   Two descendant function drivers responsible for creation of a cone and a cylinder will override only the method  <i>\::Execute()</i>. 
1432   
1433   The method <i>\::Arguments()</i> of the function driver of the nail returns the results of the functions located under it in the tree of leaves.   The method <i>\::Execute()</i> just collects the  results of the functions and makes one shape -- a nail. 
1434   
1435   This way the data model using the Function Mechanism is  ready for usage.   Do not forget to introduce the function drivers for a function  driver table with the help of *TFunction_DriverTable* class.
1436
1437 @subsection occt_ocaf_8a_5 Example 1: iteration and execution of functions. 
1438
1439   This is an example of the code for iteration and execution of functions.  
1440
1441 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
1442
1443     // The scope of functions is  defined.  
1444     Handle(TFunction_Scope) scope = TFunction_Scope::Set( anyLabel );  
1445      
1446     // The information on  modifications in the model is received.  
1447     TFunction_Logbook&amp; log = scope-GetLogbook();  
1448      
1449     // The iterator is iInitialized by  the scope of functions.  
1450     TFunction_Iterator iterator( anyLabel );  
1451     Iterator.SetUsageOfExecutionOrder( true );  
1452      
1453     // The function is iterated,  its  dependency is checked on the modified data and  executed if necessary.  
1454     for (; iterator.more(); iterator.Next())  
1455     {  
1456       // The function iterator may return a list of  current functions for execution.  
1457       // It might be useful for multi-threaded execution  of functions.  
1458       const  TDF_LabelList&amp; currentFunctions = iterator.Current();  
1459        
1460       //The list of current functions is iterated.  
1461       TDF_ListIteratorOfLabelList  currentterator( currentFucntions );  
1462       for (;  currentIterator.More(); currentIterator.Next())  
1463       {  
1464         //  An interface for the function is created.  
1465         TFunction_IFunction  interface( currentIterator.Value() );  
1466      
1467         //  The function driver is retrieved.  
1468         Handle(TFunction_Driver)  driver = interface.GetDriver();  
1469      
1470         //  The dependency of the function on the  modified data is checked.  
1471         If  (driver-MustExecute( log ))  
1472         {  
1473           // The function is executed.  
1474           int  ret = driver-Execute( log );  
1475           if ( ret ) 
1476             return  false;  
1477         } // end if check on modification  
1478       } // end of iteration of current functions  
1479     } // end of iteration of  functions.
1480
1481 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1482
1483 @subsection occt_ocaf_8a_6 Example 2: Cylinder function driver
1484
1485   This is an example of the code for a cylinder function driver. To make the things clearer, the methods <i>\::Arguments()</i>  and <i>\::Results()</i>  from the base class are also mentioned.   
1486
1487 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
1488
1489     // A virtual method  ::Arguments() returns a list of arguments of the function.  
1490     CylinderDriver::Arguments( TDF_LabelList&amp; args )  
1491     {  
1492       // The direct arguments, located at sub-leaves of  the fucntion, are collected (see picture 2).  
1493       TDF_ChildIterator  cIterator( Label(), false );  
1494       for (;  cIterator.More(); cIterator.Next() )  
1495       {  
1496         // Direct argument.  
1497         TDF_Label  sublabel = cIterator.Value();  
1498         Args.Append(  sublabel );  
1499
1500         // The references to the external data are  checked.  
1501         Handle(TDF_Reference)  ref;  
1502         If (  sublabel.FindAttribute( TDF_Reference::GetID(), ref ) )  
1503         {  
1504           args.Append(  ref-Get() );  
1505         }
1506     }
1507      
1508     // A virtual method ::Results()  returns a list of result leaves.  
1509     CylinderDriver::Results( TDF_LabelList&amp; res )  
1510     {  
1511       // The result is kept at the function  label.  
1512       Res.Append(  Label() );  
1513     }
1514      
1515     // Execution of the function  driver.  
1516     Int CylinderDriver::Execute( TFunction_Logbook&amp; log )  
1517     {  
1518       // Position of the cylinder - position of the first  function (cone)   
1519       //is  elevated along Z for height values of all  previous functions.  
1520       gp_Ax2 axes = …. // out of the scope of this guide.  
1521       // The radius value is retrieved.  
1522       // It is located at second child sub-leaf (see the  picture 2).  
1523       TDF_Label radiusLabel  = Label().FindChild( 2 );  
1524        
1525       // The multiplicator of the radius ()is retrieved.  
1526       Handle(TDataStd_Real)  radiusValue;  
1527       radiusLabel.FindAttribute(  TDataStd_Real::GetID(), radiusValue);  
1528        
1529       // The reference to the radius is retrieved.  
1530       Handle(TDF_Reference)  refRadius;  
1531       RadiusLabel.FindAttribute(  TDF_Reference::GetID(), refRadius );  
1532        
1533       // The radius value is calculated.  
1534       double radius = 0.0;
1535       
1536       if (  refRadius.IsNull() )
1537       {
1538         radius  = radiusValue-Get();  
1539       }
1540       else  
1541       {  
1542         // The referenced radius value is  retrieved.   
1543         Handle(TDataStd_Real)  referencedRadiusValue;  
1544         RefRadius-Get().FindAttribute(TDataStd_Real::GetID()  ,referencedRadiusValue );  
1545         radius  = referencedRadiusValue-Get() * radiusValue-Get();  
1546       }  
1547        
1548       // The height value is retrieved.  
1549       double height = … // similar code to taking the radius value.  
1550        
1551       // The cylinder is created.  
1552       TopoDS_Shape cylinder  = BRepPrimAPI_MakeCylinder(axes, radius, height);  
1553        
1554       // The result (cylinder) is set  
1555       TNaming_Builder  builder( Label() );  
1556       Builder.Generated(  cylinder );  
1557        
1558       // The modification of the result leaf is saved in  the log.  
1559       log.SetImpacted(  Label() );  
1560        
1561       return 0;
1562     }
1563 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1564  
1565   
1566
1567 @section occt_ocaf_9 XML Support
1568
1569 Writing and reading XML files in OCCT is provided by LDOM package, which constitutes an integral part
1570 of XML OCAF persistence, which is the optional component provided on top of Open CASCADE Technology.
1571
1572 The Light DOM (LDOM) package contains classes maintaining a data structure whose main principles conform to W3C DOM Level 1 Recommendations. The purpose of these classes as required by XML OCAF persistence schema is to: 
1573 * Maintain a tree structure of objects in memory representing the XML document. The root of the structure is an object of the *LDOM_Document* type. This object contains all the data corresponding to a given XML document and contains one object of the *LDOM_Element* type named "document element". The document element contains other *LDOM_Element* objects forming a tree. Other types of nodes: *LDOM_Attr, LDOM_Text, LDOM_Comment* and *LDOM_CDATASection* -- represent the corresponding XML types and serve as branches of the tree of elements. 
1574 * Provide class *LDOM_Parser* to read XML files and convert them to *LDOM_Document* objects.
1575 * Provide class *LDOM_XmlWriter* to convert *LDOM_Document* to a character stream in XML format and store it in file. 
1576
1577 This package covers the functionality provided by numerous products known as "DOM parsers". Unlike most of them, LDOM was specifically developed to meet the following requirements: 
1578 * To minimize the virtual memory allocated by DOM data structures. In average, the amount of memory of LDOM is the same as the XML file size (UTF-8). 
1579 * To minimize the time required for parsing and formatting XML, as well as for access to DOM data structures. 
1580
1581 Both these requirements are important when XML files are processed by applications if these files are relatively large (occupying megabytes and even hundreds of megabytes). To meet the requirements, some limitations were imposed on the DOM Level 1 specification; these limitations are insignificant in applications like OCAF. Some of these limitations can be overridden in the course of future developments. The main limitations are:
1582 * No Unicode support as well as various other encodings; only ASCII strings are used in DOM/XML. Note: There is a data type *TCollection_ExtendedString* for wide character data. This type is supported by *LDOM_String* as a sequence of numbers. 
1583 * Some superfluous methods are deleted: *getPreviousSibling, getParentNode,* etc. 
1584 * No resolution of XML Entities of any kind 
1585 * No support for DTD: the parser just checks for observance of general XML rules and never validates documents. 
1586 * Only 5 available types of DOM nodes: *LDOM_Element, LDOM_Attr, LDOM_Text, LDOM_Comment* and *LDOM_CDATASection*. 
1587 * No support of Namespaces; prefixed names are used instead of qualified names. 
1588 * No support of the interface *DOMException* (no exception when attempting to remove a non-existing node). 
1589
1590 LDOM is dependent on Kernel OCCT classes only. Therefore, it can be used outside OCAF persistence in various algorithms where DOM/XML support may be required. 
1591
1592 @subsection occt_ocaf_9_1 Document Drivers
1593
1594 The drivers for document storage and retrieval  manage  conversion between a transient OCAF
1595 Document in memory and its persistent reflection in a container (disk, memory, network). For XML Persistence, they are defined in the package XmlDrivers. 
1596
1597 The main methods (entry points) of these drivers are: 
1598 * *Write()* -- for a storage driver; 
1599 * *Read()* -- for a retrieval driver. 
1600
1601 The most common case (which is implemented in XML Persistence) is writing/reading document to/from a regular OS file. Such conversion is performed in two steps: 
1602
1603 First it is necessary to convert the transient document into another form (called persistent), suitable for writing into a file, and vice versa. 
1604 In XML Persistence LDOM_Document is used as the persistent form of an OCAF Document and the DOM_Nodes are the persistent objects. 
1605 An OCAF Document is a tree of labels with attributes. Its transformation into a persistent form can be functionally divided into two parts: 
1606 * Conversion of the labels structure, which is performed by the method XmlMDF::FromTo()
1607 * Conversion of the attributes and their underlying objects, which is performed by the corresponding attribute drivers (one driver per attribute type). 
1608
1609 The driver for each attribute is selected from a table of drivers, either by attribute
1610 type (on storage) or by the name of the corresponding DOM_Element (on retrieval).
1611 The table of drivers is created by by methods *XmlDrivers_DocumentStorageDriver::AttributeDrivers()*
1612 and *XmlDrivers_DocumentRetrievalDriver::AttributeDrivers()*. 
1613
1614 Then the persistent document is written into a file (or read from a file). 
1615 In standard persistence Storage and FSD packages contain classes for writing/reading the persistent document into a file. In XML persistence *LDOMParser* and *LDOM_XmlWriter* are used instead.
1616
1617 Usually, the library containing document storage and retrieval drivers is loaded at run time by a plugin mechanism. To support this in XML Persistence, there is a plugin *XmlPlugin* and a *Factory()* method in the *XmlDrivers* package. This method compares passed GUIDs with known GUIDs and returns the corresponding driver or generates an exception if the GUID is unknown. 
1618
1619 The application defines which GUID is needed for document storage or retrieval and in which library it should be found. This depends on document format and application resources. Resources for XML Persistence and also for standard persistence are found in the StdResource unit. They are written for the XmlOcaf document format. 
1620
1621 @subsection occt_ocaf_9_2 Attribute Drivers
1622
1623 There is one attribute driver for XML persistence for each transient attribute from a set of standard OCAF attributes, with the exception of attribute types, which are never stored (pure transient). Standard OCAF attributes are collected in six packages, and their drivers also follow this distribution. Driver for attribute <i>T*_*</i> is called <i>XmlM*_*</i>. Conversion between transient and persistent form of attribute is performed by two methods *Paste()* of attribute driver. 
1624
1625 *XmlMDF_ADriver* is the root class for all attribute drivers.
1626
1627 At the beginning of storage/retrieval process, one instance of each attribute driver is created and appended to driver table implemented as *XmlMDF_ADriverTable*.  During OCAF Data storage, attribute drivers are retrieved from the driver table by the type of attribute. In the retrieval step, a data map is created linking names of *DOM_Elements* and attribute drivers, and then attribute drivers are sought in this map by *DOM_Element* qualified tag names. 
1628
1629 Every transient attribute is saved as a *DOM_Element* (root element of OCAF attribute) with attributes and possibly sub-nodes. The name of the root element can be defined in the attribute driver as a string passed to the base class constructor. The default is the attribute type name. Similarly, namespace prefixes for each attribute can be set. There is no default value, but it is possible to pass NULL or an empty string to store attributes without namespace prefixes. 
1630
1631 The basic class *XmlMDF_ADriver* supports errors reporting via the method *WriteMessage(const TCollection_ExtendedString&)*. It sends a message string to its message driver which is initialized in the constructor with a *Handle(CDM_MessageDriver)* passed from the application by Document Storage/Retrieval Driver. 
1632
1633 @subsection occt_ocaf_9_3 XML Document Structure
1634
1635 Every XML Document has one root element, which may have attributes and contain other nodes. In OCAF XML Documents the root element is named "document" and has attribute "format" with the name of the OCAF Schema used to generate the file. The standard XML format is "XmlOcaf". The following elements are sub-elements of \<document\> and should be unique entries as its sub-elements, in a specific order. The order is:
1636 * **Element info** -- contains strings identifying the format version and other parameters of the OCAF XML document. Normally, data under the element is used by persistence algorithms to correctly retrieve and initialize an OCAF document. The data also includes a copyright string. 
1637 * **Element comments** -- consists of an unlimited number of \<comment\> sub-elements containing necessary comment strings. 
1638 * **Element label** -- the root label of the document data structure, with the XML attribute "tag" equal to 0. It contains all the OCAF data (labels, attributes) as tree of XML elements. Every sub-label is identified by a tag (positive integer) defining a unique key for all sub-labels of a label. Every label can contain any number of elements representing OCAF attributes (see OCAF Attributes Representation below).
1639 * **Element shapes** -- contains geometrical and topological entities in BRep format. These entities being referenced by OCAF attributes written under the element \<label\>. This element is empty if there are no shapes in the document. It is only output if attribute driver *XmlMNaming_NamedShapeDriver* has been added to drivers table by the *DocumentStorageDriver*.
1640
1641 ### OCAF Attributes Representation 
1642
1643 In XML documents, OCAF attributes are elements whose name identifies the OCAF attribute type. These elements may have a simple (string or number) or complex (sub-elements) structure, depending on the architecture of OCAF attribute. Every XML type for OCAF attribute possesses a unique positive integer "id" XML attribute identifying the OCAF attribute throughout the document. To ensure "id" uniqueness, the attribute name "id" is reserved and is only used to indicate and identify elements which may be referenced from other parts of the OCAF XML document. 
1644 For every standard OCAF attribute, its XML name matches the name of a C++ class in Transient data model. Generally, the XML name of OCAF attribute can be specified in the corresponding attribute driver. 
1645 XML types for OCAF attributes are declared with XML W3C Schema in a few XSD files where OCAF attributes are grouped by the package where they are defined. 
1646
1647 ### Example of resulting XML file 
1648
1649 The following example is a sample text from an XML file obtained by storing an OCAF document with two labels (0: and 0:2) and two attributes -- *TDataStd_Name* (on label 0:) and *TNaming_NamedShape* (on label 0:2). The \<shapes\> section contents are replaced by an ellipsis. 
1650
1651 ~~~~
1652 <?xml version="1.0" encoding="UTF-8"?> 
1653 <document format="XmlOcaf" xmlns="http://www.opencascade.org/OCAF/XML" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
1654 xsi:schemaLocation="http://www.opencascade.org/OCAF/XML http://www.opencascade.org/OCAF/XML/XmlOcaf.xsd">
1655
1656 <info date="2001-10-04" schemav="0" objnb="3"> 
1657 <iitem>Copyright: Open Cascade, 2001</iitem> 
1658 <iitem>STORAGE_VERSION: PCDM_ReadWriter_1</iitem> 
1659 <iitem>REFERENCE_COUNTER: 0</iitem> 
1660 <iitem>MODIFICATION_COUNTER: 1</iitem> 
1661 </info> 
1662 <comments/> 
1663 <label tag="0"> 
1664 <TDataStd_Name id="1">Document_1</TDataStd_Name> 
1665 <label tag="2"> 
1666 <TNaming_NamedShape id="2" evolution="primitive"> 
1667 <olds/> 
1668 <news> 
1669 <shape tshape="+34" index="1"/> 
1670 </news> 
1671 </TNaming_NamedShape> 
1672 </label> 
1673 </label> 
1674 \<shapes\> 
1675 ... 
1676 </shapes> 
1677 </document> 
1678
1679 ~~~~
1680
1681 @subsection occt_ocaf_9_4 XML Schema
1682
1683 The XML Schema defines the class of a document. 
1684
1685 The full structure of OCAF XML documents is described as a set of XML W3C Schema files with definitions of all XML element types. The definitions provided cannot be overridden. If any application defines new persistence schemas, it can use all the definitions from the present XSD files but if it creates new or redefines existing types, the definition must be done under other namespace(s). 
1686
1687 There are other ways to declare XML data, different from W3C Schema, and it should be possible to use them to the extent of their capabilities of expressing the particular structure and constraints of our XML data model. However, it must be noted that the W3C Schema is the primary format for declarations and as such, it is the format supported for future improvements of Open CASCADE Technology, including the development of specific applications using OCAF XML persistence. 
1688
1689 The Schema files (XSD) are intended for two purposes: 
1690 * documenting the data format of files generated by OCAF; 
1691 * validation of documents when they are used by external (non-OCAF) applications, e.g., to generate reports. 
1692
1693 The Schema definitions are not used by OCAF XML Persistence algorithms when saving and restoring XML documents. There are internal checks to ensure validity when processing every type of data. 
1694
1695 ### Management of Namespaces 
1696
1697 Both the XML format and the XML OCAF persistence code are extensible in the sense that every new development can reuse everything that has been created in previous projects. For the XML format, this extensibility is supported by assigning names of XML objects (elements) to different XML Namespaces. Hence, XML elements defined in different projects (in different persistence libraries) can easily be combined into the same XML documents. An example is the XCAF XML persistence built as an extension to the Standard OCAF XML persistence <i>[File XmlXcaf.xsd]</i>. For the correct management of Namespaces it is necessary to: 
1698 * Define *targetNamespace* in the new XSD file describing the format. 
1699 * Declare (in *XSD* files) all elements and types in the targetNamespace to appear without a namespace prefix; all other elements and types use the appropriate prefix (such as "ocaf:"). 
1700 * Add (in the new *DocumentStorageDriver*) the *targetNamespace* accompanied with its prefix, using method *XmlDrivers_DocumentStorageDriver::AddNamespace*. The same is done for all namespaces objects which are used by the new persistence, with the exception of the "ocaf" namespace. 
1701 * Pass (in every OCAF attribute driver) the namespace prefix of the *targetNamespace* to the constructor of *XmlMDF_ADriver*. 
1702
1703 @section occt_ocaf_9a Persistent  Data Storage
1704
1705 @subsection occt_ocaf_9a_1 Introduction
1706
1707 In OCAF, persistence, that is, the mechanism used to  save a document in a file, is based on an explicit formal description of the  data saved.  
1708  
1709 When you open a document, the application reads the corresponding file and first creates a memory representation of it. This representation is then converted to the application data model —  the OCAF-based data structure the application operates on. The file's memory representation  consists of objects defined by classes known as persistent. 
1710    
1711 OCAF includes a ready-to-use schema suitable for most  applications. 
1712 However, it can be extended if needed. 
1713   
1714 Applications using compound documents extensively (saving data in many files linked together) should implement data management services. It is out the scope of OCAF to provide functions such as:
1715 * Version and configuration management of compound documents;
1716 * Querying a referenced document for its referencing documents.
1717
1718 In order to ease the delegation of document management to a data management application, OCAF encapsulates the file management functions in a driver (the meta-data driver). You have to implement this driver for your application to communicate with the data management system of your choice.
1719
1720  
1721 @subsection occt_ocaf_9a_2 Schemes of Persistence
1722
1723 There are three schemes of persistence, which you can use to store and retrieve OCAF data (documents):
1724
1725   * <i> Standard</i> persistence schema, compatible with previous OCAF applications. This schema is deprecated and supports only reading of standard attributes (no writing).
1726   * <i> XmlOcaf</i> persistence, allowing the storage of all OCAF data in XML form
1727   * <i> BinOcaf</i> persistence, allowing the storage of all OCAF data in binary format form
1728
1729
1730 In an OCAF application you can use any persistence schema or
1731 even all three of them. The choice is made depending on the *Format* string of stored OCAF documents
1732 or automatically by the file header data -- on retrieval.
1733   
1734 @section occt_ocaf_10 GLOSSARY
1735
1736 * **Application** -- a document container holding all documents containing all application data. 
1737 * **Application data** -- the data produced by an application, as opposed to data referring to it. 
1738 * **Associativity of data** -- the ability to propagate modifications made to one document to other documents, which refer to such document. Modification propagation is: 
1739   * unidirectional, that is, from the referenced to the referencing document(s), or
1740   * bi-directional, from the referencing to the referenced document and vice-versa.
1741 * **Attribute** -- a container for application data. An attribute is attached to a label in the hierarchy of the data framework. 
1742 * **Child** -- a label created from another label, which by definition, is the father label. 
1743 * **Compound document** -- a set of interdependent documents, linked to each other by means of external references. These references provide the associativity of data. 
1744 * **Data framework** -- a tree-like data structure which in OCAF, is a tree of labels with data attached to them in the form of attributes. This tree of labels is accessible through the services of the *TDocStd_Document* class. 
1745 * **Document** -- a container for a data framework which grants access to the data, and is, in its turn, contained  by an application. A document also allows you to: 
1746         * Manage modifications, providing Undo and Redo functions 
1747         * Manage command transactions 
1748         * Update external links 
1749         * Manage save and restore options 
1750         * Store the names of software extensions. 
1751 * **Driver** -- an abstract class, which defines the communications protocol with a system. 
1752 * **Entry** -- an ASCII character string containing the tag list of a label. For example:
1753 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
1754 0:3:24:7:2:7 
1755 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1756
1757 * **External links** -- references from one data structure to another data structure in another document. 
1758 To store these references properly, a label must also contain an external link attribute. 
1759 * **Father** -- a label, from which other labels have been created. The other labels are, by definition, the children of this label. 
1760 * **Framework** -- a group of co-operating classes which enable a design to be re-used for a given category of problem. The framework guides the architecture of the application by breaking it up into abstract  classes, each of which has different responsibilities and collaborates in a predefined way. Application developer creates a specialized framework by: 
1761   * defining new classes which inherit from these abstract classes
1762   * composing framework class instances
1763   * implementing the services required by the framework.
1764
1765 In C++, the application behavior is implemented in virtual functions redefined in these derived classes. This is known as overriding. 
1766
1767 * **GUID** -- Global Universal ID. A string of 37 characters intended to uniquely identify an object. For example:
1768 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
1769 2a96b602-ec8b-11d0-bee7-080009dc3333 
1770 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1771
1772 * **Label** -- a point in the data framework, which allows data to be attached to it by means of attributes. It has a name in the form of an entry, which identifies its place in the data framework. 
1773 * **Modified label** -- containing attributes whose data has been modified. 
1774 * **Reference key** -- an invariant reference, which may refer to any type of data used in an application. In its transient form, it is a label in the data framework, and the data is attached to it in the form of attributes. In its persistent form, it is an entry of the label. It allows an application to recover any entity in the current session or in a previous session. 
1775 * **Resource file** -- a file containing a list of each document’s schema name and the storage and retrieval plug-ins for that document. 
1776 * **Root** -- the starting point of the data framework. This point is the top label in the framework. It is represented by the [0] entry and is created at the same time with the document you are working on. 
1777 * **Scope** -- the set of all the attributes and labels which depend on a given label. 
1778 * **Tag list** -- a list of integers, which identify the place of a label in the data framework.  This list is displayed in an entry. 
1779 * **Topological naming** -- systematic referencing of topological entities so that these entities can still be identified after the models they belong to have gone through several steps in modeling. In other words, topological naming allows you to track entities through the steps in the modeling process. This referencing is needed when a model is edited and regenerated, and can be seen as a mapping of labels and name attributes of the entities in the old version of a model to those of the corresponding entities in its new version. Note that if the topology of a model changes during the modeling, this mapping may not fully coincide. A Boolean operation, for example, may split edges. 
1780 * **Topological tracking** -- following a topological entity in a model through the steps taken to edit and regenerate that model. 
1781 * **Valid label** -- in a data framework, this is a label, which is already recomputed in the scope of regeneration sequence and includes the label containing a feature which is to be recalculated. Consider the case of a box to which you first add a fillet, then a protrusion feature. For recalculation purposes, only valid labels of each construction stage are used. In recalculating a fillet, they are only those of the box and the fillet, not the protrusion feature which was added afterwards.   
1782
1783 @section occt_ocaf_11 Samples
1784
1785 @subsection occt_ocaf_11_a Getting  Started
1786
1787   At the beginning of your development, you first define  an application class by inheriting from the Application abstract class. 
1788   You only have to create and determine the resources of the application 
1789   for specifying the format of your documents (you generally use the standard one)  and their file extension.  
1790    
1791   Then, you design the application data model by  organizing attributes you choose among those provided with OCAF. 
1792   You can specialize these attributes using the User attribute. For example, if you need  a reflection coefficient, 
1793   you aggregate a User attribute identified as a  reflection coefficient 
1794   with a Real attribute containing the value of the  coefficient (as such, you don't define a new class).  
1795    
1796   If you need application specific data not provided with  OCAF, for example, 
1797   to incorporate a finite element model in the data structure,  
1798   you define a new attribute class containing the mesh, 
1799   and you include its persistent homologue in a new file format.  
1800    
1801   Once you have implemented the commands which create and modify the data structure 
1802   according to your specification, OCAF provides you, without any additional programming:  
1803    
1804   * Persistent  reference to any data, including geometric elements — several documents can be  linked with such reference;
1805   * Document-View  association;
1806   * Ready-to-use  functions such as :
1807     * Undo-redo;  
1808     * Save and open application data.  
1809  
1810   Finally, you  develop the application's graphical user interface using the toolkit of your  choice, for example:
1811   * KDE Qt or  GNOME GTK+ on Linux;
1812   * Microsoft  Foundation Classes (MFC) on Windows Motif on Sun;
1813   * Other  commercial products such as Ilog Views.
1814  
1815   You can also implement the user interface in the Java language using 
1816   the Swing-based Java Application Desktop component (JAD)  provided with OCAF.  
1817   
1818 @subsection occt_ocaf_11_b An example of OCAF usage
1819
1820 To create a useful OCAF-based application, it is necessary to redefine two deferred methods: <i> Formats</i> and <i> ResourcesName</i>
1821
1822 In the <i> Formats </i> method, add the format of the documents, which need to be read by the application and may have been built in other applications.
1823
1824 For example:
1825
1826 ~~~~
1827     void myApplication::Formats(TColStd_SequenceOfExtendedString& Formats)
1828     {
1829       Formats.Append(TCollection_ExtendedString ("OCAF-myApplication"));
1830     }
1831 ~~~~
1832
1833 In the <i> ResourcesName</i> method, you only define the name of the resource file. This
1834 file contains several definitions for the saving and opening mechanisms associated
1835 with each format and calling of the plug-in file.
1836
1837 ~~~~
1838     Standard_CString myApplication::ResourcesName()
1839     {
1840       return Standard_CString ("Resources");
1841     }
1842 ~~~~
1843
1844 To obtain the saving and opening mechanisms, it is necessary to set two environment variables: <i> CSF_PluginDefaults</i>, which defines the path of the plug-in file, and <i> CSF_ResourcesDefault</i>, which defines the resource file:
1845
1846 ~~~~
1847     SetEnvironmentVariable ( "CSF_ResourcesDefaults",myDirectory);
1848     SetEnvironmentVariable ( "CSF_PluginDefaults",myDirectory);
1849 ~~~~
1850
1851 The plugin and the resource files of the application will be located in <i> myDirector</i>.
1852 The name of the plugin file must be <i>Plugin</i>.
1853
1854 ### Resource File
1855
1856 The resource file describes the documents (type and extension) and 
1857 the type of data that the application can manipulate 
1858 by identifying the storage and retrieval drivers appropriate for this data.
1859
1860 Each driver is unique and identified by a GUID generated, for example, with the <i> uuidgen </i> tool in Windows.
1861
1862 Five drivers are required to use all standard attributes provided within OCAF:
1863
1864   * the schema driver (ad696002-5b34-11d1-b5ba-00a0c9064368)
1865   * the document storage driver (ad696000-5b34-11d1-b5ba-00a0c9064368)
1866   * the document retrieval driver (ad696001-5b34-11d1-b5ba-00a0c9064368)
1867   * the attribute storage driver (47b0b826-d931-11d1-b5da-00a0c9064368)
1868   * the attribute retrieval driver (47b0b827-d931-11d1-b5da-00a0c9064368)
1869
1870 These drivers are provided as plug-ins and are located in the <i> PappStdPlugin</i> library.
1871
1872
1873 For example, this is a resource file, which declares a new model document OCAF-MyApplication:
1874
1875 ~~~~
1876 formatlist:OCAF-MyApplication
1877 OCAF-MyApplication.Description: MyApplication Document Version 1.0
1878 OCAF-MyApplication.FileExtension: sta
1879 OCAF-MyApplication.StoragePlugin: ad696000-5b34-11d1-b5ba-00a0c9064368
1880 OCAF-MyApplication.RetrievalPlugin: ad696001-5b34-11d1-b5ba-00a0c9064368
1881 OCAF-MyApplicationSchema: ad696002-5b34-11d1-b5ba-00a0c9064368
1882 OCAF-MyApplication.AttributeStoragePlugin: 47b0b826-d931-11d1-b5da-00a0c9064368
1883 OCAF-MyApplication.AttributeRetrievalPlugin: 47b0b827-d931-11d1-b5da-00a0c9064368
1884 ~~~~
1885  
1886   
1887 ### Plugin File
1888
1889 The plugin file describes the list of required plug-ins to run the application and the
1890 libraries in which plug-ins are located.
1891
1892 You need at least the <i> FWOSPlugin</i> and the plug-in drivers to run an OCAF application.
1893
1894 The syntax of each item is <i> Identification.Location Library_Name, </i> where:
1895 * Identification is GUID.
1896 * Location defines the location of the Identification (where its definition is found).
1897 * Library_Name is the name (and path to) the library, where the plug-in is located.
1898
1899 For example, this is a Plugin file:
1900
1901 ~~~~
1902 a148e300-5740-11d1-a904-080036aaa103.Location: FWOSPlugin
1903 ! base document drivers plugin
1904 ad696000-5b34-11d1-b5ba-00a0c9064368.Location: PAppStdPlugin
1905 ad696001-5b34-11d1-b5ba-00a0c9064368.Location: PAppStdPlugin
1906 ad696002-5b34-11d1-b5ba-00a0c9064368.Location: PAppStdPlugin
1907 47b0b826-d931-11d1-b5da-00a0c9064368.Location: PAppStdPlugin
1908 47b0b827-d931-11d1-b5da-00a0c9064368.Location: PAppStdPlugin
1909 ~~~~
1910  
1911
1912
1913 @subsection occt_ocaf_11_1 Implementation of Attribute Transformation in a HXX file
1914
1915 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
1916 \#include <TDF_Attribute.hxx>
1917
1918 \#include <gp_Ax3.hxx>
1919 \#include <gp_Pnt.hxx>
1920 \#include <gp_Vec.hxx>
1921 \#include <gp_Trsf.hxx>
1922
1923 //! This attribute implements a transformation data container
1924 class MyPackage_Transformation : public TDF_Attribute
1925 {
1926 public:
1927   //!@name Static methods 
1928
1929   //! The method returns a unique GUID of this attribute. 
1930   //! By means of this GUID this attribute may be identified   
1931   //! among other attributes attached to the same label. 
1932   Standard_EXPORT static const Standard_GUID& GetID ();
1933
1934   //! Finds or creates the attribute attached to <theLabel>. 
1935   //! The found or created attribute is returned. 
1936   Standard_EXPORT static Handle(MyPackage_Transformation) Set (const TDF_Label theLabel);
1937
1938   //!@name Methods for access to the attribute data 
1939       
1940   //! The method returns the transformation. 
1941   Standard_EXPORT gp_Trsf Get () const; 
1942
1943   //!@name Methods for setting the data of transformation 
1944
1945   //! The method defines a rotation type of transformation. 
1946   Standard_EXPORT void SetRotation (const gp_Ax1& theAxis, Standard_Real theAngle); 
1947
1948   //! The method defines a translation type of transformation. 
1949   Standard_EXPORT void SetTranslation (const gp_Vec& theVector); 
1950
1951   //! The method defines a point mirror type of transformation (point symmetry). 
1952   Standard_EXPORT void SetMirror (const gp_Pnt& thePoint); 
1953
1954   //! The method defines an axis mirror type of transformation (axial symmetry). 
1955   Standard_EXPORT void SetMirror (const gp_Ax1& theAxis); 
1956
1957   //! The method defines a point mirror type of transformation (planar symmetry). 
1958   Standard_EXPORT void SetMirror (const gp_Ax2& thePlane); 
1959
1960   //! The method defines a scale type of transformation. 
1961   Standard_EXPORT void SetScale (const gp_Pnt& thePoint, Standard_Real theScale); 
1962
1963   //! The method defines a complex type of transformation from one co-ordinate system to another. 
1964   Standard_EXPORT void SetTransformation (const gp_Ax3& theCoordinateSystem1, const gp_Ax3& theCoordinateSystem2); 
1965
1966   //!@name Overridden methods from TDF_Attribute 
1967       
1968   //! The method returns a unique GUID of the attribute. 
1969   //! By means of this GUID this attribute may be identified among other attributes attached to the same label. 
1970   Standard_EXPORT const Standard_GUID& ID () const; 
1971
1972   //! The method is called on Undo / Redo. 
1973   //! It copies the content of theAttribute into this attribute (copies the fields). 
1974   Standard_EXPORT void Restore (const Handle(TDF_Attribute)& theAttribute); 
1975
1976   //! It creates a new instance of this attribute. 
1977   //! It is called on Copy / Paste, Undo / Redo. 
1978   Standard_EXPORT Handle(TDF_Attribute) NewEmpty () const;
1979
1980   //! The method is called on Copy / Paste. 
1981   //! It copies the content of this attribute into theAttribute (copies the fields). 
1982   Standard_EXPORT void Paste (const Handle(TDF_Attribute)& theAttribute, const Handle(TDF_RelocationTable)& theRelocationTable); 
1983
1984   //! Prints the content of this attribute into the stream. 
1985   Standard_EXPORT Standard_OStream& Dump(Standard_OStream& theOS);
1986
1987   //!@name Constructor 
1988
1989   //! The C++ constructor of this atribute class. 
1990   //! Usually it is never called outside this class. 
1991   Standard_EXPORT MyPackage_Transformation();
1992
1993 private:
1994   gp_TrsfForm myType;
1995
1996   // Axes (Ax1, Ax2, Ax3) 
1997   gp_Ax1 myAx1;
1998   gp_Ax2 myAx2;
1999   gp_Ax3 myFirstAx3;
2000   gp_Ax3 mySecondAx3;
2001
2002   // Scalar values 
2003   Standard_Real myAngle;
2004   Standard_Real myScale;
2005
2006   // Points 
2007   gp_Pnt myFirstPoint;
2008   gp_Pnt mySecondPoint;
2009 }; 
2010 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2011
2012 @subsection occt_ocaf_11_2 Implementation of Attribute Transformation in a CPP file
2013
2014 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
2015 \#include <MyPackage_Transformation.hxx> 
2016
2017 //======================================================================= 
2018 //function : GetID 
2019 //purpose  : The method returns a unique GUID of this attribute. 
2020 //           By means of this GUID this attribute may be identified   
2021 //           among other attributes attached to the same label. 
2022 //======================================================================= 
2023 const Standard_GUID& MyPackage_Transformation::GetID()   
2024
2025   static Standard_GUID ID("4443368E-C808-4468-984D-B26906BA8573"); 
2026   return ID; 
2027
2028
2029 //======================================================================= 
2030 //function : Set 
2031 //purpose  : Finds or creates the attribute attached to <theLabel>. 
2032 //           The found or created attribute is returned. 
2033 //======================================================================= 
2034 Handle(MyPackage_Transformation) MyPackage_Transformation::Set(const TDF_Label& theLabel)   
2035
2036   Handle(MyPackage_Transformation) T; 
2037   if (!theLabel.FindAttribute(MyPackage_Transformation::GetID(), T))   
2038   { 
2039     T = new MyPackage_Transformation();   
2040     theLabel.AddAttribute(T); 
2041   } 
2042   return T; 
2043
2044
2045 //======================================================================= 
2046 //function : Get 
2047 //purpose  : The method returns the transformation. 
2048 //======================================================================= 
2049 gp_Trsf MyPackage_Transformation::Get() const 
2050
2051   gp_Trsf transformation; 
2052   switch (myType) 
2053   { 
2054     case gp_Identity: 
2055     { 
2056       break; 
2057     } 
2058     case gp_Rotation: 
2059     { 
2060       transformation.SetRotation(myAx1, myAngle); 
2061       break; 
2062     } 
2063     case gp_Translation: 
2064     { 
2065       transformation.SetTranslation(myFirstPoint, mySecondPoint); 
2066       break; 
2067     } 
2068     case gp_PntMirror: 
2069     { 
2070       transformation.SetMirror(myFirstPoint); 
2071       break; 
2072     } 
2073     case gp_Ax1Mirror: 
2074     { 
2075       transformation.SetMirror(myAx1); 
2076       break; 
2077     } 
2078     case gp_Ax2Mirror: 
2079     { 
2080       transformation.SetMirror(myAx2); 
2081       break; 
2082     } 
2083     case gp_Scale: 
2084     { 
2085       transformation.SetScale(myFirstPoint, myScale); 
2086       break; 
2087     } 
2088     case gp_CompoundTrsf: 
2089     { 
2090       transformation.SetTransformation(myFirstAx3, mySecondAx3); 
2091       break; 
2092     } 
2093     case gp_Other: 
2094     { 
2095       break; 
2096     } 
2097   } 
2098   return transformation; 
2099
2100
2101 //======================================================================= 
2102 //function : SetRotation 
2103 //purpose  : The method defines a rotation type of transformation. 
2104 //======================================================================= 
2105 void MyPackage_Transformation::SetRotation(const gp_Ax1& theAxis, const Standard_Real theAngle) 
2106
2107   Backup(); 
2108   myType = gp_Rotation; 
2109   myAx1 = theAxis; 
2110   myAngle = theAngle; 
2111
2112
2113 //======================================================================= 
2114 //function : SetTranslation 
2115 //purpose  : The method defines a translation type of transformation. 
2116 //======================================================================= 
2117 void MyPackage_Transformation::SetTranslation(const gp_Vec& theVector) 
2118
2119   Backup(); 
2120   myType = gp_Translation; 
2121   myFirstPoint.SetCoord(0, 0, 0); 
2122   mySecondPoint.SetCoord(theVector.X(), theVector.Y(), theVector.Z()); 
2123
2124
2125 //======================================================================= 
2126 //function : SetMirror 
2127 //purpose  : The method defines a point mirror type of transformation 
2128 //           (point symmetry). 
2129 //======================================================================= 
2130 void MyPackage_Transformation::SetMirror(const gp_Pnt& thePoint) 
2131
2132   Backup(); 
2133   myType = gp_PntMirror; 
2134   myFirstPoint = thePoint; 
2135
2136
2137 //======================================================================= 
2138 //function : SetMirror 
2139 //purpose  : The method defines an axis mirror type of transformation 
2140 //           (axial symmetry). 
2141 //======================================================================= 
2142 void MyPackage_Transformation::SetMirror(const gp_Ax1& theAxis) 
2143
2144   Backup(); 
2145   myType = gp_Ax1Mirror; 
2146   myAx1 = theAxis; 
2147
2148
2149 //======================================================================= 
2150 //function : SetMirror 
2151 //purpose  : The method defines a point mirror type of transformation 
2152 //           (planar symmetry). 
2153 //======================================================================= 
2154 void MyPackage_Transformation::SetMirror(const gp_Ax2& thePlane) 
2155
2156   Backup(); 
2157   myType = gp_Ax2Mirror; 
2158   myAx2 = thePlane; 
2159
2160
2161 //======================================================================= 
2162 //function : SetScale 
2163 //purpose  : The method defines a scale type of transformation. 
2164 //======================================================================= 
2165 void MyPackage_Transformation::SetScale(const gp_Pnt& thePoint, const Standard_Real theScale) 
2166
2167   Backup(); 
2168   myType = gp_Scale; 
2169   myFirstPoint = thePoint; 
2170   myScale = theScale; 
2171
2172
2173 //======================================================================= 
2174 //function : SetTransformation 
2175 //purpose  : The method defines a complex type of transformation 
2176 //           from one co-ordinate system to another. 
2177 //======================================================================= 
2178 void MyPackage_Transformation::SetTransformation(const gp_Ax3& theCoordinateSystem1,   
2179                                                                          const gp_Ax3& theCoordinateSystem2) 
2180
2181   Backup(); 
2182   myFirstAx3 = theCoordinateSystem1; 
2183   mySecondAx3 = theCoordinateSystem2; 
2184
2185
2186 //======================================================================= 
2187 //function : ID 
2188 //purpose  : The method returns a unique GUID of the attribute. 
2189 //           By means of this GUID this attribute may be identified   
2190 //           among other attributes attached to the same label. 
2191 //======================================================================= 
2192 const Standard_GUID& MyPackage_Transformation::ID() const   
2193 {   
2194   return GetID();   
2195
2196
2197 //======================================================================= 
2198 //function : Restore 
2199 //purpose  : The method is called on Undo / Redo. 
2200 //           It copies the content of <theAttribute> 
2201 //           into this attribute (copies the fields). 
2202 //======================================================================= 
2203 void MyPackage_Transformation::Restore(const Handle(TDF_Attribute)& theAttribute)   
2204
2205   Handle(MyPackage_Transformation) theTransformation = Handle(MyPackage_Transformation)::DownCast(theAttribute); 
2206   myType = theTransformation->myType; 
2207   myAx1 = theTransformation->myAx1; 
2208   myAx2 = theTransformation->myAx2; 
2209   myFirstAx3 = theTransformation->myFirstAx3; 
2210   mySecondAx3 = theTransformation->mySecondAx3; 
2211   myAngle = theTransformation->myAngle; 
2212   myScale = theTransformation->myScale; 
2213   myFirstPoint = theTransformation->myFirstPoint; 
2214   mySecondPoint = theTransformation->mySecondPoint; 
2215
2216
2217 //======================================================================= 
2218 //function : NewEmpty 
2219 //purpose  : It creates a new instance of this attribute. 
2220 //           It is called on Copy / Paste, Undo / Redo. 
2221 //======================================================================= 
2222 Handle(TDF_Attribute) MyPackage_Transformation::NewEmpty() const 
2223 {    
2224   return new MyPackage_Transformation();   
2225
2226
2227 //======================================================================= 
2228 //function : Paste 
2229 //purpose  : The method is called on Copy / Paste. 
2230 //           It copies the content of this attribute into 
2231 //           <theAttribute> (copies the fields). 
2232 //======================================================================= 
2233 void MyPackage_Transformation::Paste(const Handle(TDF_Attribute)& theAttribute, 
2234                                                      const Handle(TDF_RelocationTable)& ) const 
2235
2236   Handle(MyPackage_Transformation) theTransformation = Handle(MyPackage_Transformation)::DownCast(theAttribute); 
2237   theTransformation->myType = myType; 
2238   theTransformation->myAx1 = myAx1; 
2239   theTransformation->myAx2 = myAx2; 
2240   theTransformation->myFirstAx3 = myFirstAx3; 
2241   theTransformation->mySecondAx3 = mySecondAx3; 
2242   theTransformation->myAngle = myAngle; 
2243   theTransformation->myScale = myScale; 
2244   theTransformation->myFirstPoint = myFirstPoint; 
2245   theTransformation->mySecondPoint = mySecondPoint; 
2246
2247
2248 //======================================================================= 
2249 //function : Dump 
2250 //purpose  : Prints the content of this attribute into the stream. 
2251 //======================================================================= 
2252 Standard_OStream& MyPackage_Transformation::Dump(Standard_OStream& anOS) const 
2253 {    
2254   anOS = "Transformation: "; 
2255   switch (myType) 
2256   { 
2257     case gp_Identity: 
2258     { 
2259       anOS = "gp_Identity"; 
2260       break; 
2261     } 
2262     case gp_Rotation: 
2263     { 
2264       anOS = "gp_Rotation"; 
2265       break; 
2266     } 
2267     case gp_Translation: 
2268     { 
2269       anOS = "gp_Translation"; 
2270       break; 
2271     } 
2272     case gp_PntMirror: 
2273     { 
2274       anOS = "gp_PntMirror"; 
2275       break; 
2276     } 
2277     case gp_Ax1Mirror: 
2278     { 
2279       anOS = "gp_Ax1Mirror"; 
2280       break; 
2281     } 
2282     case gp_Ax2Mirror: 
2283     { 
2284       anOS = "gp_Ax2Mirror"; 
2285       break; 
2286     } 
2287     case gp_Scale: 
2288     { 
2289       anOS = "gp_Scale"; 
2290       break; 
2291     } 
2292     case gp_CompoundTrsf: 
2293     { 
2294       anOS = "gp_CompoundTrsf"; 
2295       break; 
2296     } 
2297     case gp_Other: 
2298     { 
2299       anOS = "gp_Other"; 
2300       break; 
2301     } 
2302   } 
2303   return anOS; 
2304
2305
2306 //=======================================================================
2307 //function : MyPackage_Transformation 
2308 //purpose  : A constructor. 
2309 //=======================================================================
2310 MyPackage_Transformation::MyPackage_Transformation():myType(gp_Identity){ 
2311
2312 }
2313 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2314
2315 @subsection occt_ocaf_11_3  Implementation of typical actions with standard OCAF attributes.
2316
2317 There are four sample files provided in the directory 'OpenCasCade/ros/samples/ocafsamples'. They present typical actions with OCAF services (mainly for newcomers). 
2318 The method *Sample()* of each file is not dedicated for execution 'as is', it is rather a set of logical actions using some OCAF services.
2319
2320 ### TDataStd_Sample.cxx
2321 This sample contains templates for typical actions with the following standard OCAF attributes:
2322 - Starting with data framework;
2323 - TDataStd_Integer attribute management;
2324 - TDataStd_RealArray attribute management;
2325 - TDataStd_Comment attribute management;
2326 - TDataStd_Name attribute management;
2327 - TDataStd_UAttribute attribute management;
2328 - TDF_Reference attribute management;
2329 - TDataXtd_Point attribute management;
2330 - TDataXtd_Plane attribute management;
2331 - TDataXtd_Axis attribute management;
2332 - TDataXtd_Geometry attribute management;
2333 - TDataXtd_Constraint attribute management;
2334 - TDataStd_Directory attribute management;
2335 - TDataStd_TreeNode attribute management.
2336   
2337 ### TDocStd_Sample.cxx
2338 This sample contains template for the following typical actions:
2339 - creating application;
2340 - creating the new document (document contains a framework);
2341 - retrieving the document from a label of its framework;
2342 - filling a document with data;
2343 - saving a document in the file;
2344 - closing a document;
2345 - opening the document stored in the file;
2346 - copying content of a document to another document with possibility to update the copy in the future.
2347  
2348 ### TPrsStd_Sample.cxx
2349 This sample contains template for the following typical actions:
2350 - starting with data framework;
2351 - setting the TPrsStd_AISViewer in the framework;
2352 - initialization of aViewer;
2353 - finding TPrsStd_AISViewer attribute in the DataFramework;
2354 - getting AIS_InteractiveContext from TPrsStd_AISViewer;
2355 - adding driver to the map of drivers;
2356 - getting driver from the map of drivers;
2357 - setting TNaming_NamedShape to \<ShapeLabel\>;
2358 - setting the new  TPrsStd_AISPresentation to \<ShapeLabel\>;
2359 - displaying;
2360 - erasing;
2361 - updating and displaying presentation of the attribute to be displayed;
2362 - setting a color to the displayed attribute;
2363 - getting transparency of the displayed attribute;
2364 -  modify attribute;
2365 - updating presentation of the attribute in viewer.
2366
2367 ### TNaming_Sample.cxx
2368 This sample contains template for typical actions with OCAF Topological Naming services.
2369 The following scenario is used:
2370 - data framework initialization;
2371 - creating Box1 and pushing it as PRIMITIVE in DF;
2372 - creating Box2 and pushing it as PRIMITIVE in DF;
2373 - moving Box2 (applying a transformation);
2374 - pushing the selected edges of the top face of Box1 in DF;
2375 - creating a Fillet (using the selected edges) and pushing the result as a modification of Box1;
2376 - creating a Cut (Box1, Box2) as a modification of Box1 and push it in DF;
2377 - recovering the result from DF.
2378