summaryrefslogtreecommitdiff
path: root/src/VrmlData/VrmlData_Group.cxx
blob: a5f93f0c0a6f1e64e84fde3bb890507bcdabff47 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
// File:      VrmlData_Group.cxx
// Created:   06.11.06 08:01
// Author:    Alexander GRIGORIEV
// Copyright: Open Cascade 2006


#include <VrmlData_Group.hxx>
#include <VrmlData_Geometry.hxx>
#include <VrmlData_Scene.hxx>
#include <VrmlData_WorldInfo.hxx>
#include <VrmlData_InBuffer.hxx>
#include <VrmlData_ListOfNode.hxx>
#include <VrmlData_UnknownNode.hxx>
#include <Precision.hxx>
#include <gp_Ax1.hxx>

#ifdef _MSC_VER
#define _CRT_SECURE_NO_DEPRECATE
#endif

#include <stdio.h>

IMPLEMENT_STANDARD_HANDLE  (VrmlData_Group, VrmlData_Node)
IMPLEMENT_STANDARD_RTTIEXT (VrmlData_Group, VrmlData_Node)

//=======================================================================
//function : VrmlData_Group
//purpose  : Constructor
//=======================================================================

VrmlData_Group::VrmlData_Group (const VrmlData_Scene&   theScene,
                                const char              * theName,
                                const Standard_Boolean  isTransform)
  : VrmlData_Node     (theScene, theName),
    myIsTransform     (isTransform),
    myNodes           (theScene.Allocator())
{}

//=======================================================================
//function : RemoveNode
//purpose  : 
//=======================================================================

Standard_Boolean VrmlData_Group::RemoveNode
                        (const Handle(VrmlData_Node)& theNode)
{
  Standard_Boolean aResult (Standard_False);
  for (Iterator anIter = NodeIterator(); anIter.More(); anIter.Next())
    if (anIter.Value() == theNode) {
      aResult = Standard_True;
      myNodes.Remove (anIter);
      break;
    }
  return aResult;
}

//=======================================================================
//function : SetTransform
//purpose  : 
//=======================================================================

Standard_Boolean VrmlData_Group::SetTransform (const gp_Trsf& theTrsf)
{
  Standard_Boolean aResult (Standard_False);
  if (myIsTransform) {
    myTrsf = theTrsf;
    aResult = Standard_True;
  }
  return aResult;
}

//=======================================================================
//function : VrmlData_Group::Clone
//purpose  : 
//=======================================================================

Handle(VrmlData_Node) VrmlData_Group::Clone
                                (const Handle(VrmlData_Node)& theOther) const
{
  Handle(VrmlData_Group) aResult =
    Handle(VrmlData_Group)::DownCast (VrmlData_Node::Clone(theOther));
  if (aResult.IsNull())
    aResult =
      new VrmlData_Group (theOther.IsNull() ? Scene() : theOther->Scene(),
                          Name(), myIsTransform);

  aResult->myIsTransform = myIsTransform;
  if (&aResult->Scene() == &Scene())
    aResult->myNodes = myNodes;
  else {
    // Create a dummy node to pass the different Scene instance to methods Clone
    const Handle(VrmlData_UnknownNode) aDummyNode =
      new VrmlData_UnknownNode (aResult->Scene());
    Iterator anIter (myNodes);
    for (; anIter.More(); anIter.Next()) {
      const Handle(VrmlData_Node)& aNode = anIter.Value();
      if (aNode.IsNull() == Standard_False)
        aResult->myNodes.Append(aNode->Clone (aDummyNode));
    }
  }
  if (myIsTransform)
    aResult->SetTransform (myTrsf);
  aResult->SetBox (myBox);

  return aResult;
}

//=======================================================================
//function : FindNode
//purpose  : 
//=======================================================================

Handle(VrmlData_Node) VrmlData_Group::FindNode
                                        (const char * theName,
                                         gp_Trsf&     theLocation) const
{
  Handle(VrmlData_Node) aResult;
  Iterator anIter (myNodes);
  for (; anIter.More(); anIter.Next()) {
    const Handle(VrmlData_Node)& aNode = anIter.Value();
    if (aNode.IsNull() == Standard_False) {
      if (strcmp(aNode->Name(), theName) == 0)
      {
        aResult = aNode;
        theLocation = myTrsf;
        break;
      }
      // Try a Group type of node
      if (aNode->IsKind(STANDARD_TYPE(VrmlData_Group)))
      {
        const Handle(VrmlData_Group) aGroup =
          Handle(VrmlData_Group)::DownCast (aNode);
        if (aGroup.IsNull() == Standard_False) {
          aResult = aGroup->FindNode(theName, theLocation);
          if (aResult.IsNull() == Standard_False) {
            //theLocation *= myTrsf;
            theLocation.PreMultiply(myTrsf);
            break;
          }
        }
      }
    }
  }
  return aResult;
}

//=======================================================================
//function : VrmlData_Group::Read
//purpose  : 
//=======================================================================

VrmlData_ErrorStatus VrmlData_Group::Read (VrmlData_InBuffer& theBuffer)
{
  VrmlData_ErrorStatus aStatus;
  gp_XYZ aBoxCenter(0., 0., 0.), aBoxSize(-1., -1., -1.);
  gp_XYZ aCenter  (0., 0., 0.), aScale (1., 1., 1.), aTrans (0., 0., 0.);
  gp_XYZ aRotAxis (0., 0., 1.), aScaleAxis (0., 0., 1.);
  Standard_Real aRotAngle (0.), aScaleAngle(0.);

  while (OK(aStatus, VrmlData_Scene::ReadLine(theBuffer)))
  {
    if (VRMLDATA_LCOMPARE (theBuffer.LinePtr, "bboxCenter"))
      aStatus = Scene().ReadXYZ (theBuffer, aBoxCenter,
                                 Standard_True, Standard_False);

    else if (VRMLDATA_LCOMPARE (theBuffer.LinePtr, "bboxSize"))
      aStatus = Scene().ReadXYZ (theBuffer, aBoxSize,
                                 Standard_True, Standard_False);

    else if (VRMLDATA_LCOMPARE (theBuffer.LinePtr, "children")) {
      Standard_Boolean isBracketed (Standard_False);
      // Read the opening bracket for the list of children
      if (!OK(aStatus, VrmlData_Scene::ReadLine(theBuffer)))
        break;
      if (theBuffer.LinePtr[0] == '[') {
        theBuffer.LinePtr++;
        if (!OK(aStatus, VrmlData_Scene::ReadLine(theBuffer)))
          break;
        isBracketed = Standard_True;
      }

      // Read the child nodes
      Handle(VrmlData_Node) aChildNode;
      while (OK(aStatus, VrmlData_Scene::ReadLine(theBuffer))) {
        // read the end-of-list bracket
        if (isBracketed && theBuffer.LinePtr[0] == ']') {
          theBuffer.LinePtr++;
          break;
        }
        // otherwise read a node
        if (!OK(aStatus, ReadNode (theBuffer, aChildNode)))
          break;
        AddNode (aChildNode);
        if (isBracketed == Standard_False)
          break;
      }
    } else if (VRMLDATA_LCOMPARE (theBuffer.LinePtr, "center"))
      if (myIsTransform)
        aStatus = Scene().ReadXYZ (theBuffer, aCenter,
                                   Standard_True, Standard_False);
      else {
        aStatus = VrmlData_VrmlFormatError;
        break;
      }
    else if (VRMLDATA_LCOMPARE (theBuffer.LinePtr, "rotation"))
      if (myIsTransform) {
        if (OK(aStatus, Scene().ReadXYZ (theBuffer, aRotAxis,
                                         Standard_False, Standard_False)))
        {
          if (aRotAxis.SquareModulus() < Precision::Confusion())
            aRotAxis.SetZ (1.0);
          aStatus = Scene().ReadReal (theBuffer, aRotAngle,
                                      Standard_False, Standard_False);
        }
      } else {
        aStatus = VrmlData_VrmlFormatError;
        break;
      }
    else if (VRMLDATA_LCOMPARE (theBuffer.LinePtr, "scale")) {
      if (myIsTransform)
        aStatus = Scene().ReadXYZ (theBuffer, aScale,
                                   Standard_False, Standard_True);
      else {
        aStatus = VrmlData_VrmlFormatError;
        break;
      }
    } else if (VRMLDATA_LCOMPARE (theBuffer.LinePtr, "scaleOrientation"))
      if (myIsTransform) {
        if (OK(aStatus, Scene().ReadXYZ (theBuffer, aScaleAxis,
                                         Standard_False, Standard_False)))
          aStatus = Scene().ReadReal (theBuffer, aScaleAngle,
                                      Standard_False, Standard_False);
      } else {
        aStatus = VrmlData_VrmlFormatError;
        break;
      }
    else if (VRMLDATA_LCOMPARE (theBuffer.LinePtr, "translation"))
      if (myIsTransform)
        aStatus = Scene().ReadXYZ (theBuffer, aTrans,
                                   Standard_True, Standard_False);
      else {
        aStatus = VrmlData_VrmlFormatError;
        break;
      }
    else if (VRMLDATA_LCOMPARE (theBuffer.LinePtr, "url")) {
      NCollection_List<TCollection_AsciiString> lstURL;
      if (OK(aStatus, ReadMultiString (theBuffer, lstURL))) {
        NCollection_List<TCollection_AsciiString>::Iterator anIter (lstURL);
        for (; anIter.More(); anIter.Next()) {
          ifstream aStream;
          const TCollection_AsciiString& aFileName = anIter.Value();
          if (!OK(aStatus, openFile (aStream, aFileName)))
            break;
          VrmlData_Scene aScene (Scene().Allocator());
          aScene.myLinearScale = Scene().myLinearScale;
          aScene.myVrmlDir = Scene().myVrmlDir;
          aScene << aStream;
          if (!OK(aStatus, aScene.Status()))
            break;
          VrmlData_Scene::Iterator anIterN = aScene.GetIterator();
          for (; anIterN.More(); anIterN.Next())
            if (!anIterN.Value()->IsKind(STANDARD_TYPE(VrmlData_WorldInfo)))
              AddNode (anIterN.Value());
          VrmlData_Scene::Iterator anAllIter(aScene.myAllNodes);
          for (; anAllIter.More(); anAllIter.Next()) {
            const Handle(VrmlData_Node)& aNode = anAllIter.Value();
            if (aNode->IsKind(STANDARD_TYPE(VrmlData_WorldInfo)))
              continue;
            const_cast <VrmlData_Scene&> (Scene()).myAllNodes.Append (aNode);
            aNode->myScene = &Scene();
            // The name of the imported node should be prefixed by the URL
            // because each name must remain unique in the global scene.
            if (aNode->Name())
              if (* aNode->Name() != '\0') {
                char buf[1024];
                strncpy (buf, aFileName.ToCString(), sizeof(buf));
                char * ptr = strchr (buf, '.');
                if (!ptr)
                  ptr = strchr (buf,'\0');
                * ptr = '_';
                strncpy (ptr+1, aNode->Name(), (&buf[sizeof(buf)]-ptr)-2);
                const size_t len = strlen(buf) + 1;
                char * aNewName =
                  static_cast<char *> (Scene().Allocator()->Allocate (len));
                if (aNewName) {
                  aNode->myName = aNewName;
                  memcpy (aNewName, buf, len);
                }
              }
          }
        }
      }
    } else
      break;

    if (!OK(aStatus))
      break;
  }

  // Read the terminating (closing) brace
  if (OK(aStatus))
    aStatus = readBrace (theBuffer);
  if (OK(aStatus)) {
    // Check if the Bounding Box has been imported
    if (aBoxSize.X() > -Precision::Confusion() &&
        aBoxSize.Y() > -Precision::Confusion() &&
        aBoxSize.Z() > -Precision::Confusion())
    {
      myBox.SetCenter (aBoxCenter);
      myBox.SetHSize  (aBoxSize*0.5);
    }
    if (myIsTransform) {
      // Create the corresponding transformation.
      gp_Trsf tRot, tCentInv;
      myTrsf.SetTranslation(aTrans+aCenter);
      gp_Ax1 aRotation (gp::Origin(), aRotAxis);
      tRot.SetRotation(gp_Ax1 (gp::Origin(), aRotAxis), aRotAngle);
      myTrsf.Multiply (tRot);
      // Check that the scale is uniform (the same value in all 3 directions.
      // Only in this case the scaling is applied.
      const Standard_Real aScaleDiff[2] = {
        aScale.X()-aScale.Y(),
        aScale.X()-aScale.Z()
      };
      if (aScaleDiff[0]*aScaleDiff[0] + aScaleDiff[1]*aScaleDiff[1]
          < Precision::Confusion())
      {
        gp_Trsf tScale;
        tScale.SetScale (gp::Origin(), (aScale.X()+aScale.Y()+aScale.Z())/3.);
        myTrsf.Multiply (tScale);
      }
      tCentInv.SetTranslation (aCenter.Reversed());
      myTrsf.Multiply (tCentInv);
    }
  }
  return aStatus;
}

//=======================================================================
//function : Shape
//purpose  : 
//=======================================================================

void VrmlData_Group::Shape (TopoDS_Shape&                       theShape,
                            VrmlData_DataMapOfShapeAppearance * pMapApp)
{
  VrmlData_Scene::createShape (theShape, myNodes, pMapApp);
  theShape.Location(myTrsf);
}

//=======================================================================
//function : openFile
//purpose  : 
//=======================================================================

VrmlData_ErrorStatus VrmlData_Group::openFile
                                (Standard_IStream&              theStream,
                                 const TCollection_AsciiString& theFilename)
{
  ifstream& aStream = static_cast<ifstream&> (theStream);
  VrmlData_ErrorStatus aStatus (VrmlData_EmptyData);
  NCollection_List<TCollection_ExtendedString>::Iterator aDirIter =
    Scene().VrmlDirIterator();
  for (; aDirIter.More(); aDirIter.Next()) {
    if (!aDirIter.Value().IsAscii())
      continue;
    const TCollection_AsciiString aFullName =
      TCollection_AsciiString (aDirIter.Value()) + theFilename;
    aStream.open (aFullName.ToCString(), ios::in);
    if (aStream.fail())
      aStream.clear();
    else {
      aStatus = VrmlData_StatusOK;
      break;
    }
  }
  if (aStatus == VrmlData_EmptyData) {
    aStream.open (theFilename.ToCString(), ios::in);
    if (!aStream.fail())
      aStatus = VrmlData_StatusOK;
  }
  if (aStatus == VrmlData_EmptyData)
    aStatus = VrmlData_CannotOpenFile;
  return aStatus;
}

//=======================================================================
//function : Write
//purpose  : 
//=======================================================================

VrmlData_ErrorStatus VrmlData_Group::Write (const char * thePrefix) const
{
  VrmlData_ErrorStatus aStatus (VrmlData_StatusOK);
  if (myNodes.IsEmpty() == Standard_False) {
    const VrmlData_Scene& aScene = Scene();
    Standard_Boolean isTransform = myIsTransform;
    if (isTransform && myTrsf.Form() == gp_Identity)
      isTransform = Standard_False;
    static const char * header[2] = { "Group {" , "Transform {" };
    if (OK (aStatus, aScene.WriteLine (thePrefix, header[isTransform ? 1 : 0],
                                       GlobalIndent())))
    {
      char buf[240];
      if (OK(aStatus) && aScene.IsDummyWrite() == Standard_False)
      {
        const gp_XYZ aBoxCorner[2] = {
          myBox.CornerMin(),
          myBox.CornerMax()
        };
        // Check that the box is not void
        if (aBoxCorner[0].X() < aBoxCorner[1].X() + Precision::Confusion()) {
          sprintf (buf, "bboxCenter  %.9g %.9g %.9g",
                   0.5 * (aBoxCorner[0].X() + aBoxCorner[1].X()),
                   0.5 * (aBoxCorner[0].Y() + aBoxCorner[1].Y()),
                   0.5 * (aBoxCorner[0].Z() + aBoxCorner[1].Z()));
          aStatus = aScene.WriteLine (buf);
          if (OK(aStatus)) {
            sprintf (buf, "bboxSize    %.9g %.9g %.9g",
                     aBoxCorner[1].X() - aBoxCorner[0].X(),
                     aBoxCorner[1].Y() - aBoxCorner[0].Y(),
                     aBoxCorner[1].Z() - aBoxCorner[0].Z());
            aStatus = aScene.WriteLine (buf);
          }
        }
      }
      if (OK(aStatus) && isTransform && aScene.IsDummyWrite() == Standard_False)
      {
        // Output the Scale
        const Standard_Real aScaleFactor = myTrsf.ScaleFactor();
        if ((aScaleFactor - 1.)*(aScaleFactor - 1.) >
            0.0001*Precision::Confusion())
        {
          sprintf (buf, "scale       %.12g %.12g %.12g",
                   aScaleFactor, aScaleFactor, aScaleFactor);
          aStatus = aScene.WriteLine (buf);
        }

        // Output the Translation
        const gp_XYZ& aTrans = myTrsf.TranslationPart();
        if (aTrans.SquareModulus() > 0.0001*Precision::Confusion()) {
          sprintf (buf, "translation %.12g %.12g %.12g",
                   aTrans.X(), aTrans.Y(), aTrans.Z());
          aStatus = aScene.WriteLine (buf);
        }

        // Output the Rotation
        gp_XYZ anAxis;
        Standard_Real anAngle;
        if (myTrsf.GetRotation (anAxis, anAngle)) {
          // output the Rotation
          sprintf (buf, "rotation    %.12g %.12g %.12g %.9g",
                   anAxis.X(), anAxis.Y(), anAxis.Z(), anAngle);
          aStatus = aScene.WriteLine (buf);
        }
      }

      if (OK(aStatus)) {

        aStatus = aScene.WriteLine ("children [", 0L, GlobalIndent());

        VrmlData_ListOfNode::Iterator anIterChild (myNodes);
        for (; anIterChild.More() && OK(aStatus); anIterChild.Next()) {
          const Handle(VrmlData_Node)& aNode = anIterChild.Value();
          aScene.WriteNode (0L, aNode);
        }

        if (OK(aStatus)) {
          aStatus = aScene.WriteLine ("]", 0L, -GlobalIndent());
        }
      }
      aStatus = WriteClosing();
    }
  }
  return aStatus;
}