0024624: Lost word in license statement in source files
[occt.git] / src / STEPControl / STEPControl_ActorRead.cxx
1 // Copyright (c) 1999-2014 OPEN CASCADE SAS
2 //
3 // This file is part of Open CASCADE Technology software library.
4 //
5 // This library is free software; you can redistribute it and/or modify it under
6 // the terms of the GNU Lesser General Public License version 2.1 as published
7 // by the Free Software Foundation, with special exception defined in the file
8 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
9 // distribution for complete text of the license and disclaimer of any warranty.
10 //
11 // Alternatively, this file may be used under the terms of Open CASCADE
12 // commercial license or contractual agreement.
13
14 //:k3 abv 25.11.98 rp1sd.stp
15 //:n4 abv 11.02.99 S4132: recognition of GeometricSet (instead of GeometricCurveSet)
16 //    gka 05.04.99 S4136: eliminate parameter lastpreci
17 //gka,abv 14.04.99 S4136: maintain unit context, precision and maxtolerance values
18 #include <STEPControl_ActorRead.ixx>
19 #include <OSD_Timer.hxx>
20
21 // #include <Interface_InterfaceModel.hxx>  // pour mise au point
22
23 #include <StepShape_ShapeDefinitionRepresentation.hxx>
24 #include <StepShape_ShapeRepresentation.hxx>
25 #include <StepShape_FacetedBrepAndBrepWithVoids.hxx>
26 #include <StepShape_FacetedBrep.hxx>
27 #include <StepShape_ShellBasedSurfaceModel.hxx>
28 #include <StepShape_ManifoldSolidBrep.hxx>
29 #include <StepShape_BrepWithVoids.hxx>
30 #include <StepShape_GeometricSet.hxx>
31
32 // MappedItem :
33 #include <StepRepr_MappedItem.hxx>
34 #include <StepGeom_Axis2Placement3d.hxx>
35 #include <StepRepr_RepresentationMap.hxx>
36 #include <StepToTopoDS_MakeTransformed.hxx>
37
38 // FaceSurface :
39 #include <StepShape_FaceSurface.hxx>
40 #include <StepToTopoDS_Tool.hxx>
41 #include <StepToTopoDS_DataMapOfTRI.hxx>
42 #include <StepToTopoDS_TranslateFace.hxx>
43
44 //  Unites :
45 #include <StepRepr_RepresentationContext.hxx>
46 #include <StepRepr_GlobalUnitAssignedContext.hxx>
47 #include <StepRepr_GlobalUncertaintyAssignedContext.hxx>
48 //#include <StepBasic_UncertaintyMeasureWithUnit.hxx>
49 #include <StepBasic_ProductRelatedProductCategory.hxx>
50 #include <StepGeom_GeometricRepresentationContextAndGlobalUnitAssignedContext.hxx>
51 #include <StepGeom_GeomRepContextAndGlobUnitAssCtxAndGlobUncertaintyAssCtx.hxx>
52
53 #include <STEPConstruct_UnitContext.hxx>
54 #include <UnitsMethods.hxx>
55
56 //  Representation Relationship & cie
57 #include <Interface_Graph.hxx>
58 #include <Interface_EntityIterator.hxx>
59 #include <TransferBRep.hxx>
60 #include <StepShape_ContextDependentShapeRepresentation.hxx>
61 #include <StepRepr_ShapeRepresentationRelationship.hxx>
62 #include <StepRepr_ShapeRepresentationRelationshipWithTransformation.hxx>
63 #include <StepRepr_Transformation.hxx>
64 #include <StepRepr_ItemDefinedTransformation.hxx>
65
66 #include <BRep_Builder.hxx>
67 #include <StepToTopoDS_Builder.hxx>
68 #include <TopoDS_Compound.hxx>
69 #include <TopoDS_Shape.hxx>
70
71 #include <TransferBRep_ShapeBinder.hxx>
72
73 #include <Interface_Static.hxx>
74 #include <Interface_Macros.hxx>
75 #include <Interface_InterfaceModel.hxx>
76
77 #include <StepBasic_ProductDefinition.hxx>
78 #include <StepRepr_ProductDefinitionShape.hxx>
79 #include <StepRepr_NextAssemblyUsageOccurrence.hxx>
80 #include <STEPConstruct_Assembly.hxx>
81 #include <Precision.hxx>
82 #include <StepToGeom_MakeTransformation3d.hxx>
83 #include <StepToGeom_MakeAxis2Placement.hxx>
84 #include <Geom_Axis2Placement.hxx>
85 #include <gp_Ax3.hxx>
86 #include <StepRepr_ShapeAspect.hxx>
87 #include <XSAlgo.hxx>
88 #include <XSAlgo_AlgoContainer.hxx>
89 #include <StepShape_EdgeBasedWireframeModel.hxx>
90 #include <StepShape_FaceBasedSurfaceModel.hxx>
91
92 #include <StepShape_AdvancedBrepShapeRepresentation.hxx>
93 #include <StepShape_FacetedBrepShapeRepresentation.hxx>
94 #include <StepShape_ManifoldSurfaceShapeRepresentation.hxx>
95 #include <StepShape_EdgeBasedWireframeShapeRepresentation.hxx>
96 #include <StepShape_GeometricallyBoundedSurfaceShapeRepresentation.hxx>
97 #include <StepShape_GeometricallyBoundedWireframeShapeRepresentation.hxx>
98
99 #include <TColStd_HSequenceOfTransient.hxx>
100 #include <Message_ProgressSentry.hxx>
101 #include <Message_Messenger.hxx>
102 #include <StepRepr_HSequenceOfRepresentationItem.hxx>
103 #include <StepBasic_ProductDefinition.hxx>
104 #include <Standard_Failure.hxx>
105 #include <Standard_ErrorHandler.hxx>
106 #include <StepDimTol_DatumFeature.hxx>
107 #include <StepDimTol_GeometricTolerance.hxx>
108 #include <StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol.hxx>
109
110 // For non-manifold topology processing (ssv; 12.11.2010)
111 #include <StepShape_NonManifoldSurfaceShapeRepresentation.hxx>
112 #include <StepRepr_HArray1OfRepresentationItem.hxx>
113 #include <TopTools_MapOfShape.hxx>
114 #include <TopTools_ListOfShape.hxx>
115 #include <TopoDS_Iterator.hxx>
116 #include <TopTools_ListIteratorOfListOfShape.hxx>
117 #include <TopoDS_Solid.hxx>
118 #include <BRepCheck_Shell.hxx>
119 #include <BRepCheck_Status.hxx>
120 #include <TopoDS.hxx>
121 #include <TopoDS_Shell.hxx>
122 #include <TopoDS_Face.hxx>
123 #include <TopExp_Explorer.hxx>
124 #include <StepData_StepModel.hxx>
125 #include <HeaderSection_FileName.hxx>
126
127 #define TRANSLOG
128
129 // ============================================================================
130 // Function: DumpWhatIs   
131 // Purpose: Use it in DEB mode to dump your shapes
132 // ============================================================================
133
134 #ifdef DEB
135 static void DumpWhatIs(const TopoDS_Shape& S) {
136
137   TopTools_MapOfShape aMapOfShape;
138   aMapOfShape.Add(S);
139   TopTools_ListOfShape aListOfShape;
140   aListOfShape.Append(S);
141   TopTools_ListIteratorOfListOfShape itL(aListOfShape);
142   Standard_Integer nbSolids = 0,
143                    nbShells = 0,
144                    nbOpenShells = 0,
145                    nbFaces = 0, 
146                    nbWires = 0, 
147                    nbEdges = 0, 
148                    nbVertexes = 0,
149                    nbCompounds = 0;
150
151   if (S.ShapeType() == TopAbs_COMPOUND)
152     nbCompounds++;
153
154   for( ; itL.More(); itL.Next() ) {
155     TopoDS_Iterator it( itL.Value() );
156     for ( ; it.More(); it.Next() ) {
157       TopoDS_Shape aSubShape = it.Value();
158       if ( !aMapOfShape.Add(aSubShape) )
159         continue;
160       aListOfShape.Append(aSubShape);
161       if (aSubShape.ShapeType() == TopAbs_COMPOUND)
162         nbCompounds++;
163       if (aSubShape.ShapeType() == TopAbs_SOLID)
164         nbSolids++;
165       if (aSubShape.ShapeType() == TopAbs_SHELL) {
166         if ( !aSubShape.Closed() )
167           nbOpenShells++;
168         nbShells++;
169       }
170       if (aSubShape.ShapeType() == TopAbs_FACE)
171         nbFaces++;
172       if (aSubShape.ShapeType() == TopAbs_WIRE)
173         nbWires++;
174       if (aSubShape.ShapeType() == TopAbs_EDGE)
175         nbEdges++;
176       if (aSubShape.ShapeType() == TopAbs_VERTEX)
177         nbVertexes++;
178     }
179   }
180
181   cout << "//What is?// NB COMPOUNDS: " << nbCompounds << endl;
182   cout << "//What is?// NB SOLIDS: " << nbSolids << endl;
183   cout << "//What is?// NB SHELLS: " << nbShells << endl;
184   cout << "//What is?//    OPEN SHELLS: " << nbOpenShells << endl;
185   cout << "//What is?//    CLOSED SHELLS: " << nbShells - nbOpenShells << endl;
186   cout << "//What is?// NB FACES: " << nbFaces << endl;
187   cout << "//What is?// NB WIRES: " << nbWires << endl;
188   cout << "//What is?// NB EDGES: " << nbEdges << endl;
189   cout << "//What is?// NB VERTEXES: " << nbVertexes << endl;
190 }
191 #endif
192
193 namespace {
194   // Set global var to inform outer methods that current representation item is non-manifold.
195   // The better way is to pass this information via binder or via TopoDS_Shape itself, however,
196   // this is very specific info to do so...
197   Standard_Boolean NM_DETECTED = Standard_False;
198 };
199
200 // ============================================================================
201 // Method  : STEPControl_ActorRead::STEPControl_ActorRead  ()    
202 // Purpose : Empty constructor
203 // ============================================================================
204
205 STEPControl_ActorRead::STEPControl_ActorRead() {}
206
207 // ============================================================================
208 // Method  : STEPControl_ActorRead::Recognize
209 // Purpose : tells if an entity is valid for transfer by this Actor
210 // ============================================================================
211
212 Standard_Boolean  STEPControl_ActorRead::Recognize
213   (const Handle(Standard_Transient)& start)
214 {
215   if (start.IsNull()) return Standard_False;
216
217   if (start->IsKind(STANDARD_TYPE(StepBasic_ProductDefinition))) return Standard_True;
218
219   if (start->IsKind(STANDARD_TYPE(StepRepr_NextAssemblyUsageOccurrence))) return Standard_True;
220
221   TCollection_AsciiString aProdMode = Interface_Static::CVal("read.step.product.mode");
222   if(!aProdMode.IsEqual("ON"))
223     if(start->IsKind(STANDARD_TYPE(StepShape_ShapeDefinitionRepresentation))) return Standard_True;
224
225   DeclareAndCast(StepShape_ShapeRepresentation,sr,start);
226   if (!sr.IsNull()) {
227     Standard_Integer i,nb = sr->NbItems();
228     for (i = 1; i <= nb; i ++) {
229       if (Recognize (sr->ItemsValue(i)) ) return Standard_True;
230     }
231     return Standard_False;
232   }
233
234   if (start->IsKind(STANDARD_TYPE(StepShape_FacetedBrep))) return Standard_True;
235   if (start->IsKind(STANDARD_TYPE(StepShape_BrepWithVoids))) return Standard_True;
236   if (start->IsKind(STANDARD_TYPE(StepShape_ManifoldSolidBrep))) return Standard_True;
237   if (start->IsKind(STANDARD_TYPE(StepShape_ShellBasedSurfaceModel))) return Standard_True;
238   if (start->IsKind(STANDARD_TYPE(StepShape_FacetedBrepAndBrepWithVoids))) return Standard_True;
239   if (start->IsKind(STANDARD_TYPE(StepShape_GeometricSet))) return Standard_True;
240   if (start->IsKind(STANDARD_TYPE(StepRepr_MappedItem))) return Standard_True;
241   if (start->IsKind(STANDARD_TYPE(StepShape_FaceSurface))) return Standard_True;
242   if (start->IsKind(STANDARD_TYPE(StepShape_EdgeBasedWireframeModel))) return Standard_True;
243   if (start->IsKind(STANDARD_TYPE(StepShape_FaceBasedSurfaceModel))) return Standard_True;
244
245
246 //  REPRESENTATION_RELATIONSHIP et consorts : on regarde le contenu ...
247 //  On prend WithTransformation ou non ...
248
249   if (start->IsKind (STANDARD_TYPE(StepRepr_ShapeRepresentationRelationship))) {
250     DeclareAndCast(StepRepr_ShapeRepresentationRelationship,und,start);  
251
252 //  On prend son contenu
253
254     if (Recognize(und->Rep1()) || Recognize(und->Rep2())) return Standard_True;
255     return Standard_False;
256   }
257
258   if (start->IsKind(STANDARD_TYPE(StepShape_ContextDependentShapeRepresentation))) {
259 //    DeclareAndCast(StepShape_ContextDependentShapeRepresentation,CDSR,start);
260 //    return Recognize (CDSR->RepresentationRelation());
261     return Standard_True;
262     //  on fait le pari que, si ce n est pas transferable tel quel,
263     //  des CDSR implicitement references le sont ...
264     //  Sinon cette entite n aurait pas grand sens ...
265   }
266
267   return Standard_False;
268 }
269
270
271 // ============================================================================
272 // Method  : STEPControl_ActorRead::Transfer
273 // Purpose : recursive method that acces to the root entities and start the 
274 //           mapping
275 // ============================================================================
276
277 Handle(Transfer_Binder)  STEPControl_ActorRead::Transfer
278 (const Handle(Standard_Transient)& start,
279  const Handle(Transfer_TransientProcess)& TP)
280 {  
281   // [BEGIN] Get version of preprocessor (to detect I-Deas case) (ssv; 23.11.2010)
282   Handle(StepData_StepModel) aStepModel = Handle(StepData_StepModel)::DownCast ( TP->Model() );
283   Interface_EntityIterator anEntIt = aStepModel->Header();
284   for ( anEntIt.Start(); anEntIt.More(); anEntIt.Next() ) {
285     DeclareAndCast( HeaderSection_FileName, aFileNameEntity, anEntIt.Value() );
286     if ( !aFileNameEntity.IsNull() ) {
287       Handle(TCollection_HAsciiString) aPPVersion = aFileNameEntity->PreprocessorVersion();
288       if(aPPVersion.IsNull())
289         continue;
290       #ifdef DEB
291       cout << "Preprocessor version detected: " << aPPVersion->ToCString() << endl;
292       #endif
293       Standard_Integer anIDeasResult = aPPVersion->Search("I-DEAS");
294       if (anIDeasResult != -1) {
295         #ifdef DEB
296         cout << "Recognized as I-DEAS STP" << endl;
297         #endif
298         myNMTool.SetIDEASCase(Standard_True);
299       }
300     }
301   }
302   // [END] Get version of preprocessor (to detect I-Deas case) (ssv; 23.11.2010)
303   return TransferShape (start,TP);  
304 }
305
306
307 // ============================================================================
308 // auxiliary function : ApplyTransformation
309 // ============================================================================
310 static void ApplyTransformation (TopoDS_Shape& shape, const gp_Trsf &Trsf) 
311 {
312   if ( Trsf.Form() == gp_Identity ) return;
313   TopLoc_Location theLoc ( Trsf );
314   shape.Move (theLoc);
315 }
316
317
318 // ============================================================================
319 // auxiliary function : FindContext
320 // ============================================================================
321 static Handle(StepRepr_Representation) FindContext (const Handle(Standard_Transient) &start,
322                                                     const Handle(Transfer_TransientProcess) &TP,
323                                                     const Standard_Integer level=10 )
324 {
325   Handle(StepRepr_Representation) rep;
326   const Interface_Graph& graph = TP->Graph();
327   Interface_EntityIterator subs = graph.Sharings(start);
328   for (subs.Start(); subs.More() && rep.IsNull(); subs.Next()) {
329     rep = Handle(StepRepr_Representation)::DownCast(subs.Value());
330     if ( rep.IsNull() && level >0 ) rep = FindContext ( subs.Value(), TP, level-1 );
331   }
332   return rep;
333 }
334
335 //=======================================================================
336 //function : FindShapeReprType
337 //purpose  : Returns integer corresponding to the type of the representation
338 //           as defined in read.step.shape.repr_level parameter
339 //=======================================================================
340
341 static Standard_Integer FindShapeReprType (const Handle(Standard_Transient) &start)
342 {
343   if(start->IsKind(STANDARD_TYPE(StepShape_AdvancedBrepShapeRepresentation)))
344     return 2;
345   if(start->IsKind(STANDARD_TYPE(StepShape_ManifoldSurfaceShapeRepresentation)))
346     return 3;
347   if(start->IsKind(STANDARD_TYPE(StepShape_GeometricallyBoundedSurfaceShapeRepresentation)))
348     return 4;
349   if(start->IsKind(STANDARD_TYPE(StepShape_FacetedBrepShapeRepresentation)))
350     return 5;
351   if(start->IsKind(STANDARD_TYPE(StepShape_EdgeBasedWireframeShapeRepresentation)))
352     return 6;
353   if(start->IsKind(STANDARD_TYPE(StepShape_GeometricallyBoundedWireframeShapeRepresentation)))
354     return 7;
355   return 8;
356 }
357
358 //=======================================================================
359 //function : getListSDR
360 //purpose  : Get SDRs assigned to ShapeAspect, which may potentially
361 //           correspond to hybrid models in AP203 before 1998
362 //=======================================================================
363
364 static void getListSDR(const Handle(StepRepr_ShapeAspect)& sa,
365                        Handle(TColStd_HSequenceOfTransient)& listSDR,
366                        const Handle(Transfer_TransientProcess)& TP)
367 {
368   const Interface_Graph& graph = TP->Graph();
369   
370   // check whether this ShapeAspect is used in G&DT, and if yes, ignore it
371   if(sa->IsKind(STANDARD_TYPE(StepDimTol_DatumFeature))) return;
372   Interface_EntityIterator subs5 = graph.Sharings(sa);
373   for (subs5.Start(); subs5.More(); subs5.Next()) {
374     if(subs5.Value()->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance)))
375       return;
376   }
377
378   // reiterate by referred entities and take all SDRs; note that SDRs that
379   // refer to sub-shapes of main SDR will be filtered out further during translation
380   subs5 = graph.Sharings(sa);
381   for (subs5.Start(); subs5.More() ; subs5.Next()) {
382     Handle(StepRepr_PropertyDefinition) propd = 
383       Handle(StepRepr_PropertyDefinition)::DownCast(subs5.Value());
384     if(propd.IsNull()) continue;
385     Interface_EntityIterator subs6 = graph.Sharings(propd);
386     for (subs6.Start(); subs6.More() ; subs6.Next()) {
387       Handle(StepShape_ShapeDefinitionRepresentation) sdr = 
388         Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs6.Value());
389       if ( ! sdr.IsNull() )
390         listSDR->Append(sdr);
391     }
392   }
393 }
394
395 //=======================================================================
396 //function : getSDR
397 //purpose  : Find all SDRs related to given PDS
398 //=======================================================================
399
400 static void getSDR(const Handle(StepRepr_ProductDefinitionShape)& PDS,
401                    Handle(TColStd_HSequenceOfTransient)& listSDR,
402                    Handle(TColStd_HSequenceOfTransient)& listSDRAspect,
403                    const Handle(Transfer_TransientProcess)& TP)
404 {
405   // Flag indicating preferred shape representation type, to be chosen if 
406   // several different representations are attached to the same shape
407   Standard_Integer delta = 100;
408   Standard_Integer ICS = Interface_Static::IVal("read.step.shape.repr");
409   Standard_Integer nbSDR0 = listSDR->Length();
410   
411   // Iterate by entities referring PDS
412   const Interface_Graph& graph = TP->Graph();
413   Handle(StepShape_ShapeDefinitionRepresentation) NeedSDR;
414   Interface_EntityIterator subs4 = graph.Sharings(PDS);
415   for (subs4.Start(); subs4.More(); subs4.Next()) {
416
417     // Directly assigned SDR
418     Handle(StepShape_ShapeDefinitionRepresentation) sdr = 
419       Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs4.Value());
420     if ( ! sdr.IsNull() ) {
421       Handle(StepRepr_Representation) rep = sdr->UsedRepresentation();
422
423       if ( !rep.IsNull())  {
424         // if specific representation type is preferred, choose the 
425         // representations of the closest type
426         if ( ICS == 1 ) // translate all SDRs
427           listSDR->Append(sdr);
428         else {
429           Standard_Integer iDiff = Abs ( FindShapeReprType(rep) - ICS );
430           // if more suitable representation is found, drop previous if any selected
431           if( iDiff < delta ) {
432             while ( listSDR->Length() > nbSDR0 ) 
433               listSDR->Remove(listSDR->Length());
434             delta = iDiff;
435           }
436           // take all representations of preferred or closest type
437           if ( iDiff <= delta )
438             listSDR->Append(sdr);
439         }
440       }
441       continue;
442     }
443
444     // SDRs assigned via ShapeAspect; may correspond to hybrid model in AP203 before 1998
445     Handle(StepRepr_ShapeAspect) sa = 
446       Handle(StepRepr_ShapeAspect)::DownCast(subs4.Value());
447     if ( ! sa.IsNull() ) {
448       getListSDR(sa,listSDRAspect,TP);
449       continue;
450     }
451   }
452 }
453
454
455 //=======================================================================
456 //function : TransferEntity
457 //purpose  : 
458 //=======================================================================
459  Handle(TransferBRep_ShapeBinder) STEPControl_ActorRead::TransferEntity(const Handle(StepBasic_ProductDefinition)& PD,
460                                                                         const Handle(Transfer_TransientProcess)& TP) 
461
462 {
463   Handle(Message_Messenger) sout = TP->Messenger();
464   Handle(TransferBRep_ShapeBinder) shbinder;
465   
466   TopoDS_Compound Cund;
467   TopoDS_Shape Result1;
468   BRep_Builder B;
469   B.MakeCompound (Cund);
470   
471   // Find subcomponents of assembly (NAUO)
472   // and definitions of shape of the current product (SDR)
473   Handle(TColStd_HSequenceOfTransient) listSDR = new TColStd_HSequenceOfTransient;
474   Handle(TColStd_HSequenceOfTransient) listNAUO = new TColStd_HSequenceOfTransient;
475   Handle(TColStd_HSequenceOfTransient) listSDRAspect = new TColStd_HSequenceOfTransient;
476   const Interface_Graph& graph = TP->Graph();
477   Interface_EntityIterator subs3 = graph.Sharings(PD);
478   for (subs3.Start(); subs3.More() ; subs3.Next()) {
479     // PDS is used to find shape definitions attached to this product
480     Handle(StepRepr_ProductDefinitionShape) PDS = 
481       Handle(StepRepr_ProductDefinitionShape)::DownCast(subs3.Value());
482     if ( ! PDS.IsNull() ) {
483       getSDR(PDS,listSDR,listSDRAspect,TP);
484       continue;
485     }
486     // NAUO is used to find sub-assemblies
487     Handle(StepRepr_NextAssemblyUsageOccurrence) NAUO = 
488       Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(subs3.Value());
489     if ( ! NAUO.IsNull() ) {
490       if ( PD == NAUO->RelatingProductDefinition() )
491         listNAUO->Append(NAUO);
492       continue;
493     }
494   }
495   
496   // Flag indicating whether SDRs associated with the product`s main SDR
497   // by SRRs (which correspond to hybrid model representation in AP203 since 1998) 
498   // should be taken into account 
499   Standard_Integer readSRR = Interface_Static::IVal("read.step.shape.relationship");
500   
501   // Flag indicating whether SDRs associated with the product`s main SDR
502   // by SAs (which correspond to hybrid model representation in AP203 before 1998) 
503   // should be taken into account 
504   Standard_Integer readSA = Interface_Static::IVal("read.step.shape.aspect");
505   if ( ! readSA ) 
506     listSDRAspect->Clear();  
507     
508   // remember number of normal SDRs (not those found via ShapeAspect)
509   // and merge both lists in one
510   Standard_Integer nbNotAspect = listSDR->Length();
511   listSDR->Append(listSDRAspect);
512
513   // Flag indicating level of reading assemblies: only structure (3),
514   // structure with shapes of final parts (2), or everything, including shapes
515   // possibly attached directly to intermediate assemblies (1)
516   // Special mode (4) is used to translate shape attached to this product only,
517   // ignoring sub-assemblies if any
518   Standard_Integer readAssembly = Interface_Static::IVal("read.step.assembly.level");
519   if ( readAssembly ==3 || ( readAssembly ==2 && listNAUO->Length() >0 ) ) 
520     listSDR->Clear();
521   else if ( readAssembly == 4 )
522     listNAUO->Clear();
523   
524   Standard_Integer nbEnt = listSDR->Length() + listNAUO->Length();
525   if ( nbEnt <=0 )
526     return shbinder;
527
528   // common progress indicator for translation of own shapes and sub-assemblies
529   Message_ProgressSentry PS ( TP->GetProgress(), "Part", 0, nbEnt, 1 );
530   Standard_Integer nbComponents=0, nbShapes=0;
531
532   // translate sub-assemblies
533   for ( Standard_Integer nbNauo =1; nbNauo <= listNAUO->Length() && PS.More(); nbNauo++, PS.Next()) {
534     Handle(StepRepr_NextAssemblyUsageOccurrence) NAUO = 
535       Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(listNAUO->Value(nbNauo));
536       
537 #ifdef TRANSLOG
538     if (TP->TraceLevel() > 1) 
539       sout<<" -- Actor : Ent.n0 "<<TP->Model()->Number(PD)<<" -> Shared Ent.no"<<TP->Model()->Number(NAUO)<<endl;
540 #endif
541     Handle(Transfer_Binder) binder;
542     if (!TP->IsBound(NAUO)) binder = TransferEntity(NAUO,TP);
543     else                        binder = TP->Find(NAUO);
544
545     TopoDS_Shape theResult = TransferBRep::ShapeResult (binder);
546     if (!theResult.IsNull()) {
547       Result1 = theResult;
548       // [BEGIN] ssv: OCCT#22436: extra compound in NMSSR case
549       if (NM_DETECTED && Result1.ShapeType() == TopAbs_COMPOUND)
550       {
551         TopoDS_Iterator it(Result1);
552         for ( ; it.More(); it.Next() ) 
553         {
554           TopoDS_Shape aSubShape = it.Value();
555           B.Add(Cund, aSubShape);
556         }
557       }
558       else
559         B.Add(Cund, theResult);
560       // [END] ssv: OCCT#22436: extra compound in NMSSR case
561       nbComponents++;
562     }
563   }
564
565   // translate shapes assigned directly
566   for(Standard_Integer i=1; i <= listSDR->Length() && PS.More(); i++, PS.Next()) {
567     Handle(StepShape_ShapeDefinitionRepresentation) sdr = 
568       Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(listSDR->Value(i));
569     Handle(StepShape_ShapeRepresentation) rep =  Handle(StepShape_ShapeRepresentation)::DownCast(sdr->UsedRepresentation());
570     if ( rep.IsNull() )
571       continue;
572
573     // translate SDR representation
574     Standard_Boolean isBound = Standard_True;
575     Handle(Transfer_Binder) binder = TP->Find(rep);
576     if (binder.IsNull())
577       binder = TransferEntity(rep,TP,isBound);
578
579     // if SDR is obtained from ShapeAspect and representation items have already been tramnslated,
580     // this means that that ShapeAspect is used to refer to sub-shape of the main shape
581     // (e.g. for validation properties), and we do not need to translate it actually;
582     // otherwise it is considered as part of hybrid representation in AP203 before 1998
583     if ( i > nbNotAspect && isBound)
584         continue;
585
586     // record shape resulting from translation
587     TopoDS_Shape theResult;
588     if ( ! binder.IsNull() ) {
589       theResult = TransferBRep::ShapeResult (binder);
590       if (!theResult.IsNull()) {
591         Result1 = theResult;
592         // [BEGIN] ssv: OCCT#22436: extra compound in NMSSR case
593         if (NM_DETECTED && Result1.ShapeType() == TopAbs_COMPOUND)
594         {
595           TopoDS_Iterator it(Result1);
596           for ( ; it.More(); it.Next() ) 
597           {
598             TopoDS_Shape aSubShape = it.Value();
599             B.Add(Cund, aSubShape);
600           }
601         }
602         else
603           B.Add(Cund, theResult);
604         // [END] ssv: OCCT#22436: extra compound in NMSSR case
605         nbShapes++;
606       }
607     }
608     
609     // translate possible shapes related by SRRs, which corresponds to
610     // way of writing hybrid models in AP203 since 1998, and AP209
611     // Note that both AP203 and AP209 allow main representation to be non-empty
612     if ( readSRR && /*theResult.IsNull() &&*/ i <= nbNotAspect) {
613       Interface_EntityIterator subs1 = graph.Sharings(rep);
614       Handle(Standard_Type) tSRR = STANDARD_TYPE(StepRepr_ShapeRepresentationRelationship);
615       for (subs1.Start(); subs1.More(); subs1.Next()) {
616         Handle(Standard_Transient) anitem = subs1.Value();
617         if ( anitem->DynamicType() != tSRR ) continue;
618         Handle(StepRepr_ShapeRepresentationRelationship) SRR =
619           Handle(StepRepr_ShapeRepresentationRelationship)::DownCast(anitem);
620         Standard_Integer nbrep = ( rep == SRR->Rep1() ? 2 : 1 );
621         binder = TransferEntity(SRR, TP, nbrep);
622         if ( ! binder.IsNull() ) {
623           theResult = TransferBRep::ShapeResult (binder);
624           Result1 = theResult;
625           B.Add(Cund, theResult);
626           nbShapes++;
627         }
628       }
629     }
630   }
631
632   // make a warning if both own shape and sub-assemblies are present
633   if ( nbShapes >0 && nbComponents > 0 )
634     TP->AddWarning ( PD, "Product has both sub-assemblies and directly assigned shape" );
635
636   // if only single shape is read, add it as it is; otherwise add compound
637   if( nbShapes == 1 && nbComponents == 0 )
638     shbinder = new TransferBRep_ShapeBinder (Result1);
639   else
640     shbinder = new TransferBRep_ShapeBinder (Cund);
641
642   //TP->Unbind( PD ); //:j3: unbind start (let it be bound by TransferProcess)
643   TP->Bind(PD, shbinder);
644   return shbinder;  
645 }
646
647 //=======================================================================
648 //function : TransferEntity
649 //purpose  : 
650 //=======================================================================
651
652 Handle(TransferBRep_ShapeBinder) STEPControl_ActorRead::TransferEntity(const Handle(StepRepr_NextAssemblyUsageOccurrence)& NAUO ,
653                                                                        const Handle(Transfer_TransientProcess)& TP)
654 {
655  Handle(TransferBRep_ShapeBinder) shbinder;
656   Handle(StepBasic_ProductDefinition) PD;
657   const Interface_Graph& graph = TP->Graph();
658   gp_Trsf Trsf;
659   Standard_Boolean iatrsf=Standard_False, SRRReversed=Standard_False, IsDepend=Standard_False;
660   Handle(StepRepr_ShapeRepresentationRelationship) SRR;
661   Interface_EntityIterator subs1 = graph.Sharings(NAUO);
662   for (subs1.Start(); subs1.More(); subs1.Next()) {
663     Handle(StepRepr_ProductDefinitionShape) PDS = 
664       Handle(StepRepr_ProductDefinitionShape)::DownCast(subs1.Value());
665     if(PDS.IsNull()) continue;
666     //IsPDS=Standard_True;
667     Interface_EntityIterator subs2 = graph.Sharings(PDS);
668     for (subs2.Start(); subs2.More(); subs2.Next()) {
669       Handle(StepShape_ContextDependentShapeRepresentation) CDSR = 
670         Handle(StepShape_ContextDependentShapeRepresentation)::DownCast(subs2.Value());
671       if (CDSR.IsNull()) continue;
672       IsDepend=Standard_True;
673       Handle(StepRepr_RepresentationRelationship) RR = CDSR->RepresentationRelation();
674       if (RR.IsNull()) continue;
675       SRRReversed = STEPConstruct_Assembly::CheckSRRReversesNAUO ( TP->Model(), CDSR );
676       Handle(StepRepr_Representation) rep = ( SRRReversed ? RR->Rep2() : RR->Rep1() );
677       iatrsf = ComputeSRRWT ( RR, TP, Trsf );
678       // find real ProductDefinition used rep
679       Interface_EntityIterator subs3 = TP->Graph().Sharings(rep);
680       for (subs3.Start(); subs3.More(); subs3.Next()) {
681         if ( subs3.Value()->IsKind(STANDARD_TYPE(StepShape_ShapeDefinitionRepresentation))) {
682           DeclareAndCast(StepShape_ShapeDefinitionRepresentation,SDR,subs3.Value());
683           Handle(StepRepr_ProductDefinitionShape) PDS1 = 
684             Handle(StepRepr_ProductDefinitionShape)::DownCast(SDR->Definition().PropertyDefinition());
685           //Handle(StepRepr_PropertyDefinition) PD = SDR->Definition().PropertyDefinition();
686           if(PDS1.IsNull()) continue;
687           Interface_EntityIterator subs4 = graph.Shareds(PDS1);
688           for (subs4.Start(); subs4.More(); subs4.Next()) {
689             Handle(StepBasic_ProductDefinition) PD1 = 
690               Handle(StepBasic_ProductDefinition)::DownCast(subs4.Value());
691             if(PD1.IsNull()) continue;
692             PD=PD1;
693           }
694         }
695         else if(subs3.Value()->IsKind(STANDARD_TYPE(StepRepr_ShapeRepresentationRelationship))) {
696           SRR = Handle(StepRepr_ShapeRepresentationRelationship)::DownCast(subs3.Value());
697         }
698       }
699     }
700   }
701   
702   Handle(Transfer_Binder) binder;
703   TopoDS_Shape theResult;
704   shbinder.Nullify();
705   
706   if(IsDepend) {
707     
708     if(!PD.IsNull()) {
709       binder = TP->Find(PD);
710       if ( binder.IsNull() ) binder = TransferEntity(PD,TP);
711       theResult = TransferBRep::ShapeResult(binder);
712       if (!theResult.IsNull()) {
713         if (iatrsf) {
714           if ( SRRReversed ) ApplyTransformation ( theResult, Trsf.Inverted() );
715           else               ApplyTransformation ( theResult, Trsf );
716         }
717         shbinder = new TransferBRep_ShapeBinder (theResult);
718       }
719     }
720     
721     if ( theResult.IsNull() && !SRR.IsNull() ) {
722       binder = TP->Find(SRR);
723       if ( binder.IsNull() ) {
724         binder = TransferEntity(SRR,TP);
725         theResult = TransferBRep::ShapeResult (binder);
726         if (!theResult.IsNull())
727           shbinder = new TransferBRep_ShapeBinder (theResult);
728       }
729     }
730     
731   }
732   TP->Bind(NAUO, shbinder);
733   return shbinder;
734   
735 }
736 //=======================================================================
737 //function : TransferEntity
738 //purpose  : 
739 //=======================================================================
740
741 Handle(TransferBRep_ShapeBinder) STEPControl_ActorRead::TransferEntity(const Handle(StepShape_ShapeRepresentation)& sr,
742                                                                        const Handle(Transfer_TransientProcess)& TP,
743                                                                        Standard_Boolean& isBound)
744 {
745   NM_DETECTED = Standard_False;
746   Handle(TransferBRep_ShapeBinder) shbinder;
747   if(!Recognize(sr))
748     return shbinder;
749   isBound = Standard_False;
750   Standard_Integer i,nb = sr->NbItems();
751   // Used in XSAlgo::AlgoContainer()->ProcessShape (ssv; 13.11.2010)
752   Standard_Integer nbTPitems = TP->NbMapped();
753   Handle(Message_Messenger) sout = TP->Messenger();
754   #ifdef TRANSLOG
755   if (TP->TraceLevel() > 2) 
756     sout<<" -- Actor : case  ShapeRepr. NbItems="<<nb<<endl;
757   #endif
758   
759     // Compute unit convertion factors and geometric Accuracy
760   Handle(StepRepr_Representation) oldSRContext = mySRContext; //:S4136
761   PrepareUnits(sr,TP);
762   
763   BRep_Builder B;
764   TopoDS_Compound comp;
765   B.MakeCompound (comp);
766   TopoDS_Shape OneResult;
767   Standard_Integer nsh = 0;
768   Message_ProgressSentry PS ( TP->GetProgress(), "Sub-assembly", 0, nb, 1 );
769
770   // [BEGIN] Proceed with non-manifold topology (ssv; 12.11.2010)
771   Standard_Boolean isNMMode = Interface_Static::IVal("read.step.nonmanifold");
772   Standard_Boolean isManifold = Standard_True;
773   if ( isNMMode && sr->IsKind(STANDARD_TYPE(StepShape_NonManifoldSurfaceShapeRepresentation)) ) {
774     isManifold = Standard_False;
775     NM_DETECTED = Standard_True;
776     #ifdef DEB
777     Standard_Integer NMSSRItemsLen = sr->Items()->Length();
778     cout << "NMSSR with " << NMSSRItemsLen << " items detected" << endl;
779     #endif
780   } 
781   // Special processing for I-DEAS STP case (ssv; 15.11.2010)
782   else {
783     Standard_Integer isIDeasMode = Interface_Static::IVal("read.step.ideas");
784     if (isNMMode && myNMTool.IsIDEASCase() && isIDeasMode) {
785       isManifold = Standard_False;
786       NM_DETECTED = Standard_True;
787       #ifdef DEB
788       cout << "I-DEAS post processing for non-manifold topology ENABLED" << endl;
789       #endif
790     }
791     #ifdef DEB
792     else if ( myNMTool.IsIDEASCase() )
793       cout << "I-DEAS post processing for non-manifold topology DISABLED" << endl;
794     #endif
795   }
796   myNMTool.CleanUp();
797   // Don't use NM tool in manifold cases (ssv; 24.11.2010)
798   myNMTool.SetActive(!isManifold && isNMMode);
799   // [END] Proceed with non-manifold topology (ssv; 12.11.2010)
800
801   for (i = 1; i <= nb && PS.More(); i ++,PS.Next()) {
802   //for (i = 1; i <= nb ; i ++) {
803     #ifdef TRANSLOG
804     if (TP->TraceLevel() > 2) 
805       sout<<" -- Actor, shape_representation.item n0. "<<i<<endl;
806     #endif
807     Handle(StepRepr_RepresentationItem) anitem = sr->ItemsValue(i);
808     Handle(Transfer_Binder) binder;
809     if (!TP->IsBound(anitem)) {
810       binder = TransferShape(anitem, TP, isManifold);
811     }
812     else {
813       isBound = Standard_True;
814       binder = TP->Find(anitem);
815     }
816     TopoDS_Shape theResult = TransferBRep::ShapeResult (binder);
817     if (!theResult.IsNull()) {
818       OneResult = theResult;
819       B.Add(comp, theResult);
820       nsh ++;
821     }
822   }
823   
824   // [BEGIN] Proceed with non-manifold topology (ssv; 12.11.2010)
825   if (!isManifold) {
826     Handle(Standard_Transient) info;
827     // IMPORTANT: any fixing on non-manifold topology must be done after the shape is transferred from STEP
828     TopoDS_Shape fixedResult = 
829       XSAlgo::AlgoContainer()->ProcessShape( comp, myPrecision, myMaxTol,
830                                              "read.step.resource.name", 
831                                              "read.step.sequence", info,
832                                              TP->GetProgress() );
833     XSAlgo::AlgoContainer()->MergeTransferInfo(TP, info, nbTPitems);
834
835     BRep_Builder brepBuilder;
836
837     // [BEGIN] Try to close OPEN Shells in I-DEAS case (ssv; 17.11.2010)
838     if ( myNMTool.IsIDEASCase() ) {
839             
840       // ==========================================================
841       //  For each Shell (always OPEN in I-DEAS case) find all 
842       //  the possibilities to close it with adjacent non-manifold
843       //  Shells which are stored separately in I-DEAS-like STP
844       // ==========================================================
845
846       TopTools_IndexedDataMapOfShapeListOfShape shellClosingsMap;
847       // Find possible closings for each shell
848       this->computeIDEASClosings(comp, shellClosingsMap);
849
850       // Make compound to store closed Shells
851       TopoDS_Compound compWithClosings;
852       brepBuilder.MakeCompound(compWithClosings);
853
854       // Attempt to close Shells one-by-one
855       for (Standard_Integer i = 1; i <= shellClosingsMap.Extent(); i++) {
856         TopoDS_Shell adjustedShell = this->closeIDEASShell( TopoDS::Shell( shellClosingsMap.FindKey(i) ),
857                                                             shellClosingsMap.FindFromIndex(i) );     
858         brepBuilder.Add(compWithClosings, adjustedShell);
859       }
860       // Put not suspected open Shells as they are (updated 23.11.2010)
861       TopExp_Explorer allShellsExp(comp, TopAbs_SHELL);
862       for ( ; allShellsExp.More(); allShellsExp.Next() ) {
863         TopoDS_Shape aCurrentShell = allShellsExp.Current();
864         if ( !myNMTool.IsPureNMShell(aCurrentShell) && !shellClosingsMap.Contains(aCurrentShell) )
865           brepBuilder.Add(compWithClosings, aCurrentShell);
866       }
867   
868
869       comp = compWithClosings;
870  
871     }
872     // [END] Try to close OPEN Shells in I-DEAS case (ssv; 17.11.2010)
873
874     // [BEGIN] Reconstruct Solids from Closed Shells (ssv; 15.11.2010)
875     TopoDS_Compound reconstComp;
876     brepBuilder.MakeCompound(reconstComp);
877     
878     TopoDS_Iterator it(comp);
879     for ( ; it.More(); it.Next() ) {
880       TopoDS_Shape aSubShape = it.Value();
881       if ( aSubShape.ShapeType() == TopAbs_SHELL && aSubShape.Closed() ) {
882         TopoDS_Solid nextSolid;
883         brepBuilder.MakeSolid(nextSolid);
884         brepBuilder.Add(nextSolid, aSubShape);
885         brepBuilder.Add(reconstComp, nextSolid);
886       } 
887       else if (aSubShape.ShapeType() == TopAbs_SHELL)
888         brepBuilder.Add(reconstComp, aSubShape);
889     }
890
891     comp = reconstComp;
892     // [END] Reconstruct Solids from Closed Shells (ssv; 15.11.2010)
893   }
894
895   // Bind the resulting shape
896   if      (nsh == 0) shbinder.Nullify();
897   else if (nsh == 1) shbinder = new TransferBRep_ShapeBinder (OneResult);
898   else               shbinder = new TransferBRep_ShapeBinder (comp);
899   PrepareUnits ( oldSRContext, TP ); //:S4136
900   TP->Bind(sr, shbinder);
901
902   
903   #ifdef DEB
904   DumpWhatIs(comp);
905   #endif
906   
907   return shbinder;
908   
909 }
910 //=======================================================================
911 //function : TransferEntity
912 //purpose  : 
913 //=======================================================================
914
915 Handle(TransferBRep_ShapeBinder) STEPControl_ActorRead::TransferEntity(const Handle(StepShape_ContextDependentShapeRepresentation)& CDSR,
916                                                                        const Handle(Transfer_TransientProcess)& TP)
917 {
918   Handle(TransferBRep_ShapeBinder) shbinder;
919   //:j2: treat SRRs here in order to compare them with NAUO
920   Handle(StepRepr_ShapeRepresentationRelationship) SRR = CDSR->RepresentationRelation();
921   //DeclareAndCast(StepRepr_RepresentationRelationship,SRR,CDSR->RepresentationRelation());
922   if ( SRR.IsNull() ) return shbinder;
923   
924   Standard_Boolean SRRReversed = STEPConstruct_Assembly::CheckSRRReversesNAUO ( TP->Model(), CDSR );
925   Handle(StepRepr_Representation) rep1 = ( SRRReversed ? SRR->Rep2() : SRR->Rep1() );
926   Handle(StepShape_ShapeRepresentation) rep = Handle(StepShape_ShapeRepresentation)::DownCast(rep1);
927
928   if ( SRRReversed ) 
929     TP->AddWarning ( SRR, "SRR reverses relation defined by NAUO; NAUO definition is taken" );
930   
931   TopoDS_Shape theResult;
932   
933   gp_Trsf Trsf;
934   Standard_Boolean iatrsf = ComputeSRRWT ( SRR, TP, Trsf );
935   /* Delete this part does not work gka
936   // use SDR for reading rep in order to handle subassemblies
937   Interface_EntityIterator subs = TP->Graph().Sharings(rep);
938   Standard_Integer nbitem=0;
939   for (subs.Start(); subs.More(); subs.Next()) nbitem++;
940   Message_ProgressSentry PS ( TP->GetProgress(), "Shape", 0, nbitem, 1 );
941
942   for (subs.Start(); subs.More() && PS.More() ; subs.Next(),PS.Next()) {
943     if ( subs.Value()->IsKind(STANDARD_TYPE(StepShape_ShapeDefinitionRepresentation))) {
944       DeclareAndCast(StepShape_ShapeDefinitionRepresentation,SDR,subs.Value());
945 #ifdef TRANSLOG
946       if (TP->TraceLevel() > 1) 
947         sout<<" -- Actor : Ent.n0 "<<TP->Model()->Number(CDSR)<<" -> Sharing Ent.no"<<TP->Model()->Number(SDR)<<endl;
948 #endif
949       
950       binder = TP->Find ( SDR );
951       if ( binder.IsNull() ) binder = TransferEntity(SDR,TP);
952       theResult = TransferBRep::ShapeResult (binder);
953       break;
954     }
955   }*/
956   //if ( theResult.IsNull() && ! subs.More() ) {
957   Handle(Transfer_Binder) binder;
958   Standard_Boolean isBound = Standard_False;
959     if (!TP->IsBound(rep)) binder = TransferEntity(rep,TP,isBound);
960     else binder = TP->Find(rep);
961     theResult = TransferBRep::ShapeResult (binder);
962   //}
963       
964   if ( ! theResult.IsNull() ) {
965     if ( iatrsf ) {
966       if ( SRRReversed ) ApplyTransformation ( theResult, Trsf.Inverted() );
967       else               ApplyTransformation ( theResult, Trsf );
968     }
969     shbinder = new TransferBRep_ShapeBinder (theResult);
970   }
971   else shbinder.Nullify();
972   TP->Bind(CDSR, shbinder);
973   return shbinder;
974   
975 }
976 //=======================================================================
977 //function : TransferEntity
978 //purpose  : 
979 //=======================================================================
980
981 Handle(TransferBRep_ShapeBinder) STEPControl_ActorRead::TransferEntity(const Handle(StepRepr_ShapeRepresentationRelationship)& und,
982                                                                        const Handle(Transfer_TransientProcess)& TP,
983                                                                        const Standard_Integer nbrep)
984 {
985   //  REPRESENTATION_RELATIONSHIP et la famille
986   Handle(TransferBRep_ShapeBinder) shbinder;
987   
988   if (und.IsNull()) return shbinder;
989   
990   //  On prend son contenu : Rep1 ou Rep2 , that is the question
991   //    on prend les 2. Mais quoi faire des axes
992   
993   TopoDS_Compound Cund;
994   TopoDS_Shape OneResult;
995   BRep_Builder B;
996   B.MakeCompound (Cund);
997   Standard_Integer nsh = 0;
998   
999   gp_Trsf Trsf;
1000   Standard_Boolean iatrsf = ComputeSRRWT ( und, TP, Trsf );
1001   
1002   //    Transfert : que faut-il prendre au juste ?
1003   
1004   for (Standard_Integer i = 1; i <= 2; i ++) {
1005     if(nbrep && nbrep != i)
1006       continue;
1007     Handle(StepRepr_Representation) anitemt;
1008     if (i == 1) anitemt = und->Rep1();
1009     if (i == 2) anitemt = und->Rep2();
1010     Handle(StepShape_ShapeRepresentation) anitem = Handle(StepShape_ShapeRepresentation)::DownCast(anitemt);
1011     Handle(Transfer_Binder) binder;
1012     Standard_Boolean isBound = Standard_False;
1013     if (!TP->IsBound(anitem)) binder = TransferEntity(anitem,TP,isBound);//TP->Transferring(anitem);
1014     else                        binder = TP->Find(anitem);
1015     TopoDS_Shape theResult = TransferBRep::ShapeResult (binder);
1016     if (!theResult.IsNull()) {
1017       OneResult = theResult;
1018       B.Add(Cund, theResult);
1019       nsh ++;
1020     }
1021   }
1022   
1023   //   La Transformation : selon les cas
1024   
1025   //    Appliquer la transformation
1026   
1027   if (iatrsf) {
1028     if      (nsh == 1) ApplyTransformation ( OneResult, Trsf );
1029     else if (nsh >  1) ApplyTransformation ( Cund, Trsf );
1030   }
1031   if      (nsh == 0) shbinder.Nullify();
1032   else if (nsh == 1) shbinder = new TransferBRep_ShapeBinder (OneResult);
1033   else               shbinder = new TransferBRep_ShapeBinder (Cund);
1034   TP->Bind(und, shbinder);
1035   return shbinder;
1036   
1037 }
1038
1039 //=======================================================================
1040 //function : OldWay
1041 //purpose  : 
1042 //=======================================================================
1043 //=======================================================================
1044 //function : IsNeedRepresentation
1045 //purpose  : 
1046 //=======================================================================
1047
1048 static Standard_Boolean IsNeedRepresentation(const Handle(StepRepr_ShapeAspect)& sa,
1049                                              const Handle(StepRepr_Representation)&repA ,
1050                                              const Handle(Transfer_TransientProcess)& TP)
1051 {
1052   Standard_Boolean IsSDRaspect=Standard_True;
1053   Handle(StepRepr_ProductDefinitionShape) PDSA = sa->OfShape();
1054   const Interface_Graph& graph = TP->Graph();
1055   Interface_EntityIterator subs7 = graph.Sharings(PDSA);
1056   for (subs7.Start(); ! PDSA.IsNull() && subs7.More(); subs7.Next()) {
1057     Handle(StepShape_ShapeDefinitionRepresentation) sdrA = 
1058       Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs7.Value());
1059     if ( sdrA.IsNull() ) continue;
1060     // abv 23 Feb 00: use iterator to take into account AP203 hybrid models
1061     Interface_EntityIterator subs8 = graph.Shareds(sdrA);
1062     for (subs8.Start(); subs8.More(); subs8.Next()) {
1063       Handle(StepRepr_Representation) rep2 = 
1064         Handle(StepRepr_Representation)::DownCast ( subs8.Value() );
1065       if ( rep2.IsNull() ) {
1066         Handle(StepRepr_ShapeRepresentationRelationship) SRR = 
1067           Handle(StepRepr_ShapeRepresentationRelationship)::DownCast ( subs8.Value() );
1068         if ( SRR.IsNull() ) continue;
1069         rep2 = ( sdrA->UsedRepresentation() == SRR->Rep1() ? SRR->Rep2() : SRR->Rep1() );
1070       }
1071       Standard_Integer i, j; // svv Jan 11 2000 : porting on DEC
1072       for ( i=1; i <= repA->NbItems(); i++ ) {
1073         Handle(StepRepr_RepresentationItem) it = repA->ItemsValue(i);
1074         for ( j=1; j <= rep2->NbItems(); j++ )
1075           if ( it == rep2->ItemsValue(j) ) break;
1076         if ( j > rep2->NbItems() ) break;
1077       }
1078       if ( i > repA->NbItems() ) IsSDRaspect=Standard_False;
1079     }
1080   }
1081   return IsSDRaspect;
1082 }
1083 //=======================================================================
1084 //function : OldWay
1085 //purpose  : 
1086 //=======================================================================
1087
1088 Handle(TransferBRep_ShapeBinder) STEPControl_ActorRead::OldWay(const Handle(Standard_Transient)& start,
1089                                                                const Handle(Transfer_TransientProcess)& TP)
1090 {
1091   Handle(Message_Messenger) sout = TP->Messenger();
1092   const Interface_Graph& graph = TP->Graph();
1093   Handle(TransferBRep_ShapeBinder) shbinder;
1094   DeclareAndCast(StepShape_ShapeDefinitionRepresentation,sdr,start);
1095   Handle(StepRepr_Representation) rep = sdr->UsedRepresentation();
1096
1097   // abv 7 Oct 99: TRJ2: skip SDRs used only for defining SHAPE_ASPECT (validation properties)
1098   // BUT ONLY if they have representation duplicated with other SDR,
1099   // (SHAPE_ASPECT also used by some systems to define geometry)
1100   Handle(StepRepr_PropertyDefinition) PD = sdr->Definition().PropertyDefinition();
1101   if ( ! PD.IsNull() ) {
1102     Handle(StepRepr_ShapeAspect) SA = PD->Definition().ShapeAspect();
1103     if ( ! SA.IsNull() ) {
1104       if(!IsNeedRepresentation(SA,rep,TP))
1105         return shbinder;
1106     }
1107   }
1108     
1109 #ifdef TRANSLOG
1110   if (TP->TraceLevel() > 2) 
1111     sout<<" -- Actor : case  shape_definition_representation."<<endl;
1112 #endif
1113   Handle(Transfer_Binder) binder = TP->Find(rep);
1114   if (binder.IsNull()) binder = TP->Transferring(rep);
1115 //:j2    if (!binder.IsNull()) return binder;
1116
1117 //    SDR designant des CDSR (lien implicite, via la UsedRepr)
1118
1119   TopoDS_Compound Cund;
1120   TopoDS_Shape OneResult;
1121   BRep_Builder B;
1122   B.MakeCompound (Cund);
1123   Standard_Integer nsh = 0;
1124
1125   //:j2
1126   shbinder = new TransferBRep_ShapeBinder;
1127   TP->Bind ( start, shbinder ); //:j3 abv 23 Oct 98: rp1sd.stp: bind something to protect against loops
1128   if (!binder.IsNull()) {
1129     TopoDS_Shape theResult = TransferBRep::ShapeResult (binder);
1130     if (!theResult.IsNull()) {
1131       OneResult = theResult;
1132       B.Add(Cund, theResult);
1133       nsh ++;
1134       shbinder->SetResult (theResult);
1135     }
1136   }
1137
1138   // process subcomponents of assembly (CDSR) and hybrid models (SRR)
1139   Interface_EntityIterator subs = graph.Shareds(start);
1140   Handle(Standard_Type) tCDSR = STANDARD_TYPE(StepShape_ContextDependentShapeRepresentation);
1141   Handle(Standard_Type) tSRR = STANDARD_TYPE(StepRepr_ShapeRepresentationRelationship);
1142   Standard_Integer nbitem=0;
1143   for (subs.Start();subs.More();subs.Next()) nbitem++;
1144   Message_ProgressSentry PS ( TP->GetProgress(), "Sub", 0, nbitem, 1 );
1145   for (subs.Start(); subs.More() && PS.More(); subs.Next() ,PS.Next()) {
1146     Handle(Standard_Transient) anitem = subs.Value();
1147     if ( anitem->DynamicType() != tCDSR && anitem->DynamicType() != tSRR ) continue;
1148 //      DeclareAndCast(StepShape_ContextDependentShapeRepresentation,anitem,subs.Value());
1149 //      if (anitem.IsNull()) continue;
1150 #ifdef TRANSLOG
1151     if (TP->TraceLevel() > 1) 
1152       sout<<" -- Actor : Ent.n0 "<<TP->Model()->Number(start)<<" -> Shared Ent.no"<<TP->Model()->Number(anitem)<<endl;
1153 #endif
1154
1155     if (!TP->IsBound(anitem)) binder = TP->Transferring(anitem);
1156     else                        binder = TP->Find(anitem);
1157     TopoDS_Shape theResult = TransferBRep::ShapeResult (binder);
1158     if (!theResult.IsNull()) {
1159       OneResult = theResult;
1160       B.Add(Cund, theResult);
1161       nsh += 2; //abv 11.10.00: 2 instead of 1 in order to keep assembly structure
1162     }
1163   }
1164
1165   if      (nsh == 0) shbinder = new TransferBRep_ShapeBinder (Cund);//shbinder.Nullify();
1166   else if (nsh == 1) shbinder = new TransferBRep_ShapeBinder (OneResult);
1167   else               shbinder = new TransferBRep_ShapeBinder (Cund);
1168   TP->Unbind( start ); //:j3: unbind start (let it be bound by TransferProcess)
1169   return shbinder;
1170 }
1171
1172 //=======================================================================
1173 //function : TransferEntity
1174 //purpose  : 
1175 //=======================================================================
1176
1177 Handle(TransferBRep_ShapeBinder) STEPControl_ActorRead::TransferEntity(const Handle(StepGeom_GeometricRepresentationItem)& start,
1178                                                                        const Handle(Transfer_TransientProcess)& TP,
1179                                                                        const Standard_Boolean isManifold)
1180 {
1181   Handle(Message_Messenger) sout = TP->Messenger();
1182   Handle(TransferBRep_ShapeBinder) shbinder;
1183   Standard_Boolean found = Standard_False;
1184   StepToTopoDS_Builder myShapeBuilder;
1185   TopoDS_Shape mappedShape;
1186   Standard_Integer nbTPitems = TP->NbMapped();
1187 #ifdef TRANSLOG
1188   OSD_Timer chrono;
1189   if (TP->TraceLevel() > 2) 
1190     sout << "Begin transfer STEP -> CASCADE, Type "
1191          << start->DynamicType()->Name() << endl;
1192   chrono.Start();
1193 #endif
1194   
1195   //:S4136
1196   Handle(StepRepr_Representation) oldSRContext = mySRContext;
1197   if ( mySRContext.IsNull() ) { // if no context, try to find it (ex: r0701_ug.stp #4790)
1198     Handle(StepRepr_Representation) context = FindContext ( start, TP );
1199     if ( context.IsNull() ) {
1200       TP->AddWarning ( start, "Entity with no unit context; default units taken" );
1201       ResetUnits();
1202     }
1203     else PrepareUnits ( context, TP );
1204   }
1205   myShapeBuilder.SetPrecision(myPrecision);
1206   myShapeBuilder.SetMaxTol(myMaxTol);
1207
1208   // Start progress scope (no need to check if progress exists -- it is safe)
1209   Message_ProgressSentry aPSentry(TP->GetProgress(), "Transfer stage", 0, 2, 1);
1210
1211   try {
1212     OCC_CATCH_SIGNALS
1213   if (start->IsKind(STANDARD_TYPE(StepShape_FacetedBrep))) {
1214     myShapeBuilder.Init(GetCasted(StepShape_FacetedBrep, start), TP);
1215     found = Standard_True;
1216   } 
1217   else if (start->IsKind(STANDARD_TYPE(StepShape_BrepWithVoids))) {
1218     myShapeBuilder.Init(GetCasted(StepShape_BrepWithVoids, start), TP);
1219     found = Standard_True;
1220   } 
1221   else if (start->IsKind(STANDARD_TYPE(StepShape_ManifoldSolidBrep))) {
1222     myShapeBuilder.Init(GetCasted(StepShape_ManifoldSolidBrep, start), TP);
1223     found = Standard_True;
1224   } 
1225   else if (start->IsKind(STANDARD_TYPE(StepShape_ShellBasedSurfaceModel))) {
1226     myShapeBuilder.Init(GetCasted(StepShape_ShellBasedSurfaceModel, start), TP, myNMTool);
1227     found = Standard_True;
1228   } 
1229   else if (start->IsKind(STANDARD_TYPE(StepShape_FacetedBrepAndBrepWithVoids))) {
1230     myShapeBuilder.Init(GetCasted(StepShape_FacetedBrepAndBrepWithVoids, start), TP);
1231     found = Standard_True;
1232   } 
1233   else if (start->IsKind(STANDARD_TYPE(StepShape_GeometricSet))) {
1234     myShapeBuilder.Init(GetCasted(StepShape_GeometricSet, start), TP);
1235     found = Standard_True;
1236   }
1237   else if (start->IsKind(STANDARD_TYPE(StepShape_EdgeBasedWireframeModel))) {
1238     myShapeBuilder.Init(GetCasted(StepShape_EdgeBasedWireframeModel, start), TP);
1239     found = Standard_True;
1240   }
1241   else if (start->IsKind(STANDARD_TYPE(StepShape_FaceBasedSurfaceModel))) {
1242     myShapeBuilder.Init(GetCasted(StepShape_FaceBasedSurfaceModel, start), TP);
1243     found = Standard_True;
1244   }
1245 }
1246   catch(Standard_Failure) {
1247     TP->AddFail(start,"Exeption is raised. Entity was not translated.");
1248     TP->Bind(start, shbinder);
1249     return shbinder;
1250   }
1251
1252   aPSentry.Next();
1253   
1254   if (found && myShapeBuilder.IsDone()) {
1255     mappedShape = myShapeBuilder.Value();
1256     // Apply ShapeFix (on manifold shapes only. Non-manifold topology is processed separately: ssv; 13.11.2010)
1257     if (isManifold) {
1258       Handle(Standard_Transient) info;
1259       mappedShape = 
1260         XSAlgo::AlgoContainer()->ProcessShape( mappedShape, myPrecision, myMaxTol,
1261                                                "read.step.resource.name", 
1262                                                "read.step.sequence", info,
1263                                                TP->GetProgress() );
1264       XSAlgo::AlgoContainer()->MergeTransferInfo(TP, info, nbTPitems);
1265     }
1266   }
1267   found = !mappedShape.IsNull();
1268   if (found && shbinder.IsNull()) shbinder = new TransferBRep_ShapeBinder (mappedShape);
1269 #ifdef TRANSLOG
1270   chrono.Stop();
1271   if (TP->TraceLevel() > 2) 
1272     sout<<"End transfer STEP -> CASCADE :" << (found ? "OK" : " : no result")<<endl;
1273   if (TP->TraceLevel() > 2) 
1274     chrono.Show();
1275 #endif
1276   if ( oldSRContext.IsNull() && ! mySRContext.IsNull() ) //:S4136
1277     PrepareUnits ( oldSRContext, TP );
1278   TP->Bind(start, shbinder);
1279   return shbinder;
1280 }
1281
1282  
1283 //=======================================================================
1284 //function : TransferEntity
1285 //purpose  : 
1286 //=======================================================================
1287
1288 Handle(TransferBRep_ShapeBinder) STEPControl_ActorRead::TransferEntity(const Handle(StepRepr_MappedItem)&  mapit,
1289                                                               const Handle(Transfer_TransientProcess)& TP)
1290 {
1291   Handle(TransferBRep_ShapeBinder) shbinder;
1292   
1293     // --------------------------------------------------------------
1294   // On se trouve ici dans un contexte " d'assemblage geometrique "
1295   //    - MappedItem
1296   // --------------------------------------------------------------
1297   
1298   //:S4136: abv 20 Apr 99: as1ug.stp: MAPPED_ITEM transformation computed
1299   //        taking into account units of origin and target SHAPE_REPRESENTATIONs
1300   
1301   //  La Shape, et la mise en position
1302   Handle(StepShape_ShapeRepresentation) maprep =  Handle(StepShape_ShapeRepresentation)::
1303     DownCast(mapit->MappingSource()->MappedRepresentation());
1304   //Handle(StepRepr_Representation) maprep = mapit->MappingSource()->MappedRepresentation();
1305   Standard_Boolean isBound = Standard_False; 
1306   Handle(Transfer_Binder) binder = TP->Find(maprep);
1307   if (binder.IsNull())    binder = TransferEntity(maprep,TP,isBound);
1308   shbinder = Handle(TransferBRep_ShapeBinder)::DownCast(binder);
1309   if (shbinder.IsNull()) TP->AddWarning(mapit,"No Shape Produced");
1310   else {
1311     TopoDS_Shape mappedShape = shbinder->Result();
1312     if ( ! mappedShape.IsNull() ) {
1313       
1314       //  Positionnement : 2 formules
1315       //  1/ Ax2 dans Source et comme Target  : passage de Source a Target
1316       //  2/ CartesianOperator3d comme Target : on applique
1317       
1318       gp_Trsf Trsf;
1319       Standard_Boolean ok = Standard_False;
1320       
1321       Handle(StepGeom_CartesianTransformationOperator3d) CartOp =
1322         Handle(StepGeom_CartesianTransformationOperator3d)::DownCast(mapit->MappingTarget());
1323       if ( ! CartOp.IsNull() ) {
1324         ok = StepToGeom_MakeTransformation3d::Convert( CartOp, Trsf );
1325       }
1326       else {
1327         Handle(StepGeom_Axis2Placement3d) Origin = 
1328           Handle(StepGeom_Axis2Placement3d)::DownCast(mapit->MappingSource()->MappingOrigin());
1329         Handle(StepGeom_Axis2Placement3d) Target = 
1330           Handle(StepGeom_Axis2Placement3d)::DownCast(mapit->MappingTarget());
1331         if ( ! Origin.IsNull() && ! Target.IsNull() ) {
1332           ok = Standard_True;
1333           Handle(StepRepr_Representation) rep = mySRContext; // NOTE: copy of handle !
1334           ComputeTransformation ( Origin, Target, maprep, rep, TP, Trsf );
1335           ok = Standard_True;
1336         }
1337       }
1338       
1339       if ( ok ) ApplyTransformation ( mappedShape, Trsf );
1340       else TP->AddWarning (mapit,"Mapped Item, case not recognized, location ignored");
1341       
1342       shbinder = new TransferBRep_ShapeBinder (mappedShape);
1343     }
1344   }
1345   TP->Bind(mapit, shbinder);
1346   return shbinder;
1347 }
1348 //=======================================================================
1349 //function : TransferEntity
1350 //purpose  : 
1351 //=======================================================================
1352
1353 Handle(TransferBRep_ShapeBinder) STEPControl_ActorRead::TransferEntity(const Handle(StepShape_FaceSurface)& fs,
1354                                                                        const Handle(Transfer_TransientProcess)& TP)
1355 {
1356
1357   //    Cas bien utile meme si non reconnu explicitement
1358   Handle(TransferBRep_ShapeBinder) sb;
1359   Standard_Integer nbTPitems = TP->NbMapped();
1360   try {
1361     OCC_CATCH_SIGNALS
1362
1363   StepToTopoDS_Tool         myTool;
1364   StepToTopoDS_DataMapOfTRI aMap;
1365   
1366   myTool.Init(aMap, TP);
1367   StepToTopoDS_TranslateFace myTF;
1368   myTF.SetPrecision(myPrecision);
1369   myTF.SetMaxTol(myMaxTol);
1370   
1371   // Non-manifold topology is not processed here (ssv; 15.11.2010)
1372   StepToTopoDS_NMTool dummyNMTool;
1373   myTF.Init (fs, myTool, dummyNMTool);
1374   Handle(StepRepr_Representation) oldSRContext = mySRContext;
1375   if ( mySRContext.IsNull() ) { // if no context, try to find it (ex: r0701_ug.stp #4790)
1376     Handle(StepRepr_Representation) context = FindContext ( fs, TP );
1377     if ( context.IsNull() ) {
1378       TP->AddWarning ( fs, "Entity with no unit context; default units taken" );
1379       ResetUnits();
1380     }
1381     else PrepareUnits ( context, TP );
1382   }
1383   
1384   // Apply ShapeFix
1385   Handle(Transfer_Binder) binder = TP->Find (fs);
1386   sb = Handle(TransferBRep_ShapeBinder)::DownCast ( binder );
1387   if ( ! sb.IsNull() && ! sb->Result().IsNull() ) {
1388     TopoDS_Shape S = sb->Result();
1389     
1390     Handle(Standard_Transient) info;
1391     TopoDS_Shape shape = XSAlgo::AlgoContainer()->ProcessShape( S, myPrecision, myMaxTol,
1392                                                                 "read.step.resource.name", 
1393                                                                 "read.step.sequence", info,
1394                                                                 TP->GetProgress() );
1395     //      TopoDS_Shape shape = XSAlgo::AlgoContainer()->PerformFixShape( S, TP, myPrecision, myMaxTol );
1396     if ( shape != S ) 
1397       sb->SetResult ( shape );
1398     
1399     XSAlgo::AlgoContainer()->MergeTransferInfo(TP, info, nbTPitems);
1400   }
1401
1402   
1403   if ( oldSRContext.IsNull() && ! mySRContext.IsNull() ) //:S4136
1404     PrepareUnits ( oldSRContext, TP ); 
1405   TP->Bind(fs, sb);
1406   return sb; // TP->Find (start);
1407 }
1408   catch(Standard_Failure)
1409   {
1410     TP->AddFail(fs,"Exeption is raised. Entity was not translated.");
1411     sb.Nullify();
1412     TP->Bind(fs, sb);
1413     return sb;
1414   }
1415 }
1416 //=======================================================================
1417 //function : TransferShape
1418 //purpose  : 
1419 //=======================================================================
1420
1421 Handle(Transfer_Binder) STEPControl_ActorRead::TransferShape(const Handle(Standard_Transient)& start,
1422                                                              const Handle(Transfer_TransientProcess)& TP,
1423                                                              const Standard_Boolean isManifold)
1424 {
1425   if (start.IsNull()) return NullResult();
1426   XSAlgo::AlgoContainer()->PrepareForTransfer();
1427
1428 //  myContext.SetModel ( Handle(StepData_StepModel)::DownCast ( TP->Model() ) ); // for asking IsAP203?
1429   
1430   Handle(Message_Messenger) sout = TP->Messenger();
1431 #ifdef TRANSLOG
1432 //  POUR MISE AU POINT, a supprimer ensuite
1433 //  sout<<"STEP->Shape, ent n0 "<<TP->Model()->Number(start)<<" Level="<<TP->NestingLevel()<<endl;
1434   if (TP->TraceLevel() > 1) 
1435     sout<<" -- Actor : Transfer Ent.n0 "<<TP->Model()->Number(start)<<"  Type "<<start->DynamicType()->Name()<<endl;
1436 #endif
1437   
1438   Handle(TransferBRep_ShapeBinder) shbinder;
1439   
1440
1441   // Product Definition Entities
1442   // They should be treated with Design Manager
1443    // case ShapeDefinitionRepresentation if ProductMode != ON
1444   TCollection_AsciiString aProdMode = Interface_Static::CVal("read.step.product.mode");
1445   if(!aProdMode.IsEqual("ON") && 
1446      start->IsKind(STANDARD_TYPE(StepShape_ShapeDefinitionRepresentation))) 
1447     shbinder = OldWay(start,TP);
1448   //skl
1449   
1450   else if(start->IsKind(STANDARD_TYPE(StepBasic_ProductDefinition))) {
1451     Handle(StepBasic_ProductDefinition) PD = 
1452       Handle(StepBasic_ProductDefinition)::DownCast(start);
1453      shbinder = TransferEntity(PD,TP);
1454   }
1455   
1456   // NextAssemblyUsageOccurrence
1457   else if (start->IsKind(STANDARD_TYPE(StepRepr_NextAssemblyUsageOccurrence))) {
1458     Handle(StepRepr_NextAssemblyUsageOccurrence) NAUO = 
1459       Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(start);
1460      shbinder = TransferEntity(NAUO,TP);
1461   }
1462   //end skl
1463     
1464   // Shape Representation
1465   else if (start->IsKind(STANDARD_TYPE(StepShape_ShapeRepresentation))) {
1466     DeclareAndCast(StepShape_ShapeRepresentation,sr,start);
1467     Standard_Boolean isBound = Standard_False;
1468     shbinder = TransferEntity(sr,TP,isBound);
1469   }
1470   
1471     // --------------------------------------------------------------
1472     // On se trouve ici aussi dans un contexte " d'assemblage geometrique "
1473     //    - ShapeRepresentationRelationship + Transformation ou non
1474     // --------------------------------------------------------------
1475
1476   else if (start->IsKind(STANDARD_TYPE(StepShape_ContextDependentShapeRepresentation))) {
1477     DeclareAndCast(StepShape_ContextDependentShapeRepresentation,CDSR,start);
1478     shbinder =  TransferEntity(CDSR,TP);
1479   }
1480
1481   else if (start->IsKind (STANDARD_TYPE(StepRepr_ShapeRepresentationRelationship)) ) {
1482     //  REPRESENTATION_RELATIONSHIP et la famille
1483
1484     DeclareAndCast(StepRepr_ShapeRepresentationRelationship,und,start);
1485     shbinder =  TransferEntity(und,TP);
1486   }
1487
1488   else if (start->IsKind (STANDARD_TYPE(StepGeom_GeometricRepresentationItem)) ) {
1489     // Here starts the entity to be treated : Shape Representation Subtype
1490   // It can be also other Root entities
1491     DeclareAndCast(StepGeom_GeometricRepresentationItem,git,start);
1492     shbinder = TransferEntity(git, TP, isManifold);
1493   }
1494   else if (start->IsKind(STANDARD_TYPE(StepRepr_MappedItem))) {
1495     DeclareAndCast(StepRepr_MappedItem,mapit,start);
1496     shbinder=  TransferEntity(mapit,TP);
1497   }
1498   else if (start->IsKind(STANDARD_TYPE(StepShape_FaceSurface))) {
1499     DeclareAndCast(StepShape_FaceSurface,fs,start);
1500     shbinder =  TransferEntity(fs,TP);
1501   }
1502
1503 //  if (!shbinder.IsNull()) TP->Bind(start,binder);
1504   
1505   return shbinder;
1506 }
1507 // ============================================================================
1508 // Method  : STEPControl_ActorRead::PrepareUnits
1509 // Purpose : Set the unit conversion factors
1510 // ============================================================================
1511
1512 void STEPControl_ActorRead::PrepareUnits(const Handle(StepRepr_Representation)& rep,
1513                                          const Handle(Transfer_TransientProcess)& TP)
1514 {
1515   mySRContext = rep;
1516   
1517   Standard_Integer stat1, stat2 = 0;  // sera alimente par STEPControl_Unit
1518 //  DeclareAndCast(StepShape_ShapeRepresentation,sr,start);
1519   if (rep.IsNull()) {
1520 //    TP->AddWarning(sr,"Not a ShapeRepresentation, default unit taken");
1521     ResetUnits();
1522     return;
1523   }
1524   
1525   // Get Units Applied to this model
1526   Handle(StepRepr_RepresentationContext) theRepCont = rep->ContextOfItems();
1527   if (theRepCont.IsNull()) {
1528     TP->AddWarning(rep,"Bad RepresentationContext, default unit taken");
1529     ResetUnits();
1530     return;
1531   }
1532
1533   // --------------------------------------------------
1534   // Complex ENTITY : GeometricRepresentationContext &&
1535   //                  GlobalUnitAssignedContext
1536   // --------------------------------------------------
1537
1538   STEPConstruct_UnitContext myUnit;
1539   Handle(StepRepr_GlobalUnitAssignedContext)        theGUAC;
1540   Handle(StepRepr_GlobalUncertaintyAssignedContext) aTol;
1541
1542   if (theRepCont->IsKind(STANDARD_TYPE(StepGeom_GeometricRepresentationContextAndGlobalUnitAssignedContext))) {
1543     DeclareAndCast(StepGeom_GeometricRepresentationContextAndGlobalUnitAssignedContext, theGRCAGAUC,theRepCont);
1544     theGUAC = theGRCAGAUC->GlobalUnitAssignedContext();
1545 //    TP->AddWarning(theRepCont,"No Length Uncertainty, last defined one is taken");
1546   }
1547
1548   // ----------------------------------------------------
1549   // Complex ENTITY : GeometricRepresentationContext   &&
1550   //                  GlobalUnitAssignedContext        &&
1551   //                  GlobalUncertaintyAssignedContext
1552   // ----------------------------------------------------
1553
1554   if (theRepCont->IsKind(STANDARD_TYPE(StepGeom_GeomRepContextAndGlobUnitAssCtxAndGlobUncertaintyAssCtx))) {
1555     DeclareAndCast(StepGeom_GeomRepContextAndGlobUnitAssCtxAndGlobUncertaintyAssCtx,
1556                    theGRCAGAUC,theRepCont);
1557     theGUAC = theGRCAGAUC->GlobalUnitAssignedContext();
1558     aTol    = theGRCAGAUC->GlobalUncertaintyAssignedContext();
1559   }
1560
1561
1562   // ----------------------------------------------------
1563   // Decoding and Setting the Values
1564   // ----------------------------------------------------
1565
1566   if (!theGUAC.IsNull()) {
1567     stat1 = myUnit.ComputeFactors(theGUAC);
1568     Standard_Integer anglemode = Interface_Static::IVal("step.angleunit.mode");
1569     Standard_Real angleFactor = ( anglemode == 0 ? myUnit.PlaneAngleFactor() :
1570                                   anglemode == 1 ? 1. : M_PI/180. );
1571     UnitsMethods::InitializeFactors(myUnit.LengthFactor(),
1572                                     angleFactor,
1573                                     myUnit.SolidAngleFactor());
1574     if (stat1 != 0) TP->AddWarning (theRepCont,myUnit.StatusMessage(stat1));
1575   }
1576
1577   if (!aTol.IsNull()) {
1578     stat2 = myUnit.ComputeTolerance (aTol);
1579     if (stat2 != 0) TP->AddWarning (theRepCont,myUnit.StatusMessage(stat2));
1580   }
1581
1582 //  myPrecision = Precision::Confusion();
1583   if (Interface_Static::IVal("read.precision.mode") == 1)  //:i1 gka S4136 05.04.99
1584     myPrecision = Interface_Static::RVal("read.precision.val");
1585   else if (myUnit.HasUncertainty())
1586     myPrecision = myUnit.Uncertainty() * myUnit.LengthFactor();
1587   else {
1588     TP->AddWarning(theRepCont,"No Length Uncertainty, value of read.precision.val is taken");
1589     myPrecision = Interface_Static::RVal("read.precision.val");
1590   }
1591   myMaxTol = Max ( myPrecision, Interface_Static::RVal("read.maxprecision.val") );
1592   // Assign uncertainty
1593 //  Interface_Static::SetRVal("lastpreci",UpdatedValue);
1594 #ifdef TRANSLOG
1595   if (TP->TraceLevel() > 1) 
1596     TP->Messenger() <<"  Cc1ToTopoDS : Length Unit = "<<myUnit.LengthFactor()<<"  Tolerance CASCADE = "<<myPrecision<<endl;
1597 #endif
1598 }
1599
1600 //=======================================================================
1601 //function : ResetUnits
1602 //purpose  : 
1603 //=======================================================================
1604
1605 void  STEPControl_ActorRead::ResetUnits ()
1606 {
1607   UnitsMethods::InitializeFactors ( 1, 1, 1 );
1608   myPrecision = Interface_Static::RVal("read.precision.val");
1609   myMaxTol = Max ( myPrecision, Interface_Static::RVal("read.maxprecision.val") );
1610 }
1611
1612 //=======================================================================
1613 //function : ComputeTransformation
1614 //purpose  : 
1615 //=======================================================================
1616
1617 //:S4136 abv 20 Apr 99: as1ug.stp: compute transformation taking units into account
1618 Standard_Boolean STEPControl_ActorRead::ComputeTransformation (const Handle(StepGeom_Axis2Placement3d) &Origin, 
1619                                                                const Handle(StepGeom_Axis2Placement3d) &Target,
1620                                                                const Handle(StepRepr_Representation) &OrigContext, 
1621                                                                const Handle(StepRepr_Representation) &TargContext,
1622                                                                const Handle(Transfer_TransientProcess) &TP,
1623                                                                gp_Trsf &Trsf)
1624 {
1625   Trsf = gp_Trsf();  // reinit
1626   if ( Origin.IsNull() || Target.IsNull() ) return Standard_False;
1627
1628   //:abv 31.10.01: TEST_MCI_2.step: check that Ax1 and Ax2 belong to 
1629   // corresponding reps and fix case of inversion error
1630   Handle(StepGeom_Axis2Placement3d) org = Origin;
1631   Handle(StepGeom_Axis2Placement3d) trg = Target;
1632   Standard_Integer code1=0, code2=0, i;
1633   for ( i=1; code1 != 1 && i <= OrigContext->NbItems(); i++ ) {
1634     if ( OrigContext->ItemsValue(i) == org ) code1 = 1;
1635     else if ( OrigContext->ItemsValue(i) == trg ) code1 = -1;
1636   }
1637   for ( i=1; code2 != 1 && i <= TargContext->NbItems(); i++ ) {
1638     if ( TargContext->ItemsValue(i) == org ) code2 = -1;
1639     else if ( TargContext->ItemsValue(i) == trg ) code2 = 1;
1640   }
1641   if ( code1 != 1 && code2 != 1 ) {
1642     if ( code1 == -1 && code2 == -1 ) {
1643       Handle(StepGeom_Axis2Placement3d) swp = org; org = trg; trg = swp;
1644       TP->AddWarning ( org, "Axis placements are swapped in SRRWT; corrected" );
1645     }
1646     else {
1647       TP->AddWarning ( ( code1 == 1 ? trg : org ), 
1648                        "Axis placement used by SRRWT does not belong to corresponding representation" );
1649     }
1650   }
1651   
1652   // translate axis_placements taking units into account 
1653   Handle(StepRepr_Representation) oldSRContext = mySRContext;
1654   if ( OrigContext  != oldSRContext ) PrepareUnits(OrigContext,TP);
1655   Handle(Geom_Axis2Placement) theOrig;
1656   StepToGeom_MakeAxis2Placement::Convert(org,theOrig);
1657   if ( TargContext  != OrigContext  ) PrepareUnits(TargContext,TP);
1658   Handle(Geom_Axis2Placement) theTarg;
1659   StepToGeom_MakeAxis2Placement::Convert(trg,theTarg);
1660   if ( oldSRContext != TargContext  ) PrepareUnits(oldSRContext,TP);
1661
1662   gp_Ax3 ax3Orig(theOrig->Ax2());
1663   gp_Ax3 ax3Targ(theTarg->Ax2());
1664
1665   //  ne pas se tromper de sens !
1666   Trsf.SetTransformation(ax3Targ, ax3Orig);
1667   return Trsf.Form() != gp_Identity;
1668 }
1669
1670 //=======================================================================
1671 //function : ReadSRRWT
1672 //purpose  : 
1673 //=======================================================================
1674
1675 //:j2 abv 22 Oct 98: auxiliary function: reading transformation from SRRWT
1676 Standard_Boolean STEPControl_ActorRead::ComputeSRRWT (const Handle(StepRepr_RepresentationRelationship) &SRR,
1677                                                       const Handle(Transfer_TransientProcess) &TP,
1678                                                       gp_Trsf &Trsf)
1679 {
1680   Trsf = gp_Trsf(); // init
1681   
1682   DeclareAndCast(StepRepr_ShapeRepresentationRelationshipWithTransformation,srwt,SRR);
1683   if ( srwt.IsNull() ) return Standard_False;
1684
1685   StepRepr_Transformation SelectTrans = srwt->TransformationOperator();
1686   
1687   // cartesian transformation
1688   Handle(StepGeom_CartesianTransformationOperator3d) CartOp = 
1689     Handle(StepGeom_CartesianTransformationOperator3d)::DownCast(SelectTrans.Value());
1690   if ( ! CartOp.IsNull() ) {
1691     // reset units (by Rep2 - ?)
1692     Handle(StepRepr_Representation) oldSRContext = mySRContext;
1693     if ( SRR->Rep2() != oldSRContext ) PrepareUnits(SRR->Rep2(),TP);
1694     StepToGeom_MakeTransformation3d::Convert( CartOp, Trsf );
1695     if ( SRR->Rep2() != oldSRContext ) PrepareUnits(oldSRContext,TP);
1696     return Trsf.Form() != gp_Identity;
1697   }
1698
1699   // item-defined transformation
1700   Handle(StepRepr_ItemDefinedTransformation) ItemDef =
1701     SelectTrans.ItemDefinedTransformation();
1702   if ( ItemDef.IsNull() ) return Standard_False;
1703   
1704   Handle(StepGeom_Axis2Placement3d) Ax1 =
1705     Handle(StepGeom_Axis2Placement3d)::DownCast(ItemDef->TransformItem1());
1706   Handle(StepGeom_Axis2Placement3d) Ax2 =
1707     Handle(StepGeom_Axis2Placement3d)::DownCast(ItemDef->TransformItem2());
1708   if ( Ax1.IsNull() || Ax2.IsNull() ) return Standard_False;
1709   return ComputeTransformation ( Ax1, Ax2, SRR->Rep1(), SRR->Rep2(), TP, Trsf);
1710 }
1711
1712 //=======================================================================
1713 // Method  : closeIDEASShell
1714 // Purpose : Attempts to close the passed Shell with the passed closing
1715 //           Shells. Cuts redundant Faces from the closing Shells if any
1716 //=======================================================================
1717
1718 TopoDS_Shell STEPControl_ActorRead::closeIDEASShell(const TopoDS_Shell& shell,
1719                                                     const TopTools_ListOfShape& closingShells) {
1720
1721   // Make Shell to provide closeness adjustments
1722   TopoDS_Shell result;
1723   BRep_Builder brepBuilder;
1724   brepBuilder.MakeShell(result);
1725         
1726   // Firstly, add all existing faces to the new Shell
1727   TopExp_Explorer currentFExp(shell, TopAbs_FACE);
1728   for ( ; currentFExp.More(); currentFExp.Next() ) {
1729     TopoDS_Face currentFace = TopoDS::Face( currentFExp.Current() ); 
1730     brepBuilder.Add(result, currentFace);
1731   }
1732
1733   TopTools_ListIteratorOfListOfShape itL(closingShells);
1734   TopTools_ListOfShape closingFaces;
1735
1736   // Then add the closing faces
1737   for ( ; itL.More(); itL.Next() ) {
1738     TopoDS_Shape currentClosing = itL.Value();
1739     TopExp_Explorer faceExp(currentClosing, TopAbs_FACE);
1740
1741     for ( ; faceExp.More(); faceExp.Next() ) {
1742       TopoDS_Face currentFace = TopoDS::Face( faceExp.Current() ); 
1743       brepBuilder.Add(result, currentFace);
1744       // Store each added closing face for subsequent processing
1745       closingFaces.Append(currentFace);
1746     }
1747   }
1748
1749   // Check if the result is closed
1750   BRepCheck_Shell checker( TopoDS::Shell(result) );
1751   BRepCheck_Status checkStatus = checker.Closed();
1752   if (checkStatus == BRepCheck_NoError)
1753     result.Closed(Standard_True);
1754   else
1755     return shell; // Cannot close this shell, skip it so...
1756
1757   // Try to remove redundant Faces
1758   for ( itL.Initialize(closingFaces); itL.More(); itL.Next() ) {
1759     TopoDS_Face currentFace = TopoDS::Face( itL.Value() );
1760     // Remove face to see if Shell is still closed
1761     brepBuilder.Remove(result, currentFace);
1762     BRepCheck_Shell subChecker( TopoDS::Shell(result) );
1763     BRepCheck_Status subCheckStatus = subChecker.Closed();
1764     // If Shell becomes open, just put the deleted face back
1765     if (subCheckStatus != BRepCheck_NoError)
1766       brepBuilder.Add(result, currentFace);
1767     else {
1768       #ifdef DEB
1769       cout << "Redundant closing face detected: REMOVED from shell";
1770       #endif
1771     }
1772   }
1773
1774   return result;
1775
1776 }
1777
1778 //=======================================================================
1779 // Method  : computeIDEASClosings
1780 // Purpose : For each Shell from the compound passed (comp), find all
1781 //           non-manifold adjacent Shells and put the results into
1782 //           the passed map (shellClosingMap)
1783 //=======================================================================
1784
1785 void STEPControl_ActorRead::computeIDEASClosings(const TopoDS_Compound& comp,
1786                                                  TopTools_IndexedDataMapOfShapeListOfShape& shellClosingsMap) {
1787   TopExp_Explorer shellExpA(comp, TopAbs_SHELL);
1788
1789   for ( ; shellExpA.More(); shellExpA.Next() ) {
1790     TopoDS_Shape shellA = shellExpA.Current();
1791     TopExp_Explorer shellExpB(comp, TopAbs_SHELL);
1792     TopTools_ListOfShape closingShells;
1793
1794     for ( ; shellExpB.More(); shellExpB.Next() ) {
1795       TopoDS_Shape shellB = shellExpB.Current();
1796       if ( shellA.IsSame(shellB) )
1797         continue;
1798       // Check whether ShellB is non-manifold and adjacent to ShellA.
1799       // If so, ShellA has a chance to be closed with ShellB
1800       if ( myNMTool.IsSuspectedAsClosing(shellA, shellB) )
1801         closingShells.Append(shellB);
1802     }
1803       
1804     if ( !closingShells.IsEmpty() )
1805       shellClosingsMap.Add(shellA, closingShells);
1806   }
1807
1808 }