69aaa4218929c82903a83492017fe73c0c46be12
[occt.git] / src / STEPCAFControl / STEPCAFControl_Writer.cxx
1 // Created on: 2000-08-15
2 // Created by: Andrey BETENEV
3 // Copyright (c) 2000-2014 OPEN CASCADE SAS
4 //
5 // This file is part of Open CASCADE Technology software library.
6 //
7 // This library is free software; you can redistribute it and/or modify it under
8 // the terms of the GNU Lesser General Public License version 2.1 as published
9 // by the Free Software Foundation, with special exception defined in the file
10 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
11 // distribution for complete text of the license and disclaimer of any warranty.
12 //
13 // Alternatively, this file may be used under the terms of Open CASCADE
14 // commercial license or contractual agreement.
15
16 // CURRENT LIMITATIONS: 
17 // when val props and names assigned to instance of 
18 // component in assembly, it is in fact supposed that only one CDSR corresponds
19 // to such shape. This can be wrong and should be handled more carefully
20 // (analysis of SDRs which the CDSR links should be done)
21 // Names and validation props are supported for top-level shapes only
22
23 #include <STEPCAFControl_Writer.ixx>
24 #include <STEPControl_StepModelType.hxx>
25 #include <XCAFDoc_ShapeTool.hxx>
26 #include <TDF_LabelSequence.hxx>
27 #include <TopoDS_Shape.hxx>
28 #include <XCAFPrs_DataMapOfShapeStyle.hxx>
29 #include <XCAFPrs.hxx>
30 #include <XCAFPrs_DataMapOfStyleShape.hxx>
31 #include <XCAFPrs_Style.hxx>
32 #include <XCAFPrs_DataMapIteratorOfDataMapOfStyleShape.hxx>
33 #include <TopTools_SequenceOfShape.hxx>
34 #include <TopoDS_Iterator.hxx>
35 #include <STEPConstruct_Styles.hxx>
36 #include <XCAFDoc_ColorTool.hxx>
37 #include <STEPConstruct.hxx>
38 #include <TopTools_MapOfShape.hxx>
39 #include <XSControl_TransferWriter.hxx>
40 #include <TDataStd_Name.hxx>
41 #include <StepShape_ShapeDefinitionRepresentation.hxx>
42 #include <TransferBRep_ShapeMapper.hxx>
43 #include <TransferBRep.hxx>
44 #include <StepRepr_PropertyDefinition.hxx>
45 #include <StepBasic_ProductDefinition.hxx>
46 #include <StepBasic_Product.hxx>
47 #include <TCollection_HAsciiString.hxx>
48 #include <TCollection_AsciiString.hxx>
49 #include <Transfer_FinderProcess.hxx>
50 #include <StepBasic_ProductDefinitionFormation.hxx>
51 #include <XCAFDoc_DocumentTool.hxx>
52 #include <TDF_Label.hxx>
53 #include <STEPCAFControl_Controller.hxx>
54 #include <STEPCAFControl_IteratorOfDictionaryOfExternFile.hxx>
55 #include <STEPConstruct_ExternRefs.hxx>
56 #include <Interface_Static.hxx>
57 #include <TopoDS_Compound.hxx>
58 #include <BRep_Builder.hxx>
59 #include <Transfer_ActorOfFinderProcess.hxx>
60 #include <STEPCAFControl_ActorWrite.hxx>
61 #include <STEPConstruct_ValidationProps.hxx>
62 #include <XCAFDoc_Area.hxx>
63 #include <XCAFDoc_Volume.hxx>
64 #include <XCAFDoc_Centroid.hxx>
65 #include <StepShape_ContextDependentShapeRepresentation.hxx>
66 #include <StepRepr_ProductDefinitionShape.hxx>
67 #include <StepBasic_ProductDefinitionRelationship.hxx>
68 #include <XCAFDoc_GraphNode.hxx>
69 #include <XCAFDoc_LayerTool.hxx>
70 #include <StepVisual_PresentationLayerAssignment.hxx>
71 #include <XCAFDoc.hxx>
72 #include <StepVisual_HArray1OfLayeredItem.hxx>
73 #include <TColStd_HSequenceOfTransient.hxx>
74 #include <TDF_Tool.hxx>
75 #include <Message_Messenger.hxx>
76 #include <TDF_ChildIterator.hxx>
77
78 #include <Transfer_Binder.hxx>
79 #include <Transfer_TransientListBinder.hxx>
80 #include <StepVisual_InvisibleItem.hxx>
81 #include <TDataStd_UAttribute.hxx>
82 #include <StepVisual_Invisibility.hxx>
83 #include <StepVisual_HArray1OfInvisibleItem.hxx>
84 #include <HeaderSection_FileSchema.hxx>
85 #include <StepData_StepModel.hxx>
86 #include <StepAP214_Protocol.hxx>
87 #include <OSD_Path.hxx>
88 #include <XSControl_WorkSession.hxx>
89 #include <StepRepr_HArray1OfRepresentationItem.hxx>
90 #include <MoniTool_DataMapIteratorOfDataMapOfShapeTransient.hxx>
91 #include <StepRepr_Representation.hxx>
92 #include <StepVisual_MechanicalDesignGeometricPresentationRepresentation.hxx>
93 #include <Quantity_TypeOfColor.hxx>
94 #include <StepVisual_HArray1OfPresentationStyleAssignment.hxx>
95 #include <StepVisual_PresentationStyleAssignment.hxx>
96 #include <StepVisual_StyledItem.hxx>
97 #include <StepVisual_PresentationStyleByContext.hxx>
98 #include <StepVisual_HArray1OfPresentationStyleSelect.hxx>
99 #include <TDF_AttributeSequence.hxx>
100 #include <TColStd_MapOfTransient.hxx>
101 // #include <TColStd_IndexedDataMapOfTransientTransient.hxx>
102 #include <StepRepr_NextAssemblyUsageOccurrence.hxx>
103 #include <Interface_EntityIterator.hxx>
104 #include <StepRepr_SpecifiedHigherUsageOccurrence.hxx>
105
106 // added by skl 15.01.2004 for D&GT writing
107 #include <XCAFDoc_DimTolTool.hxx>
108 #include <XCAFDoc_DimTol.hxx>
109 #include <XCAFDoc_Datum.hxx>
110 #include <STEPConstruct_DataMapOfAsciiStringTransient.hxx>
111 #include <STEPConstruct_DataMapOfPointTransient.hxx>
112 #include <StepBasic_MeasureValueMember.hxx>
113 #include <StepBasic_SiUnitAndLengthUnit.hxx>
114 #include <StepGeom_GeometricRepresentationContextAndGlobalUnitAssignedContext.hxx>
115 #include <StepGeom_GeomRepContextAndGlobUnitAssCtxAndGlobUncertaintyAssCtx.hxx>
116 #include <StepBasic_LengthMeasureWithUnit.hxx>
117 #include <StepShape_EdgeCurve.hxx>
118 #include <StepShape_AdvancedFace.hxx>
119 #include <StepShape_OrientedEdge.hxx>
120 #include <StepShape_EdgeLoop.hxx>
121 #include <StepShape_FaceBound.hxx>
122 #include <StepShape_ConnectedFaceSet.hxx>
123 #include <StepShape_ShapeRepresentation.hxx>
124 #include <StepShape_DimensionalSize.hxx>
125 #include <StepShape_ShapeDimensionRepresentation.hxx>
126 #include <StepShape_DimensionalCharacteristicRepresentation.hxx>
127 #include <StepRepr_ShapeAspect.hxx>
128 #include <StepRepr_ShapeAspectRelationship.hxx>
129 #include <StepRepr_ReprItemAndLengthMeasureWithUnit.hxx>
130 //#include <StepRepr_CompoundItemDefinition.hxx>
131 //#include <StepRepr_CompoundItemDefinitionMember.hxx>
132 #include <StepRepr_ValueRange.hxx>
133 #include <StepData_Logical.hxx>
134 #include <StepDimTol_DatumFeature.hxx>
135 #include <StepDimTol_Datum.hxx>
136 #include <StepDimTol_DatumReference.hxx>
137 #include <StepDimTol_HArray1OfDatumReference.hxx>
138 #include <StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol.hxx>
139 #include <StepDimTol_ModifiedGeometricTolerance.hxx>
140 #include <StepDimTol_GeometricToleranceWithDatumReference.hxx>
141 #include <StepDimTol_AngularityTolerance.hxx>
142 #include <StepDimTol_CircularRunoutTolerance.hxx>
143 #include <StepDimTol_CoaxialityTolerance.hxx>
144 #include <StepDimTol_ConcentricityTolerance.hxx>
145 #include <StepDimTol_ParallelismTolerance.hxx>
146 #include <StepDimTol_PerpendicularityTolerance.hxx>
147 #include <StepDimTol_SymmetryTolerance.hxx>
148 #include <StepDimTol_TotalRunoutTolerance.hxx>
149 #include <StepDimTol_CylindricityTolerance.hxx>
150 #include <StepDimTol_FlatnessTolerance.hxx>
151 #include <StepDimTol_LineProfileTolerance.hxx>
152 #include <StepDimTol_PositionTolerance.hxx>
153 #include <StepDimTol_RoundnessTolerance.hxx>
154 #include <StepDimTol_StraightnessTolerance.hxx>
155 #include <StepDimTol_SurfaceProfileTolerance.hxx>
156 #include <TColStd_HArray1OfReal.hxx>
157 #include <TColStd_HArray1OfTransient.hxx>
158
159 // added by skl 12.02.2004 for writing materials
160 #include <XCAFDoc_MaterialTool.hxx>
161 #include <XCAFDoc_Material.hxx>
162 #include <TDataStd_TreeNode.hxx>
163 #include <StepRepr_DescriptiveRepresentationItem.hxx>
164 #include <StepBasic_SiUnitAndMassUnit.hxx>
165 #include <StepBasic_DerivedUnitElement.hxx>
166 #include <StepBasic_HArray1OfDerivedUnitElement.hxx>
167 #include <StepBasic_DerivedUnit.hxx>
168 #include <StepRepr_MeasureRepresentationItem.hxx>
169 #include <StepBasic_ProductDefinition.hxx>
170
171 //=======================================================================
172 //function : GetLabelName
173 //purpose  : auxilary function: take name of label and append it to str
174 //=======================================================================
175 static Standard_Boolean GetLabelName (const TDF_Label &L, Handle(TCollection_HAsciiString) &str)
176 {
177   Handle(TDataStd_Name) N;
178   if ( ! L.FindAttribute ( TDataStd_Name::GetID(), N ) ) return Standard_False;
179   TCollection_ExtendedString name = N->Get();
180   if ( name.Length() <=0 ) return Standard_False;
181
182   // set name, converting it to Ascii and removing spaces
183   TCollection_AsciiString buf ( name, '?' );
184   buf.LeftAdjust();
185   buf.RightAdjust();
186   buf.ChangeAll(' ','_');
187   str->AssignCat ( buf.ToCString() );
188   return Standard_True;
189 }
190
191
192 //=======================================================================
193 //function : STEPCAFControl_Writer
194 //purpose  :
195 //=======================================================================
196
197 STEPCAFControl_Writer::STEPCAFControl_Writer () :
198        myColorMode( Standard_True ),
199        myNameMode ( Standard_True ),
200        myLayerMode( Standard_True ),
201        myPropsMode( Standard_True ),
202        mySHUOMode ( Standard_True ),
203        myDGTMode  ( Standard_True ),
204        myMatMode  ( Standard_True )
205 {
206   STEPCAFControl_Controller::Init();
207   Handle(XSControl_WorkSession) WS = new XSControl_WorkSession;
208   Init ( WS );
209 }
210
211
212 //=======================================================================
213 //function : STEPCAFControl_Writer
214 //purpose  :
215 //=======================================================================
216
217 STEPCAFControl_Writer::STEPCAFControl_Writer (const Handle(XSControl_WorkSession)& WS,
218                                               const Standard_Boolean scratch)
219 {
220   STEPCAFControl_Controller::Init();
221   Init ( WS, scratch );
222   myColorMode = Standard_True;
223   myNameMode = Standard_True;
224   myLayerMode = Standard_True;
225   myPropsMode = Standard_True;
226   mySHUOMode = Standard_True;
227 }
228
229
230 //=======================================================================
231 //function : Init
232 //purpose  :
233 //=======================================================================
234
235 void STEPCAFControl_Writer::Init (const Handle(XSControl_WorkSession)& WS,
236                                   const Standard_Boolean scratch)
237 {
238   WS->SelectNorm ( "STEP" );
239   myWriter.SetWS (WS,scratch);
240   myFiles = new STEPCAFControl_DictionaryOfExternFile;
241   myLabEF.Clear();
242   myLabels.Clear();
243 }
244
245
246 //=======================================================================
247 //function : Write
248 //purpose  :
249 //=======================================================================
250
251 IFSelect_ReturnStatus STEPCAFControl_Writer::Write (const Standard_CString filename)
252 {
253   IFSelect_ReturnStatus status = myWriter.Write ( filename );
254
255   // get directory name of the main file
256   OSD_Path mainfile ( filename );
257   mainfile.SetName ( "" );
258   mainfile.SetExtension ( "" );
259   TCollection_AsciiString dpath;
260   mainfile.SystemName ( dpath );
261
262   STEPCAFControl_IteratorOfDictionaryOfExternFile it ( myFiles );
263   for ( ; it.More(); it.Next() ) {
264     Handle(STEPCAFControl_ExternFile) EF = it.Value();
265     if ( EF->GetWriteStatus() != IFSelect_RetVoid ) continue;
266
267     // construct extern file name
268     TCollection_AsciiString fname = OSD_Path::AbsolutePath ( dpath, EF->GetName()->String() );
269     if ( fname.Length() <= 0 ) fname = EF->GetName()->String();
270 #ifdef OCCT_DEBUG
271     cout << "Writing external file: " << fname.ToCString() << endl;
272 #endif
273     
274     EF->SetWriteStatus ( EF->GetWS()->SendAll ( fname.ToCString() ) );
275   }
276
277   return status;
278 }
279
280
281 //=======================================================================
282 //function : Transfer
283 //purpose  :
284 //=======================================================================
285
286 Standard_Boolean STEPCAFControl_Writer::Transfer (const Handle(TDocStd_Document) &doc,
287                                                   const STEPControl_StepModelType mode,
288                                                   const Standard_CString multi)
289 {
290   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( doc->Main() );
291   if ( STool.IsNull() ) return Standard_False;
292
293   TDF_LabelSequence labels;
294   STool->GetFreeShapes ( labels );
295   return Transfer ( myWriter, labels, mode, multi );
296 }
297
298
299 //=======================================================================
300 //function : Transfer
301 //purpose  :
302 //=======================================================================
303
304 Standard_Boolean STEPCAFControl_Writer::Transfer (const TDF_Label &L,
305                                                   const STEPControl_StepModelType mode,
306                                                   const Standard_CString multi)
307 {
308   TDF_LabelSequence labels;
309   labels.Append ( L );
310   return Transfer ( myWriter, labels, mode, multi );
311 }
312
313
314 //=======================================================================
315 //function : Perform
316 //purpose  :
317 //=======================================================================
318
319 Standard_Boolean STEPCAFControl_Writer::Perform (const Handle(TDocStd_Document) &doc,
320                                                  const Standard_CString filename)
321 {
322   if ( ! Transfer ( doc ) ) return Standard_False;
323   return Write ( filename ) == IFSelect_RetDone;
324 }
325
326
327 //=======================================================================
328 //function : Perform
329 //purpose  :
330 //=======================================================================
331
332 Standard_Boolean STEPCAFControl_Writer::Perform (const Handle(TDocStd_Document) &doc,
333                                                  const TCollection_AsciiString &filename)
334 {
335   if ( ! Transfer ( doc ) ) return Standard_False;
336   return Write ( filename.ToCString() ) == IFSelect_RetDone;
337 }
338
339
340 //=======================================================================
341 //function : ExternFiles
342 //purpose  :
343 //=======================================================================
344
345 const Handle(STEPCAFControl_DictionaryOfExternFile) &STEPCAFControl_Writer::ExternFiles () const
346 {
347   return myFiles;
348 }
349
350
351 //=======================================================================
352 //function : ExternFile
353 //purpose  :
354 //=======================================================================
355
356 Standard_Boolean STEPCAFControl_Writer::ExternFile (const TDF_Label &L,
357                                                     Handle(STEPCAFControl_ExternFile) &ef) const
358 {
359   ef.Nullify();
360   if ( ! myLabEF.IsBound ( L ) ) return Standard_False;
361   ef = myLabEF.Find ( L );
362   return Standard_True;
363 }
364
365
366 //=======================================================================
367 //function : ExternFile
368 //purpose  :
369 //=======================================================================
370
371 Standard_Boolean STEPCAFControl_Writer::ExternFile (const Standard_CString name,
372                                                     Handle(STEPCAFControl_ExternFile) &ef) const
373 {
374   ef.Nullify();
375   if ( ! myFiles.IsNull() || ! myFiles->HasItem ( name ) )
376     return Standard_False;
377   ef = myFiles->Item ( name );
378   return Standard_True;
379 }
380
381
382 //=======================================================================
383 //function : Writer
384 //purpose  :
385 //=======================================================================
386
387 STEPControl_Writer &STEPCAFControl_Writer::ChangeWriter ()
388 {
389   return myWriter;
390 }
391
392
393 //=======================================================================
394 //function : Writer
395 //purpose  :
396 //=======================================================================
397
398 const STEPControl_Writer &STEPCAFControl_Writer::Writer () const
399 {
400   return myWriter;
401 }
402
403
404 //=======================================================================
405 //function : Transfer
406 //purpose  :
407 //=======================================================================
408
409 Standard_Boolean STEPCAFControl_Writer::Transfer (STEPControl_Writer &writer,
410                                                   const TDF_LabelSequence &labels,
411                                                   const STEPControl_StepModelType mode,
412                                                   const Standard_CString multi,
413                                                   const Standard_Boolean isExternFile)
414 {
415   if ( labels.Length() <=0 ) return Standard_False;
416
417   Handle(STEPCAFControl_ActorWrite) Actor =
418     Handle(STEPCAFControl_ActorWrite)::DownCast ( writer.WS()->NormAdaptor()->ActorWrite() );
419
420   // translate free top-level shapes of the DECAF document
421   Standard_Integer ap = Interface_Static::IVal ("write.step.schema");
422   TDF_LabelSequence sublabels;
423   for ( Standard_Integer i=1; i <= labels.Length(); i++ ) {
424     TDF_Label L = labels.Value(i);
425     TopoDS_Shape dummy;
426     if ( myLabels.IsBound ( L ) ) continue; // already processed
427
428     TopoDS_Shape shape = XCAFDoc_ShapeTool::GetShape ( L );
429     if ( shape.IsNull() ) continue;
430     
431     // write shape either as a whole, or as multifile (with extern refs)
432     if ( ! multi /* || ! XCAFDoc_ShapeTool::IsAssembly ( L ) */ ) {
433       Actor->SetStdMode ( Standard_False );
434
435       // fill sequence of (sub) shapes for which attributes should be written
436       // and set actor to handle assemblies in a proper way
437       TDF_LabelSequence comp;
438       XCAFDoc_ShapeTool::GetComponents ( L, comp, Standard_True );
439       for ( Standard_Integer k=1; k <= comp.Length(); k++ ) {
440         TDF_Label ref;
441         if ( ! XCAFDoc_ShapeTool::GetReferredShape ( comp(k), ref ) ) continue;
442         if ( ! myLabels.IsBound ( ref ) ) {
443           TopoDS_Shape refS = XCAFDoc_ShapeTool::GetShape ( ref );
444           myLabels.Bind ( ref, refS );
445           sublabels.Append ( ref );
446           if ( XCAFDoc_ShapeTool::IsAssembly ( ref ) )
447             Actor->RegisterAssembly ( refS );
448         }
449       }
450       myLabels.Bind ( L, shape );
451       sublabels.Append ( L );
452       if ( XCAFDoc_ShapeTool::IsAssembly ( L ) )
453         Actor->RegisterAssembly ( shape );
454
455       writer.Transfer(shape,mode,Standard_False);
456       Actor->SetStdMode ( Standard_True ); // restore default behaviour
457     }
458     else {
459       // translate final solids
460       TopoDS_Shape Sass = TransferExternFiles ( L, mode, sublabels, multi );
461
462       // translate main assembly structure
463 /*
464       if ( ap == 3 ) { // if AP203, switch to AP214
465         Interface_Static::SetCVal ("write.step.schema", "AP214DIS");
466         Handle(StepData_StepModel) model = 
467           Handle(StepData_StepModel)::DownCast ( writer.WS()->Model() );
468         if ( model->HasHeaderEntity(STANDARD_TYPE(HeaderSection_FileSchema)) ) {
469           Handle(HeaderSection_FileSchema) fs = 
470             Handle(HeaderSection_FileSchema)::DownCast ( model->HeaderEntity(STANDARD_TYPE(HeaderSection_FileSchema)) );
471           Handle(TCollection_HAsciiString) str = fs->SchemaIdentifiersValue ( 1 );
472           Handle(TCollection_HAsciiString) ap214 = new TCollection_HAsciiString ( "AUTOMOTIVE_DESIGN" );
473           if ( str->Search ( ap214 ) <0 ) {
474             str->Clear();
475             str->AssignCat ( ap214 );
476           }
477         }
478       }
479 */      
480       Standard_Integer assemblymode = Interface_Static::IVal ("write.step.assembly");
481       Interface_Static::SetCVal ("write.step.assembly", "On");
482       writer.Transfer ( Sass, STEPControl_AsIs );
483       Interface_Static::SetIVal ("write.step.assembly", assemblymode);
484       Interface_Static::SetIVal ("write.step.schema", ap);
485     }
486   }
487
488   writer.WS()->ComputeGraph(Standard_True );// added by skl 03.11.2003 since we use
489                                             // writer.Transfer() wihtout compute graph
490
491   // write names
492   if ( GetNameMode() )
493     WriteNames ( writer.WS(), sublabels );
494
495   if ( !multi ) {
496     // write colors
497     if ( GetColorMode() )
498       WriteColors ( writer.WS(), sublabels );
499     
500     // write layers
501     if ( GetLayerMode() )
502       WriteLayers ( writer.WS(), sublabels );
503
504     // write SHUO entities
505     if ( GetSHUOMode() && !isExternFile ) 
506       // do not store SHUO for extern reference for the moment
507       WriteSHUOs (  writer.WS(), sublabels );
508     
509     // write G&DTs
510     if(GetDimTolMode())
511       WriteDGTs(writer.WS(),sublabels);
512
513     // write Materials
514     if(GetMaterialMode())
515       WriteMaterials(writer.WS(),sublabels);
516
517     // register all MDGPRs in model
518     MoniTool_DataMapIteratorOfDataMapOfShapeTransient anItr(myMapCompMDGPR);
519     for (; anItr.More(); anItr.Next()) {
520       Handle(Interface_InterfaceModel) Model = writer.WS()->Model();
521       Model->AddWithRefs( anItr.Value() );
522     }
523   }
524   
525   if ( multi ) { // external refs
526     WriteExternRefs ( writer.WS(), sublabels );
527   }
528
529   // write validation props
530 //  if ( multi && ap ==3 ) {
531 //      Interface_Static::SetCVal ("write.step.schema", "AP214DIS");
532 //  }
533   if ( GetPropsMode() ) 
534     WriteValProps ( writer.WS(), sublabels, multi );
535
536   Interface_Static::SetIVal ("write.step.schema", ap);
537
538   // refresh graph
539   writer.WS()->ComputeGraph ( Standard_True );
540
541   /* ================================
542     *  Write names for the sub-shapes
543     * ================================ */
544
545   if ( Interface_Static::IVal("write.stepcaf.subshapes.name") )
546   {
547     Handle(XSControl_TransferWriter) TW = this->ChangeWriter().WS()->TransferWriter();
548     Handle(Transfer_FinderProcess) FP = TW->FinderProcess();
549
550     for ( int i = 1; i <= labels.Length(); i++ )
551     {
552       TDF_Label L = labels.Value(i);
553
554       for ( TDF_ChildIterator it(L, Standard_True); it.More(); it.Next() )
555       {
556         TDF_Label SubL = it.Value();
557
558         // Access name recorded in OCAF TDataStd_Name attribute
559         Handle(TCollection_HAsciiString) hSubName = new TCollection_HAsciiString;
560         if ( !GetLabelName(SubL, hSubName) )
561           continue;
562
563         // Access topological data
564         TopoDS_Shape SubS = XCAFDoc_ShapeTool::GetShape(SubL);
565         if ( SubS.IsNull() )
566           continue;
567
568         // Access the correspondent STEP Representation Item
569         Handle(StepRepr_RepresentationItem) RI;
570         Handle(TransferBRep_ShapeMapper) aShMapper = TransferBRep::ShapeMapper(FP, SubS);
571         if ( !FP->FindTypedTransient(aShMapper, STANDARD_TYPE(StepRepr_RepresentationItem), RI) )
572           continue;
573
574         // Record the name
575         RI->SetName(hSubName);
576       }
577     }
578   }
579
580   return Standard_True;
581 }
582
583
584 //=======================================================================
585 //function : TransferExternFiles
586 //purpose  :
587 //=======================================================================
588
589 TopoDS_Shape STEPCAFControl_Writer::TransferExternFiles (const TDF_Label &L,
590                                                          const STEPControl_StepModelType mode,
591                                                          TDF_LabelSequence &labels,
592                                                          const Standard_CString prefix)
593 {
594   // if label already translated, just return the shape
595   if ( myLabels.IsBound ( L ) ) {
596     return myLabels.Find ( L );
597   }
598
599   TopoDS_Compound C;
600   BRep_Builder B;
601   B.MakeCompound ( C );
602   labels.Append ( L );
603
604   // if not assembly, write to separate file
605   if ( ! XCAFDoc_ShapeTool::IsAssembly ( L ) ) {
606
607     // prepare for transfer
608     Handle(XSControl_WorkSession) newWS = new XSControl_WorkSession;
609     newWS->SelectNorm ( "STEP" );
610     STEPControl_Writer sw ( newWS, Standard_True );
611     TDF_LabelSequence Lseq;
612     Lseq.Append ( L );
613
614     // construct the name for extern file
615     Handle(TCollection_HAsciiString) basename = new TCollection_HAsciiString;
616     if ( prefix && prefix[0] ) basename->AssignCat ( prefix );
617     GetLabelName ( L, basename );
618     Handle(TCollection_HAsciiString) name = new TCollection_HAsciiString ( basename );
619     name->AssignCat ( ".stp" );
620     if ( myFiles->HasItem ( name->ToCString() ) ) { // avoid confusions
621       for ( Standard_Integer k=1; k < 32000; k++ ) {
622         name = new TCollection_HAsciiString ( basename );
623         name->AssignCat ( "_" );
624         name->AssignCat ( TCollection_AsciiString ( k ).ToCString() );
625         name->AssignCat ( ".stp" );
626         if ( ! myFiles->HasItem ( name->ToCString() ) ) break;
627       }
628     }
629
630     // translate and record extern file
631     Handle(STEPCAFControl_ExternFile) EF = new STEPCAFControl_ExternFile;
632     EF->SetWS ( newWS );
633     EF->SetName ( name );
634     EF->SetLabel ( L );
635     Standard_Integer assemblymode = Interface_Static::IVal ("write.step.assembly");
636     Interface_Static::SetCVal ("write.step.assembly", "Off");
637     const Standard_CString multi = 0;
638     EF->SetTransferStatus ( Transfer ( sw, Lseq, mode, multi, Standard_True ) );
639     Interface_Static::SetIVal ("write.step.assembly", assemblymode);
640     myLabEF.Bind ( L, EF );
641     myFiles->SetItem ( name->ToCString(), EF );
642
643     // return empty compound as replacement for the shape
644     myLabels.Bind ( L, C );
645     return C;
646   }
647
648   // else iterate on components add create structure of empty compounds
649   // representing the assembly
650   TDF_LabelSequence comp;
651   XCAFDoc_ShapeTool::GetComponents ( L, comp, Standard_False );
652   for ( Standard_Integer k=1; k <= comp.Length(); k++ ) {
653     TDF_Label lab = comp(k);
654     TDF_Label ref;
655     if ( ! XCAFDoc_ShapeTool::GetReferredShape ( lab, ref ) ) continue;
656     TopoDS_Shape Scomp = TransferExternFiles ( ref, mode, labels, prefix );
657     Scomp.Location ( XCAFDoc_ShapeTool::GetLocation ( lab ) );
658     B.Add ( C, Scomp );
659   }
660   myLabels.Bind ( L, C );
661   return C;
662 }
663
664
665 //=======================================================================
666 //function : WriteExternRefs
667 //purpose  :
668 //=======================================================================
669
670 Standard_Boolean STEPCAFControl_Writer::WriteExternRefs (const Handle(XSControl_WorkSession) &WS,
671                                                          const TDF_LabelSequence &labels) const
672 {
673   if ( labels.Length() <=0 ) return Standard_False;
674
675   Handle(XSControl_TransferWriter) TW = WS->TransferWriter();
676   Handle(Transfer_FinderProcess) FP = TW->FinderProcess();
677   STEPConstruct_ExternRefs EFTool ( WS );
678   Standard_Integer schema = Interface_Static::IVal("write.step.schema");
679   for ( Standard_Integer k=1; k <= labels.Length(); k++ ) {
680     TDF_Label lab = labels(k);
681     if ( XCAFDoc_ShapeTool::IsAssembly ( lab ) ) continue; // skip assemblies
682
683     // get extern file
684     Handle(STEPCAFControl_ExternFile) EF;
685     if ( ! ExternFile ( lab, EF ) ) continue; // should never be
686
687     // find SDR
688     if ( ! myLabels.IsBound ( lab ) ) continue; // not recorded as translated, skip
689     TopoDS_Shape S = myLabels.Find ( lab );
690
691     Handle(StepShape_ShapeDefinitionRepresentation) SDR;
692     Handle(TransferBRep_ShapeMapper) mapper = TransferBRep::ShapeMapper ( FP, S );
693     if ( ! FP->FindTypedTransient ( mapper, STANDARD_TYPE(StepShape_ShapeDefinitionRepresentation), SDR ) ) {
694 #ifdef OCCT_DEBUG
695       cout << "Warning: Cannot find SDR for " << S.TShape()->DynamicType()->Name() << endl;
696 #endif
697       continue;
698     }
699
700     // add extern ref
701     const Standard_CString format = (const Standard_CString) ( schema == 3 ? "STEP AP203" : "STEP AP214" );
702     // try to get PD from SDR
703     StepRepr_RepresentedDefinition RD = SDR->Definition();
704     Handle(StepRepr_PropertyDefinition) aPropDef = RD.PropertyDefinition();
705     if (aPropDef.IsNull()) {
706 #ifdef OCCT_DEBUG
707       cout << "Warning: STEPCAFControl_Writer::WriteExternRefs StepRepr_PropertyDefinition is null for " << S.TShape()->DynamicType()->Name() << endl;
708 #endif
709       continue;
710     }
711     StepRepr_CharacterizedDefinition CharDef = aPropDef->Definition();
712     Handle(StepBasic_ProductDefinition) PD = CharDef.ProductDefinition();
713     if (PD.IsNull()) {
714 #ifdef OCCT_DEBUG
715       cout << "Warning: STEPCAFControl_Writer::WriteExternRefs StepBasic_ProductDefinition is null for " << S.TShape()->DynamicType()->Name() << endl;
716 #endif
717       continue;
718     }
719     EFTool.AddExternRef ( EF->GetName()->ToCString(), PD, format );
720   }
721   EFTool.WriteExternRefs(schema);
722   return Standard_True;
723 }
724
725
726 //=======================================================================
727 //function : FindEntities
728 //purpose  : auxilary
729 //=======================================================================
730 static Standard_Integer FindEntities (const Handle(Transfer_FinderProcess) &FP,
731                                       const TopoDS_Shape &S,
732                                       TopLoc_Location &L,
733                                       TColStd_SequenceOfTransient &seqRI)
734 {
735   Handle(StepRepr_RepresentationItem) item = STEPConstruct::FindEntity ( FP, S, L );
736
737   if ( ! item.IsNull() ) {
738     seqRI.Append ( item );
739     return 1;
740   }
741       
742   // may be S was splited during shape processing
743   Handle(TransferBRep_ShapeMapper) mapper = TransferBRep::ShapeMapper ( FP, S );
744   Handle(Transfer_Binder) bnd = FP->Find ( mapper );
745   if ( bnd.IsNull() ) return 0;
746   
747   Handle(Transfer_TransientListBinder) TransientListBinder =
748     //Handle(Transfer_TransientListBinder)::DownCast( bnd->Next(Standard_True) );
749     Handle(Transfer_TransientListBinder)::DownCast( bnd );
750   Standard_Integer nres=0;
751   if ( TransientListBinder.IsNull() && S.ShapeType() == TopAbs_COMPOUND) 
752   {
753     for ( TopoDS_Iterator it(S); it.More(); it.Next() ) {
754       Handle(StepRepr_RepresentationItem) item = STEPConstruct::FindEntity ( FP, it.Value(), L );
755       if ( item.IsNull() ) continue;
756       nres++;
757       seqRI.Append ( item );
758     }
759   }
760   else
761   {
762     const Standard_Integer nb = TransientListBinder->NbTransients();
763     for (Standard_Integer i=1; i<=nb; i++) {
764       Handle(Standard_Transient) t = TransientListBinder->Transient(i);
765       item = Handle(StepRepr_RepresentationItem)::DownCast(t);
766       if ( item.IsNull() ) continue;
767       nres++;
768       seqRI.Append ( item );
769     }
770   }
771 /*  works but is obsolete: another approach
772   if (i<=nb) {
773     TopoDS_Shape comp = TransferBRep::ShapeResult(bnd);
774     if ( ! comp.IsNull() && comp.ShapeType() < S.ShapeType() ) {
775       for ( TopoDS_Iterator it(comp); it.More(); it.Next() ) {
776         MakeSTEPStyles(Styles, it.Value(), settings, STEPstyle, 
777                        Map, ( hasOwn ? &style : 0 ) );
778       }
779     }
780   }
781 */
782   return nres;
783 }
784
785
786 //=======================================================================
787 //function : getStyledItem
788 //purpose  : auxilary
789 //=======================================================================
790 static Standard_Boolean getStyledItem(const TopoDS_Shape& S,
791                                       const Handle(XCAFDoc_ShapeTool)& STool,
792                                       const STEPConstruct_Styles &Styles, 
793                                       Handle(StepVisual_StyledItem) &resSelItem,
794                                       const MoniTool_DataMapOfShapeTransient& myMapCompMDGPR)
795 {
796   TDF_Label aTopShL = STool->FindShape(S, Standard_False);
797   TopoDS_Shape aTopLevSh = STool->GetShape( aTopShL );
798   Standard_Boolean found = Standard_False;
799   if ( !aTopLevSh.IsNull() &&  myMapCompMDGPR.IsBound( aTopLevSh ) ) {
800     Handle(StepVisual_PresentationRepresentation) aMDGPR = 
801       Handle(StepVisual_PresentationRepresentation)::DownCast( myMapCompMDGPR.Find( aTopLevSh ) );
802     Handle(StepRepr_HArray1OfRepresentationItem) anSelItmHArr = aMDGPR->Items();
803     // search for PSA of Monifold solid
804     if ( !anSelItmHArr.IsNull() )
805     {
806       for (Standard_Integer si = 1; si <= anSelItmHArr->Length(); si++) {
807         Handle(StepVisual_StyledItem) aSelItm =
808           Handle(StepVisual_StyledItem)::DownCast(anSelItmHArr->Value(si));
809
810         if ( aSelItm.IsNull() ) 
811           continue;
812
813         // check that it is a stiled item for monifold solid brep
814         TopLoc_Location Loc;
815         TColStd_SequenceOfTransient aNewseqRI;
816         FindEntities ( Styles.FinderProcess(), aTopLevSh, Loc, aNewseqRI );
817         if ( aNewseqRI.Length() > 0 )
818         {
819           
820           Handle(StepRepr_RepresentationItem) anItem = aSelItm->Item();
821           Standard_Boolean isSameMonSolBR = Standard_False;
822           for (Standard_Integer mi = 1; mi <= aNewseqRI.Length(); mi++) {
823             if ( !anItem.IsNull() && anItem == aNewseqRI.Value( mi ) ) {
824               isSameMonSolBR = Standard_True;
825               break;
826             }
827           }
828           if (!isSameMonSolBR)
829             continue;
830         }
831         
832         
833         for (Standard_Integer jsi = 1; jsi <= aSelItm->NbStyles() && !found; jsi++) {
834           Handle(StepVisual_PresentationStyleAssignment) aFatherPSA =
835             Handle(StepVisual_PresentationStyleAssignment)::DownCast(aSelItm->StylesValue(jsi));
836           // check for PSA for top-level (not Presentation style by contex for NAUO)
837           if (aFatherPSA.IsNull() || aFatherPSA->IsKind(STANDARD_TYPE(StepVisual_PresentationStyleByContext)))
838             continue;
839           resSelItem = aSelItm;
840           found = Standard_True;
841         }
842       }
843     }
844   }
845   return found;
846 }
847
848
849 //=======================================================================
850 //function : setDefaultInstanceColor
851 //purpose  : auxilary
852 //=======================================================================
853 static Standard_Boolean setDefaultInstanceColor (const Handle(StepVisual_StyledItem) &aSelItm,
854                                                  Handle(StepVisual_PresentationStyleAssignment)& PSA)
855 {
856    Standard_Boolean found = Standard_False;
857   for (Standard_Integer jsi = 1; jsi <= aSelItm->NbStyles() && !found; jsi++) {
858     Handle(StepVisual_PresentationStyleAssignment) aFatherPSA =
859     Handle(StepVisual_PresentationStyleAssignment)::DownCast(aSelItm->StylesValue(jsi));
860   // check for PSA for top-level (not Presentation style by contex for NAUO)
861   if (aFatherPSA.IsNull() || aFatherPSA->IsKind(STANDARD_TYPE(StepVisual_PresentationStyleByContext))) 
862     return Standard_False;
863           
864   // get style select from father PSA
865   if (aFatherPSA->NbStyles() > 0) {
866     Handle(StepVisual_HArray1OfPresentationStyleSelect) aFatherStyles =
867       new StepVisual_HArray1OfPresentationStyleSelect(1, aFatherPSA->NbStyles());
868     for (Standard_Integer k = 1; k <= aFatherPSA->NbStyles(); k++) {
869       StepVisual_PresentationStyleSelect PSS;
870       StepVisual_PresentationStyleSelect olDPSS = aFatherPSA->StylesValue(k);
871       if (!olDPSS.PointStyle().IsNull())
872         PSS.SetValue (olDPSS.PointStyle());
873       else if (!olDPSS.CurveStyle().IsNull())
874         PSS.SetValue (olDPSS.CurveStyle());
875       else if (!olDPSS.SurfaceStyleUsage().IsNull())
876         PSS.SetValue (olDPSS.SurfaceStyleUsage());
877       else {
878         found = Standard_False;
879         break;
880       }
881       //aFatherStyles->SetValue( k, PSS );
882       aFatherStyles->SetValue( k, olDPSS );
883       found = Standard_True;
884     }
885             // init PSA of NAUO
886     if (found) {
887       PSA->Init( aFatherStyles );
888     }
889   }
890     
891   }
892   return found;
893 }
894
895
896 //=======================================================================
897 //function : MakeSTEPStyles
898 //purpose  : auxilary
899 //=======================================================================
900 static void MakeSTEPStyles (STEPConstruct_Styles &Styles,
901                             const TopoDS_Shape &S,
902                             const XCAFPrs_DataMapOfShapeStyle &settings,
903                             Handle(StepVisual_StyledItem) &override,
904                             TopTools_MapOfShape &Map,
905                             const MoniTool_DataMapOfShapeTransient& myMapCompMDGPR,
906                             STEPConstruct_DataMapOfAsciiStringTransient &DPDCs,
907                             STEPConstruct_DataMapOfPointTransient &ColRGBs,
908                             const Handle(XCAFDoc_ColorTool)& CTool,
909                             const XCAFPrs_Style *inherit = 0,
910                             const Standard_Boolean isComponent = Standard_False)
911 {
912   // skip already processed shapes
913   if ( ! Map.Add ( S ) ) return;
914
915   // check if shape has its own style (r inherits from ancestor)
916   XCAFPrs_Style style;
917   if ( inherit ) style = *inherit;
918   if ( settings.IsBound(S) ) {
919     XCAFPrs_Style own = settings.Find(S);
920     if ( !own.IsVisible() ) style.SetVisibility ( Standard_False );
921     if ( own.IsSetColorCurv() ) style.SetColorCurv ( own.GetColorCurv() );
922     if ( own.IsSetColorSurf() ) style.SetColorSurf ( own.GetColorSurf() );
923   }
924
925   // translate colors to STEP
926   Handle(StepVisual_Colour) surfColor, curvColor;
927   if ( style.IsSetColorSurf() )
928     surfColor = Styles.EncodeColor(style.GetColorSurf(),DPDCs,ColRGBs);
929   if ( style.IsSetColorCurv() )
930     curvColor = Styles.EncodeColor(style.GetColorCurv(),DPDCs,ColRGBs);
931   
932   Standard_Boolean hasOwn = ( ! surfColor.IsNull() || 
933                               ! curvColor.IsNull() ||
934                               ! style.IsVisible() );
935
936   // find target item and assign style to it
937   Handle(StepVisual_StyledItem) STEPstyle = override;
938   if ( hasOwn ) {
939     if ( S.ShapeType() != TopAbs_COMPOUND || isComponent ) { // skip compounds, let subshapes inherit its colors
940       TopLoc_Location L;
941       TColStd_SequenceOfTransient seqRI;
942       Standard_Integer nb = FindEntities ( Styles.FinderProcess(), S, L, seqRI );
943 #ifdef OCCT_DEBUG
944       if ( nb <=0 ) cout << "Warning: Cannot find RI for " << S.TShape()->DynamicType()->Name() << endl;
945 #endif
946       //Get overridden style gka 10.06.03
947       if ( isComponent && nb) 
948         getStyledItem(S, CTool->ShapeTool(), Styles, override,myMapCompMDGPR);
949        
950            
951       for ( Standard_Integer i=1; i <= nb; i++ ) {
952         Handle(StepRepr_RepresentationItem) item = 
953           Handle(StepRepr_RepresentationItem)::DownCast(seqRI(i));
954         Handle(StepVisual_PresentationStyleAssignment) PSA;
955         if ( style.IsVisible() || !surfColor.IsNull() || !curvColor.IsNull() ) {
956           PSA = Styles.MakeColorPSA ( item, surfColor, curvColor, isComponent );
957         }
958         else {
959           // default white color
960           surfColor = Styles.EncodeColor(Quantity_Color(1,1,1,Quantity_TOC_RGB),DPDCs,ColRGBs);
961           PSA = Styles.MakeColorPSA ( item, surfColor, curvColor, isComponent );
962           if ( isComponent ) 
963             setDefaultInstanceColor( override, PSA);
964           
965         } // end of component case
966         
967         STEPstyle = Styles.AddStyle ( item, PSA, override );
968         hasOwn = Standard_False;
969       }
970     }
971   }
972
973   // iterate on subshapes (except vertices :)
974   if ( S.ShapeType() == TopAbs_EDGE ) return;
975   if ( !isComponent ) // PTV 10.02.2003
976     for ( TopoDS_Iterator it(S); it.More(); it.Next() ) {
977       MakeSTEPStyles ( Styles, it.Value(), settings, STEPstyle,
978                       Map, myMapCompMDGPR, DPDCs, ColRGBs, CTool,
979                       ( hasOwn ? &style : 0 ) );
980     }
981 }
982
983 /*
984 static Standard_Boolean getFatherColor (const TDF_Label& L,
985                                         const Handle(XCAFDoc_ColorTool)& CTool,
986                                         XCAFPrs_Style& style)
987 {
988   Standard_Boolean done = Standard_False;
989   TopoDS_Shape aSh = CTool->ShapeTool()->GetShape( L );
990   TDF_Label aFL = CTool->ShapeTool()->FindShape( aSh );
991   if (aFL.IsNull() || aFL == L)
992     return done;
993   Quantity_Color C;
994   if ( CTool->GetColor ( aFL, XCAFDoc_ColorGen, C ) ) {
995     style.SetColorCurv ( C );
996     style.SetColorSurf ( C );
997     done = Standard_True;
998   }
999   if ( CTool->GetColor ( aFL, XCAFDoc_ColorSurf, C ) ) {
1000     style.SetColorSurf ( C );
1001     done = Standard_True;
1002   }
1003   if ( CTool->GetColor ( aFL, XCAFDoc_ColorCurv, C ) ) {
1004     style.SetColorCurv ( C );
1005     done = Standard_True;
1006   }
1007   
1008   return done;
1009 }
1010 */
1011
1012
1013 //=======================================================================
1014 //function : WriteColors
1015 //purpose  : 
1016 //=======================================================================
1017
1018 Standard_Boolean STEPCAFControl_Writer::WriteColors (const Handle(XSControl_WorkSession) &WS,
1019                                                      const TDF_LabelSequence &labels)
1020 {
1021   if ( labels.Length() <=0 ) return Standard_False;
1022
1023   // Iterate on shapes in the document
1024   Handle(XCAFDoc_ColorTool) CTool = XCAFDoc_DocumentTool::ColorTool( labels(1) );
1025   if ( CTool.IsNull() ) return Standard_False;
1026
1027   STEPConstruct_Styles Styles ( WS );
1028   STEPConstruct_DataMapOfAsciiStringTransient DPDCs;
1029   STEPConstruct_DataMapOfPointTransient ColRGBs;
1030   for ( Standard_Integer i=1; i <= labels.Length(); i++ ) {
1031     TDF_Label L = labels.Value(i);
1032
1033     Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool( labels(1) );
1034     // Skip assemblies: colors assigned to assemblies and their instances
1035     // are not supported (it is not clear how to encode that in STEP)
1036     if ( XCAFDoc_ShapeTool::IsAssembly ( L ) ) {
1037 #ifdef OCCT_DEBUG
1038       cout << "Warning: Cannot write color  for Assembly" << endl;
1039       cout << "Info: Check for colors assigned to components in assembly" << endl;
1040 #endif
1041       // PTV 22.01.2003 Write color for instances.
1042       TDF_LabelSequence compLabels;
1043       if ( aSTool.IsNull() )
1044         continue;
1045       if (!aSTool->GetComponents(L, compLabels))
1046         continue;
1047       WriteColors(WS, compLabels);
1048       continue;
1049     }
1050     Styles.ClearStyles();
1051
1052     // get a target shape and try to find corresponding context
1053     // (all the colors set under that label will be put into that context)
1054     TopoDS_Shape S;
1055     if ( ! XCAFDoc_ShapeTool::GetShape ( L, S ) ) continue;
1056     Standard_Boolean isComponent = aSTool->IsComponent( L );
1057     TopoDS_Shape aTopSh = S;
1058     Handle(StepRepr_RepresentationContext) Context = Styles.FindContext ( S );
1059     if ( isComponent ) {
1060       TDF_Label aTopShL = aSTool->FindShape(S, Standard_False);
1061       if (aTopShL.IsNull())
1062         continue;
1063       aTopSh = aSTool->GetShape( aTopShL );
1064       Context = Styles.FindContext ( aTopSh );
1065     }
1066     if ( Context.IsNull() )
1067         continue;
1068     
1069     // collect settings set on that label
1070     XCAFPrs_DataMapOfShapeStyle settings;
1071     TDF_LabelSequence seq;
1072     seq.Append ( L );
1073     XCAFDoc_ShapeTool::GetSubShapes ( L, seq );
1074     Standard_Boolean isVisible = Standard_True;
1075     for ( Standard_Integer j = 1; j <= seq.Length(); j++ ) {
1076       TDF_Label lab = seq.Value(j);
1077       XCAFPrs_Style style;
1078       Quantity_Color C;
1079       if ( lab == L ) {
1080         // check for invisible status of object on label
1081         if ( !CTool->IsVisible( lab ) ) {
1082           isVisible = Standard_False;
1083           style.SetVisibility( Standard_False );
1084         }
1085       }
1086       if ( CTool->GetColor ( lab, XCAFDoc_ColorGen, C ) ) {
1087         style.SetColorCurv ( C );
1088         style.SetColorSurf ( C );
1089       }
1090       if ( CTool->GetColor ( lab, XCAFDoc_ColorSurf, C ) )
1091         style.SetColorSurf ( C );
1092       if ( CTool->GetColor ( lab, XCAFDoc_ColorCurv, C ) )
1093         style.SetColorCurv ( C );
1094       
1095       // commented, cause we are need to take reference from 
1096 //       if ( isComponent && lab == L && !isVisible)
1097 //         if ( !style.IsSetColorSurf() && !style.IsSetColorCurv() ) {
1098 //           getFatherColor ( L, CTool, style);
1099 //         }
1100       if ( ! style.IsSetColorCurv() && ! style.IsSetColorSurf() && isVisible ) continue;
1101
1102       TopoDS_Shape sub = XCAFDoc_ShapeTool::GetShape ( lab );
1103       settings.Bind ( sub, style );
1104     }
1105     
1106     if ( settings.Extent() <=0 ) continue;
1107
1108     // iterate on subshapes and create STEP styles
1109     Handle(StepVisual_StyledItem) override;
1110     TopTools_MapOfShape Map;
1111     
1112     MakeSTEPStyles(Styles,S,settings,override,Map,myMapCompMDGPR,DPDCs,ColRGBs,CTool,0,isComponent);
1113     
1114     // create MDGPR and record it in model
1115     Handle(StepVisual_MechanicalDesignGeometricPresentationRepresentation) aMDGPR;
1116
1117     if (!isComponent) {
1118       if ( myMapCompMDGPR.IsBound( aTopSh )) {
1119 #ifdef OCCT_DEBUG
1120         cerr << "Error: Current Top-Level shape have MDGPR already " << endl;
1121 #endif
1122       }
1123       Styles.CreateMDGPR ( Context, aMDGPR );
1124       if (!aMDGPR.IsNull())
1125         myMapCompMDGPR.Bind( aTopSh, aMDGPR );
1126     }
1127     else {
1128       // create SDR and add to model.
1129       Handle(XSControl_TransferWriter) TW = WS->TransferWriter();
1130       Handle(Transfer_FinderProcess) FP = TW->FinderProcess();
1131       Handle(TransferBRep_ShapeMapper) mapper = TransferBRep::ShapeMapper ( FP, S );
1132       Handle(StepShape_ContextDependentShapeRepresentation) CDSR;
1133       if ( FP->FindTypedTransient(mapper, 
1134                                   STANDARD_TYPE(StepShape_ContextDependentShapeRepresentation),
1135                                   CDSR) ) {
1136         // create SDR for NAUO
1137         Handle(StepRepr_ProductDefinitionShape) nullPDS; // important to be NULL
1138         Styles.CreateNAUOSRD( Context, CDSR, nullPDS );
1139         
1140         // search for MDGPR of the component top-level shape
1141         if ( myMapCompMDGPR.IsBound( aTopSh )) {
1142           aMDGPR = Handle(StepVisual_MechanicalDesignGeometricPresentationRepresentation)::DownCast( myMapCompMDGPR.Find( aTopSh ) );
1143         } else {
1144           aMDGPR = new StepVisual_MechanicalDesignGeometricPresentationRepresentation;
1145           Handle(TCollection_HAsciiString) ReprName = new TCollection_HAsciiString ( "" );
1146           aMDGPR->SetName( ReprName );
1147           aMDGPR->SetContextOfItems( Context );
1148           myMapCompMDGPR.Bind ( aTopSh, aMDGPR );
1149         }
1150         Handle(StepRepr_HArray1OfRepresentationItem) oldItems = aMDGPR->Items();
1151         Standard_Integer oldLengthlen = 0;
1152         if (!oldItems.IsNull())
1153           oldLengthlen = oldItems->Length();
1154         const Standard_Integer nbIt = oldLengthlen + Styles.NbStyles();
1155         if(!nbIt)
1156           continue;
1157         Handle(StepRepr_HArray1OfRepresentationItem) newItems =
1158           new StepRepr_HArray1OfRepresentationItem(1, nbIt);
1159         Standard_Integer si;
1160         Standard_Integer el = 1;
1161         for ( si=1; si <= oldLengthlen; si++ )
1162           newItems->SetValue( el++, oldItems->Value( si ) );
1163         for ( si=1; si <= Styles.NbStyles(); si++ ) {
1164           newItems->SetValue( el++, Handle(StepRepr_RepresentationItem)::DownCast(Styles.Style(si)));
1165 //           WP->Model()->AddWithRefs ( Handle(StepRepr_RepresentationItem)::DownCast (Styles.Style(si)));
1166         }
1167        
1168         if (newItems->Length() > 0)
1169           aMDGPR->SetItems( newItems );
1170       } //end of work with CDSR
1171     }
1172     if ( !isVisible ) {
1173     // create invisibility item and refer for stiledItem
1174       Handle(StepVisual_Invisibility) Invsblt = new StepVisual_Invisibility();
1175       Handle(StepVisual_HArray1OfInvisibleItem) HInvsblItm = 
1176         new StepVisual_HArray1OfInvisibleItem (1,Styles.NbStyles());
1177       // put all style item into the harray
1178       for ( Standard_Integer si=1; si <= Styles.NbStyles(); si++ ) {
1179         Handle(StepRepr_RepresentationItem) styledItm =
1180           Handle(StepRepr_RepresentationItem)::DownCast(Styles.Style(si));
1181         StepVisual_InvisibleItem anInvItem;
1182         anInvItem.SetValue( styledItm );
1183         HInvsblItm->SetValue( si, anInvItem );
1184       }
1185       // set the invisibility of items
1186       Invsblt->Init( HInvsblItm );
1187       WS->Model()->AddWithRefs( Invsblt );
1188     }
1189   }
1190
1191   return Standard_True;
1192 }
1193
1194
1195 //=======================================================================
1196 //function : WriteNames
1197 //purpose  :
1198 //=======================================================================
1199
1200 Standard_Boolean STEPCAFControl_Writer::WriteNames (const Handle(XSControl_WorkSession) &WS,
1201                                                     const TDF_LabelSequence &labels) const
1202 {
1203   if ( labels.Length() <=0 ) return Standard_False;
1204
1205   // get working data
1206   Handle(Interface_InterfaceModel) Model = WS->Model();
1207   Handle(XSControl_TransferWriter) TW = WS->TransferWriter();
1208   Handle(Transfer_FinderProcess) FP = TW->FinderProcess();
1209 //  Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( labels(1) );
1210 //  if ( STool.IsNull() ) return Standard_False;
1211
1212   // Iterate on requested shapes
1213   for ( Standard_Integer i=1; i <= labels.Length(); i++ ) {
1214     TDF_Label L = labels.Value(i);
1215
1216     // get name
1217     Handle(TCollection_HAsciiString) hName = new TCollection_HAsciiString;
1218     if ( ! GetLabelName (L, hName) ) continue;
1219 //    Handle(TDataStd_Name) N;
1220 //    if ( ! L.FindAttribute ( TDataStd_Name::GetID(), N ) ) continue;
1221 //    TCollection_ExtendedString name = N->Get();
1222 //    if ( name.Length() <=0 ) continue;
1223
1224     // find target STEP entity for the current shape
1225 //    TopoDS_Shape S;
1226 //    if ( ! XCAFDoc_ShapeTool::GetShape ( L, S ) ) continue;
1227     if ( ! myLabels.IsBound ( L ) ) continue; // not recorded as translated, skip
1228     TopoDS_Shape S = myLabels.Find ( L );
1229
1230     Handle(StepShape_ShapeDefinitionRepresentation) SDR;
1231     Handle(TransferBRep_ShapeMapper) mapper = TransferBRep::ShapeMapper ( FP, S );
1232     if ( ! FP->FindTypedTransient ( mapper, STANDARD_TYPE(StepShape_ShapeDefinitionRepresentation), SDR ) ) {
1233 #ifdef OCCT_DEBUG
1234       cout << "Warning: Cannot find SDR for " << S.TShape()->DynamicType()->Name() << endl;
1235 #endif
1236       continue;
1237     }
1238
1239     // set the name to the PRODUCT
1240     Handle(StepRepr_PropertyDefinition) PropD = SDR->Definition().PropertyDefinition();
1241     if ( PropD.IsNull() ) continue;
1242     Handle(StepBasic_ProductDefinition) PD = PropD->Definition().ProductDefinition();
1243     if ( PD.IsNull() ) continue;
1244     Handle(StepBasic_Product) Prod = PD->Formation()->OfProduct();
1245
1246     Prod->SetId ( hName );
1247     Prod->SetName ( hName );
1248
1249     // write names for components of assemblies
1250     if ( XCAFDoc_ShapeTool::IsAssembly ( L ) ) {
1251       TDF_LabelSequence seq;
1252       XCAFDoc_ShapeTool::GetComponents ( L, seq );
1253       for (Standard_Integer k=1; k <= seq.Length(); k++) {
1254         TDF_Label lab = seq(k);
1255
1256         // get shape with correct location
1257         TDF_Label Lref;
1258         if ( ! XCAFDoc_ShapeTool::GetReferredShape ( lab, Lref ) || 
1259              ! myLabels.IsBound ( Lref ) ) continue;
1260         S = myLabels.Find ( Lref );
1261         S.Move ( XCAFDoc_ShapeTool::GetLocation ( lab ) );
1262         
1263         hName = new TCollection_HAsciiString;
1264         if ( ! GetLabelName (lab, hName) ) continue;
1265         
1266         // find the target CDSR corresponding to a shape
1267         mapper = TransferBRep::ShapeMapper ( FP, S );
1268         Handle(Transfer_Binder) binder = FP->Find ( mapper );
1269         Handle(StepShape_ContextDependentShapeRepresentation) CDSR;
1270         if ( ! FP->FindTypedTransient (mapper,STANDARD_TYPE(StepShape_ContextDependentShapeRepresentation), CDSR) ) 
1271           continue;
1272         Handle(StepRepr_ProductDefinitionShape) PDS = CDSR->RepresentedProductRelation();
1273         Handle(StepBasic_ProductDefinitionRelationship) NAUO = PDS->Definition().ProductDefinitionRelationship();
1274         if ( ! NAUO.IsNull() ) NAUO->SetName ( hName );
1275       }
1276     }
1277   }
1278
1279   return Standard_True;
1280 }
1281
1282
1283 //=======================================================================
1284 //function : WritePropsForLabel
1285 //purpose  :
1286 //=======================================================================
1287 static Standard_Boolean WritePropsForLabel(const Handle(XSControl_WorkSession) &WS,
1288                                            const Handle(XCAFDoc_ShapeTool) &aSTool,
1289                                            const STEPCAFControl_DataMapOfLabelShape &myLabels,
1290                                            const TDF_Label &L,
1291                                            const Standard_CString multi)
1292 {
1293   if(L.IsNull()) return Standard_False;
1294
1295   STEPConstruct_ValidationProps Props ( WS );
1296
1297   TopoDS_Shape S = aSTool->GetShape(L);
1298   if(S.IsNull()) return Standard_False;
1299
1300   if ( ! multi || XCAFDoc_ShapeTool::IsAssembly ( L ) ) {
1301     // write area
1302     Handle(XCAFDoc_Area) A;
1303     L.FindAttribute ( XCAFDoc_Area::GetID(), A );
1304     if ( ! A.IsNull() ) {
1305       Props.AddArea ( S, A->Get() );
1306     }
1307     // write volume
1308     Handle(XCAFDoc_Volume) V;
1309     L.FindAttribute ( XCAFDoc_Volume::GetID(), V );
1310     if ( ! V.IsNull() ) {
1311       Props.AddVolume ( S, V->Get() );
1312     }
1313   }
1314   // write centroid
1315   Handle(XCAFDoc_Centroid) C;
1316   L.FindAttribute ( XCAFDoc_Centroid::GetID(), C );
1317   if ( ! C.IsNull() ) {
1318     Props.AddCentroid ( S, C->Get() );
1319   }
1320
1321   if( XCAFDoc_ShapeTool::IsCompound(L) || XCAFDoc_ShapeTool::IsAssembly(L) ) {
1322     if(L.HasChild()) {
1323       for(Standard_Integer ich=1; ich<=L.NbChildren(); ich++) {
1324         WritePropsForLabel(WS,aSTool,myLabels,L.FindChild(ich),multi);
1325       }
1326     }
1327   }
1328
1329   return Standard_True;
1330 }
1331
1332
1333 //=======================================================================
1334 //function : WriteValProps
1335 //purpose  :
1336 //=======================================================================
1337
1338 Standard_Boolean STEPCAFControl_Writer::WriteValProps (const Handle(XSControl_WorkSession) &WS,
1339                                                        const TDF_LabelSequence &labels,
1340                                                        const Standard_CString multi) const
1341 {
1342   if ( labels.Length() <=0 ) return Standard_False;
1343
1344   // get working data
1345 //  STEPConstruct_ValidationProps Props ( WS );
1346   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool( labels(1) );
1347
1348   // Iterate on requested shapes
1349   for ( Standard_Integer i=1; i <= labels.Length(); i++ ) {
1350     TDF_Label L = labels.Value(i);
1351
1352     WritePropsForLabel(WS,aSTool,myLabels,L,multi);
1353 /*    
1354     // find target STEP entity for the current shape
1355     if ( ! myLabels.IsBound ( L ) ) continue; // not recorded as translated, skip
1356     TopoDS_Shape S = myLabels.Find ( L );
1357
1358     // write area and volume (except for components in multifile mode)
1359     if ( ! multi || XCAFDoc_ShapeTool::IsAssembly ( L ) ) {
1360       Handle(XCAFDoc_Area) A;
1361       L.FindAttribute ( XCAFDoc_Area::GetID(), A );
1362       if ( ! A.IsNull() ) Props.AddArea ( S, A->Get() );
1363
1364       Handle(XCAFDoc_Volume) V;
1365       L.FindAttribute ( XCAFDoc_Volume::GetID(), V );
1366       if ( ! V.IsNull() ) Props.AddVolume ( S, V->Get() );
1367     }
1368
1369     // write centroid
1370     Handle(XCAFDoc_Centroid) C;
1371     L.FindAttribute ( XCAFDoc_Centroid::GetID(), C );
1372     if ( ! C.IsNull() ) Props.AddCentroid ( S, C->Get() );
1373
1374     // write centroid for components of assemblies
1375     if ( XCAFDoc_ShapeTool::IsAssembly ( L ) ) {
1376       TDF_LabelSequence seq;
1377       XCAFDoc_ShapeTool::GetComponents ( L, seq );
1378       for (Standard_Integer k=1; k <= seq.Length(); k++) {
1379         TDF_Label lab = seq(k);
1380
1381         // get shape with correct location
1382         TDF_Label Lref;
1383         if ( ! XCAFDoc_ShapeTool::GetReferredShape ( lab, Lref ) || 
1384              ! myLabels.IsBound ( Lref ) ) continue;
1385         TopLoc_Location Loc = XCAFDoc_ShapeTool::GetLocation ( lab );
1386         S = myLabels.Find ( Lref );
1387         S.Move ( Loc );
1388                 
1389         C.Nullify();
1390         lab.FindAttribute ( XCAFDoc_Centroid::GetID(), C );
1391         // if centroid is not assigned to an instance, 
1392         // use (shifted) centroid of original shape
1393         gp_Pnt center;
1394         if ( C.IsNull() ) {
1395           Lref.FindAttribute ( XCAFDoc_Centroid::GetID(), C );
1396           if ( C.IsNull() ) continue;
1397           center = C->Get().Transformed ( Loc.Transformation() );
1398         }
1399         else center = C->Get();
1400
1401         Props.AddCentroid ( S, center, Standard_True );
1402       }
1403     }
1404 */
1405   }
1406
1407   return Standard_True;
1408 }
1409
1410
1411 //=======================================================================
1412 //function : WriteLayers
1413 //purpose  : 
1414 //=======================================================================
1415
1416 Standard_Boolean STEPCAFControl_Writer::WriteLayers (const Handle(XSControl_WorkSession) &WS,
1417                                                      const TDF_LabelSequence  &labels ) const
1418 {
1419   
1420   if ( labels.Length() <=0 ) return Standard_False;
1421
1422   // get working data
1423   Handle(Interface_InterfaceModel) Model = WS->Model();
1424   Handle(XSControl_TransferWriter) TW = WS->TransferWriter();
1425   Handle(Transfer_FinderProcess) FP = TW->FinderProcess();
1426   Handle(XCAFDoc_LayerTool) LTool = XCAFDoc_DocumentTool::LayerTool( labels(1) );
1427   if (LTool.IsNull() ) return Standard_False;
1428
1429   TDF_LabelSequence LayerLS;
1430   LTool->GetLayerLabels(LayerLS);
1431   if ( LayerLS.Length() <=0 ) return Standard_False;
1432
1433   // Iterate on requested layers and for each layer take set of shapes.
1434   for ( Standard_Integer i=1; i <= LayerLS.Length(); i++ ) {
1435     TDF_Label L = LayerLS.Value(i);
1436     
1437     // get labels of shapes in that layer
1438     TDF_LabelSequence ShapeLs;
1439     LTool->GetShapesOfLayer(L, ShapeLs);
1440     if ( ShapeLs.Length() <=0 ) continue;
1441     
1442     // name of layer: if not set, is considered as being empty
1443     Handle(TCollection_HAsciiString) hName = new TCollection_HAsciiString;
1444     GetLabelName ( L, hName );
1445
1446     // Find target STEP entity for each shape and add to StepVisual_PresentationLayerAssignment items.
1447     TColStd_SequenceOfTransient seqRI;
1448     for ( Standard_Integer j=1; j <= ShapeLs.Length(); j++) {
1449       TDF_Label shLabel = ShapeLs.Value(j);
1450       if ( shLabel.IsNull() ) continue;
1451       
1452       // there is no way to assign layer to instance in STEP
1453       if ( XCAFDoc_ShapeTool::IsAssembly ( shLabel ) ||
1454            XCAFDoc_ShapeTool::IsReference ( shLabel ) )
1455         continue;
1456       
1457       // check that the shape is one of (uub)labels written during current transfer
1458       Standard_Integer k = 1;
1459       for ( ; k <= labels.Length(); k++ )
1460         if ( shLabel.IsDescendant ( labels(k) ) ) break;
1461       if ( k > labels.Length() ) continue;
1462
1463       // get target STEP entity
1464       TopoDS_Shape oneShape = XCAFDoc_ShapeTool::GetShape(shLabel);
1465       
1466       TopLoc_Location Loc;
1467       Standard_Integer nb = 
1468         FindEntities ( FP, oneShape, Loc, seqRI );
1469       if ( nb <=0 ) 
1470         FP->Messenger() << "Warning: Cannot find RI for " << oneShape.TShape()->DynamicType()->Name() << endl;
1471     }
1472     if ( seqRI.Length() <= 0 ) continue;
1473
1474     // analyze visibility
1475     Handle(StepVisual_PresentationLayerAssignment) StepLayerAs = new StepVisual_PresentationLayerAssignment;
1476     Handle(TCollection_HAsciiString) descr;
1477     Handle(TDataStd_UAttribute) aUAttr;
1478     Standard_Boolean isLinv = Standard_False;
1479     if (L.FindAttribute(XCAFDoc::InvisibleGUID(), aUAttr)) {
1480       descr = new TCollection_HAsciiString ("invisible");
1481 #ifdef OCCT_DEBUG
1482       FP->Messenger() << "\tLayer \"" << hName->String().ToCString() << "\" is invisible"<<endl;
1483 #endif
1484       isLinv = Standard_True;
1485     }
1486     else descr = new TCollection_HAsciiString ("visible");
1487     
1488     // create layer entity
1489     Handle(StepVisual_HArray1OfLayeredItem) HArrayOfLItem = 
1490       new StepVisual_HArray1OfLayeredItem ( 1, seqRI.Length() );
1491     for (Standard_Integer i1 = 1; i1<=seqRI.Length(); i1++) {
1492       StepVisual_LayeredItem LI;
1493       LI.SetValue ( seqRI.Value(i1) );
1494       HArrayOfLItem->SetValue( i1, LI );
1495     }
1496     StepLayerAs->Init(hName, descr, HArrayOfLItem);
1497     Model->AddWithRefs( StepLayerAs );
1498     // PTV 23.01.2003 add the invisibility AFTER adding layer into the model.
1499     // add the invisibility for the layer
1500     if (isLinv) {
1501       // Invisibility Item for containig invisible layers.
1502       Handle(StepVisual_HArray1OfInvisibleItem) HInvsblItm = new StepVisual_HArray1OfInvisibleItem (1,1);
1503       StepVisual_InvisibleItem InvIt;
1504       InvIt.SetValue( StepLayerAs );
1505       HInvsblItm->SetValue( 1, InvIt);
1506       
1507       Handle(StepVisual_Invisibility) Invsblt = new StepVisual_Invisibility();
1508       Invsblt->Init( HInvsblItm );
1509       Model->AddWithRefs( Invsblt );
1510     }
1511   }
1512   return Standard_True;
1513 }
1514
1515
1516 //=======================================================================
1517 //function : getSHUOstyle
1518 //purpose  : auxilary
1519 //=======================================================================
1520 static Standard_Boolean getSHUOstyle(const TDF_Label& aSHUOlab,
1521                                      const Handle(XCAFDoc_ColorTool)& CTool,
1522                                      XCAFPrs_Style& SHUOstyle)
1523 {
1524   Quantity_Color C;
1525   if (!CTool->IsVisible( aSHUOlab ) )
1526     SHUOstyle.SetVisibility(Standard_False);
1527   else {
1528     if ( CTool->GetColor ( aSHUOlab, XCAFDoc_ColorGen, C ) ) {
1529       SHUOstyle.SetColorCurv ( C );
1530       SHUOstyle.SetColorSurf ( C );
1531     }
1532     if ( CTool->GetColor ( aSHUOlab, XCAFDoc_ColorSurf, C ) )
1533       SHUOstyle.SetColorSurf ( C );
1534     if ( CTool->GetColor ( aSHUOlab, XCAFDoc_ColorCurv, C ) )
1535       SHUOstyle.SetColorCurv ( C );
1536   }
1537   if ( !SHUOstyle.IsSetColorCurv() && 
1538       !SHUOstyle.IsSetColorSurf() &&
1539       SHUOstyle.IsVisible() )
1540     return Standard_False;
1541   return Standard_True;
1542 }
1543
1544
1545 //=======================================================================
1546 //function : getProDefinitionOfNAUO
1547 //purpose  : auxilary
1548 //=======================================================================
1549 static Standard_Boolean getProDefinitionOfNAUO(const Handle(XSControl_WorkSession)& WS,
1550                                                const TopoDS_Shape& theShape,
1551                                                Handle(StepBasic_ProductDefinition)& PD,
1552                                                Handle(StepRepr_NextAssemblyUsageOccurrence)& NAUO,
1553                                                Standard_Boolean IsRelating)
1554 {
1555   if ( theShape.IsNull() )
1556     return Standard_False;
1557   // get CDSR
1558   Handle(XSControl_TransferWriter) TW = WS->TransferWriter();
1559   Handle(Transfer_FinderProcess) FP = TW->FinderProcess();
1560   Handle(StepShape_ContextDependentShapeRepresentation) CDSR;
1561   Handle(TransferBRep_ShapeMapper) mapper = TransferBRep::ShapeMapper ( FP, theShape );
1562   if (!FP->FindTypedTransient(mapper, 
1563                               STANDARD_TYPE(StepShape_ContextDependentShapeRepresentation),
1564                               CDSR))
1565     return Standard_False;
1566   // get PDS of NAUO
1567   Handle(StepRepr_ProductDefinitionShape) PDS = CDSR->RepresentedProductRelation();
1568   if (PDS.IsNull())
1569     return Standard_False;
1570   // get the NAUO entity
1571   Interface_Graph aGraph = WS->HGraph()->Graph();
1572   Interface_EntityIterator subs = aGraph.Shareds(PDS);
1573   for ( subs.Start(); subs.More(); subs.Next() ) {
1574     if (!subs.Value()->IsKind(STANDARD_TYPE(StepRepr_NextAssemblyUsageOccurrence)))
1575       continue;
1576     NAUO = Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(subs.Value());
1577     break;
1578   }
1579   if ( NAUO.IsNull() )
1580     return Standard_False;
1581   // get Relatinf or Related product definition
1582   if ( !IsRelating )
1583     PD = NAUO->RelatedProductDefinition();
1584   else
1585     PD = NAUO->RelatingProductDefinition();
1586   if ( PD.IsNull() )
1587     return Standard_False;
1588   return Standard_True;
1589 }
1590
1591
1592 //=======================================================================
1593 //function : writeSHUO
1594 //purpose  : auxilary
1595 //=======================================================================
1596 static Standard_Boolean writeSHUO (const Handle(XCAFDoc_GraphNode)& theSHUO,
1597                                    const Handle(XCAFDoc_ShapeTool)& theSTool,
1598                                    const Handle(XSControl_WorkSession)& WS,
1599                                    Handle(StepRepr_SpecifiedHigherUsageOccurrence)& theTopSHUO,
1600                                    TopoDS_Shape& NAUOShape,
1601                                    Handle(StepBasic_ProductDefinition)& theRelatingPD,
1602                                    Standard_Boolean& isDeepest)
1603 {
1604   // set the ProductDefinitionRelationship descriptin information as empty strings.
1605   Handle(TCollection_HAsciiString) EmptyString = new TCollection_HAsciiString("");
1606   
1607   TDF_LabelSequence aNextUsageLabs;
1608   theSTool->GetSHUONextUsage( theSHUO->Label(), aNextUsageLabs );
1609   Handle(XCAFDoc_GraphNode) NuSHUO;
1610   if ( theTopSHUO.IsNull() ) {
1611     // the top SHUO
1612     if (aNextUsageLabs.Length() < 1)
1613       return Standard_False;
1614     theSTool->GetSHUO( aNextUsageLabs.Value(1), NuSHUO );
1615     if (NuSHUO.IsNull())
1616       return Standard_False;
1617     // get relating product definition
1618     TopoDS_Shape aTopCompShape = theSTool->GetShape( theSHUO->Label().Father() ); 
1619     Handle(StepRepr_NextAssemblyUsageOccurrence) UUNAUO;
1620     if (!getProDefinitionOfNAUO( WS, aTopCompShape,
1621                                  theRelatingPD, UUNAUO, Standard_True ))
1622       return Standard_False;
1623     // get related product definition
1624     TopoDS_Shape aNUShape = theSTool->GetShape( NuSHUO->Label().Father() );
1625     Handle(StepBasic_ProductDefinition) aRelatedPD;
1626     Handle(StepRepr_NextAssemblyUsageOccurrence) NUNAUO;
1627     if (!getProDefinitionOfNAUO( WS, aNUShape,
1628                                  aRelatedPD, NUNAUO, Standard_False ))
1629       return Standard_False;
1630     
1631     theTopSHUO = new StepRepr_SpecifiedHigherUsageOccurrence;
1632     // create deepest shuo EmptyString
1633     theTopSHUO->Init(/*id*/EmptyString, /*name*/EmptyString,
1634                      /*no description*/Standard_False,/*description*/EmptyString,
1635                      theRelatingPD, aRelatedPD,
1636                      /*no ACURefDesignator*/Standard_False,/*ACURefDesignator*/EmptyString,
1637                      /*upper_usage*/UUNAUO, /*next_usage*/NUNAUO);
1638     // write the other SHUO.
1639     if(!writeSHUO( NuSHUO, theSTool, WS, theTopSHUO, NAUOShape, theRelatingPD, isDeepest )) {
1640       theTopSHUO.Nullify();
1641       return Standard_False;
1642     }
1643     
1644     return Standard_True;
1645   }
1646 //   Handle(XCAFDoc_GraphNode) NuSHUO;
1647   if ( aNextUsageLabs.Length() > 0) {
1648     // store SHUO recursive
1649 #ifdef OCCT_DEBUG
1650     if ( aNextUsageLabs.Length() > 1 )
1651       cout << "Warning: store only one next_usage of current SHUO"  << endl;
1652 #endif    
1653     theSTool->GetSHUO( aNextUsageLabs.Value(1), NuSHUO );
1654     Handle(StepRepr_SpecifiedHigherUsageOccurrence) aNUEntSHUO =
1655       new StepRepr_SpecifiedHigherUsageOccurrence;
1656     if (!writeSHUO( NuSHUO, theSTool, WS, aNUEntSHUO, NAUOShape, theRelatingPD, isDeepest ))
1657       return Standard_False;
1658     
1659     // store the deepest SHUO to the dociment
1660     TopoDS_Shape aNUSh, aUUSh;
1661     aNUSh = theSTool->GetShape( NuSHUO->Label().Father() );
1662     aUUSh = theSTool->GetShape( theSHUO->Label().Father() );
1663     // get relating PD with upper_usage and related PD with next_usage
1664     Handle(StepBasic_ProductDefinition) nullPD;// no need to use,case have shared <theRelatingPD>
1665     Handle(StepBasic_ProductDefinition) aRelatedPD;
1666     Handle(StepRepr_NextAssemblyUsageOccurrence) UUNAUO, NUNAUO;
1667     if (!getProDefinitionOfNAUO( WS, aUUSh, nullPD, UUNAUO, Standard_True ) ||
1668         !getProDefinitionOfNAUO( WS, aNUSh, aRelatedPD, NUNAUO, Standard_False )) {
1669 #ifdef OCCT_DEBUG
1670       cout << "Warning: cannot get related or relating PD" << endl;
1671 #endif
1672       return Standard_False;
1673     }
1674     aNUEntSHUO->Init(/*id*/EmptyString, /*name*/EmptyString,
1675                      /*no description*/Standard_False,/*description*/EmptyString,
1676                      theRelatingPD, aRelatedPD,
1677                      /*no ACURefDesignator*/Standard_False,/*ACURefDesignator*/EmptyString,
1678                      /*upper_usage*/theTopSHUO, /*next_usage*/NUNAUO);
1679     if ( isDeepest ) {
1680       isDeepest = Standard_False;
1681     }
1682     WS->Model()->AddWithRefs ( aNUEntSHUO );
1683     return Standard_True;
1684   } // end of recurse storing
1685     
1686   // get shape 
1687   TDF_Label aShapeL = theSHUO->Label().Father();
1688   NAUOShape = theSTool->GetShape( aShapeL );
1689   // return to the deepest level from SHUO shape level
1690   // it is because SHUO is attribute on deep level and shape level.
1691   isDeepest = Standard_True;
1692   return Standard_True;
1693 }
1694
1695
1696 //=======================================================================
1697 //function : createSHUOStyledItem
1698 //purpose  : auxilary
1699 //=======================================================================
1700 static Standard_Boolean createSHUOStyledItem (const XCAFPrs_Style& style,
1701                                               const Handle(StepRepr_ProductDefinitionShape)& PDS,
1702                                               const Handle(XSControl_WorkSession) &WS,
1703                                               const TopoDS_Shape& Sh,
1704                                               const Handle(XCAFDoc_ShapeTool)& STool,
1705                                               MoniTool_DataMapOfShapeTransient& myMapCompMDGPR)
1706 {
1707   // create styled item for the indicated SHUO and store to the model
1708   STEPConstruct_Styles Styles( WS );
1709   // translate colors to STEP
1710   Handle(StepVisual_Colour) surfColor, curvColor;
1711   if ( style.IsSetColorSurf() )
1712     surfColor = Styles.EncodeColor ( style.GetColorSurf() );
1713   if ( style.IsSetColorCurv() )
1714     curvColor = Styles.EncodeColor ( style.GetColorCurv() );
1715   Standard_Boolean isComponent = Standard_True;// cause need to get PSBC
1716   Handle(StepRepr_RepresentationItem) item;
1717   // set default color for invisible SHUO.
1718   Standard_Boolean isSetDefaultColor = Standard_False;
1719   if (surfColor.IsNull() && curvColor.IsNull() && !style.IsVisible() ) {
1720     surfColor = Styles.EncodeColor ( Quantity_Color( 1, 1, 1, Quantity_TOC_RGB ) );
1721     isSetDefaultColor = Standard_True;
1722   }
1723   Handle(StepVisual_PresentationStyleAssignment) PSA =
1724     Styles.MakeColorPSA ( item, surfColor, curvColor, isComponent );
1725   Handle(StepVisual_StyledItem) override; //null styled item
1726   
1727   // find the repr item of the shape
1728   Handle(XSControl_TransferWriter) TW = WS->TransferWriter();
1729   Handle(Transfer_FinderProcess) FP = TW->FinderProcess();
1730   Handle(TransferBRep_ShapeMapper) mapper = TransferBRep::ShapeMapper ( FP, Sh );
1731   Handle(StepShape_ContextDependentShapeRepresentation) CDSR;
1732   FP->FindTypedTransient(mapper, 
1733                          STANDARD_TYPE(StepShape_ContextDependentShapeRepresentation),
1734                          CDSR);
1735   if ( CDSR.IsNull() )
1736     return Standard_False;
1737   // find context
1738   Handle(StepRepr_RepresentationContext) Context = Styles.FindContext( Sh );
1739   TopoDS_Shape aTopSh = Sh;
1740   if (Context.IsNull()) {
1741     TDF_Label aTopShL = STool->FindShape(Sh, Standard_False);
1742     if (aTopShL.IsNull())
1743       return Standard_False;
1744     aTopSh = STool->GetShape( aTopShL );
1745     Context = Styles.FindContext ( aTopSh );
1746   }
1747   if (Context.IsNull())
1748     return Standard_False;
1749   // get representation item of the shape
1750   TopLoc_Location L;
1751   TColStd_SequenceOfTransient seqRI;
1752   FindEntities ( FP, Sh, L, seqRI );
1753 #ifdef OCCT_DEBUG
1754   if ( seqRI.Length() <=0 ) 
1755     FP->Messenger() << "Warning: Cannot find RI for " << Sh.TShape()->DynamicType()->Name() << endl;
1756 #endif
1757   item = Handle(StepRepr_RepresentationItem)::DownCast(seqRI(1));
1758   //get overridden styled item
1759   getStyledItem(Sh,STool, Styles, override,myMapCompMDGPR);
1760   
1761   // get STEP STYLED ITEM
1762   Handle(StepVisual_StyledItem) STEPstyle = Styles.AddStyle ( item, PSA, override );
1763   // create SR, SDR and all necessary references between them and ST, PDS, PSBC, GRC
1764   Styles.CreateNAUOSRD( Context, CDSR, PDS );
1765   
1766   // add step styled item of SHUO to the model
1767   // do it by additing styled item to the MDGPR
1768   if ( !aTopSh.IsNull() &&  !myMapCompMDGPR.IsBound( aTopSh ) ) {
1769     // create MDGPR and record it in model
1770 #ifdef OCCT_DEBUG
1771     cout << "Warning: " << __FILE__ << ": Create new MDGPR for SHUO instance"  << endl;
1772 #endif
1773     Handle(StepVisual_MechanicalDesignGeometricPresentationRepresentation) aMDGPR;
1774     Styles.CreateMDGPR ( Context, aMDGPR );
1775     if (!aMDGPR.IsNull())
1776       myMapCompMDGPR.Bind( aTopSh, aMDGPR );
1777   }
1778   else if ( !aTopSh.IsNull() &&  myMapCompMDGPR.IsBound( aTopSh ) ) {
1779     // get MDGPR of the top-level shape
1780     Handle(StepVisual_PresentationRepresentation) aMDGPR = 
1781       Handle(StepVisual_PresentationRepresentation)::DownCast( myMapCompMDGPR.Find( aTopSh ) );
1782     // get old styled items to not lose it
1783     Handle(StepRepr_HArray1OfRepresentationItem) oldItems = aMDGPR->Items();
1784     Standard_Integer oldLengthlen = 0;
1785     if (!oldItems.IsNull())
1786       oldLengthlen = oldItems->Length();
1787     // create new array of styled items by an olds and new one
1788     Handle(StepRepr_HArray1OfRepresentationItem) newItems =
1789       new StepRepr_HArray1OfRepresentationItem(1, oldLengthlen + 1);
1790     Standard_Integer si;
1791     Standard_Integer el = 1;
1792     for ( si=1; si <= oldLengthlen; si++ )
1793       newItems->SetValue( el++, oldItems->Value( si ) );
1794     newItems->SetValue( el++, Handle(StepRepr_RepresentationItem)::DownCast(STEPstyle) );
1795     // init MDGPR be new array of styled items
1796     if (newItems->Length() > 0)
1797       aMDGPR->SetItems( newItems );
1798   }
1799   else {
1800     WS->Model()->AddWithRefs ( STEPstyle ); // add as root to the model, but it is not good
1801 #ifdef OCCT_DEBUG
1802     cout << "Warning: " << __FILE__ << ": adds styled item of SHUO as root, casue cannot find MDGPR" << endl;
1803 #endif
1804   }
1805   // create invisibility item for the styled item
1806   if ( !style.IsVisible() ) {
1807     if (isSetDefaultColor) {
1808       // try to set default color from top-level shape
1809       
1810       setDefaultInstanceColor(override, PSA);
1811     }
1812     // create invisibility item and refer for stiledItem
1813     Handle(StepVisual_Invisibility) Invsblt = new StepVisual_Invisibility();
1814     Handle(StepVisual_HArray1OfInvisibleItem) HInvsblItm = 
1815       new StepVisual_HArray1OfInvisibleItem (1,1);
1816     // put all style item into the harray
1817     StepVisual_InvisibleItem anInvItem;
1818     anInvItem.SetValue( STEPstyle );
1819     HInvsblItm->SetValue( 1, anInvItem );
1820     Invsblt->Init( HInvsblItm );
1821     WS->Model()->AddWithRefs( Invsblt );
1822   }
1823   
1824   return Standard_True;
1825 }
1826
1827
1828 //=======================================================================
1829 //function : WriteSHUOs
1830 //purpose  : 
1831 //=======================================================================
1832
1833 Standard_Boolean STEPCAFControl_Writer::WriteSHUOs (const Handle(XSControl_WorkSession) &WS,
1834                                                     const TDF_LabelSequence  &labels )
1835 {
1836   if ( labels.Length() <=0 ) return Standard_False;
1837
1838   // get working data
1839   Handle(Interface_InterfaceModel) Model = WS->Model();
1840   Handle(XSControl_TransferWriter) TW = WS->TransferWriter();
1841   Handle(Transfer_FinderProcess) FP = TW->FinderProcess();
1842   Handle(XCAFDoc_ColorTool) CTool = XCAFDoc_DocumentTool::ColorTool( labels(1) );
1843   if (CTool.IsNull() )
1844     return Standard_False;
1845   // map of transfered SHUO
1846   TColStd_MapOfTransient aMapOfMainSHUO;
1847 //   TColStd_IndexedDataMapOfTransientTransient aIndxMapOfSHUOEnt;
1848   // Iterate on requested shapes
1849   for ( Standard_Integer i=1; i <= labels.Length(); i++ ) {
1850     TDF_Label L = labels.Value(i);
1851     if ( ! myLabels.IsBound ( L ) ) continue; // not recorded as translated, skip
1852 //     TopoDS_Shape S = myLabels.Find ( L );
1853     if ( XCAFDoc_ShapeTool::IsAssembly ( L ) ) {
1854       TDF_LabelSequence seq;
1855       XCAFDoc_ShapeTool::GetComponents ( L, seq );
1856       // iterates on components of assembly
1857       for (Standard_Integer k=1; k <= seq.Length(); k++) {
1858         TDF_Label lab = seq(k);
1859         TDF_AttributeSequence anAttrSeq;
1860         CTool->ShapeTool()->GetAllComponentSHUO( lab, anAttrSeq );
1861         // work with SHUO
1862         for (Standard_Integer j = 1; j <= anAttrSeq.Length(); j++) {
1863           Handle(XCAFDoc_GraphNode) aSHUO = 
1864             Handle(XCAFDoc_GraphNode)::DownCast(anAttrSeq.Value( j ));
1865           // take label of SHUO
1866           TDF_Label aSHUOlab = aSHUO->Label();
1867           TDF_LabelSequence aUpLabels;
1868           // check is it SHUO of upper_usage
1869           CTool->ShapeTool()->GetSHUOUpperUsage( aSHUOlab, aUpLabels );
1870           if ( aUpLabels.Length() > 0 )
1871             continue; // transfer only main SHUO
1872           if ( aMapOfMainSHUO.Contains( aSHUO ) )
1873             continue; // do not try to transfer SHUO twice
1874           aMapOfMainSHUO.Add( aSHUO );
1875           // check if it is styled SHUO
1876           XCAFPrs_Style SHUOstyle;
1877           if ( !getSHUOstyle ( aSHUOlab, CTool, SHUOstyle ) ) {
1878 #ifdef OCCT_DEBUG
1879             cout << "Warning: " << __FILE__ << ": do not store SHUO without any style to the STEP model" << endl;
1880 #endif
1881             continue;
1882           }
1883           // write SHUO to the model amd then add structure type.
1884           TopoDS_Shape NAUOShape; // shape of the deepest NAUO in the SHUO structure
1885           Standard_Boolean isDeepest = Standard_False;
1886           Handle(StepRepr_SpecifiedHigherUsageOccurrence) anEntOfSHUO;
1887           Handle(StepBasic_ProductDefinition) aRelatingPD;
1888           // create the top SHUO and all other.
1889           writeSHUO( aSHUO, CTool->ShapeTool(), WS, anEntOfSHUO, NAUOShape, aRelatingPD, isDeepest );
1890           if ( anEntOfSHUO.IsNull() || NAUOShape.IsNull() ) {
1891 #ifdef OCCT_DEBUG
1892             cout << "Warning: " << __FILE__ << ": Cannot store SHUO" << endl;
1893 #endif
1894             continue;
1895           }
1896           // create new Product Definition Shape for TOP SHUO
1897 #ifdef OCCT_DEBUG
1898             cout << "Info: " << __FILE__ << ": Create NEW PDS for current SHUO " << endl;
1899 #endif
1900           Handle(StepRepr_ProductDefinitionShape) PDS = new StepRepr_ProductDefinitionShape;
1901           Handle(TCollection_HAsciiString) aPDSname = new TCollection_HAsciiString("SHUO");
1902           Handle(TCollection_HAsciiString) descrStr = new TCollection_HAsciiString("");
1903           StepRepr_CharacterizedDefinition aCharDef;
1904           aCharDef.SetValue( anEntOfSHUO );
1905           PDS->Init( aPDSname, Standard_False, descrStr, aCharDef );
1906           
1907           // create styled item for SHUO and add to the model
1908           createSHUOStyledItem ( SHUOstyle, PDS, WS, NAUOShape, CTool->ShapeTool(), myMapCompMDGPR );
1909           
1910         } // end work with SHUO
1911       } // end of an assembly components
1912     } // end of IsAssembly case
1913     // nothing to do if it is not assembly
1914     continue;
1915   } // end of iterates on indicated labels
1916   return Standard_True;
1917 }
1918
1919
1920 //=======================================================================
1921 //function : FindPDSforDGT
1922 //purpose  : auxilary: find PDS for AdvancedFace or EdgeCurve for creation
1923 //                     needed ShapeAspect in D&GT structure
1924 //=======================================================================
1925 static Standard_Boolean FindPDSforDGT(const Interface_Graph &aGraph,
1926                                       const Handle(Standard_Transient) &ent,
1927                                       Handle(StepRepr_ProductDefinitionShape) &PDS,
1928                                       Handle(StepRepr_RepresentationContext) &RC,
1929                                       Handle(StepShape_AdvancedFace) &AF,
1930                                       Handle(StepShape_EdgeCurve) &EC)
1931 {
1932   if( !ent->IsKind(STANDARD_TYPE(StepShape_EdgeCurve)) && 
1933       !ent->IsKind(STANDARD_TYPE(StepShape_AdvancedFace)) ) 
1934     return Standard_False;
1935
1936   AF = Handle(StepShape_AdvancedFace)::DownCast(ent);
1937   if( ent->IsKind(STANDARD_TYPE(StepShape_EdgeCurve)) ) {
1938     EC = Handle(StepShape_EdgeCurve)::DownCast(ent);
1939     Interface_EntityIterator subs = aGraph.Sharings(EC);
1940     for(subs.Start(); subs.More() && AF.IsNull(); subs.Next()) {
1941       Handle(StepShape_OrientedEdge) OE = Handle(StepShape_OrientedEdge)::DownCast(subs.Value());
1942       if(OE.IsNull()) continue;
1943       Interface_EntityIterator subs1 = aGraph.Sharings(OE);
1944       for(subs1.Start(); subs1.More() && AF.IsNull(); subs1.Next()) {
1945         Handle(StepShape_EdgeLoop) EL = Handle(StepShape_EdgeLoop)::DownCast(subs1.Value());
1946         if(EL.IsNull()) continue;
1947         Interface_EntityIterator subs2 = aGraph.Sharings(EL);
1948         for(subs2.Start(); subs2.More() && AF.IsNull(); subs2.Next()) {
1949           Handle(StepShape_FaceBound) FB = Handle(StepShape_FaceBound)::DownCast(subs2.Value());
1950           if(FB.IsNull()) continue;
1951           Interface_EntityIterator subs3 = aGraph.Sharings(FB);
1952           for(subs3.Start(); subs3.More() && AF.IsNull(); subs3.Next()) {
1953             AF = Handle(StepShape_AdvancedFace)::DownCast(subs3.Value());
1954           }
1955         }
1956       }
1957     }
1958   }
1959   if(AF.IsNull()) return Standard_False;
1960
1961   Interface_EntityIterator subs = aGraph.Sharings(AF);
1962   for(subs.Start(); subs.More() && PDS.IsNull(); subs.Next()) {
1963     Handle(StepShape_ConnectedFaceSet) CFS =
1964       Handle(StepShape_ConnectedFaceSet)::DownCast(subs.Value());
1965     if(CFS.IsNull()) continue;
1966     Interface_EntityIterator subs1 = aGraph.Sharings(CFS);
1967     for(subs1.Start(); subs1.More() && PDS.IsNull(); subs1.Next()) {
1968       Handle(StepRepr_RepresentationItem) RI = 
1969         Handle(StepRepr_RepresentationItem)::DownCast(subs1.Value());
1970       if(RI.IsNull()) continue;
1971       Interface_EntityIterator subs2 = aGraph.Sharings(RI);
1972       for(subs2.Start(); subs2.More() && PDS.IsNull(); subs2.Next()) {
1973         Handle(StepShape_ShapeRepresentation) SR = 
1974           Handle(StepShape_ShapeRepresentation)::DownCast(subs2.Value());
1975         if(SR.IsNull()) continue;
1976         RC = SR->ContextOfItems();
1977         Interface_EntityIterator subs3 = aGraph.Sharings(SR);
1978         for(subs3.Start(); subs3.More() && PDS.IsNull(); subs3.Next()) {
1979           Handle(StepShape_ShapeDefinitionRepresentation) SDR = 
1980             Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs3.Value());
1981           if(SDR.IsNull()) continue;
1982           Handle(StepRepr_PropertyDefinition) PropD = SDR->Definition().PropertyDefinition();
1983           if(PropD.IsNull()) continue;
1984           PDS = Handle(StepRepr_ProductDefinitionShape)::DownCast(PropD);
1985         }
1986       }
1987     }
1988   }
1989   
1990   return Standard_True;
1991 }
1992
1993
1994 //=======================================================================
1995 //function : WriteDGTs
1996 //purpose  : 
1997 //=======================================================================
1998
1999 Standard_Boolean STEPCAFControl_Writer::WriteDGTs (const Handle(XSControl_WorkSession) &WS,
2000                                                    const TDF_LabelSequence  &labels ) const
2001 {
2002   
2003   if ( labels.Length() <=0 ) return Standard_False;
2004
2005   // get working data
2006   Handle(Interface_InterfaceModel) Model = WS->Model();
2007   Handle(XSControl_TransferWriter) TW = WS->TransferWriter();
2008   Handle(Transfer_FinderProcess) FP = TW->FinderProcess();
2009
2010   const Handle(Interface_HGraph) aHGraph = WS->HGraph();
2011   if(aHGraph.IsNull())
2012     return Standard_False;
2013
2014   Interface_Graph aGraph = aHGraph->Graph();
2015   Handle(XCAFDoc_DimTolTool) DGTTool = XCAFDoc_DocumentTool::DimTolTool( labels(1) );
2016   if(DGTTool.IsNull() ) return Standard_False;
2017
2018   TDF_LabelSequence DGTLabels;
2019   STEPConstruct_DataMapOfAsciiStringTransient DatumMap;
2020
2021   // write Datums
2022   DGTTool->GetDatumLabels(DGTLabels);
2023   if(DGTLabels.Length()<=0) return Standard_False;
2024   Standard_Integer i;
2025   for(i=1; i<=DGTLabels.Length(); i++) {
2026     TDF_Label DatumL = DGTLabels.Value(i);
2027     TDF_Label ShapeL;
2028     if(!DGTTool->GetRefShapeLabel(DatumL,ShapeL)) continue;
2029     // find target shape
2030     TopoDS_Shape aShape = XCAFDoc_ShapeTool::GetShape(ShapeL);
2031     TopLoc_Location Loc;
2032     TColStd_SequenceOfTransient seqRI;
2033     FindEntities( FP, aShape, Loc, seqRI );
2034     if ( seqRI.Length() <= 0 ) {
2035       FP->Messenger() << "Warning: Cannot find RI for "<<aShape.TShape()->DynamicType()->Name()<<endl;
2036       continue;
2037     }
2038     Handle(StepRepr_ProductDefinitionShape) PDS;
2039     Handle(StepRepr_RepresentationContext) RC;
2040     Handle(Standard_Transient) ent = seqRI.Value(1);
2041     Handle(StepShape_AdvancedFace) AF;
2042     Handle(StepShape_EdgeCurve) EC;
2043     FindPDSforDGT(aGraph,ent,PDS,RC,AF,EC);
2044     if(PDS.IsNull()) continue;
2045     //cout<<"Model->Number(PDS)="<<Model->Number(PDS)<<endl;
2046     Handle(XCAFDoc_Datum) DatumAttr;
2047     if(!DatumL.FindAttribute(XCAFDoc_Datum::GetID(),DatumAttr)) continue;
2048     Handle(TCollection_HAsciiString) aName = DatumAttr->GetName();
2049     Handle(TCollection_HAsciiString) aDescription = DatumAttr->GetDescription();
2050     Handle(TCollection_HAsciiString) anIdentification = DatumAttr->GetIdentification();
2051     Handle(StepDimTol_DatumFeature) DF = new StepDimTol_DatumFeature;
2052     Handle(StepDimTol_Datum) aDatum = new StepDimTol_Datum;
2053     DF->Init(aName, new TCollection_HAsciiString, PDS, StepData_LTrue);
2054     Model->AddWithRefs(DF);
2055     aDatum->Init(aName, new TCollection_HAsciiString, PDS, StepData_LFalse, anIdentification);
2056     Model->AddWithRefs(aDatum);
2057     Handle(StepRepr_ShapeAspectRelationship) SAR = new StepRepr_ShapeAspectRelationship;
2058     SAR->SetName(aName);
2059     SAR->SetRelatingShapeAspect(DF);
2060     SAR->SetRelatedShapeAspect(aDatum);
2061     Model->AddWithRefs(SAR);
2062     // write chain for DatumFeature
2063     StepRepr_CharacterizedDefinition CD;
2064     CD.SetValue(DF);
2065     Handle(StepRepr_PropertyDefinition) PropD = new StepRepr_PropertyDefinition;
2066     PropD->Init(aName,Standard_True,aDescription,CD);
2067     Model->AddWithRefs(PropD);
2068     StepRepr_RepresentedDefinition RD;
2069     RD.SetValue(PropD);
2070     Handle(StepShape_ShapeRepresentation) SR = new StepShape_ShapeRepresentation;
2071     Handle(StepRepr_HArray1OfRepresentationItem) HARI =
2072       new StepRepr_HArray1OfRepresentationItem(1,1);
2073     HARI->SetValue(1,AF);
2074     SR->Init(aName,HARI,RC);
2075     Handle(StepShape_ShapeDefinitionRepresentation) SDR = new StepShape_ShapeDefinitionRepresentation;
2076     SDR->Init(RD,SR);
2077     Model->AddWithRefs(SDR);
2078     // write chain for Datum 
2079     StepRepr_CharacterizedDefinition CD1;
2080     CD1.SetValue(aDatum);
2081     Handle(StepRepr_PropertyDefinition) PropD1 = new StepRepr_PropertyDefinition;
2082     PropD1->Init(aName,Standard_True,aDescription,CD1);
2083     Model->AddWithRefs(PropD1);
2084     StepRepr_RepresentedDefinition RD1;
2085     RD1.SetValue(PropD1);
2086     Handle(StepShape_ShapeRepresentation) SR1 = new StepShape_ShapeRepresentation;
2087     Handle(StepRepr_HArray1OfRepresentationItem) HARI1 =
2088       new StepRepr_HArray1OfRepresentationItem(1,1);
2089     HARI1->SetValue(1,AF->FaceGeometry());
2090     SR1->Init(aName,HARI1,RC);
2091     Model->AddWithRefs(SR1);
2092     Handle(StepShape_ShapeDefinitionRepresentation) SDR1 = new StepShape_ShapeDefinitionRepresentation;
2093     SDR1->Init(RD1,SR1);
2094     Model->AddWithRefs(SDR1);
2095     // add created Datum into Map
2096     TCollection_AsciiString stmp(aName->ToCString());
2097     stmp.AssignCat(aDescription->ToCString());
2098     stmp.AssignCat(anIdentification->ToCString());
2099     DatumMap.Bind(stmp,aDatum);
2100   }
2101
2102   // write Tolerances and Dimensions
2103   DGTLabels.Clear();
2104   DGTTool->GetDimTolLabels(DGTLabels);
2105   if(DGTLabels.Length()<=0) return Standard_False;
2106   for(i=1; i<=DGTLabels.Length(); i++) {
2107     TDF_Label DimTolL = DGTLabels.Value(i);
2108     TDF_Label ShapeL;
2109     if(!DGTTool->GetRefShapeLabel(DimTolL,ShapeL)) continue;
2110     // find target shape
2111     TopoDS_Shape aShape = XCAFDoc_ShapeTool::GetShape(ShapeL);
2112     TopLoc_Location Loc;
2113     TColStd_SequenceOfTransient seqRI;
2114     FindEntities( FP, aShape, Loc, seqRI );
2115     if ( seqRI.Length() <= 0 ) {
2116       FP->Messenger() << "Warning: Cannot find RI for "<<aShape.TShape()->DynamicType()->Name()<<endl;
2117       continue;
2118     }
2119     Handle(StepRepr_ProductDefinitionShape) PDS;
2120     Handle(StepRepr_RepresentationContext) RC;
2121     Handle(Standard_Transient) ent = seqRI.Value(1);
2122     Handle(StepShape_AdvancedFace) AF;
2123     Handle(StepShape_EdgeCurve) EC;
2124     FindPDSforDGT(aGraph,ent,PDS,RC,AF,EC);
2125     if(PDS.IsNull()) continue;
2126     //cout<<"Model->Number(PDS)="<<Model->Number(PDS)<<endl;
2127
2128     Handle(XCAFDoc_DimTol) DimTolAttr;
2129     if(!DimTolL.FindAttribute(XCAFDoc_DimTol::GetID(),DimTolAttr)) continue;
2130     Standard_Integer kind = DimTolAttr->GetKind();
2131     Handle(TColStd_HArray1OfReal) aVal = DimTolAttr->GetVal();
2132     Handle(TCollection_HAsciiString) aName = DimTolAttr->GetName();
2133     Handle(TCollection_HAsciiString) aDescription = DimTolAttr->GetDescription();
2134
2135     // common part of writing D&GT entities
2136     StepRepr_CharacterizedDefinition CD;
2137     Handle(StepRepr_ShapeAspect) SA = new StepRepr_ShapeAspect;
2138     SA->Init(aName, new TCollection_HAsciiString, PDS, StepData_LTrue);
2139     Model->AddWithRefs(SA);
2140     CD.SetValue(SA);
2141     Handle(StepRepr_PropertyDefinition) PropD = new StepRepr_PropertyDefinition;
2142     PropD->Init(aName,Standard_True,aDescription,CD);
2143     Model->AddWithRefs(PropD);
2144     StepRepr_RepresentedDefinition RD;
2145     RD.SetValue(PropD);
2146     Handle(StepShape_ShapeRepresentation) SR = new StepShape_ShapeRepresentation;
2147     Handle(StepRepr_HArray1OfRepresentationItem) HARI =
2148       new StepRepr_HArray1OfRepresentationItem(1,1);
2149     if(kind<20) 
2150       HARI->SetValue(1,EC);
2151     else
2152       HARI->SetValue(1,AF);
2153     SR->Init(aName,HARI,RC);
2154     Handle(StepShape_ShapeDefinitionRepresentation) SDR = new StepShape_ShapeDefinitionRepresentation;
2155     SDR->Init(RD,SR);
2156     Model->AddWithRefs(SDR);
2157     // define aUnit for creation LengthMeasureWithUnit (common for all)
2158     StepBasic_Unit aUnit;
2159     Handle(StepBasic_SiUnitAndLengthUnit) SLU;
2160     Handle(StepGeom_GeometricRepresentationContextAndGlobalUnitAssignedContext) Ctx =
2161       Handle(StepGeom_GeometricRepresentationContextAndGlobalUnitAssignedContext)::DownCast(RC);
2162     if(!Ctx.IsNull()) {
2163       for(Standard_Integer j=1; j<=Ctx->NbUnits(); j++) {
2164         if(Ctx->UnitsValue(j)->IsKind(STANDARD_TYPE(StepBasic_SiUnitAndLengthUnit))) {
2165           SLU = Handle(StepBasic_SiUnitAndLengthUnit)::DownCast(Ctx->UnitsValue(j));
2166           break;
2167         }
2168       }
2169     }
2170     if(SLU.IsNull()) {
2171       Handle(StepGeom_GeomRepContextAndGlobUnitAssCtxAndGlobUncertaintyAssCtx) Ctx1 =
2172         Handle(StepGeom_GeomRepContextAndGlobUnitAssCtxAndGlobUncertaintyAssCtx)::DownCast(RC);
2173       if(!Ctx1.IsNull()) {
2174         for(Standard_Integer j=1; j<=Ctx1->NbUnits(); j++) {
2175           if(Ctx1->UnitsValue(j)->IsKind(STANDARD_TYPE(StepBasic_SiUnitAndLengthUnit))) {
2176             SLU = Handle(StepBasic_SiUnitAndLengthUnit)::DownCast(Ctx1->UnitsValue(j));
2177             break;
2178           }
2179         }
2180       }
2181     }
2182     if(SLU.IsNull()) {
2183       SLU = new StepBasic_SiUnitAndLengthUnit;
2184     }
2185     aUnit.SetValue(SLU);
2186
2187     // specific part of writing D&GT entities
2188     if(kind<20) { //dimension
2189       Handle(StepShape_DimensionalSize) DimSize = new StepShape_DimensionalSize;
2190       DimSize->Init(SA,aDescription);
2191       Model->AddWithRefs(DimSize);
2192       if(aVal->Length()>1) {
2193         // create MeasureWithUnits
2194         Handle(StepBasic_MeasureValueMember) MVM1 = new StepBasic_MeasureValueMember;
2195         MVM1->SetName("POSITIVE_LENGTH_MEASURE");
2196         MVM1->SetReal(aVal->Value(1));
2197         Handle(StepBasic_MeasureWithUnit) MWU1 = new StepBasic_MeasureWithUnit;
2198         MWU1->Init(MVM1,aUnit);
2199         Handle(StepBasic_MeasureValueMember) MVM2 = new StepBasic_MeasureValueMember;
2200         MVM2->SetName("POSITIVE_LENGTH_MEASURE");
2201         MVM2->SetReal(aVal->Value(2));
2202         Handle(StepBasic_MeasureWithUnit) MWU2 = new StepBasic_MeasureWithUnit;
2203         MWU2->Init(MVM2,aUnit);
2204         Handle(StepRepr_RepresentationItem) RI1 = new StepRepr_RepresentationItem;
2205         RI1->Init(new TCollection_HAsciiString("lower limit"));
2206         Handle(StepRepr_RepresentationItem) RI2 = new StepRepr_RepresentationItem;
2207         RI2->Init(new TCollection_HAsciiString("upper limit"));
2208         Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) RILMU1 =
2209           new StepRepr_ReprItemAndLengthMeasureWithUnit;
2210         RILMU1->Init(MWU1,RI1);
2211         Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) RILMU2 =
2212           new StepRepr_ReprItemAndLengthMeasureWithUnit;
2213         RILMU2->Init(MWU2,RI2);
2214         Model->AddWithRefs(RILMU1);
2215         Model->AddWithRefs(RILMU2);
2216         //Handle(StepRepr_CompoundItemDefinitionMember) CIDM =
2217         //  new StepRepr_CompoundItemDefinitionMember;
2218         //Handle(TColStd_HArray1OfTransient) ArrTr = new TColStd_HArray1OfTransient(1,2);
2219         //ArrTr->SetValue(1,RILMU1);
2220         //ArrTr->SetValue(2,RILMU2);
2221         //CIDM->SetArrTransient(ArrTr);
2222         //CIDM->SetName("SET_REPRESENTATION_ITEM");
2223         //StepRepr_CompoundItemDefinition CID;
2224         //CID.SetValue(CIDM);
2225         Handle(StepRepr_HArray1OfRepresentationItem) HARIVR =
2226           new StepRepr_HArray1OfRepresentationItem(1,2);
2227         HARIVR->SetValue(1,RILMU1);
2228         HARIVR->SetValue(2,RILMU2);
2229         Handle(StepRepr_ValueRange) VR = new StepRepr_ValueRange;
2230         //VR->Init(aName,CID);
2231         VR->Init(aName,HARIVR);
2232         Model->AddEntity(VR);
2233         Handle(StepShape_ShapeDimensionRepresentation) SDimR =
2234           new StepShape_ShapeDimensionRepresentation;
2235         Handle(StepRepr_HArray1OfRepresentationItem) HARI =
2236           new StepRepr_HArray1OfRepresentationItem(1,1);
2237         HARI->SetValue(1,VR);
2238         SDimR->Init(aName,HARI,RC);
2239         Model->AddWithRefs(SDimR);
2240         Handle(StepShape_DimensionalCharacteristicRepresentation) DimCharR =
2241           new StepShape_DimensionalCharacteristicRepresentation;
2242         StepShape_DimensionalCharacteristic DimChar;
2243         DimChar.SetValue(DimSize);
2244         DimCharR->Init(DimChar,SDimR);
2245         Model->AddEntity(DimCharR);
2246       }
2247     }
2248     else if(kind<50) { //tolerance
2249       if(kind<35) { // tolerance with datum system
2250         TDF_LabelSequence DatumLabels;
2251         DGTTool->GetDatumTolerLabels(DimTolL,DatumLabels);
2252         Standard_Integer NbDR = DatumLabels.Length();
2253         Handle(StepDimTol_HArray1OfDatumReference) HADR = new StepDimTol_HArray1OfDatumReference(1,NbDR);
2254         for(Standard_Integer j=1; j<=NbDR; j++) {
2255           Handle(XCAFDoc_Datum) DatumAttr;
2256           TDF_Label DatumL = DatumLabels.Value(j);
2257           if(!DatumL.FindAttribute(XCAFDoc_Datum::GetID(),DatumAttr)) continue;
2258           Handle(TCollection_HAsciiString) aNameD = DatumAttr->GetName();
2259           Handle(TCollection_HAsciiString) aDescriptionD = DatumAttr->GetDescription();
2260           Handle(TCollection_HAsciiString) anIdentificationD = DatumAttr->GetIdentification();
2261           TCollection_AsciiString stmp(aNameD->ToCString());
2262           stmp.AssignCat(aDescriptionD->ToCString());
2263           stmp.AssignCat(anIdentificationD->ToCString());
2264           if(DatumMap.IsBound(stmp)) {
2265             Handle(StepDimTol_Datum) aDatum = 
2266               Handle(StepDimTol_Datum)::DownCast(DatumMap.Find(stmp));
2267             Handle(StepDimTol_DatumReference) DR = new StepDimTol_DatumReference;
2268             DR->Init(j,aDatum);
2269             Model->AddWithRefs(DR);
2270             HADR->SetValue(j,DR);
2271           }
2272         }
2273         // create LengthMeasureWithUnit
2274         Handle(StepBasic_MeasureValueMember) MVM = new StepBasic_MeasureValueMember;
2275         MVM->SetName("LENGTH_MEASURE");
2276         MVM->SetReal(aVal->Value(1));
2277         Handle(StepBasic_LengthMeasureWithUnit) LMWU = new StepBasic_LengthMeasureWithUnit;
2278         LMWU->Init(MVM,aUnit);
2279         // create tolerance by it's type
2280         if(kind<24) {
2281           Handle(StepDimTol_GeometricToleranceWithDatumReference) GTWDR =
2282             new StepDimTol_GeometricToleranceWithDatumReference;
2283           GTWDR->SetDatumSystem(HADR);
2284           Handle(StepDimTol_ModifiedGeometricTolerance) MGT =
2285             new StepDimTol_ModifiedGeometricTolerance;
2286           if(kind==21) MGT->SetModifier(StepDimTol_MaximumMaterialCondition);
2287           else if(kind==22) MGT->SetModifier(StepDimTol_LeastMaterialCondition);
2288           else if(kind==23) MGT->SetModifier(StepDimTol_RegardlessOfFeatureSize);
2289           Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol) GTComplex =
2290             new StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol;
2291           GTComplex->Init(aName,aDescription,LMWU,SA,GTWDR,MGT);
2292           Model->AddWithRefs(GTComplex);
2293         }
2294         else if(kind==24) {
2295           Handle(StepDimTol_AngularityTolerance) aToler =
2296             new StepDimTol_AngularityTolerance;
2297           aToler->Init(aName,aDescription,LMWU,SA,HADR);
2298           Model->AddWithRefs(aToler);
2299         }
2300         else if(kind==25) {
2301           Handle(StepDimTol_CircularRunoutTolerance) aToler =
2302             new StepDimTol_CircularRunoutTolerance;
2303           aToler->Init(aName,aDescription,LMWU,SA,HADR);
2304           Model->AddWithRefs(aToler);
2305         }
2306         else if(kind==26) {
2307           Handle(StepDimTol_CoaxialityTolerance) aToler =
2308             new StepDimTol_CoaxialityTolerance;
2309           aToler->Init(aName,aDescription,LMWU,SA,HADR);
2310           Model->AddWithRefs(aToler);
2311         }
2312         else if(kind==27) {
2313           Handle(StepDimTol_ConcentricityTolerance) aToler =
2314             new StepDimTol_ConcentricityTolerance;
2315           aToler->Init(aName,aDescription,LMWU,SA,HADR);
2316           Model->AddWithRefs(aToler);
2317         }
2318         else if(kind==28) {
2319           Handle(StepDimTol_ParallelismTolerance) aToler =
2320             new StepDimTol_ParallelismTolerance;
2321           aToler->Init(aName,aDescription,LMWU,SA,HADR);
2322           Model->AddWithRefs(aToler);
2323         }
2324         else if(kind==29) {
2325           Handle(StepDimTol_PerpendicularityTolerance) aToler =
2326             new StepDimTol_PerpendicularityTolerance;
2327           aToler->Init(aName,aDescription,LMWU,SA,HADR);
2328           Model->AddWithRefs(aToler);
2329         }
2330         else if(kind==30) {
2331           Handle(StepDimTol_SymmetryTolerance) aToler =
2332             new StepDimTol_SymmetryTolerance;
2333           aToler->Init(aName,aDescription,LMWU,SA,HADR);
2334           Model->AddWithRefs(aToler);
2335         }
2336         else if(kind==31) {
2337           Handle(StepDimTol_TotalRunoutTolerance) aToler =
2338             new StepDimTol_TotalRunoutTolerance;
2339           aToler->Init(aName,aDescription,LMWU,SA,HADR);
2340           Model->AddWithRefs(aToler);
2341         }
2342       }
2343     }
2344   }
2345
2346   return Standard_True;
2347 }
2348
2349
2350 //=======================================================================
2351 //function : FindPDSforRI
2352 //purpose  : auxilary: 
2353 //=======================================================================
2354 static Standard_Boolean FindPDSforRI(const Interface_Graph &aGraph,
2355                                      const Handle(Standard_Transient) &ent,
2356                                      Handle(StepRepr_ProductDefinitionShape) &PDS,
2357                                      Handle(StepRepr_RepresentationContext) &RC)
2358 {
2359   if(!ent->IsKind(STANDARD_TYPE(StepRepr_RepresentationItem))) return Standard_False;
2360   Interface_EntityIterator subs = aGraph.Sharings(ent);
2361   for(subs.Start(); subs.More() && PDS.IsNull(); subs.Next()) {
2362     Handle(StepShape_ShapeRepresentation) SR = 
2363       Handle(StepShape_ShapeRepresentation)::DownCast(subs.Value());
2364     if(SR.IsNull()) continue;
2365     RC = SR->ContextOfItems();
2366     Interface_EntityIterator subs1 = aGraph.Sharings(SR);
2367     for(subs1.Start(); subs1.More() && PDS.IsNull(); subs1.Next()) {
2368       Handle(StepShape_ShapeDefinitionRepresentation) SDR = 
2369         Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs1.Value());
2370       if(SDR.IsNull()) continue;
2371       Handle(StepRepr_PropertyDefinition) PropD = SDR->Definition().PropertyDefinition();
2372       if(PropD.IsNull()) continue;
2373       PDS = Handle(StepRepr_ProductDefinitionShape)::DownCast(PropD);
2374     }
2375   }
2376   return Standard_True;
2377 }
2378
2379
2380 //=======================================================================
2381 //function : WriteMaterials
2382 //purpose  : 
2383 //=======================================================================
2384
2385 Standard_Boolean STEPCAFControl_Writer::WriteMaterials (const Handle(XSControl_WorkSession) &WS,
2386                                                         const TDF_LabelSequence  &labels ) const
2387 {
2388   
2389   if ( labels.Length() <=0 ) return Standard_False;
2390
2391   // get working data
2392   Handle(Interface_InterfaceModel) Model = WS->Model();
2393   Handle(XSControl_TransferWriter) TW = WS->TransferWriter();
2394   Handle(Transfer_FinderProcess) FP = TW->FinderProcess();
2395
2396   const Handle(Interface_HGraph) aHGraph = WS->HGraph();
2397   if(aHGraph.IsNull())
2398     return Standard_False;
2399
2400   Interface_Graph aGraph = WS->HGraph()->Graph();
2401   Handle(XCAFDoc_ShapeTool) ShTool = XCAFDoc_DocumentTool::ShapeTool( labels(1) );
2402   if(ShTool.IsNull() ) return Standard_False;
2403   Handle(XCAFDoc_MaterialTool) MatTool = XCAFDoc_DocumentTool::MaterialTool( labels(1) );
2404   if(MatTool.IsNull() ) return Standard_False;
2405
2406   STEPConstruct_DataMapOfAsciiStringTransient MapDRI,MapMRI;
2407   TDF_LabelSequence TopLabels;
2408   ShTool->GetShapes(TopLabels);
2409   for(Standard_Integer i=1; i<=TopLabels.Length(); i++) {
2410     TDF_Label ShL = TopLabels.Value(i);
2411     Handle(TDataStd_TreeNode) Node;
2412     if( ShL.FindAttribute(XCAFDoc::MaterialRefGUID(),Node) && Node->HasFather() ) {
2413       // find PDS for current shape
2414       TopoDS_Shape aShape = XCAFDoc_ShapeTool::GetShape(ShL);
2415       TopLoc_Location Loc;
2416       TColStd_SequenceOfTransient seqRI;
2417       FindEntities( FP, aShape, Loc, seqRI );
2418       if(seqRI.Length()<=0) continue;
2419       Handle(StepRepr_ProductDefinitionShape) PDS;
2420       Handle(StepRepr_RepresentationContext) RC;
2421       Handle(Standard_Transient) ent = seqRI.Value(1);
2422       FindPDSforRI(aGraph,ent,PDS,RC);
2423       if(PDS.IsNull()) continue;
2424       Handle(StepBasic_ProductDefinition) aProdDef = 
2425         PDS->Definition().ProductDefinition();
2426       if(aProdDef.IsNull())
2427         continue;
2428       // write material entities
2429       TDF_Label MatL = Node->Father()->Label();
2430       Handle(TCollection_HAsciiString) aName;
2431       Handle(TCollection_HAsciiString) aDescription;
2432       Standard_Real aDensity;
2433       Handle(TCollection_HAsciiString) aDensName;
2434       Handle(TCollection_HAsciiString) aDensValType;
2435       Handle(StepRepr_Representation) RepDRI = new StepRepr_Representation;
2436       Handle(StepRepr_Representation) RepMRI = new StepRepr_Representation;
2437       if(MatTool->GetMaterial(MatL,aName,aDescription,aDensity,aDensName,aDensValType)) {
2438         if(aName->Length()==0) continue;
2439         TCollection_AsciiString aKey(aName->ToCString());
2440         if(MapDRI.IsBound(aKey)) {
2441           RepDRI = Handle(StepRepr_Representation)::DownCast(MapDRI.Find(aKey));
2442           if(MapMRI.IsBound(aKey)) {
2443             RepMRI = Handle(StepRepr_Representation)::DownCast(MapMRI.Find(aKey));
2444           }
2445         }
2446         else {
2447           // write DRI
2448           Handle(StepRepr_DescriptiveRepresentationItem) DRI = new StepRepr_DescriptiveRepresentationItem;
2449           DRI->Init(aName,aDescription);
2450           Handle(StepRepr_HArray1OfRepresentationItem) HARI = new StepRepr_HArray1OfRepresentationItem(1,1);
2451           HARI->SetValue(1,DRI);
2452           RepDRI->Init(new TCollection_HAsciiString("material name"),HARI,RC);
2453           Model->AddWithRefs(RepDRI);
2454           // write MRI
2455           if(aDensity>0) {
2456             // mass
2457             Handle(StepBasic_SiUnitAndMassUnit) SMU = new StepBasic_SiUnitAndMassUnit;
2458             SMU->SetName(StepBasic_sunGram);
2459             Handle(StepBasic_DerivedUnitElement) DUE1 = new StepBasic_DerivedUnitElement;
2460             DUE1->Init(SMU,3.0);
2461             // length
2462             Handle(StepBasic_SiUnitAndLengthUnit) SLU = new StepBasic_SiUnitAndLengthUnit;
2463             SLU->Init(Standard_True,StepBasic_spCenti,StepBasic_sunMetre);
2464             Handle(StepBasic_DerivedUnitElement) DUE2 = new StepBasic_DerivedUnitElement;
2465             DUE2->Init(SLU,2.0);
2466             // other
2467             Handle(StepBasic_HArray1OfDerivedUnitElement) HADUE = new StepBasic_HArray1OfDerivedUnitElement(1,2);
2468             HADUE->SetValue(1,DUE1);
2469             HADUE->SetValue(2,DUE2);
2470             Handle(StepBasic_DerivedUnit) DU = new StepBasic_DerivedUnit;
2471             DU->Init(HADUE);
2472             Model->AddWithRefs(DU);
2473             StepBasic_Unit aUnit;
2474             aUnit.SetValue(DU);
2475             Handle(StepBasic_MeasureValueMember) MVM = new StepBasic_MeasureValueMember;
2476             MVM->SetName(aDensValType->ToCString());
2477             MVM->SetReal(aDensity);
2478             Handle(StepRepr_MeasureRepresentationItem) MRI = new StepRepr_MeasureRepresentationItem;
2479             MRI->Init(aDensName,MVM,aUnit);
2480             HARI = new StepRepr_HArray1OfRepresentationItem(1,1);
2481             HARI->SetValue(1,MRI);
2482             RepMRI->Init(new TCollection_HAsciiString("density"),HARI,RC);
2483             Model->AddWithRefs(RepMRI);
2484           }
2485           //WriteNewMaterial(Model,aName,aDescription,aDensity,aDensName,aDensValType,RC,RepDRI,RepMRI);
2486           MapDRI.Bind(aKey,RepDRI);
2487           if(!RepMRI.IsNull()) MapMRI.Bind(aKey,RepMRI);
2488         }
2489       }
2490       // write chain PDS---(DRI,MRI)
2491       StepRepr_CharacterizedDefinition CD1;
2492       CD1.SetValue(aProdDef);
2493       Handle(StepRepr_PropertyDefinition) PropD1 = new StepRepr_PropertyDefinition;
2494       PropD1->Init(new TCollection_HAsciiString("material property"),Standard_True,
2495                    new TCollection_HAsciiString("material name"),CD1);
2496       Model->AddWithRefs(PropD1);
2497       StepRepr_RepresentedDefinition RD1;
2498       RD1.SetValue(PropD1);
2499       Handle(StepRepr_PropertyDefinitionRepresentation) PDR1 =
2500         new StepRepr_PropertyDefinitionRepresentation;
2501       PDR1->Init(RD1,RepDRI);
2502       Model->AddWithRefs(PDR1);
2503       StepRepr_CharacterizedDefinition CD2;
2504       CD2.SetValue(aProdDef);
2505       Handle(StepRepr_PropertyDefinition) PropD2 = new StepRepr_PropertyDefinition;
2506       PropD2->Init(new TCollection_HAsciiString("material property"),Standard_True,
2507                    new TCollection_HAsciiString("density"),CD2);
2508       Model->AddWithRefs(PropD2);
2509       StepRepr_RepresentedDefinition RD2;
2510       RD2.SetValue(PropD2);
2511       Handle(StepRepr_PropertyDefinitionRepresentation) PDR2 =
2512         new StepRepr_PropertyDefinitionRepresentation;
2513       PDR2->Init(RD2,RepMRI);
2514       Model->AddWithRefs(PDR2);
2515     }
2516   }
2517
2518   return Standard_True;
2519 }
2520
2521
2522 //=======================================================================
2523 //function : SetColorMode
2524 //purpose  : 
2525 //=======================================================================
2526
2527 void STEPCAFControl_Writer::SetColorMode (const Standard_Boolean colormode)
2528 {
2529   myColorMode = colormode;
2530 }
2531
2532
2533 //=======================================================================
2534 //function : GetColorMode
2535 //purpose  : 
2536 //=======================================================================
2537
2538 Standard_Boolean STEPCAFControl_Writer::GetColorMode () const
2539 {
2540   return myColorMode;
2541 }
2542
2543
2544 //=======================================================================
2545 //function : SetNameMode
2546 //purpose  : 
2547 //=======================================================================
2548
2549 void STEPCAFControl_Writer::SetNameMode (const Standard_Boolean namemode)
2550 {
2551   myNameMode = namemode;
2552 }
2553
2554
2555 //=======================================================================
2556 //function : GetNameMode
2557 //purpose  : 
2558 //=======================================================================
2559
2560 Standard_Boolean STEPCAFControl_Writer::GetNameMode () const
2561 {
2562   return myNameMode;
2563 }
2564
2565
2566 //=======================================================================
2567 //function : SetLayerMode
2568 //purpose  : 
2569 //=======================================================================
2570
2571 void STEPCAFControl_Writer::SetLayerMode (const Standard_Boolean layermode)
2572 {
2573   myLayerMode = layermode;
2574 }
2575
2576
2577 //=======================================================================
2578 //function : GetLayerMode
2579 //purpose  : 
2580 //=======================================================================
2581
2582 Standard_Boolean STEPCAFControl_Writer::GetLayerMode () const
2583 {
2584   return myLayerMode;
2585 }
2586
2587
2588 //=======================================================================
2589 //function : SetPropsMode
2590 //purpose  : 
2591 //=======================================================================
2592
2593 void STEPCAFControl_Writer::SetPropsMode (const Standard_Boolean propsmode)
2594 {
2595   myPropsMode = propsmode;
2596 }
2597
2598
2599 //=======================================================================
2600 //function : GetPropsMode
2601 //purpose  : 
2602 //=======================================================================
2603
2604 Standard_Boolean STEPCAFControl_Writer::GetPropsMode () const
2605 {
2606   return myPropsMode;
2607 }
2608
2609
2610 //=======================================================================
2611 //function : SetSHUOMode
2612 //purpose  : 
2613 //=======================================================================
2614
2615 void STEPCAFControl_Writer::SetSHUOMode (const Standard_Boolean mode)
2616 {
2617   mySHUOMode = mode;
2618 }
2619
2620
2621 //=======================================================================
2622 //function : GetSHUOMode
2623 //purpose  : 
2624 //=======================================================================
2625
2626 Standard_Boolean STEPCAFControl_Writer::GetSHUOMode () const
2627 {
2628   return mySHUOMode;
2629 }
2630
2631
2632 //=======================================================================
2633 //function : SetDimTolMode
2634 //purpose  : 
2635 //=======================================================================
2636
2637 void STEPCAFControl_Writer::SetDimTolMode(const Standard_Boolean dimtolmode)
2638 {
2639   myDGTMode = dimtolmode;
2640 }
2641
2642
2643 //=======================================================================
2644 //function : GetDimTolMode
2645 //purpose  : 
2646 //=======================================================================
2647
2648 Standard_Boolean STEPCAFControl_Writer::GetDimTolMode() const
2649 {
2650   return myDGTMode;
2651 }
2652
2653
2654 //=======================================================================
2655 //function : SetMaterialMode
2656 //purpose  : 
2657 //=======================================================================
2658
2659 void STEPCAFControl_Writer::SetMaterialMode(const Standard_Boolean matmode)
2660 {
2661   myMatMode = matmode;
2662 }
2663
2664
2665 //=======================================================================
2666 //function : GetMaterialMode
2667 //purpose  : 
2668 //=======================================================================
2669
2670 Standard_Boolean STEPCAFControl_Writer::GetMaterialMode() const
2671 {
2672   return myMatMode;
2673 }