Logo Search packages:      
Sourcecode: salome version File versions  Download package

VISU_TimeAnimation.cxx

//  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
//
//  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
//  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2.1 of the License.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
//
//  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
//  File   : VISU_TimeAnimation.cxx
//  Author : Vitaly SMETANNIKOV
//  Module : VISU
//
#include "VISU_TimeAnimation.h"

#ifdef WNT
#include <windows.h>
#include <vfw.h>
#include <QMessageBox>
#endif

#include "VISUConfig.hh"

#include "VISU_Result_i.hh"
#include "VISU_Prs3d_i.hh"
#include "VISU_Mesh_i.hh"
#include "VISU_IsoSurfaces_i.hh"
#include "VISU_DeformedShape_i.hh"
#include "VISU_DeformedShapeAndScalarMap_i.hh"
#include "VISU_CutPlanes_i.hh"
#include "VISU_Plot3D_i.hh"
#include "VISU_CutLines_i.hh"
#include "VISU_CutSegment_i.hh"
#include "VISU_Vectors_i.hh"
#include "VISU_StreamLines_i.hh"
#include "VISU_GaussPoints_i.hh"
#include "VISU_ViewManager_i.hh"
#include "VISU_View_i.hh"

#include "VISU_ScalarBarActor.hxx"
#include "VISU_Actor.h"

#include "SalomeApp_Study.h"

#include "SVTK_ViewWindow.h"

#include "SALOME_Event.h"

#include "SUIT_ResourceMgr.h"
#include "SUIT_Application.h"
#include "SUIT_Session.h"
#include "SUIT_Study.h"
#include "SUIT_MessageBox.h"

#include "SALOMEDSClient_AttributeString.hxx"
#include "SALOMEDSClient_AttributeName.hxx"

#include "Utils_ExceptHandlers.hxx"

#include <QPixmap>
#include <QImage>
#include <QImageWriter>
#include <QStringList>
#include <QDir>

#if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
#define NO_CAS_CATCH
#endif

#include <Standard_Failure.hxx>

#ifdef NO_CAS_CATCH
#include <Standard_ErrorHandler.hxx>
#endif

using namespace std;

//------------------------------------------------------------------------
namespace VISU 
{
  //------------------------------------------------------------------------
  class ExecutionState 
  {
    bool myIsActive;
    QMutex myIsActiveMutex;
  public:
    ExecutionState(bool isActive = false)
      : myIsActive(isActive) {}

    bool IsActive() {
      bool state;
      myIsActiveMutex.lock();
      state = myIsActive;
      myIsActiveMutex.unlock();
      return state;
    }
    bool SetActive(bool isActive) {
      bool state;
      myIsActiveMutex.lock();
      state = myIsActive;
      myIsActive = isActive;
      myIsActiveMutex.unlock();
      return state;
    }
  };


  //------------------------------------------------------------------------
  struct TCompositeMinMaxController : virtual TVTKMinMaxController
  {
    typedef ColoredPrs3d_i* TKey;
    typedef std::map< TKey, VISU::PMinMaxController > TMinMaxContainer;
    TMinMaxContainer myMinMaxContainer;    

    void
    AddController(ColoredPrs3d_i* theReference, 
              VISU::PMinMaxController theMinMaxController)
    {
      myMinMaxContainer[ TKey( theReference ) ] = theMinMaxController;
    }

    virtual
    void
    UpdateReference(ColoredPrs3d_i* theFromPrs3, ColoredPrs3d_i* theToPrs3d)
    {
      TMinMaxContainer::iterator anIter = myMinMaxContainer.find( TKey( theFromPrs3 ) );
      if ( anIter != myMinMaxContainer.end() ) {
      myMinMaxContainer.erase( anIter );
      myMinMaxContainer[ TKey( theToPrs3d ) ] = VISU::CreateDefaultMinMaxController( theToPrs3d );      
      }
    }

    virtual
    vtkFloatingPointType
    GetComponentMin(vtkIdType theCompID)
    {
      vtkFloatingPointType aMin = TMinMaxController::GetComponentMin(theCompID);
      if ( !myMinMaxContainer.empty() ) {
      TMinMaxContainer::const_iterator anIter = myMinMaxContainer.begin();
      for(; anIter != myMinMaxContainer.end(); anIter++){
        VISU::PMinMaxController aMinMaxController = anIter->second;
        aMin = std::min(aMin, aMinMaxController->GetComponentMin(theCompID));
      }
      }
      return aMin;
    }

    virtual
    vtkFloatingPointType
    GetComponentMax(vtkIdType theCompID)
    {
      vtkFloatingPointType aMax = TMinMaxController::GetComponentMax(theCompID);
      if ( !myMinMaxContainer.empty() ) {
      TMinMaxContainer::const_iterator anIter = myMinMaxContainer.begin();
      for(; anIter != myMinMaxContainer.end(); anIter++){
        VISU::PMinMaxController aMinMaxController = anIter->second;
        aMax = std::max(aMax, aMinMaxController->GetComponentMax(theCompID));
      }
      }
      return aMax;
    }
  };

  typedef SALOME::GenericObjPtr<TCompositeMinMaxController> PCompositeMinMaxController;
}

//------------------------------------------------------------------------
VISU_TimeAnimation::VISU_TimeAnimation (_PTR(Study) theStudy,
                                        VISU::View3D_ptr theView3D)
{
  myStudy = theStudy;
  myExecutionState = new VISU::ExecutionState(false);
  myFrame = 0;
  mySpeed = VISU::GetResourceMgr()->integerValue("VISU", "speed", 1);
  myProportional = VISU::GetResourceMgr()->booleanValue("VISU", "use_proportional_timing", false);
  myView = 0;

  if (!CORBA::is_nil(theView3D)) {
    VISU::View3D_i* pView = dynamic_cast<VISU::View3D_i*>(GetServant(theView3D).in());
    SUIT_ViewWindow* aVW = pView->GetViewWindow();
    setViewer( dynamic_cast<SVTK_ViewWindow*>(aVW) );
  }

  myAnimationMode = VISU::Animation::PARALLEL;
  myTimeMinVal = 0;
  myTimeMaxVal = 0;
  myTimeMin = 0;
  myTimeMax = 0;
  myLastError = "";
  myCycling = VISU::GetResourceMgr()->booleanValue("VISU", "cycled_animation", false);
  myCleaningMemoryAtEachFrame = VISU::GetResourceMgr()->booleanValue("VISU", "clean_memory_at_each_frame", false);

  myAnimEntry = "";

  myDumpPath = "";
  myAVIMaker = "jpeg2yuv";
}


//------------------------------------------------------------------------
VISU_TimeAnimation::~VISU_TimeAnimation()
{
  if (QThread::isRunning() && !QThread::isFinished()) {
    stopAnimation();
    QThread::wait(500);
    if (QThread::isRunning() && !QThread::isFinished()) {
      QThread::terminate();
    }
  }

  for (int i = 0; i < getNbFields() && myView; i++) {
    clearData(myFieldsLst[i]);
  }
  clearFieldData();

  delete myExecutionState;

  myDumpPath = "";

  /* Terminates the execution of the thread. 
   * The thread may or may not be terminated immediately, 
   * depending on the operating system's scheduling policies. 
   *  
   * Use QThread::wait() after terminate() for synchronous termination.
   *
   * When the thread is terminated, all threads waiting for the the thread to finish will be woken up.
   * 
   * Warning: This function is dangerous, and its use is discouraged. 
   * The thread can be terminated at any point in its code path. 
   * Threads can be terminated while modifying data. 
   * There is no chance for the thread to cleanup after itself, 
   * unlock any held mutexes, etc. In short, use this function only if absolutely necessary. 
   */
  //QThread::wait(100);
  //QThread::terminate();
  //QThread::wait(400);
}


//------------------------------------------------------------------------
void VISU_TimeAnimation::_connectView()
{
  connect( myView, SIGNAL( destroyed() ), this, SLOT( onViewDeleted() ) );
}

//------------------------------------------------------------------------
bool VISU_TimeAnimation::addField (_PTR(SObject) theField)
{
  if (!theField) return false;

  FieldData aNewData;
  aNewData.myField = theField;
  aNewData.myNbFrames = 0;
  aNewData.myPrsType = VISU::TSCALARMAP;
  aNewData.myOffset[0] = aNewData.myOffset[1] = aNewData.myOffset[2] = 0;

  // initialize myResult in aNewData
  _PTR(SObject) aSObj = theField->GetFather();
  aSObj = aSObj->GetFather();
  aSObj = aSObj->GetFather();
  CORBA::Object_var anObject = VISU::ClientSObjectToObject(aSObj);
  if (CORBA::is_nil(anObject)) return false;
  aNewData.myResult = dynamic_cast<VISU::Result_i*>(VISU::GetServant(anObject).in());

  VISU::Storable::TRestoringMap aMap = VISU::Storable::GetStorableMap(aNewData.myField);
  if(VISU::Storable::FindValue(aMap,"myComment") != "FIELD")
    return false;

  aNewData.myNbTimes = VISU::Storable::FindValue(aMap,"myNbTimeStamps").toLong();

  if ( myAnimationMode == VISU::Animation::PARALLEL ) { // parallel animation mode
    if ( aNewData.myNbTimes < 2 )
      return false;
    if ( !myFieldsLst.isEmpty() && myFieldsLst.first().myNbTimes != aNewData.myNbTimes )
      return false;
    if ( myFieldsLst.isEmpty() )
      myFieldsAbsFrames.push_back(aNewData.myNbTimes);
  }
  else { // successive animation mode
    if ( aNewData.myNbTimes < 1 )
      return false;

    long aNumCompCurr = VISU::Storable::FindValue(aMap, "myNumComponent").toLong();
    if ( !myFieldsLst.isEmpty() ) {
      VISU::Storable::TRestoringMap aFMap = VISU::Storable::GetStorableMap(myFieldsLst.first().myField);
      long aNumComp = VISU::Storable::FindValue(aFMap, "myNumComponent").toLong();
      if ( aNumCompCurr != aNumComp )
      return false;
    }

    if ( !myFieldsLst.isEmpty() )
      myFieldsAbsFrames.push_back(myFieldsAbsFrames.back() + aNewData.myNbTimes);
    else
      myFieldsAbsFrames.push_back(aNewData.myNbTimes);
  }
    
  myFieldsLst.append(aNewData);
  
  //find Min/Max timestamps
  _PTR(ChildIterator) anIter = myStudy->NewChildIterator(theField);
  anIter->Next(); // First is reference on support
  if ( myFieldsLst.size() == 1 ) { // the first field
    myTimeMin = getTimeValue(anIter->Value());
    myTimeMax = getTimeValue(anIter->Value());
  }
  for(; anIter->More(); anIter->Next()) {
    if ( myTimeMin > getTimeValue(anIter->Value()) )
      myTimeMin = getTimeValue(anIter->Value());
    if ( myTimeMax < getTimeValue(anIter->Value()) )
      myTimeMax = getTimeValue(anIter->Value());
  }
  
  return true;
}

//------------------------------------------------------------------------
bool VISU_TimeAnimation::addField (SALOMEDS::SObject_ptr theField)
{
  SALOMEDS::SObject_var theFieldDup = SALOMEDS::SObject::_duplicate(theField);
  _PTR(SObject) aField = VISU::GetClientSObject(theFieldDup, myStudy);
  return addField(aField);
}


//------------------------------------------------------------------------
void VISU_TimeAnimation::_clearData(FieldData& theData) {
  if (!myView) {
    MESSAGE("Viewer is not defined for animation");
    return;
  }
  theData.myTiming.clear();
  vtkRenderer* aRen = myView->getRenderer();
  if (!theData.myActors.empty()) {
    for (int i = 0, iEnd = theData.myActors.size(); i < iEnd; i++) {
      if (theData.myActors[i] != 0) {
      theData.myActors[i]->RemoveFromRender(aRen);
      }
    }
    theData.myActors.clear();
  }
  if (!theData.myPrs.empty()) {
    for (int i = 0, iEnd = theData.myPrs.size(); i < iEnd; i++)
      if (theData.myPrs[i] != 0) {
      theData.myPrs[i]->_remove_ref();
      }
    theData.myPrs.clear();
  }
  theData.myNbFrames = 0;
  myView->update();
}

//------------------------------------------------------------------------
void VISU_TimeAnimation::clearData(FieldData& theData) {
  ProcessVoidEvent(new TVoidMemFun1ArgEvent<VISU_TimeAnimation,FieldData&>
                   (this,&VISU_TimeAnimation::_clearData,theData));
}

namespace
{
  //------------------------------------------------------------------------
  template<class TPrs3d>
  void
  GeneratePresentations(_PTR(Study) theStudy,
                  FieldData& theData,
                  VISU::Result_i* theResult,
                  bool theIsRangeDefined,
                  CORBA::Double theTimeMin,
                  CORBA::Double theTimeMax,
                  QList<long> theSequence)
  {
    _PTR(ChildIterator) anIter = theStudy->NewChildIterator(theData.myField);
    anIter->Next(); // First is reference on support

    long aSequenceLength = theSequence.count();
    bool isSequenceDefined = aSequenceLength > 0;
    if (isSequenceDefined)
      theData.myPrs.resize(aSequenceLength,NULL);

    long aFrameId = 0;
    long aSequenceIndex = 1;
    for(; anIter->More(); anIter->Next(), aSequenceIndex++){
      if (aFrameId == theData.myNbTimes) {
      MESSAGE("There are extra timestamps in field");
      return;
      }
      _PTR(SObject) aTimeStamp = anIter->Value();
      if(!aTimeStamp) 
      continue;

      long aSequenceId = -1;

      theData.myTiming[aFrameId] = VISU_TimeAnimation::getTimeValue(aTimeStamp);
      if (theIsRangeDefined) {
      if (theData.myTiming[aFrameId] < theTimeMin) 
        continue;
      if (theData.myTiming[aFrameId] > theTimeMax) 
        break;
      }
      else if (isSequenceDefined) {
      aSequenceId = theSequence.indexOf( aSequenceIndex );
      if( aSequenceId == -1 )
        continue;
      }

      VISU::Storable::TRestoringMap aTimeMap = VISU::Storable::GetStorableMap(aTimeStamp);
      QString aMeshName = VISU::Storable::FindValue(aTimeMap,"myMeshName");
      VISU::Entity anEntity = (VISU::Entity) VISU::Storable::FindValue(aTimeMap,"myEntityId").toInt();
      QString aFieldName = VISU::Storable::FindValue(aTimeMap,"myFieldName");
      int aTimeStampId = VISU::Storable::FindValue(aTimeMap,"myTimeStampId").toInt();
      
      bool anIsCreated = false;
      TPrs3d* aPresent = new TPrs3d(VISU::ColoredPrs3d_i::EDoNotPublish);
      aPresent->SetCResult(theResult);
      aPresent->SetMeshName(aMeshName.toLatin1().data());
      aPresent->SetEntity(anEntity);
      aPresent->SetFieldName(aFieldName.toLatin1().data());
      aPresent->SetTimeStampNumber(aTimeStampId);
      try{       
#ifdef NO_CAS_CATCH
        OCC_CATCH_SIGNALS;
#endif
        if(aPresent->Apply(false)){
          /*
          if(isSequenceDefined)
          {
            theData.myPrs[aSequenceId] = aPresent;
            aFrameId++;
          }
          else
          */
          theData.myPrs[aFrameId++] = aPresent;
          anIsCreated = true;
        }
      }catch(Standard_Failure) {
        Handle(Standard_Failure) aFail = Standard_Failure::Caught();
        INFOS("Follow signal was occured :\n"<<aFail->GetMessageString());
      }catch(std::exception& exc){
        INFOS("Follow exception was occured :\n"<<exc.what());
      }catch(...){
        INFOS("Unknown exception was occured!");
      }
      if(!anIsCreated)
      aPresent->_remove_ref();
    }

    theData.myNbFrames = aFrameId;

    if (theData.myPrsType != VISU::TGAUSSPOINTS) {
      for(long aFrameId = 0; aFrameId < theData.myNbFrames; aFrameId++) {
      if (VISU::ScalarMap_i* aPrs = dynamic_cast<VISU::ScalarMap_i*>(theData.myPrs[aFrameId])){
        aPrs->SetOffset(theData.myOffset);
      }
      }
    }
  }
}

double getMinFieldsValue( QList<FieldData>& theFieldsLst )
{
  // for successive animation mode only
  double aRes;
  for (int i = 0; i < theFieldsLst.count(); i++) {
    if ( theFieldsLst[i].myPrs[0] ) {
      aRes = theFieldsLst[i].myPrs[0]->GetMin();
      break;
    }
  }

  for (int i = 1; i < theFieldsLst.count() && theFieldsLst[i].myPrs[0]; i++) {
    if ( aRes > theFieldsLst[i].myPrs[0]->GetMin() )
      aRes = theFieldsLst[i].myPrs[0]->GetMin();    
  }
  return aRes;
}

double getMaxFieldsValue( QList<FieldData>& theFieldsLst )
{
  // for successive animation mode only
  double aRes;
  for (int i = 0; i < theFieldsLst.count(); i++) {
    if ( theFieldsLst[i].myPrs[0] ) {
      aRes = theFieldsLst[i].myPrs[0]->GetMax();
      break;
    }
  }

  for (int i = 1; i < theFieldsLst.count() && theFieldsLst[i].myPrs[0]; i++) {
    if ( aRes < theFieldsLst[i].myPrs[0]->GetMax() )
      aRes = theFieldsLst[i].myPrs[0]->GetMax();    
  }
  return aRes;
}

void VISU_TimeAnimation::generatePresentations(CORBA::Long theFieldNum)
{
  int nbf = myFieldsLst.size();
  if( theFieldNum<0 || theFieldNum>nbf-1 )
    return;

  FieldData& aData = myFieldsLst[theFieldNum];

  // Delete previous presentations
  clearData(aData);

  VISU::Result_i* aResult = createPresent(aData.myField);
  VISU::Storable::TRestoringMap aMap = VISU::Storable::GetStorableMap(aData.myField);
  aData.myNbFrames = aData.myNbTimes;
  //VISU::Storable::FindValue(aMap,"myNbTimeStamps").toLong();

  aData.myPrs.resize(aData.myNbTimes,NULL);
  aData.myTiming.resize(aData.myNbTimes);

  QList<long> aSequence;
  if( isSequenceDefined() )
  {
    bool ok = getIndicesFromSequence( mySequence, aSequence );
    if( !ok )
      return;
  }

  using namespace VISU;
  switch (aData.myPrsType) {
  case VISU::TSCALARMAP:
    GeneratePresentations<ScalarMap_i>(myStudy,
                               aData,
                               aResult,
                               isRangeDefined(),
                               myTimeMinVal,
                               myTimeMaxVal,
                               aSequence);
    break;
  case VISU::TISOSURFACES: // Iso Surfaces
    GeneratePresentations<IsoSurfaces_i>(myStudy,
                               aData,
                               aResult,
                               isRangeDefined(),
                               myTimeMinVal,
                               myTimeMaxVal,
                               aSequence);
    break;
  case VISU::TCUTPLANES: // Cut Planes
    GeneratePresentations<CutPlanes_i>(myStudy,
                               aData,
                               aResult,
                               isRangeDefined(),
                               myTimeMinVal,
                               myTimeMaxVal,
                               aSequence);
    break;
  case VISU::TCUTLINES: // Cut Lines
    GeneratePresentations<CutLines_i>(myStudy,
                              aData,
                              aResult,
                              isRangeDefined(),
                              myTimeMinVal,
                              myTimeMaxVal,
                              aSequence);
    break;
  case VISU::TCUTSEGMENT: // Cut Segment
    GeneratePresentations<CutSegment_i>(myStudy,
                                aData,
                                aResult,
                                isRangeDefined(),
                                myTimeMinVal,
                                myTimeMaxVal,
                                aSequence);
    break;
  case VISU::TPLOT3D: // Plot3d
    GeneratePresentations<Plot3D_i>(myStudy,
                            aData,
                            aResult,
                            isRangeDefined(),
                            myTimeMinVal,
                            myTimeMaxVal,
                            aSequence);
    break;
  case VISU::TDEFORMEDSHAPE: // Deformed Shape
    GeneratePresentations<DeformedShape_i>(myStudy,
                                 aData,
                                 aResult,
                                 isRangeDefined(),
                                 myTimeMinVal,
                                 myTimeMaxVal,
                                 aSequence);
    break;
  case VISU::TVECTORS: // Vectors
    GeneratePresentations<Vectors_i>(myStudy,
                             aData,
                             aResult,
                             isRangeDefined(),
                             myTimeMinVal,
                             myTimeMaxVal,
                             aSequence);
    break;
  case VISU::TSTREAMLINES: // Stream Lines
    GeneratePresentations<StreamLines_i>(myStudy,
                               aData,
                               aResult,
                               isRangeDefined(),
                               myTimeMinVal,
                               myTimeMaxVal,
                               aSequence);
    break;
  case VISU::TGAUSSPOINTS: // Gauss Points
    GeneratePresentations<GaussPoints_i>(myStudy,
                               aData,
                               aResult,
                               isRangeDefined(),
                               myTimeMinVal,
                               myTimeMaxVal,
                               aSequence);
    break;
  case VISU::TSCALARMAPONDEFORMEDSHAPE: // Scalar map on deformed shape
  case VISU::TDEFORMEDSHAPEANDSCALARMAP:
    GeneratePresentations<DeformedShapeAndScalarMap_i>(myStudy,
                                           aData,
                                           aResult,
                                           isRangeDefined(),
                                           myTimeMinVal,
                                           myTimeMaxVal,
                                           aSequence);
    break;
  default:
    MESSAGE("Not implemented for this presentation type: " << aData.myPrsType);
    return;
  }
  
  if ( myAnimationMode == VISU::Animation::SUCCESSIVE ) { // successive animation mode
    if ( myFieldsAbsFrames.size() == getNbFields() ) 
      myFieldsAbsFrames.clear();
    if ( theFieldNum > 0 )
      myFieldsAbsFrames.push_back(myFieldsAbsFrames.back() + aData.myNbFrames);      
    else
      myFieldsAbsFrames.push_back(aData.myNbFrames);

    if (theFieldNum == getNbFields() - 1) {
      if ( aData.myPrsType != VISU::TGAUSSPOINTS && aData.myPrsType != TDEFORMEDSHAPEANDSCALARMAP && aData.myPrsType != TSCALARMAPONDEFORMEDSHAPE) {

      // Initialize the MinMax controller
      VISU::PCompositeMinMaxController aMinMaxController(new VISU::TCompositeMinMaxController());
      if ( myAnimationMode == VISU::Animation::PARALLEL ) {
        FieldData& aFieldData = getFieldData(theFieldNum);
        VISU::ColoredPrs3d_i* aPrs3d = aFieldData.myPrs[0];
        aMinMaxController->AddController( aPrs3d, VISU::CreateDefaultMinMaxController( aPrs3d ) );
      } else {
        for (int aFieldId = 0; aFieldId < getNbFields(); aFieldId++) {
          FieldData& aFieldData = getFieldData(aFieldId);
          VISU::ColoredPrs3d_i* aPrs3d = aFieldData.myPrs[0];
          aMinMaxController->AddController( aPrs3d, VISU::CreateDefaultMinMaxController( aPrs3d ) );
        }
      }

      double aMin = getMinFieldsValue(myFieldsLst);
      double aMax = getMaxFieldsValue(myFieldsLst);

      for (int aFieldId = 0; aFieldId < getNbFields(); aFieldId++) {
        FieldData& aFieldData = getFieldData(aFieldId);
        for (long aFrameId = 0; aFrameId < aFieldData.myNbFrames; aFrameId++) {
          VISU::ColoredPrs3d_i* aPrs3d = aFieldData.myPrs[aFrameId];
          aPrs3d->SetMinMaxController(aMinMaxController);
          if (VISU::IsoSurfaces_i* anIsoSurfaces = dynamic_cast<VISU::IsoSurfaces_i*>(aPrs3d))
            anIsoSurfaces->SetSubRange(aMin, aMax);
        }
      }
      }
    }
  }
}


//------------------------------------------------------------------------
CORBA::Boolean VISU_TimeAnimation::_generateFrames() {
  if (!myView) {
    MESSAGE("Viewer is not defined for animation");
    return false;
  }

  myLastError = QString("Frame(s) for ");
  bool aNoError = true;

  clearView();

  for (int i = 0; i < getNbFields(); i++) {
    FieldData& aData = myFieldsLst[i];
    aData.myActors.resize(aData.myNbFrames,NULL);
    for (long j = 0; j < aData.myNbFrames; j++) {
      VISU_Actor* aActor = NULL;
      try{
      aData.myPrs[j]->SetOffset(aData.myOffset);
      aActor = aData.myPrs[j]->CreateActor();
      myView->AddActor(aActor);
      bool condition = ( myAnimationMode == VISU::Animation::PARALLEL ) ? (j == 0) : (j == 0 && i == 0);
      if(condition)
        aActor->VisibilityOn();
      else
        aActor->VisibilityOff();
      }catch(...){ //catch(std::runtime_error& exc){
      aNoError = false;
      myLastError += QString("%1 ").arg(aData.myTiming[j]);
      }
      aData.myActors[j] = aActor;
    }
  }
  myFrame = 0;
  myLastError += QString(" timestamp(s) cannot be created.");
  ProcessVoidEvent(new TVoidMemFun2ArgEvent<VISU_TimeAnimation,long,double>(this, &VISU_TimeAnimation::_emitFrameChanged,
                                                          myFrame, myFieldsLst[0].myTiming[myFrame]));
  myView->Repaint();
  return aNoError;
}

//------------------------------------------------------------------------
CORBA::Boolean VISU_TimeAnimation::generateFrames()
{
  return ProcessEvent(new TMemFunEvent<VISU_TimeAnimation,bool>
                      (this,&VISU_TimeAnimation::_generateFrames));
}

//------------------------------------------------------------------------
void VISU_TimeAnimation::_clearView() {
  if (!myView) {
    MESSAGE("Viewer is not defined for animation");
    return;
  }
  vtkRenderer* aRen = myView->getRenderer();
  for (int i = 0; i < getNbFields(); i++) {
    FieldData& aData = myFieldsLst[i];
    if (!aData.myActors.empty()) {
      for (int i = 0, iEnd = aData.myActors.size(); i < iEnd; i++) {
      if (aData.myActors[i] != 0) {
        aData.myActors[i]->RemoveFromRender(aRen);
      }
      }
      aData.myActors.clear();
    }
  }
  VISU::RepaintView(myView);
}

//------------------------------------------------------------------------
void VISU_TimeAnimation::clearView()
{
  ProcessVoidEvent(new TVoidMemFunEvent<VISU_TimeAnimation>
                   (this,&VISU_TimeAnimation::_clearView));
}

//------------------------------------------------------------------------
void VISU_TimeAnimation::_visibilityOff(int num_field, int num_frame) {
  if (!myView) {
    MESSAGE("Viewer is not defined for animation");
    return;
  }
  if ( num_field < 0 || num_frame < 0 ) return;
  FieldData& aData = myFieldsLst[num_field];
  if ( aData.myActors.empty() ) return;
  VISU_Actor* aActor = aData.myActors[num_frame];
  if (! myCleaningMemoryAtEachFrame) {
    //
    // Usual behaviour : VisibilityOff()
    // Problem : It don't clean the memory so if there is
    //           a lot of frames, the memory grows dramatically
    //
    aActor->VisibilityOff();
  } else {
    //
    // myCleaningMemoryAtEachFrame behaviour:
    // Delete the actor and re-creation it with VisibilityOff()
    // since it takes memory only at VisibilityOn()
    //
    // Delete the actor
    aActor->RemoveFromRender(myView->getRenderer());
    // Re-create the actor
    aActor = aData.myPrs[num_frame]->CreateActor();
    myView->AddActor(aActor);
    aActor->VisibilityOff();
    aData.myActors[num_frame] = aActor;
  }
}

//------------------------------------------------------------------------
void VISU_TimeAnimation::visibilityOff(int num_field, int num_frame)
{
  ProcessVoidEvent(new TVoidMemFun2ArgEvent<VISU_TimeAnimation,int,int>
                   (this,&VISU_TimeAnimation::_visibilityOff,num_field,num_frame));
}

//------------------------------------------------------------------------
void VISU_TimeAnimation::stopAnimation()
{
  myExecutionState->SetActive(false);
}

//------------------------------------------------------------------------
void VISU_TimeAnimation::_startAnimation() {
  if (!myExecutionState->IsActive()) {
    myExecutionState->SetActive(true);
    QThread::start();
  }
}

//------------------------------------------------------------------------
void VISU_TimeAnimation::startAnimation()
{
  ProcessVoidEvent(new TVoidMemFunEvent<VISU_TimeAnimation>
                   (this,&VISU_TimeAnimation::_startAnimation));
}

//------------------------------------------------------------------------
void VISU_TimeAnimation::_nextFrame() {
  if (!myView) {
    MESSAGE("Viewer is not defined for animation");
    return;
  }
  stopAnimation();
  if (myFrame < getNbFrames() - 1 ) { //(myFieldsLst[0].myNbFrames-1)) {
    int i;
    std::pair<int,long> aPair;
    int aFieldId;
    long aFrameId;

    if ( myAnimationMode == VISU::Animation::PARALLEL ) { // parallel animation mode
      for (i = 0; i < getNbFields(); i++)
      if (myFieldsLst[i].myActors[myFrame] != 0)
        visibilityOff(i, myFrame);
    }
    else { //successive animation mode
      aPair = getRelativeFrameNumber(myFrame);
      aFieldId = aPair.first;
      aFrameId = aPair.second;
      if (myFieldsLst[aFieldId].myActors[aFrameId] != 0)
      visibilityOff(aFieldId, aFrameId);
    }

    myFrame++;

    if ( myAnimationMode == VISU::Animation::PARALLEL ) { // parallel animation mode
      for (i = 0; i < getNbFields(); i++)
      if (myFieldsLst[i].myActors[myFrame] != 0)
        myFieldsLst[i].myActors[myFrame]->VisibilityOn();

      ProcessVoidEvent(new TVoidMemFun2ArgEvent<VISU_TimeAnimation,long,double>(this, &VISU_TimeAnimation::_emitFrameChanged,
                                                            myFrame, myFieldsLst[0].myTiming[myFrame]));
    }
    else { //successive animation mode
      aPair = getRelativeFrameNumber(myFrame);
      aFieldId = aPair.first;
      aFrameId = aPair.second;
      if (myFieldsLst[aFieldId].myActors[aFrameId] != 0)
      myFieldsLst[aFieldId].myActors[aFrameId]->VisibilityOn();

      ProcessVoidEvent(new TVoidMemFun2ArgEvent<VISU_TimeAnimation,long,double>(this, &VISU_TimeAnimation::_emitFrameChanged,
                                                            myFrame, myFieldsLst[aFieldId].myTiming[aFrameId]));
    }
    myView->Repaint();
  }
}

//------------------------------------------------------------------------
void VISU_TimeAnimation::nextFrame()
{
  ProcessVoidEvent(new TVoidMemFunEvent<VISU_TimeAnimation>
                   (this,&VISU_TimeAnimation::_nextFrame));
}

//------------------------------------------------------------------------
void VISU_TimeAnimation::_prevFrame() {
  if (!myView) {
    MESSAGE("Viewer is not defined for animation");
    return;
  }
  stopAnimation();
  if (myFrame > 0) {
    int i;
    std::pair<int,long> aPair;
    int aFieldId;
    long aFrameId;

    if ( myAnimationMode == VISU::Animation::PARALLEL ) { // parallel animation mode
      for (i = 0; i < getNbFields(); i++)
      if (myFieldsLst[i].myActors[myFrame] != 0)
        visibilityOff(i, myFrame);
    }
    else { //successive animation mode
      aPair = getRelativeFrameNumber(myFrame);
      aFieldId = aPair.first;
      aFrameId = aPair.second;
      if (myFieldsLst[aFieldId].myActors[aFrameId] != 0)
        visibilityOff(aFieldId, aFrameId);
    }

    myFrame--;

    if ( myAnimationMode == VISU::Animation::PARALLEL ) { // parallel animation mode
      for (i = 0; i < getNbFields(); i++)
      if (myFieldsLst[i].myActors[myFrame] != 0)
        myFieldsLst[i].myActors[myFrame]->VisibilityOn();

      ProcessVoidEvent(new TVoidMemFun2ArgEvent<VISU_TimeAnimation,long,double>(this, &VISU_TimeAnimation::_emitFrameChanged,
                                                            myFrame, myFieldsLst[0].myTiming[myFrame]));
    }
    else { //successive animation mode
      aPair = getRelativeFrameNumber(myFrame);
      aFieldId = aPair.first;
      aFrameId = aPair.second;
      if (myFieldsLst[aFieldId].myActors[aFrameId] != 0)
        myFieldsLst[aFieldId].myActors[aFrameId]->VisibilityOn();

      ProcessVoidEvent(new TVoidMemFun2ArgEvent<VISU_TimeAnimation,long,double>(this, &VISU_TimeAnimation::_emitFrameChanged,
                                                            myFrame, myFieldsLst[aFieldId].myTiming[aFrameId]));
    }
    myView->Repaint();
  }
}

//------------------------------------------------------------------------
void VISU_TimeAnimation::prevFrame()
{
  ProcessVoidEvent(new TVoidMemFunEvent<VISU_TimeAnimation>
                   (this,&VISU_TimeAnimation::_prevFrame));
}

//------------------------------------------------------------------------
void VISU_TimeAnimation::_firstFrame() {
  if (!myView) {
    MESSAGE("Viewer is not defined for animation");
    return;
  }
  stopAnimation();
  int i;
  if ( myAnimationMode == VISU::Animation::PARALLEL ) { // parallel animation mode
    for (i = 0; i < getNbFields(); i++)
      if(!myFieldsLst[i].myActors.empty())
      if (myFieldsLst[i].myActors[myFrame] != 0)
        visibilityOff(i, myFrame);
    }
  else { //successive animation mode
    std::pair<int,long> aPair = getRelativeFrameNumber(myFrame);
    int aFieldId = aPair.first;
    long aFrameId = aPair.second;
    if(!myFieldsLst[aFieldId].myActors.empty())
      if (myFieldsLst[aFieldId].myActors[aFrameId] != 0)
      visibilityOff(aFieldId, aFrameId);
  }
  myFrame = 0;

  int imax;
  if ( myAnimationMode == VISU::Animation::PARALLEL ) // parallel animation mode 
    imax = getNbFields();
  else //successive animation mode
    imax = 1;

  for (i = 0; i < imax; i++)
    if(!myFieldsLst[i].myActors.empty())
      if (myFieldsLst[i].myActors[myFrame] != 0)
      myFieldsLst[i].myActors[myFrame]->VisibilityOn();

  if(!myFieldsLst[0].myTiming.empty()){
    ProcessVoidEvent(new TVoidMemFun2ArgEvent<VISU_TimeAnimation,long,double>(this, &VISU_TimeAnimation::_emitFrameChanged,
                                                            myFrame, myFieldsLst[0].myTiming[myFrame]));
    myView->Repaint();
  }
}

//------------------------------------------------------------------------
void VISU_TimeAnimation::firstFrame()
{
  ProcessVoidEvent(new TVoidMemFunEvent<VISU_TimeAnimation>
                   (this,&VISU_TimeAnimation::_firstFrame));
}

//------------------------------------------------------------------------
void VISU_TimeAnimation::_lastFrame() {
  if (!myView) {
    MESSAGE("Viewer is not defined for animation");
    return;
  }
  stopAnimation();
  int i;
  std::pair<int,long> aPair;
  int aFieldId;
  long aFrameId;

  if ( myAnimationMode == VISU::Animation::PARALLEL ) { // parallel animation mode
    for (i = 0; i < getNbFields(); i++)
      if (myFieldsLst[i].myActors[myFrame] != 0)
      visibilityOff(i, myFrame);
  }
  else { //successive animation mode
    aPair = getRelativeFrameNumber(myFrame);
    aFieldId = aPair.first;
    aFrameId = aPair.second;
    if (myFieldsLst[aFieldId].myActors[aFrameId] != 0)
      visibilityOff(aFieldId, aFrameId);
  }

  myFrame = getNbFrames() - 1; //myFieldsLst[0].myNbFrames-1;

  if ( myAnimationMode == VISU::Animation::PARALLEL ) { // parallel animation mode
    for (i = 0; i < getNbFields(); i++)
      if (myFieldsLst[i].myActors[myFrame] != 0)
      myFieldsLst[i].myActors[myFrame]->VisibilityOn();
    
    ProcessVoidEvent(new TVoidMemFun2ArgEvent<VISU_TimeAnimation,long,double>(this, &VISU_TimeAnimation::_emitFrameChanged,
                                                            myFrame, myFieldsLst[0].myTiming[myFrame]));
  }
  else { //successive animation mode
    aPair = getRelativeFrameNumber(myFrame);
    aFieldId = aPair.first;
    aFrameId = aPair.second;
    if (myFieldsLst[aFieldId].myActors[aFrameId] != 0)
      myFieldsLst[aFieldId].myActors[aFrameId]->VisibilityOn();

    ProcessVoidEvent(new TVoidMemFun2ArgEvent<VISU_TimeAnimation,long,double>(this, &VISU_TimeAnimation::_emitFrameChanged,
                                                            myFrame, myFieldsLst[aFieldId].myTiming[aFrameId]));
  }

  myView->Repaint();
}

//------------------------------------------------------------------------
void VISU_TimeAnimation::lastFrame()
{
  ProcessVoidEvent(new TVoidMemFunEvent<VISU_TimeAnimation>
                   (this,&VISU_TimeAnimation::_lastFrame));
}


//------------------------------------------------------------------------
// For Batchmode using
void VISU_TimeAnimation::_gotoFrame(CORBA::Long theFrame) {
  if (!myView) {
    MESSAGE("Viewer is not defined for animation");
    return;
  }
  if ((theFrame < 0) || (theFrame > (getNbFrames()-1)))
    return;
  stopAnimation();
  int i;
  std::pair<int,long> aPair;
  int aFieldId;
  long aFrameId;
  
  if ( myAnimationMode == VISU::Animation::PARALLEL ) { // parallel animation mode
    for (i = 0; i < getNbFields(); i++)
      if (myFieldsLst[i].myActors[myFrame] != 0)
      visibilityOff(i, myFrame);
  }
  else { //successive animation mode
    aPair = getRelativeFrameNumber(myFrame);
    aFieldId = aPair.first;
    aFrameId = aPair.second;
    if (myFieldsLst[aFieldId].myActors[aFrameId] != 0)
      visibilityOff(aFieldId, aFrameId);
  }

  myFrame = theFrame;

  if ( myAnimationMode == VISU::Animation::PARALLEL ) { // parallel animation mode
    for (i = 0; i < getNbFields(); i++)
      if (myFieldsLst[i].myActors[myFrame] != 0)
      myFieldsLst[i].myActors[myFrame]->VisibilityOn();

    ProcessVoidEvent(new TVoidMemFun2ArgEvent<VISU_TimeAnimation,long,double>(this, &VISU_TimeAnimation::_emitFrameChanged,
                                                            myFrame, myFieldsLst[0].myTiming[myFrame]));
  }
  else { //successive animation mode
    aPair = getRelativeFrameNumber(myFrame);
    aFieldId = aPair.first;
    aFrameId = aPair.second;
    if (myFieldsLst[aFieldId].myActors[aFrameId] != 0)
      myFieldsLst[aFieldId].myActors[aFrameId]->VisibilityOn();

    ProcessVoidEvent(new TVoidMemFun2ArgEvent<VISU_TimeAnimation,long,double>(this, &VISU_TimeAnimation::_emitFrameChanged,
                                                            myFrame, myFieldsLst[aFieldId].myTiming[aFrameId]));
  }

  myView->Repaint();
}

//------------------------------------------------------------------------
void VISU_TimeAnimation::gotoFrame(CORBA::Long theFrame)
{
  ProcessVoidEvent(new TVoidMemFun1ArgEvent<VISU_TimeAnimation,CORBA::Long>
                   (this,&VISU_TimeAnimation::_gotoFrame,theFrame));
}

//------------------------------------------------------------------------
void VISU_TimeAnimation::_emitFrameChanged(long theNewFrame, double theTime)
{
  emit frameChanged(theNewFrame, theTime);
}

//------------------------------------------------------------------------
void VISU_TimeAnimation::_emitStopped()
{
  emit stopped();
}

//------------------------------------------------------------------------
VISU::ColoredPrs3d_ptr VISU_TimeAnimation::getPresentation(CORBA::Long theField, CORBA::Long theFrame) {
  if ((theField > getNbFields()) || (theField < 0))
    return VISU::ColoredPrs3d::_nil();
  if ((theFrame < 0) || (theFrame > (myFieldsLst[theField].myNbFrames - 1)))
    return VISU::ColoredPrs3d::_nil();
  return myFieldsLst[theField].myPrs[theFrame]->_this();
}

//------------------------------------------------------------------------
void VISU_TimeAnimation::setPresentationType(CORBA::Long theFieldNum, VISU::VISUType theType) {
  if ( theFieldNum < 0 || theFieldNum >= myFieldsLst.size() )
    return;

  myFieldsLst[theFieldNum].myPrsType = theType;
}

//------------------------------------------------------------------------
VISU::VISUType VISU_TimeAnimation::getPresentationType(CORBA::Long theFieldNum) {
  if ( theFieldNum < 0 || theFieldNum >= myFieldsLst.size() )
    return VISU::TNONE;
  
  return myFieldsLst[theFieldNum].myPrsType;
}

//------------------------------------------------------------------------
CORBA::Long VISU_TimeAnimation::getNbFrames() {
  if ( myAnimationMode == VISU::Animation::PARALLEL ) // parallel animation mode
    return (getNbFields() > 0)? myFieldsLst[0].myNbFrames : 0;
  else //successive animation mode
    return (getNbFields() > 0 && !myFieldsAbsFrames.empty()) ? myFieldsAbsFrames[myFieldsAbsFrames.size()-1] : 0;
}

//------------------------------------------------------------------------
long VISU_TimeAnimation::getAbsoluteFrameNumber(std::pair<int,long> theFieldTimeStamp)
{
  long aRes = -1;
  if ( getNbFields() > 0 ) {
    int aFieldId = theFieldTimeStamp.first;
    long aFrameNum = theFieldTimeStamp.second + 1;
    if ( myAnimationMode == VISU::Animation::PARALLEL ) { // parallel animation mode
      if ( aFrameNum <= myFieldsAbsFrames[0] )
        aRes = aFrameNum;
    }
    else { //successive animation mode
      if ( aFieldId == 0 && aFrameNum <= myFieldsAbsFrames[aFieldId] )
      aRes = aFrameNum;
      else if ( aFieldId && aFrameNum <= myFieldsAbsFrames[aFieldId] - myFieldsAbsFrames[aFieldId-1] )
      aRes = myFieldsAbsFrames[aFieldId-1] + aFrameNum;
    }
  }
  return aRes - 1;
}

//------------------------------------------------------------------------
std::pair<int,long> VISU_TimeAnimation::getRelativeFrameNumber(long theFrame)
{
  std::pair<int,long> aRes;
  if ( getNbFields() > 0 && theFrame < getNbFrames() ) {
    theFrame = theFrame + 1;
    if ( myAnimationMode == VISU::Animation::PARALLEL ) { // parallel animation mode
      aRes.first = 0;
      aRes.second = theFrame - 1;
    }
    else { //successive animation mode
      for (int i = 0, iEnd = myFieldsAbsFrames.size(); i < iEnd; i++)
      if ( myFieldsAbsFrames[i] >= theFrame ) {
        aRes.first = i;
        if ( i == 0 )
          aRes.second = theFrame - 1;
        else
          aRes.second = theFrame-myFieldsAbsFrames[i-1] - 1;
        break;
      }
    }
  }
  return aRes;
}

//------------------------------------------------------------------------
void VISU_TimeAnimation::parallelAnimation( bool& theIsDumping, QList<int>& theIndexList )
{
  double k = 1;
  double aOneVal = 1;
  FieldData& aFirstFieldData = myFieldsLst[0];
  if (aFirstFieldData.myNbFrames > 2)
    aOneVal = ( myTimeMax - myTimeMin ) / getNbFrames();
  int aNbFiles = 0;

  bool aHasNextFrame = aFirstFieldData.myField && aFirstFieldData.myNbFrames > 0;
  while (aHasNextFrame && myExecutionState->IsActive()) {
    ProcessVoidEvent(new TVoidMemFun2ArgEvent<VISU_TimeAnimation,long,double>
                     (this, &VISU_TimeAnimation::_emitFrameChanged,
                      myFrame, aFirstFieldData.myTiming[myFrame]));
    if (myExecutionState->IsActive()) {
      for (int i = 0; i < getNbFields(); i++) {
        FieldData& aData = myFieldsLst[i];
      if (aData.myNbFrames == 0)
        continue;
        if (myFrame > 0) {
          if (aData.myActors[myFrame-1] != 0)
            visibilityOff(i, myFrame-1);
        } else {
        if (aData.myActors[aData.myNbFrames-1] != 0)
          visibilityOff(i, aData.myNbFrames-1);
        }
        if (aData.myActors[myFrame] != 0 && myView) {
          ProcessVoidEvent(new TVoidMemFunEvent<VISU_Actor>(aData.myActors[myFrame],
                                                            &VISU_Actor::VisibilityOn));
        }
      }
      if (!myView)
      return;
      bool repainArg = false;
      ProcessVoidEvent(new TVoidMemFun1ArgEvent<SVTK_ViewWindow,bool>(myView,
                                                                      &SVTK_ViewWindow::Repaint,
                                                                      repainArg));
    }

    k = 1;
    if (myProportional) {
      switch (myFrame) {
      case 0:
        break;
      case 1:
        if (aFirstFieldData.myNbFrames > 2)
          k = (aFirstFieldData.myTiming[myFrame+1] -
               aFirstFieldData.myTiming[myFrame]) / aOneVal;
        break;
      default:
        if (myFrame < (aFirstFieldData.myNbFrames - 1))
          k = (aFirstFieldData.myTiming[myFrame+1] -
               aFirstFieldData.myTiming[myFrame]) / aOneVal;
      }
    }
    int delay = (int)(1000. * k / mySpeed);
    theIsDumping = !myDumpPath.isEmpty();
    if (delay < 1 && theIsDumping) {
      // We must unlock mutex for some time before grabbing to allow view updating
      delay = 1;
    }
    msleep(delay);
    if (!myExecutionState->IsActive()) 
      return;

    if (theIsDumping) {
      // We must unlock mutex for some time before grabbing to allow view updating
      msleep(delay);
      if (!myExecutionState->IsActive()) 
      return;

      if (!(aFirstFieldData.myField)) // break, if field was deleted.
      break;

      saveImages( 0, aOneVal, aNbFiles, theIndexList );
    }

    if (!myExecutionState->IsActive()) 
      break;

    myFrame++;
    if (myFrame == aFirstFieldData.myNbFrames) {
      if (!myCycling) {
        aHasNextFrame = false;
      myFrame--;
      }
      else
      myFrame = 0;
    }
  } // while (aHasNextFrame && myExecutionState->IsActive())
}

//------------------------------------------------------------------------
void VISU_TimeAnimation::successiveAnimation( bool& theIsDumping, QList<int>& theIndexList )
{
  if (myFrame >= getNbFrames() - 1)
  {
    myExecutionState->SetActive(false);
    return;
  }

  double k = 1;
  double aOneVal = 1;
  FieldData& aFirstFieldData = myFieldsLst[0];
  if (aFirstFieldData.myNbFrames > 2)
    aOneVal = ( myTimeMax - myTimeMin ) / getNbFrames();
  int aNbFiles = 0;
  long aFrame = myFrame;

  bool aHasNextFrame = true;
  while (aHasNextFrame && myExecutionState->IsActive())
  {
    for (int aFieldId = 0;
         (aFieldId < getNbFields()) && (myFieldsLst[aFieldId].myField);
         aFieldId++, aFrame = 0)
    {
      if (!myExecutionState->IsActive()) break;

      FieldData& aData = myFieldsLst[aFieldId];
      if ( !aData.myPrs[0] ) continue;
      for (; aFrame < aData.myNbFrames && myExecutionState->IsActive(); aFrame++, myFrame++)
      {
      ProcessVoidEvent(new TVoidMemFun2ArgEvent<VISU_TimeAnimation,long,double>
                         (this, &VISU_TimeAnimation::_emitFrameChanged,
                          myFrame, myFieldsLst[aFieldId].myTiming[aFrame]));

      if (myExecutionState->IsActive()) {
          if (aFrame > 0) {
            if (aData.myActors[aFrame-1] != 0)
              visibilityOff(aFieldId, aFrame-1);
          } else if ( myFrame > 0) {
            if (myFieldsLst[aFieldId-1].myActors[myFieldsLst[aFieldId-1].myNbFrames-1] != 0)
              visibilityOff(aFieldId-1, myFieldsLst[aFieldId-1].myNbFrames-1);
          } else if ( myCycling ) {
            if (myFieldsLst[getNbFields()-1].myActors[myFieldsLst[getNbFields()-1].myNbFrames-1] != 0)
              visibilityOff(getNbFields()-1, myFieldsLst[getNbFields()-1].myNbFrames-1);
          } else {
            if (aData.myActors[aData.myNbFrames-1] != 0)
              visibilityOff(aFieldId, aData.myNbFrames-1);
          }
          if (aData.myActors[aFrame] != 0 && myView) {
            ProcessVoidEvent(new TVoidMemFunEvent<VISU_Actor>(aData.myActors[aFrame],
                                                              &VISU_Actor::VisibilityOn));
          }

        if (!myView)
          return;
          bool repainArg = false;
          ProcessVoidEvent(new TVoidMemFun1ArgEvent<SVTK_ViewWindow,bool>(myView,
                                                                          &SVTK_ViewWindow::Repaint,
                                                                          repainArg));
      }

      k = 1;
      if (myProportional) {
        switch (aFrame) {
        case 0:
          break;
        case 1:
          if (aFirstFieldData.myNbFrames > 2)
            k = (aFirstFieldData.myTiming[aFrame+1] -
               aFirstFieldData.myTiming[aFrame]) / aOneVal;
          break;
        default:
          if (aFrame < (aFirstFieldData.myNbFrames - 1))
            k = (aFirstFieldData.myTiming[aFrame+1] -
               aFirstFieldData.myTiming[aFrame]) / aOneVal;
        }
      }
      int delay = (int)(1000. * k / mySpeed);
      theIsDumping = !myDumpPath.isEmpty();
      if (delay < 1 && theIsDumping) {
        // We must unlock mutex for some time before grabbing to allow view updating
        delay = 1;
      }
      msleep(delay);

      if (!myExecutionState->IsActive()) return;

      if (theIsDumping) {
        // We must unlock mutex for some time before grabbing to allow view updating
        msleep(delay);
        if (!myExecutionState->IsActive()) return;

        if (!(myFieldsLst[aFieldId].myField)) // break, if field was deleted.
          break;

        saveImages( aFieldId, aOneVal, aNbFiles, theIndexList );
      }
      } // for (; aFrame < aData.myNbFrames && myExecutionState->IsActive(); aFrame++, myFrame++)
    } // for (int aFieldId = 0;

    if (!myCycling) {
      aHasNextFrame = false;
      myFrame--;
    }
    else {
      myFrame = 0;
      aFrame = myFrame;
    }
  } // while (aHasNextFrame && myExecutionState->IsActive())
}

//------------------------------------------------------------------------
void VISU_TimeAnimation::saveImages( int theFieldId, 
                             double& theOneVal, int& theNbFiles, 
                             QList<int>& theIndexList )
{
  if (myDumpFormat.compare("AVI") != 0) {
    QString aFile(myDumpPath);

    int aFrameNb = myFrame; // parallel animation mode
    if ( myAnimationMode == VISU::Animation::SUCCESSIVE ) // successive animation mode
      aFrameNb = getRelativeFrameNumber(myFrame).second;

    int aMaxNb = myFieldsLst[theFieldId].myTiming.size();
    int nbDigits = QString("%1").arg(aMaxNb).length();
    QString aFormat = QString("%.%1d_").arg(nbDigits);

    QString aName;
    aName.sprintf(aFormat.toLatin1().data(), aFrameNb);
    aName += QString("%1").arg(myFieldsLst[theFieldId].myTiming[aFrameNb]);

    int aPos = -1;
    while ((aPos = aName.indexOf(".")) > -1 )
      aName.replace(aPos, 1, "_");
    aFile += aName;
    aFile += ".";
    aFile += myDumpFormat.toLower();
    ProcessVoidEvent(new TVoidMemFunEvent<SVTK_ViewWindow>
                 (myView,&SVTK_ViewWindow::RefreshDumpImage)); // IPAL13602
    ProcessEvent(new TMemFun2ArgEvent<SUIT_ViewWindow,bool,const QString&,const QString&>
             (myView,&SUIT_ViewWindow::dumpViewToFormat,aFile,myDumpFormat));
  } else {
    QFileInfo aFileInfo(myDumpPath);
    QString aDirPath = aFileInfo.absolutePath();
    QString aBaseName = aFileInfo.fileName();
    
    switch (myFrame) {
    case 0: 
      break;
    case 1:
      myFileIndex += 5;
      break;
    default:
      if (myProportional) {
      FieldData& aFirstFieldData = myFieldsLst[0];
      double p = (aFirstFieldData.myTiming[myFrame] -
                aFirstFieldData.myTiming[myFrame-1]) / theOneVal;
      myFileIndex += (long) (5*p);
      } else {
      myFileIndex += 5;
      }
    }
    
    QString aFile = aDirPath + QDir::separator() + aBaseName;
    aFile += "_";
    aFile += QString("%1").arg(myFileIndex).rightJustified(8, '0');
    aFile += ".jpeg";
    
    /* check image size is divisable 16
       myView->dumpViewToFormat(aFile,"JPEG");
    */
    SUIT_ViewWindow* aView = myView;
    ProcessVoidEvent(new TVoidMemFunEvent<SVTK_ViewWindow>(myView,&SVTK_ViewWindow::RefreshDumpImage)); // IPAL13602
    QImage img = ProcessEvent(new TMemFunEvent<SUIT_ViewWindow,QImage>(aView,&SUIT_ViewWindow::dumpView));
    if (!img.isNull()) {
      int width = img.width(); width = (width/16)*16;
      int height = img.height(); height = (height/16)*16;
      QImage copy = img.copy(0, 0, width, height);
      if (copy.save(aFile, "JPEG")) {
      theIndexList.append(myFileIndex);
      theNbFiles++;
      }
    }
  }
}

//------------------------------------------------------------------------
void VISU_TimeAnimation::run()
{
  if (!myView) {
    MESSAGE("Viewer is not defined for animation");
    return;
  }

  bool isDumping = !myDumpPath.isEmpty();
  myFileIndex = 0;
  QList<int> anIndexList;

  if ( myAnimationMode == VISU::Animation::PARALLEL ) // parallel animation mode
    parallelAnimation( isDumping, anIndexList );
  else //successive animation mode
    successiveAnimation( isDumping, anIndexList );

  // make AVI file if need
  if (isDumping && myDumpFormat.compare("AVI") == 0 && myExecutionState->IsActive()) {
    double aFPS = 17.3 * mySpeed;

    QFileInfo aFileInfo(myDumpPath);
    QString aDirPath = aFileInfo.absolutePath();
    QString aBaseName = aFileInfo.fileName();

    // add missing files
    if (anIndexList.count() > 1) {
      QString aFFile = aDirPath + QDir::separator() + aBaseName;
      aFFile += QString("_%1.jpeg");
      int aStartIndex = anIndexList[0], anEndIndex;
      for (int i = 1; i < anIndexList.count(); i++) {
      anEndIndex = anIndexList[i];
      QString aCurFile = aFFile.arg(QString::number(aStartIndex).rightJustified(8, '0'));
      QStringList aCommands;
      for (int j = aStartIndex+1; j < anEndIndex; j++) {
        QString aFile = aFFile.arg(QString::number(j).rightJustified(8, '0'));
        aCommands.append(QString("ln -s %1 %2").arg(aCurFile).arg(aFile));
      }
      system(aCommands.join(" ; \\\n").toLatin1().data());
      aStartIndex = anEndIndex;
      }
    }

    // make AVI file
    QString aPattern = aDirPath + QDir::separator() + aBaseName;
    aPattern += "_\%08d.jpeg";

    QString aCmd = myAVIMaker;
    aCmd += " -I p";
    aCmd += " -v 0";
    aCmd += QString(" -f %1").arg(aFPS);
    // aCmd += QString(" -n %1").arg(aNbFiles);
    aCmd += QString(" -n %1").arg(myFileIndex+1);
    aCmd += QString(" -j %1").arg(aPattern);
    aCmd += " | yuv2lav";
    aCmd += QString(" -o %1").arg(myDumpPath);
    system(aCmd.toLatin1().data());

    // remove temporary jpeg files
    aCmd = "( ";
    aCmd += QString("cd %1").arg(aDirPath);
    aCmd += "; ls";
    aCmd += QString(" | egrep '%1_[0-9]*.jpeg'").arg(aBaseName);
    aCmd += " | xargs rm";
    aCmd += " )";
    system(aCmd.toLatin1().data());
  }

  if (myExecutionState->IsActive())
    ProcessVoidEvent(new TVoidMemFunEvent<VISU_TimeAnimation>(this,&VISU_TimeAnimation::_emitStopped));
  myExecutionState->SetActive(false);
}

//------------------------------------------------------------------------
VISU::Result_i* VISU_TimeAnimation::createPresent (_PTR(SObject) theField)
{
  _PTR(SObject) aSObj = theField->GetFather();
  aSObj = aSObj->GetFather();
  aSObj = aSObj->GetFather();
  CORBA::Object_var anObject = VISU::ClientSObjectToObject(aSObj);
  if (CORBA::is_nil(anObject)) return NULL;
  return dynamic_cast<VISU::Result_i*>(VISU::GetServant(anObject).in());
}

//------------------------------------------------------------------------
double VISU_TimeAnimation::getTimeValue (_PTR(SObject) theTimeStamp)
{
  _PTR(GenericAttribute) anAttr;
  if (theTimeStamp->FindAttribute(anAttr, "AttributeName")) {
    _PTR(AttributeName) aName (anAttr);
    QString aNameString (aName->Value().c_str());
    int time_len = aNameString.indexOf(',');
    if (time_len > -1)
      return aNameString.left(time_len).toDouble();
    else
      return aNameString.toDouble();
  }
  return -1.0;
}

//------------------------------------------------------------------------
void VISU_TimeAnimation::setSpeed(CORBA::Long theSpeed)
{
  mySpeed = (theSpeed<1)? 1 : theSpeed;
}

//------------------------------------------------------------------------
void VISU_TimeAnimation::setAnimationSequence(const char* theSequence)
{
  mySequence = QString( theSequence );
}

//------------------------------------------------------------------------
char* VISU_TimeAnimation::getAnimationSequence()
{
  return strdup( mySequence.toLatin1().data() );
}

//------------------------------------------------------------------------
CORBA::Boolean VISU_TimeAnimation::isSequenceDefined()
{
  return !mySequence.isEmpty();
}

//------------------------------------------------------------------------
bool VISU_TimeAnimation::getIndicesFromSequence( QString theSequence, QList<long>& theIndices )
{
  bool isCorrect = true;

  theIndices.clear();

  QStringList aList = theSequence.split( ",", QString::SkipEmptyParts );
  QStringList::iterator it = aList.begin();
  QStringList::iterator itEnd = aList.end();
  for( ; it != itEnd; ++it )
  {
    if( !isCorrect )
      break;

    isCorrect = false;

    QString aString = *it;
    if( aString.isEmpty() )
      continue;

    bool ok = false;
    int aSingleIndex = aString.toLong( &ok );
    if( ok )
    {
      theIndices.append( aSingleIndex );
      isCorrect = true;
    }
    else if( aString.contains( '-' ) == 1 )
    {
      QString aLeftIndexStr = aString.section( '-', 0, 0 );
      QString aRightIndexStr = aString.section( '-', -1 );

      ok = false;
      int aLeftIndex = aLeftIndexStr.toLong( &ok );
      if( !ok )
      continue;

      ok = false;
      int aRightIndex = aRightIndexStr.toLong( &ok );
      if( !ok )
      continue;

      if( aLeftIndex >= aRightIndex )
      continue;

      for( int i = aLeftIndex; i <= aRightIndex; i++ )
      theIndices.append( i );

      isCorrect = true;
    }
  }

  return isCorrect;
}

//------------------------------------------------------------------------
std::string VISU_TimeAnimation::setDumpFormat(const char* theFormat)
{
  myDumpFormat = theFormat;
  QList<QByteArray> aDumpFormats = QImageWriter::supportedImageFormats();
  if (myDumpFormat.isEmpty() || 
      (aDumpFormats.indexOf(theFormat) < 0 && myDumpFormat.compare("AVI") != 0)) {
    if (aDumpFormats.indexOf("JPEG"))
      myDumpFormat = "JPEG";
    else
      myDumpFormat = aDumpFormats.at(0);
  }
  return myDumpFormat.toLatin1().data();
}

//------------------------------------------------------------------------
bool VISU_TimeAnimation::checkAVIMaker() const
{
  QList<QByteArray> aDumpFormats = QImageWriter::supportedImageFormats();
  if (aDumpFormats.indexOf("JPEG") < 0) return false;

  QString aCmd("which ");
  aCmd += myAVIMaker;
  aCmd += " >& /dev/null";
  int iErr = system(aCmd.toLatin1().data());
  return (iErr == 0);
}

//************************************************************************
int VISU_TimeAnimation::myNBAnimations = 0;
QString VISU_TimeAnimation::GenerateName()
{
  return VISU::GenerateName("Animation", myNBAnimations++);
}

//------------------------------------------------------------------------
std::string GetPresentationComment (VISU::VISUType thePrsType)
{
  std::string aPrsCmt;
  switch (thePrsType) {
  case VISU::TSCALARMAP:
    aPrsCmt = VISU::ScalarMap_i::myComment;
    break;
  case VISU::TISOSURFACES:
    aPrsCmt = VISU::IsoSurfaces_i::myComment;
    break;
  case VISU::TCUTPLANES:
    aPrsCmt = VISU::CutPlanes_i::myComment;
    break;
  case VISU::TCUTLINES:
    aPrsCmt = VISU::CutLines_i::myComment;
    break;
  case VISU::TCUTSEGMENT:
    aPrsCmt = VISU::CutSegment_i::myComment;
    break;
  case VISU::TPLOT3D:
    aPrsCmt = VISU::Plot3D_i::myComment;
    break;
  case VISU::TDEFORMEDSHAPE:
    aPrsCmt = VISU::DeformedShape_i::myComment;
    break;
  case VISU::TVECTORS:
    aPrsCmt = VISU::Vectors_i::myComment;
    break;
  case VISU::TSTREAMLINES:
    aPrsCmt = VISU::StreamLines_i::myComment;
    break;
  case VISU::TGAUSSPOINTS:
    aPrsCmt = VISU::GaussPoints_i::myComment;
    break;
  case VISU::TSCALARMAPONDEFORMEDSHAPE:
  case VISU::TDEFORMEDSHAPEANDSCALARMAP:
    aPrsCmt = VISU::DeformedShapeAndScalarMap_i::myComment;
    break;
  default:
    aPrsCmt = "Unknown presentation";
    break;
  }
  return aPrsCmt;
}

//------------------------------------------------------------------------
SALOMEDS::SObject_ptr VISU_TimeAnimation::publishInStudy()
{
  if (myStudy->GetProperties()->IsLocked()) {
    SUIT_MessageBox::warning(0,
                       QObject::tr("WRN_VISU_WARNING"),
                       QObject::tr("WRN_STUDY_LOCKED"),
                       QObject::tr("BUT_OK"));
    return SALOMEDS::SObject::_nil();
  }

  _PTR(StudyBuilder) aStudyBuilder = myStudy->NewBuilder();
  aStudyBuilder->NewCommand();  // There is a transaction
  _PTR(SComponent) aSComponent = VISU::ClientFindOrCreateVisuComponent(myStudy);
  std::string aSComponentEntry = aSComponent->GetID();

  QString aComment;
  aComment.sprintf("myComment=ANIMATION;myTimeMinVal=%g;myTimeMaxVal=%g;mySequence=%s;myMode=%d",
                   myTimeMinVal,
               myTimeMaxVal,
               mySequence.toLatin1().data(),
               myAnimationMode);

  string anEntry = VISU::CreateAttributes(myStudy,
                                aSComponentEntry.c_str(),
                                VISU::NO_ICON,
                                VISU::NO_IOR,
                                          GenerateName().toLatin1().data(),
                                VISU::NO_PERFSITENT_REF,
                                aComment.toLatin1().data(),
                                true);
  myAnimEntry = anEntry.c_str();
  _PTR(SObject) aAnimSObject = myStudy->FindObjectID(anEntry.c_str());

  for (int i = 0; i < getNbFields(); i++) {
    FieldData& aData = myFieldsLst[i];
    if (aData.myPrs.empty()) {
      generatePresentations(i);
    }
    if ( !aData.myPrs.empty() ) {
      _PTR(SObject) newObj = aStudyBuilder->NewObject(aAnimSObject);
      aStudyBuilder->Addreference(newObj, aData.myField);
      
      ostringstream strOut;
      aData.myPrs[0]->ToStream(strOut);
      string aPrsComment = strOut.str();
      string aPrsMyComment = aData.myPrs[0]->GetComment();
      if(aPrsMyComment == "PRSMERGER")
      aPrsMyComment = "SCALARMAP";
      VISU::CreateAttributes(myStudy, 
                       newObj->GetID().c_str(),
                       VISU::NO_ICON,
                       VISU::NO_IOR,
                       aPrsMyComment.c_str(),
                       VISU::NO_PERFSITENT_REF,
                       aPrsComment.c_str(),
                       true);
    }
  }
  aStudyBuilder->CommitCommand();

  return VISU::GetSObject(aAnimSObject)._retn();
}

//------------------------------------------------------------------------
void VISU_TimeAnimation::saveAnimation()
{
  if (myStudy->GetProperties()->IsLocked()) return;
  if (myAnimEntry.isEmpty()) return;

  _PTR(SObject) aAnimSObject = myStudy->FindObjectID(myAnimEntry.toLatin1().data());
  if (!aAnimSObject) return;

  _PTR(StudyBuilder) aStudyBuilder = myStudy->NewBuilder();
  aStudyBuilder->NewCommand();  // There is a transaction
  _PTR(SComponent) aSComponent = VISU::ClientFindOrCreateVisuComponent(myStudy);
  std::string aSComponentEntry = aSComponent->GetID();

  QString aComment;
  aComment.sprintf("myComment=ANIMATION;myTimeMinVal=%g;myTimeMaxVal=%g;mySequence=%s;myMode=%d",
                   myTimeMinVal,
               myTimeMaxVal,
               mySequence.toLatin1().data(),
               myAnimationMode);

  _PTR(GenericAttribute) anAttr;
  anAttr = aStudyBuilder->FindOrCreateAttribute(aAnimSObject, "AttributeString");
  _PTR(AttributeString) aCmnt (anAttr);
  aCmnt->SetValue(aComment.toLatin1().data());

  _PTR(ChildIterator) anIter = myStudy->NewChildIterator(aAnimSObject);
  int i = 0, nbf = getNbFields();
  for (anIter->Init(); anIter->More(); anIter->Next(), i++) {
    if (i >= nbf) break; // it must not be
    FieldData& aData = myFieldsLst[i];

    // Get presentation name and comment
    if (aData.myPrs.empty()) {
      generatePresentations(i);
    }
    ostringstream strOut;
    aData.myPrs[0]->ToStream(strOut);
    string aPrsComment = strOut.str();
    string aPrsNameTxt = aData.myPrs[0]->GetComment();
    if(aPrsNameTxt == "PRSMERGER")
      aPrsNameTxt = "SCALARMAP";
    // Save in study
    _PTR(SObject) aRefObj = anIter->Value();
    _PTR(ChildIterator) anPrsIter = myStudy->NewChildIterator(aRefObj);
    anPrsIter->Init();

    if (anPrsIter->More()) {
      _PTR(SObject) aPrsObj = anPrsIter->Value();
      anAttr = aStudyBuilder->FindOrCreateAttribute(aPrsObj, "AttributeString");
      aCmnt = _PTR(AttributeString)(anAttr);
      aCmnt->SetValue(aPrsComment.c_str());

      anAttr = aStudyBuilder->FindOrCreateAttribute(aPrsObj, "AttributeName");
      _PTR(AttributeName) aPrsName (anAttr);
      aPrsName->SetValue(aPrsNameTxt);

    } else {
      VISU::CreateAttributes(myStudy, 
                       aRefObj->GetID().c_str(),
                       VISU::NO_ICON,
                       VISU::NO_IOR,
                             aPrsNameTxt.c_str(),
                       VISU::NO_PERFSITENT_REF,
                       aPrsComment.c_str(),
                       true);
    }
  }
  aStudyBuilder->CommitCommand();
}

//------------------------------------------------------------------------
void VISU_TimeAnimation::restoreFromStudy(SALOMEDS::SObject_ptr theField)
{
  _PTR(SObject) aAnimSObject = VISU::GetClientSObject(theField, myStudy);
  restoreFromStudy(aAnimSObject);
}

void VISU_TimeAnimation::restoreFromStudy(_PTR(SObject) theField)
{
  _PTR(SObject) aAnimSObject = theField;

  VISU::Storable::TRestoringMap aMap = VISU::Storable::GetStorableMap(aAnimSObject);
  if (aMap.empty()) 
    return;

  bool isExist;
  myTimeMinVal = VISU::Storable::FindValue(aMap,"myTimeMinVal",&isExist).toDouble();
  myTimeMaxVal = VISU::Storable::FindValue(aMap,"myTimeMaxVal",&isExist).toDouble();
  mySequence = VISU::Storable::FindValue(aMap,"mySequence",&isExist);
  myAnimationMode = VISU::Animation::AnimationMode(VISU::Storable::FindValue(aMap,"myMode",&isExist).toInt());

  _PTR(ChildIterator) anIter = myStudy->NewChildIterator(aAnimSObject);
  for (anIter->Init(); anIter->More(); anIter->Next()) {
    _PTR(SObject) aRefObj = anIter->Value();
    _PTR(SObject) aFieldObj;

    if (!aRefObj->ReferencedObject(aFieldObj) ) 
      continue;

    int nbAttr = aFieldObj->GetAllAttributes().size();
    //std::string name1 = aFieldObj->GetName();
    if(nbAttr<1)
      continue;

    addField(aFieldObj);
    if ( isRangeDefined() || isSequenceDefined() ) 
      myFieldsAbsFrames.pop_back();

    FieldData& aData = getFieldData(getNbFields()-1);
    
    // Get Presentation object
    _PTR(ChildIterator) anPrsIter = myStudy->NewChildIterator(aRefObj);
    anPrsIter->Init();
    if (!anPrsIter->More()) 
      continue;
    _PTR(SObject) aPrsObj = anPrsIter->Value();
    _PTR(GenericAttribute) anAttr;
    if (!aPrsObj->FindAttribute(anAttr, "AttributeName")) 
      continue;
    _PTR(AttributeName) aName (anAttr);
    string aStr = aName->Value();
    QString strName (aStr.c_str());

    if (strName == VISU::ScalarMap_i::myComment.c_str())
      aData.myPrsType = VISU::TSCALARMAP;
    else if (strName == VISU::IsoSurfaces_i::myComment.c_str())
      aData.myPrsType = VISU::TISOSURFACES;
    else if (strName == VISU::CutPlanes_i::myComment.c_str())
      aData.myPrsType = VISU::TCUTPLANES;
    else if (strName == VISU::CutLines_i::myComment.c_str())
      aData.myPrsType = VISU::TCUTLINES;
    else if (strName == VISU::CutSegment_i::myComment.c_str())
      aData.myPrsType = VISU::TCUTSEGMENT;
    else if (strName == VISU::Plot3D_i::myComment.c_str())
      aData.myPrsType = VISU::TPLOT3D;
    else if (strName == VISU::DeformedShape_i::myComment.c_str())
      aData.myPrsType = VISU::TDEFORMEDSHAPE;
    else if (strName == VISU::Vectors_i::myComment.c_str())
      aData.myPrsType = VISU::TVECTORS;
    else if (strName == VISU::StreamLines_i::myComment.c_str())
      aData.myPrsType = VISU::TSTREAMLINES;
    else if (strName == VISU::GaussPoints_i::myComment.c_str())
      aData.myPrsType = VISU::TGAUSSPOINTS;
    else if (strName == VISU::DeformedShapeAndScalarMap_i::myComment.c_str())
      aData.myPrsType = VISU::TDEFORMEDSHAPEANDSCALARMAP;
    else
      continue;
    generatePresentations(getNbFields()-1);

    VISU::Storable::TRestoringMap aPrsMap = VISU::Storable::GetStorableMap(aPrsObj);
    if (aPrsMap.empty())
      continue;
    if (aData.myPrs[0]) {
      aData.myPrs[0]->Restore(VISU::GetSObject(aData.myField), aPrsMap);
      aData.myPrs[0]->GetOffset(aData.myOffset);
    }
    for (int i = 1; i < aData.myNbFrames; i++) {
      if (!aData.myPrs[0])
      continue;
      bool anIsFixedRange = false;
      if (aData.myPrsType != VISU::TGAUSSPOINTS) {
      if (VISU::ScalarMap_i* aPrs = dynamic_cast<VISU::ScalarMap_i*>(aData.myPrs[i]))
        anIsFixedRange = aPrs->IsRangeFixed();
      }
      if (aData.myPrsType == VISU::TDEFORMEDSHAPEANDSCALARMAP) {
      if (VISU::DeformedShapeAndScalarMap_i* aDeformedPrs =
          dynamic_cast<VISU::DeformedShapeAndScalarMap_i*>(aData.myPrs[i])) {
        //Set correct time stamp number
        int aTimeStampNum = aDeformedPrs->GetScalarTimeStampNumber();
        aDeformedPrs->SameAs(aData.myPrs[0]);
        aDeformedPrs->SetScalarField(aDeformedPrs->GetScalarEntity(),
                               aDeformedPrs->GetScalarFieldName(),
                               aTimeStampNum);
      }
      }
      else
      aData.myPrs[i]->SameAs(aData.myPrs[0]);
    }
  }
  string aStr = aAnimSObject->GetID();
  myAnimEntry = aStr.c_str();
}

void VISU_TimeAnimation::onViewDeleted()
{
  myView = 0;
  stopAnimation();
}

void VISU_TimeAnimation::ApplyProperties(CORBA::Long theFieldNum, VISU::ColoredPrs3d_ptr thePrs)
  throw (SALOME::SALOME_Exception)
{
  Unexpect aCatch(SALOME_SalomeException);

  VISU::ColoredPrs3d_i* aPrs_i = dynamic_cast<VISU::ColoredPrs3d_i*>(GetServant(thePrs).in());

  if ( !aPrs_i ) 
    THROW_SALOME_CORBA_EXCEPTION("Error : invalid dynamic cast of the given presentation to VISU::ColoredPrs3d_i",
                         SALOME::INTERNAL_ERROR);
  
  if ( myAnimationMode == VISU::Animation::PARALLEL ) { // parallel animation mode
    FieldData& aData = myFieldsLst[theFieldNum];
    
    if ( aData.myPrs.empty() )
      THROW_SALOME_CORBA_EXCEPTION("Error : presentations for the given field is not yet created!",
                           SALOME::INTERNAL_ERROR);
    
    if ( aPrs_i->GetCResult() != aData.myPrs[0]->GetCResult() )
      THROW_SALOME_CORBA_EXCEPTION("Error : the MED file is not the same!",
                           SALOME::INTERNAL_ERROR);
    
    for (int i = 0; i < aData.myNbFrames; i++) {
      bool anIsFixedRange = false;
      if (aData.myPrsType != VISU::TGAUSSPOINTS) {
      if (VISU::ScalarMap_i* aPrs = dynamic_cast<VISU::ScalarMap_i*>(aData.myPrs[i]))
        anIsFixedRange = aPrs->IsRangeFixed();
      }
      aData.myPrs[i]->SameAs(aPrs_i);
    }
  }
  else if ( myAnimationMode == VISU::Animation::SUCCESSIVE ) { // successive animation mode
    for (int f = 0; f < getNbFields(); f++) {
      FieldData& aData = myFieldsLst[f];
      
      if ( aData.myPrs.empty() )
      THROW_SALOME_CORBA_EXCEPTION("Error : presentations for the given field is not yet created!",
                             SALOME::INTERNAL_ERROR);
      
      for (int i = 0; i < aData.myNbFrames; i++) {
      aData.myPrs[i]->SameAs(aPrs_i);
      }
    }
  }
}

//========================================================================
//========================================================================
//========================================================================
struct TNewAnimationEvent: public SALOME_Event
{
  std::string myStudyName;
  VISU::View3D_ptr myView3D;

  typedef VISU_TimeAnimation* TResult;
  TResult myResult;

  TNewAnimationEvent (std::string theStudyName, VISU::View3D_ptr theView3D):
    myStudyName(theStudyName),
    myView3D(VISU::View3D::_duplicate(theView3D)),
    myResult(NULL)
  {}

  virtual
  void
  Execute()
  {
    SUIT_Session* aSession = SUIT_Session::session();
    QList<SUIT_Application*> anApplications = aSession->applications();
    QList<SUIT_Application*>::Iterator anIter = anApplications.begin();
    while ( anIter !=  anApplications.end() ) {
      SUIT_Application* anApp = *anIter;
      if (SUIT_Study* aSStudy = anApp->activeStudy()) {
        if (SalomeApp_Study* aStudy = dynamic_cast<SalomeApp_Study*>(aSStudy)) {
          if (_PTR(Study) aCStudy = aStudy->studyDS()) {
            if (myStudyName == aCStudy->Name()) {
              myResult = new VISU_TimeAnimation (aCStudy, myView3D);
              break;
            }
          }
        }
      }
      anIter++;
    }
  }
};

VISU_TimeAnimation_i::VISU_TimeAnimation_i (SALOMEDS::Study_ptr theStudy,
                                            VISU::View3D_ptr theView3D)
{
  std::string aStudyName = theStudy->Name();
  myAnim = ProcessEvent(new TNewAnimationEvent (aStudyName, theView3D));
}

VISU_TimeAnimation_i::~VISU_TimeAnimation_i()
{
  delete myAnim;
}

bool VISU_TimeAnimation_i::addField (SALOMEDS::SObject_ptr theField)
{
  return myAnim->addField(theField);
}

void VISU_TimeAnimation_i::clearFields ()
{
  for (int i = 0; i < myAnim->getNbFields(); i++) {
    myAnim->clearData(myAnim->getFieldData(i));
  }
  myAnim->clearFieldData();
}

CORBA::Boolean VISU_TimeAnimation_i::generateFrames()
{
  //return ProcessEvent(new TMemFunEvent<VISU_TimeAnimation,bool>
  //                    (myAnim,&VISU_TimeAnimation::generateFrames));
  return myAnim->generateFrames();
}

void VISU_TimeAnimation_i::generatePresentations (CORBA::Long theFieldNum)
{
  myAnim->generatePresentations(theFieldNum);
}

void VISU_TimeAnimation_i::clearView()
{
  //ProcessVoidEvent(new TVoidMemFunEvent<VISU_TimeAnimation>
  //                 (myAnim,&VISU_TimeAnimation::clearView));
  myAnim->clearView();
}

void VISU_TimeAnimation_i::stopAnimation()
{
  //ProcessVoidEvent(new TVoidMemFunEvent<VISU_TimeAnimation>
  //                 (myAnim,&VISU_TimeAnimation::stopAnimation));
  myAnim->stopAnimation();
}

void VISU_TimeAnimation_i::startAnimation()
{
  //ProcessVoidEvent(new TVoidMemFunEvent<VISU_TimeAnimation>
  //                 (myAnim,&VISU_TimeAnimation::startAnimation));
  myAnim->startAnimation();
}

void VISU_TimeAnimation_i::nextFrame()
{
  //ProcessVoidEvent(new TVoidMemFunEvent<VISU_TimeAnimation>
  //                 (myAnim,&VISU_TimeAnimation::nextFrame));
  myAnim->nextFrame();
}

void VISU_TimeAnimation_i::prevFrame()
{
  //ProcessVoidEvent(new TVoidMemFunEvent<VISU_TimeAnimation>
  //                 (myAnim,&VISU_TimeAnimation::prevFrame));
  myAnim->prevFrame();
}

void VISU_TimeAnimation_i::firstFrame()
{
  //ProcessVoidEvent(new TVoidMemFunEvent<VISU_TimeAnimation>
  //                 (myAnim,&VISU_TimeAnimation::firstFrame));
  myAnim->firstFrame();
}

void VISU_TimeAnimation_i::lastFrame()
{
  //ProcessVoidEvent(new TVoidMemFunEvent<VISU_TimeAnimation>
  //                 (myAnim,&VISU_TimeAnimation::lastFrame));
  myAnim->lastFrame();
}

void VISU_TimeAnimation_i::gotoFrame(CORBA::Long theFrame)
{
  //ProcessVoidEvent(new TVoidMemFun1ArgEvent<VISU_TimeAnimation,CORBA::Long>
  //                 (myAnim,&VISU_TimeAnimation::gotoFrame,theFrame));
  myAnim->gotoFrame(theFrame);
}

CORBA::Long VISU_TimeAnimation_i::getNbFields()
{
  return myAnim->getNbFields();
}

CORBA::Long VISU_TimeAnimation_i::getNbFrames()
{
  return myAnim->getNbFrames();
}

CORBA::Boolean VISU_TimeAnimation_i::isRunning()
{
  return myAnim->isRunning();
}

CORBA::Long VISU_TimeAnimation_i::getCurrentFrame()
{
  return myAnim->getCurrentFrame();
}

VISU::ColoredPrs3d_ptr VISU_TimeAnimation_i::getPresentation
                    (CORBA::Long theField, CORBA::Long theFrame)
{
  return myAnim->getPresentation(theField,theFrame);
}

void VISU_TimeAnimation_i::setPresentationType (CORBA::Long theFieldNum,
                                                VISU::VISUType theType)
{
  myAnim->setPresentationType(theFieldNum,theType);
}

VISU::VISUType VISU_TimeAnimation_i::getPresentationType (CORBA::Long theFieldNum)
{
  return myAnim->getPresentationType(theFieldNum);
}

void VISU_TimeAnimation_i::setSpeed(CORBA::Long theSpeed)
{
  myAnim->setSpeed(theSpeed);
}

CORBA::Long VISU_TimeAnimation_i::getSpeed()
{
  return myAnim->getSpeed();
}

CORBA::Boolean VISU_TimeAnimation_i::isProportional()
{
  return myAnim->isProportional();
}

void VISU_TimeAnimation_i::setAnimationRange (CORBA::Double theMin,
                                              CORBA::Double theMax)
{
  myAnim->setAnimationRange(theMin,theMax);
}

CORBA::Double VISU_TimeAnimation_i::getMinRange()
{
  return myAnim->getMinRange();
}

CORBA::Double VISU_TimeAnimation_i::getMaxRange()
{
  return myAnim->getMaxRange();
}

CORBA::Boolean VISU_TimeAnimation_i::isRangeDefined()
{
  return myAnim->isRangeDefined();
}

void VISU_TimeAnimation_i::setAnimationSequence (const char* theSequence)
{
  myAnim->setAnimationSequence(theSequence);
}

char* VISU_TimeAnimation_i::getAnimationSequence()
{
  return myAnim->getAnimationSequence();
}

CORBA::Boolean VISU_TimeAnimation_i::isSequenceDefined()
{
  return myAnim->isSequenceDefined();
}

void VISU_TimeAnimation_i::dumpTo (const char* thePath)
{
  myAnim->dumpTo(thePath);
}

char* VISU_TimeAnimation_i::setDumpFormat (const char* theFormat)
{
  string aDumpFormat = myAnim->setDumpFormat(theFormat);
  return CORBA::string_dup(aDumpFormat.c_str());
}

CORBA::Boolean VISU_TimeAnimation_i::isCycling()
{
  return myAnim->isCycling();
}

CORBA::Boolean VISU_TimeAnimation_i::isCleaningMemoryAtEachFrame(){
  return myAnim->isCleaningMemoryAtEachFrame();
}

CORBA::Double VISU_TimeAnimation_i::getMinTime()
{
  return myAnim->getMinTime();
}

CORBA::Double VISU_TimeAnimation_i::getMaxTime()
{
  return myAnim->getMaxTime();
}

void VISU_TimeAnimation_i::setProportional (CORBA::Boolean theProp)
{
  myAnim->setProportional(theProp);
}

void VISU_TimeAnimation_i::setCycling (CORBA::Boolean theCycle)
{
  myAnim->setCycling(theCycle);
}

void VISU_TimeAnimation_i::setCleaningMemoryAtEachFrame(CORBA::Boolean theCycle){
  myAnim->setCleaningMemoryAtEachFrame(theCycle);
}

SALOMEDS::SObject_ptr VISU_TimeAnimation_i::publishInStudy()
{
  return myAnim->publishInStudy();
}

void VISU_TimeAnimation_i::restoreFromStudy(SALOMEDS::SObject_ptr theObj)
{
  myAnim->restoreFromStudy(theObj);
}

CORBA::Boolean VISU_TimeAnimation_i::isSavedInStudy()
{
  return myAnim->isSavedInStudy();
}

void VISU_TimeAnimation_i::saveAnimation()
{
  myAnim->saveAnimation();
}

void VISU_TimeAnimation_i::setAnimationMode(VISU::Animation::AnimationMode theMode)
{
  myAnim->setAnimationMode(theMode);
}

VISU::Animation::AnimationMode VISU_TimeAnimation_i::getAnimationMode()
{
  return VISU::Animation::AnimationMode(myAnim->getAnimationMode());
}

void VISU_TimeAnimation_i::ApplyProperties(CORBA::Long theFieldNum, VISU::ColoredPrs3d_ptr thePrs)
  throw (SALOME::SALOME_Exception)
{
  myAnim->ApplyProperties(theFieldNum, thePrs);
}

Generated by  Doxygen 1.6.0   Back to index