<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_BASEFUNCTIONSET_FINITEVOLUME_HH
#define DUNE_GDT_BASEFUNCTIONSET_FINITEVOLUME_HH

#include <type_traits>

#include <dune/common/typetraits.hh>
#include <dune/common/fvector.hh>
#include <dune/common/fmatrix.hh>

#include <dune/stuff/common/vector.hh>
#include <dune/stuff/common/matrix.hh>

#include "../../basefunctionset/interface.hh"

namespace Dune {
namespace GDT {
namespace BaseFunctionSet {

// forward, to be used in the traits and to allow for specialization
template <class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCols = 1>
class FiniteVolume
{
  static_assert(Dune::AlwaysFalse<EntityImp>::value, "Untested for these dimensions!");
};

template <class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCols>
class FiniteVolumeTraits
{
public:
  typedef FiniteVolume<EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols> derived_type;
  typedef RangeFieldImp BackendType;
  typedef EntityImp EntityType;
};

template <class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp>
class FiniteVolume<EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1, 1>
    : public BaseFunctionSetInterface<FiniteVolumeTraits<EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1, 1>,
                                      DomainFieldImp, domainDim, RangeFieldImp, 1, 1>
{
  typedef FiniteVolume<EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1, 1> ThisType;
  typedef BaseFunctionSetInterface<FiniteVolumeTraits<EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1, 1>,
                                   DomainFieldImp, domainDim, RangeFieldImp, 1, 1> BaseType;

public:
  typedef FiniteVolumeTraits<EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1, 1> Traits;
  typedef typename Traits::BackendType BackendType;
  typedef typename Traits::EntityType EntityType;

  using typename BaseType::DomainFieldType;
  using BaseType::dimDomain;
  using typename BaseType::DomainType;
  using typename BaseType::RangeFieldType;
  using BaseType::dimRange;
  using BaseType::dimRangeCols;
  using typename BaseType::RangeType;
  using typename BaseType::JacobianRangeType;

  FiniteVolume(const EntityType& en)
    : BaseType(en)
  {
  }

  FiniteVolume(ThisType&& source)
    : BaseType(source.entity())
  {
  }

  FiniteVolume(const ThisType& /*other*/) = delete;

  ThisType& operator=(const ThisType& /*other*/) = delete;

  const BackendType& backend() const
  {
    return 1.0;
  }

  virtual size_t size() const DS_OVERRIDE DS_FINAL
  {
    return 1;
  }

  virtual size_t order() const DS_OVERRIDE DS_FINAL
  {
    return 0;
  }

  virtual void evaluate(const DomainType& /*xx*/, std::vector<RangeType>& ret) const DS_OVERRIDE DS_FINAL
  {
    assert(ret.size() >= 0);
    ret[0] = 1.0;
  }

  using BaseType::evaluate;

  virtual void jacobian(const DomainType& /*xx*/, std::vector<JacobianRangeType>& ret) const DS_OVERRIDE DS_FINAL
  {
    assert(ret.size() >= 0);
    ret[0] *= 0.0;
  }

  using BaseType::jacobian;
}; // class FiniteVolume< ..., 1, 1 >

template <class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim>
class FiniteVolume<EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1>
    : public BaseFunctionSetInterface<FiniteVolumeTraits<EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim,
                                                         1>,
                                      DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1>
{
  typedef FiniteVolume<EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1> ThisType;
  typedef BaseFunctionSetInterface<FiniteVolumeTraits<EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1>,
                                   DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1> BaseType;

public:
  typedef FiniteVolumeTraits<EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1> Traits;
  typedef typename Traits::BackendType BackendType;
  typedef typename Traits::EntityType EntityType;

  using typename BaseType::DomainFieldType;
  using BaseType::dimDomain;
  using typename BaseType::DomainType;
  using typename BaseType::RangeFieldType;
  using BaseType::dimRange;
  using BaseType::dimRangeCols;
  using typename BaseType::RangeType;
  using typename BaseType::JacobianRangeType;

  FiniteVolume(const EntityType& en)
    : BaseType(en)
  {
  }

  FiniteVolume(ThisType&& source)
    : BaseType(source.entity())
  {
  }

  FiniteVolume(const ThisType& /*other*/) = delete;

  ThisType& operator=(const ThisType& /*other*/) = delete;

  const BackendType& backend() const
  {
    return 1.0;
  }

  virtual size_t size() const DS_OVERRIDE DS_FINAL
  {
    return dimRange;
  }

  virtual size_t order() const DS_OVERRIDE DS_FINAL
  {
    return 0;
  }

  virtual void evaluate(const DomainType& /*xx*/, std::vector<RangeType>& ret) const DS_OVERRIDE DS_FINAL
  {
    assert(ret.size() >= dimRange);
    for (size_t ii = 0; ii < dimRange; ++ii) {
      Stuff::Common::clear(ret[ii]);
      ret[ii][ii] = RangeFieldType(1);
    }
  } // ... evaluate(...)

  using BaseType::evaluate;

  virtual void jacobian(const DomainType& /*xx*/, std::vector<JacobianRangeType>& ret) const DS_OVERRIDE DS_FINAL
  {
    assert(ret.size() >= dimRange);
    for (size_t ii = 0; ii < dimRange; ++ii)
      Stuff::Common::clear(ret[ii]);
  } // ... jacobian(...)

  using BaseType::jacobian;
}; // class FiniteVolume< ..., rangeDim, 1 >

} // namespace BaseFunctionSet
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_BASEFUNCTIONSET_FINITEVOLUME_HH
<commit_msg>[basefunctionset.finitevolume] fix 'backend'<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_BASEFUNCTIONSET_FINITEVOLUME_HH
#define DUNE_GDT_BASEFUNCTIONSET_FINITEVOLUME_HH

#include <type_traits>

#include <dune/common/typetraits.hh>
#include <dune/common/fvector.hh>
#include <dune/common/fmatrix.hh>

#include <dune/stuff/common/vector.hh>
#include <dune/stuff/common/matrix.hh>

#include "../../basefunctionset/interface.hh"

namespace Dune {
namespace GDT {
namespace BaseFunctionSet {

// forward, to be used in the traits and to allow for specialization
template <class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCols = 1>
class FiniteVolume
{
  static_assert(Dune::AlwaysFalse<EntityImp>::value, "Untested for these dimensions!");
};

template <class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCols>
class FiniteVolumeTraits
{
public:
  typedef FiniteVolume<EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols> derived_type;
  typedef RangeFieldImp BackendType;
  typedef EntityImp EntityType;
};

template <class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp>
class FiniteVolume<EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1, 1>
    : public BaseFunctionSetInterface<FiniteVolumeTraits<EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1, 1>,
                                      DomainFieldImp, domainDim, RangeFieldImp, 1, 1>
{
  typedef FiniteVolume<EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1, 1> ThisType;
  typedef BaseFunctionSetInterface<FiniteVolumeTraits<EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1, 1>,
                                   DomainFieldImp, domainDim, RangeFieldImp, 1, 1> BaseType;

public:
  typedef FiniteVolumeTraits<EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1, 1> Traits;
  typedef typename Traits::BackendType BackendType;
  typedef typename Traits::EntityType EntityType;

  using typename BaseType::DomainFieldType;
  using BaseType::dimDomain;
  using typename BaseType::DomainType;
  using typename BaseType::RangeFieldType;
  using BaseType::dimRange;
  using BaseType::dimRangeCols;
  using typename BaseType::RangeType;
  using typename BaseType::JacobianRangeType;

  FiniteVolume(const EntityType& en)
    : BaseType(en)
    , backend_(1)
  {
  }

  FiniteVolume(ThisType&& source)
    : BaseType(source.entity())
    , backend_(1)
  {
  }

  FiniteVolume(const ThisType& /*other*/) = delete;

  ThisType& operator=(const ThisType& /*other*/) = delete;

  const BackendType& backend() const
  {
    return backend_;
  }

  virtual size_t size() const DS_OVERRIDE DS_FINAL
  {
    return 1;
  }

  virtual size_t order() const DS_OVERRIDE DS_FINAL
  {
    return 0;
  }

  virtual void evaluate(const DomainType& /*xx*/, std::vector<RangeType>& ret) const DS_OVERRIDE DS_FINAL
  {
    assert(ret.size() >= 0);
    ret[0] = 1.0;
  }

  using BaseType::evaluate;

  virtual void jacobian(const DomainType& /*xx*/, std::vector<JacobianRangeType>& ret) const DS_OVERRIDE DS_FINAL
  {
    assert(ret.size() >= 0);
    ret[0] *= 0.0;
  }

  using BaseType::jacobian;

private:
  const BackendType backend_;
}; // class FiniteVolume< ..., 1, 1 >

template <class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim>
class FiniteVolume<EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1>
    : public BaseFunctionSetInterface<FiniteVolumeTraits<EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim,
                                                         1>,
                                      DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1>
{
  typedef FiniteVolume<EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1> ThisType;
  typedef BaseFunctionSetInterface<FiniteVolumeTraits<EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1>,
                                   DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1> BaseType;

public:
  typedef FiniteVolumeTraits<EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1> Traits;
  typedef typename Traits::BackendType BackendType;
  typedef typename Traits::EntityType EntityType;

  using typename BaseType::DomainFieldType;
  using BaseType::dimDomain;
  using typename BaseType::DomainType;
  using typename BaseType::RangeFieldType;
  using BaseType::dimRange;
  using BaseType::dimRangeCols;
  using typename BaseType::RangeType;
  using typename BaseType::JacobianRangeType;

  FiniteVolume(const EntityType& en)
    : BaseType(en)
    , backend_(1)
  {
  }

  FiniteVolume(ThisType&& source)
    : BaseType(source.entity())
    , backend_(1)
  {
  }

  FiniteVolume(const ThisType& /*other*/) = delete;

  ThisType& operator=(const ThisType& /*other*/) = delete;

  const BackendType& backend() const
  {
    return backend_;
  }

  virtual size_t size() const DS_OVERRIDE DS_FINAL
  {
    return dimRange;
  }

  virtual size_t order() const DS_OVERRIDE DS_FINAL
  {
    return 0;
  }

  virtual void evaluate(const DomainType& /*xx*/, std::vector<RangeType>& ret) const DS_OVERRIDE DS_FINAL
  {
    assert(ret.size() >= dimRange);
    for (size_t ii = 0; ii < dimRange; ++ii) {
      Stuff::Common::clear(ret[ii]);
      ret[ii][ii] = RangeFieldType(1);
    }
  } // ... evaluate(...)

  using BaseType::evaluate;

  virtual void jacobian(const DomainType& /*xx*/, std::vector<JacobianRangeType>& ret) const DS_OVERRIDE DS_FINAL
  {
    assert(ret.size() >= dimRange);
    for (size_t ii = 0; ii < dimRange; ++ii)
      Stuff::Common::clear(ret[ii]);
  } // ... jacobian(...)

  using BaseType::jacobian;

private:
  const BackendType backend_;
}; // class FiniteVolume< ..., rangeDim, 1 >

} // namespace BaseFunctionSet
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_BASEFUNCTIONSET_FINITEVOLUME_HH
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkInformation.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkInformation.h"

#include "vtkGarbageCollector.h"
#include "vtkInformationDataObjectKey.h"
#include "vtkInformationExecutiveKey.h"
#include "vtkInformationInformationKey.h"
#include "vtkInformationInformationVectorKey.h"
#include "vtkInformationIntegerKey.h"
#include "vtkInformationIntegerVectorKey.h"
#include "vtkInformationKeyVectorKey.h"
#include "vtkInformationObjectBaseKey.h"
#include "vtkInformationStringKey.h"
#include "vtkObjectFactory.h"
#include "vtkSmartPointer.h"

#include <vtkstd/map>

vtkCxxRevisionMacro(vtkInformation, "1.1.2.3");
vtkStandardNewMacro(vtkInformation);

//----------------------------------------------------------------------------
class vtkInformationInternals
{
public:
  typedef vtkstd::map<vtkInformationKey*,
                      vtkSmartPointer<vtkObjectBase> > MapType;
  MapType Map;
};

//----------------------------------------------------------------------------
vtkInformation::vtkInformation()
{
  this->Internal = new vtkInformationInternals;
  this->GarbageCollecting = 0;
}

//----------------------------------------------------------------------------
vtkInformation::~vtkInformation()
{
  delete this->Internal;
}

//----------------------------------------------------------------------------
void vtkInformation::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
  vtkInformationInternals::MapType::const_iterator i;
  for(i=this->Internal->Map.begin(); i != this->Internal->Map.end(); ++i)
    {
    os << indent << i->first << ": " << i->second.GetPointer() << "\n";
    }
}

//----------------------------------------------------------------------------
void vtkInformation::SetAsObjectBase(vtkInformationKey* key,
                                     vtkObjectBase* value)
{
  if(key)
    {
    vtkInformationInternals::MapType::iterator i =
      this->Internal->Map.find(key);
    if(i != this->Internal->Map.end())
      {
      if(value)
        {
        i->second = value;
        }
      else
        {
        this->Internal->Map.erase(i);
        }
      }
    else if(value)
      {
      this->Internal->Map[key] = value;
      }
    }
}

//----------------------------------------------------------------------------
vtkObjectBase* vtkInformation::GetAsObjectBase(vtkInformationKey* key)
{
  if(key)
    {
    vtkInformationInternals::MapType::const_iterator i =
      this->Internal->Map.find(key);
    if(i != this->Internal->Map.end())
      {
      return i->second.GetPointer();
      }
    }
  return 0;
}

//----------------------------------------------------------------------------
void vtkInformation::Clear()
{
  this->Copy(0);
}

//----------------------------------------------------------------------------
void vtkInformation::Copy(vtkInformation* from)
{
  if(from)
    {
    this->Internal->Map = from->Internal->Map;
    }
  else
    {
    this->Internal->Map.clear();
    }
}

//----------------------------------------------------------------------------
void vtkInformation::CopyEntry(vtkInformation* from, vtkInformationKey* key)
{
  key->Copy(from, this);
}

//----------------------------------------------------------------------------
void vtkInformation::CopyEntries(vtkInformation* from,
                                 vtkInformationKeyVectorKey* key)
{
  int numberOfKeys = from->Length(key);
  vtkInformationKey** keys = from->Get(key);
  for(int i=0; i < numberOfKeys; ++i)
    {
    this->CopyEntry(from, keys[i]);
    }
}

//----------------------------------------------------------------------------
#define VTK_INFORMATION_DEFINE_SCALAR_PROPERTY(name, type)                  \
  void vtkInformation::Set(vtkInformation##name##Key* key, type value)      \
    {                                                                       \
    key->Set(this, value);                                                  \
    }                                                                       \
  void vtkInformation::Remove(vtkInformation##name##Key* key)               \
    {                                                                       \
    key->Remove(this);                                                      \
    }                                                                       \
  type vtkInformation::Get(vtkInformation##name##Key* key)                  \
    {                                                                       \
    return key->Get(this);                                                  \
    }                                                                       \
  int vtkInformation::Has(vtkInformation##name##Key* key)                   \
    {                                                                       \
    return key->Has(this);                                                  \
    }
VTK_INFORMATION_DEFINE_SCALAR_PROPERTY(Integer, int);
VTK_INFORMATION_DEFINE_SCALAR_PROPERTY(String, const char*);
VTK_INFORMATION_DEFINE_SCALAR_PROPERTY(DataObject, vtkDataObject*);
VTK_INFORMATION_DEFINE_SCALAR_PROPERTY(Executive, vtkExecutive*);
VTK_INFORMATION_DEFINE_SCALAR_PROPERTY(Information, vtkInformation*);
VTK_INFORMATION_DEFINE_SCALAR_PROPERTY(InformationVector, vtkInformationVector*);
VTK_INFORMATION_DEFINE_SCALAR_PROPERTY(ObjectBase, vtkObjectBase*);
#undef VTK_INFORMATION_DEFINE_SCALAR_PROPERTY

//----------------------------------------------------------------------------
#define VTK_INFORMATION_DEFINE_VECTOR_PROPERTY(name, type)                  \
  void vtkInformation::Append(vtkInformation##name##VectorKey* key,         \
                              type value)                                   \
    {                                                                       \
    key->Append(this, value);                                               \
    }                                                                       \
  void vtkInformation::Set(vtkInformation##name##VectorKey* key,            \
                           type* value, int length)                         \
    {                                                                       \
    key->Set(this, value, length);                                          \
    }                                                                       \
  type* vtkInformation::Get(vtkInformation##name##VectorKey* key)           \
    {                                                                       \
    return key->Get(this);                                                  \
    }                                                                       \
  void vtkInformation::Get(vtkInformation##name##VectorKey* key,            \
                           type* value)                                     \
    {                                                                       \
    key->Get(this, value);                                                  \
    }                                                                       \
  int vtkInformation::Length(vtkInformation##name##VectorKey* key)          \
    {                                                                       \
    return key->Length(this);                                               \
    }                                                                       \
  void vtkInformation::Remove(vtkInformation##name##VectorKey* key)         \
    {                                                                       \
    key->Remove(this);                                                      \
    }                                                                       \
  int vtkInformation::Has(vtkInformation##name##VectorKey* key)             \
    {                                                                       \
    return key->Has(this);                                                  \
    }
VTK_INFORMATION_DEFINE_VECTOR_PROPERTY(Integer, int);
VTK_INFORMATION_DEFINE_VECTOR_PROPERTY(Key, vtkInformationKey*);
#undef VTK_INFORMATION_DEFINE_VECTOR_PROPERTY

//----------------------------------------------------------------------------
vtkInformationKey* vtkInformation::GetKey(vtkInformationKey* key)
{
  return key;
}

//----------------------------------------------------------------------------
vtkInformationKey* vtkInformation::GetKey(vtkInformationDataObjectKey* key)
{
  return key;
}

//----------------------------------------------------------------------------
vtkInformationKey* vtkInformation::GetKey(vtkInformationExecutiveKey* key)
{
  return key;
}

//----------------------------------------------------------------------------
vtkInformationKey* vtkInformation::GetKey(vtkInformationInformationKey* key)
{
  return key;
}

//----------------------------------------------------------------------------
vtkInformationKey* vtkInformation::GetKey(vtkInformationInformationVectorKey* key)
{
  return key;
}

//----------------------------------------------------------------------------
vtkInformationKey* vtkInformation::GetKey(vtkInformationIntegerKey* key)
{
  return key;
}

//----------------------------------------------------------------------------
vtkInformationKey* vtkInformation::GetKey(vtkInformationIntegerVectorKey* key)
{
  return key;
}

//----------------------------------------------------------------------------
vtkInformationKey* vtkInformation::GetKey(vtkInformationStringKey* key)
{
  return key;
}

//----------------------------------------------------------------------------
void vtkInformation::UnRegister(vtkObjectBase *o)
{
  int check = (this->GetReferenceCount() > 1);
  this->Superclass::UnRegister(o);
  if(check && !this->GarbageCollecting)
    {
    vtkGarbageCollector::Check(this);
    }
}

//----------------------------------------------------------------------------
void vtkInformation::ReportReferences(vtkGarbageCollector* collector)
{
  this->Superclass::ReportReferences(collector);
  vtkInformationInternals::MapType::const_iterator i;
  for(i=this->Internal->Map.begin(); i != this->Internal->Map.end(); ++i)
    {
    i->first->Report(this, collector);
    }
}

//----------------------------------------------------------------------------
void vtkInformation::GarbageCollectionStarting()
{
  this->GarbageCollecting = 1;
  this->Superclass::GarbageCollectionStarting();
}

//----------------------------------------------------------------------------
void vtkInformation::RemoveReferences()
{
  this->Internal->Map.clear();
  this->Superclass::RemoveReferences();
}
<commit_msg>BUG: Fixed Copy implementation to avoid deleting objects during copy.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkInformation.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkInformation.h"

#include "vtkGarbageCollector.h"
#include "vtkInformationDataObjectKey.h"
#include "vtkInformationExecutiveKey.h"
#include "vtkInformationInformationKey.h"
#include "vtkInformationInformationVectorKey.h"
#include "vtkInformationIntegerKey.h"
#include "vtkInformationIntegerVectorKey.h"
#include "vtkInformationKeyVectorKey.h"
#include "vtkInformationObjectBaseKey.h"
#include "vtkInformationStringKey.h"
#include "vtkObjectFactory.h"
#include "vtkSmartPointer.h"

#include <vtkstd/map>

vtkCxxRevisionMacro(vtkInformation, "1.1.2.4");
vtkStandardNewMacro(vtkInformation);

//----------------------------------------------------------------------------
class vtkInformationInternals
{
public:
  typedef vtkstd::map<vtkInformationKey*,
                      vtkSmartPointer<vtkObjectBase> > MapType;
  MapType Map;
};

//----------------------------------------------------------------------------
vtkInformation::vtkInformation()
{
  this->Internal = new vtkInformationInternals;
  this->GarbageCollecting = 0;
}

//----------------------------------------------------------------------------
vtkInformation::~vtkInformation()
{
  delete this->Internal;
}

//----------------------------------------------------------------------------
void vtkInformation::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
  vtkInformationInternals::MapType::const_iterator i;
  for(i=this->Internal->Map.begin(); i != this->Internal->Map.end(); ++i)
    {
    os << indent << i->first << ": " << i->second.GetPointer() << "\n";
    }
}

//----------------------------------------------------------------------------
void vtkInformation::SetAsObjectBase(vtkInformationKey* key,
                                     vtkObjectBase* value)
{
  if(key)
    {
    vtkInformationInternals::MapType::iterator i =
      this->Internal->Map.find(key);
    if(i != this->Internal->Map.end())
      {
      if(value)
        {
        i->second = value;
        }
      else
        {
        this->Internal->Map.erase(i);
        }
      }
    else if(value)
      {
      this->Internal->Map[key] = value;
      }
    }
}

//----------------------------------------------------------------------------
vtkObjectBase* vtkInformation::GetAsObjectBase(vtkInformationKey* key)
{
  if(key)
    {
    vtkInformationInternals::MapType::const_iterator i =
      this->Internal->Map.find(key);
    if(i != this->Internal->Map.end())
      {
      return i->second.GetPointer();
      }
    }
  return 0;
}

//----------------------------------------------------------------------------
void vtkInformation::Clear()
{
  this->Copy(0);
}

//----------------------------------------------------------------------------
void vtkInformation::Copy(vtkInformation* from)
{
  vtkInformationInternals* oldInternal = this->Internal;
  this->Internal = new vtkInformationInternals;
  if(from)
    {
    vtkInformationInternals::MapType::const_iterator i;
    for(i=from->Internal->Map.begin(); i != from->Internal->Map.end(); ++i)
      {
      this->CopyEntry(from, i->first);
      }
    }
  delete oldInternal;
}

//----------------------------------------------------------------------------
void vtkInformation::CopyEntry(vtkInformation* from, vtkInformationKey* key)
{
  key->Copy(from, this);
}

//----------------------------------------------------------------------------
void vtkInformation::CopyEntries(vtkInformation* from,
                                 vtkInformationKeyVectorKey* key)
{
  int numberOfKeys = from->Length(key);
  vtkInformationKey** keys = from->Get(key);
  for(int i=0; i < numberOfKeys; ++i)
    {
    this->CopyEntry(from, keys[i]);
    }
}

//----------------------------------------------------------------------------
#define VTK_INFORMATION_DEFINE_SCALAR_PROPERTY(name, type)                  \
  void vtkInformation::Set(vtkInformation##name##Key* key, type value)      \
    {                                                                       \
    key->Set(this, value);                                                  \
    }                                                                       \
  void vtkInformation::Remove(vtkInformation##name##Key* key)               \
    {                                                                       \
    key->Remove(this);                                                      \
    }                                                                       \
  type vtkInformation::Get(vtkInformation##name##Key* key)                  \
    {                                                                       \
    return key->Get(this);                                                  \
    }                                                                       \
  int vtkInformation::Has(vtkInformation##name##Key* key)                   \
    {                                                                       \
    return key->Has(this);                                                  \
    }
VTK_INFORMATION_DEFINE_SCALAR_PROPERTY(Integer, int);
VTK_INFORMATION_DEFINE_SCALAR_PROPERTY(String, const char*);
VTK_INFORMATION_DEFINE_SCALAR_PROPERTY(DataObject, vtkDataObject*);
VTK_INFORMATION_DEFINE_SCALAR_PROPERTY(Executive, vtkExecutive*);
VTK_INFORMATION_DEFINE_SCALAR_PROPERTY(Information, vtkInformation*);
VTK_INFORMATION_DEFINE_SCALAR_PROPERTY(InformationVector, vtkInformationVector*);
VTK_INFORMATION_DEFINE_SCALAR_PROPERTY(ObjectBase, vtkObjectBase*);
#undef VTK_INFORMATION_DEFINE_SCALAR_PROPERTY

//----------------------------------------------------------------------------
#define VTK_INFORMATION_DEFINE_VECTOR_PROPERTY(name, type)                  \
  void vtkInformation::Append(vtkInformation##name##VectorKey* key,         \
                              type value)                                   \
    {                                                                       \
    key->Append(this, value);                                               \
    }                                                                       \
  void vtkInformation::Set(vtkInformation##name##VectorKey* key,            \
                           type* value, int length)                         \
    {                                                                       \
    key->Set(this, value, length);                                          \
    }                                                                       \
  type* vtkInformation::Get(vtkInformation##name##VectorKey* key)           \
    {                                                                       \
    return key->Get(this);                                                  \
    }                                                                       \
  void vtkInformation::Get(vtkInformation##name##VectorKey* key,            \
                           type* value)                                     \
    {                                                                       \
    key->Get(this, value);                                                  \
    }                                                                       \
  int vtkInformation::Length(vtkInformation##name##VectorKey* key)          \
    {                                                                       \
    return key->Length(this);                                               \
    }                                                                       \
  void vtkInformation::Remove(vtkInformation##name##VectorKey* key)         \
    {                                                                       \
    key->Remove(this);                                                      \
    }                                                                       \
  int vtkInformation::Has(vtkInformation##name##VectorKey* key)             \
    {                                                                       \
    return key->Has(this);                                                  \
    }
VTK_INFORMATION_DEFINE_VECTOR_PROPERTY(Integer, int);
VTK_INFORMATION_DEFINE_VECTOR_PROPERTY(Key, vtkInformationKey*);
#undef VTK_INFORMATION_DEFINE_VECTOR_PROPERTY

//----------------------------------------------------------------------------
vtkInformationKey* vtkInformation::GetKey(vtkInformationKey* key)
{
  return key;
}

//----------------------------------------------------------------------------
vtkInformationKey* vtkInformation::GetKey(vtkInformationDataObjectKey* key)
{
  return key;
}

//----------------------------------------------------------------------------
vtkInformationKey* vtkInformation::GetKey(vtkInformationExecutiveKey* key)
{
  return key;
}

//----------------------------------------------------------------------------
vtkInformationKey* vtkInformation::GetKey(vtkInformationInformationKey* key)
{
  return key;
}

//----------------------------------------------------------------------------
vtkInformationKey* vtkInformation::GetKey(vtkInformationInformationVectorKey* key)
{
  return key;
}

//----------------------------------------------------------------------------
vtkInformationKey* vtkInformation::GetKey(vtkInformationIntegerKey* key)
{
  return key;
}

//----------------------------------------------------------------------------
vtkInformationKey* vtkInformation::GetKey(vtkInformationIntegerVectorKey* key)
{
  return key;
}

//----------------------------------------------------------------------------
vtkInformationKey* vtkInformation::GetKey(vtkInformationStringKey* key)
{
  return key;
}

//----------------------------------------------------------------------------
void vtkInformation::UnRegister(vtkObjectBase *o)
{
  int check = (this->GetReferenceCount() > 1);
  this->Superclass::UnRegister(o);
  if(check && !this->GarbageCollecting)
    {
    vtkGarbageCollector::Check(this);
    }
}

//----------------------------------------------------------------------------
void vtkInformation::ReportReferences(vtkGarbageCollector* collector)
{
  this->Superclass::ReportReferences(collector);
  vtkInformationInternals::MapType::const_iterator i;
  for(i=this->Internal->Map.begin(); i != this->Internal->Map.end(); ++i)
    {
    i->first->Report(this, collector);
    }
}

//----------------------------------------------------------------------------
void vtkInformation::GarbageCollectionStarting()
{
  this->GarbageCollecting = 1;
  this->Superclass::GarbageCollectionStarting();
}

//----------------------------------------------------------------------------
void vtkInformation::RemoveReferences()
{
  this->Internal->Map.clear();
  this->Superclass::RemoveReferences();
}
<|endoftext|>


<commit_before>#include "TiledMapLoader.h"

#include "cocos2d.h"

using namespace cocos2d;

namespace avalon {
namespace io {

TiledMapLoader::TiledMapLoader(const std::string& mapFileName)
: mapFileName(mapFileName)
{
}

void TiledMapLoader::setBox2dContainer(avalon::physics::Box2dContainer& container)
{
    box2dContainer = &container;
}

bool TiledMapLoader::isFiltered(const std::string& name, const std::list<std::string>& filter)
{
    if (filter.empty()) {
        return false;
    }

    auto iter = std::find(filter.begin(), filter.end(), name);
    if (iter == filter.end()) {
        return true;
    }

    return false;
}

cocos2d::TMXTiledMap* TiledMapLoader::load()
{
    auto map = TMXTiledMap::create(mapFileName.c_str());
    if (!map) {
        throw std::invalid_argument("Mapfile not found!");
    }

    loadGidFactories(*map);
    loadNamedFactories(*map);

    return map;
}

void TiledMapLoader::loadGidFactories(cocos2d::TMXTiledMap& map)
{
    for (auto& child : map.getChildren()) {
        auto mapLayer = dynamic_cast<TMXLayer*>(child);
        if (!mapLayer) {
            continue;
        }
        for (int x = 0; x < map.getMapSize().width; ++x) {
            for (int y = 0; y < map.getMapSize().height; ++y) {

                auto currentGID = mapLayer->getTileGIDAt({x, y});

                if (!gidFactories.count(currentGID)) {
                    continue;
                }

                auto info = map.getPropertiesForGID(currentGID);
                auto data = info.asValueMap();

                if (!data.count("gid")) data["gid"] = cocos2d::Value(currentGID);
                if (!data.count("x")) data["x"] = cocos2d::Value(static_cast<float>(x));
                if (!data.count("y")) data["y"] = cocos2d::Value(static_cast<float>(y));

                Configuration config{data, mapLayer->getLayerName(), map, box2dContainer};
                for (auto& callback : gidFactories.at(currentGID)) {
                    callback(config);
                }
            }
        }
    }
}

void TiledMapLoader::loadNamedFactories(cocos2d::TMXTiledMap& map)
{
    for (auto& arrayElement : map.getObjectGroups()) {
        auto objectGroup = dynamic_cast<TMXObjectGroup*>(arrayElement);
        if (!objectGroup) {
            continue;
        }

        for (auto& value : objectGroup->getObjects()) {
            auto valueMap = value.asValueMap();
            if (valueMap.empty())
                continue;

            if (!valueMap.count("name")) {
                continue;
            }

            auto name = valueMap["name"].asString();
            if (!nameFactories.count(name)) {
                continue;
            }

            Configuration config{valueMap, objectGroup->getGroupName(), map, box2dContainer};
            for (auto& callback : nameFactories.at(name)) {
                callback(config);
            }
        }
    }
}

void TiledMapLoader::registerCallbackForName(const std::string& name, const Callback& callback, const std::list<std::string>& layerFilter)
{
    if (!nameFactories.count(name)) {
        nameFactories[name] = CallbackList();
    }

    nameFactories[name].push_back([this, callback, layerFilter](const Configuration& config) {
        if (!isFiltered(config.layer, layerFilter)) {
            callback(config);
        }
    });
}

void TiledMapLoader::registerCallbackForGID(const int gid, const Callback& callback, const std::list<std::string>& layerFilter)
{
    if (!gidFactories.count(gid)) {
        gidFactories[gid] = CallbackList();
    }

    gidFactories[gid].push_back([this, callback, layerFilter](const Configuration& config) {
        if (!isFiltered(config.layer, layerFilter)) {
            callback(config);
        }
    });
}

} // namespace io
} // namespace avalon
<commit_msg>re-use Value object in TiledMapLoader::loadGidFactories<commit_after>#include "TiledMapLoader.h"

#include "cocos2d.h"

using namespace cocos2d;

namespace avalon {
namespace io {

TiledMapLoader::TiledMapLoader(const std::string& mapFileName)
: mapFileName(mapFileName)
{
}

void TiledMapLoader::setBox2dContainer(avalon::physics::Box2dContainer& container)
{
    box2dContainer = &container;
}

bool TiledMapLoader::isFiltered(const std::string& name, const std::list<std::string>& filter)
{
    if (filter.empty()) {
        return false;
    }

    auto iter = std::find(filter.begin(), filter.end(), name);
    if (iter == filter.end()) {
        return true;
    }

    return false;
}

cocos2d::TMXTiledMap* TiledMapLoader::load()
{
    auto map = TMXTiledMap::create(mapFileName.c_str());
    if (!map) {
        throw std::invalid_argument("Mapfile not found!");
    }

    loadGidFactories(*map);
    loadNamedFactories(*map);

    return map;
}

void TiledMapLoader::loadGidFactories(cocos2d::TMXTiledMap& map)
{
    Value* info = nullptr;

    for (auto& child : map.getChildren()) {
        auto mapLayer = dynamic_cast<TMXLayer*>(child);
        if (!mapLayer) {
            continue;
        }

        for (int x = 0; x < map.getMapSize().width; ++x) {
            for (int y = 0; y < map.getMapSize().height; ++y) {

                auto currentGID = mapLayer->getTileGIDAt({x, y});
                if (!gidFactories.count(currentGID)) {
                    continue;
                }

                map.getPropertiesForGID(currentGID, &info);
                auto data = info->asValueMap();

                if (!data.count("gid")) data["gid"] = Value(static_cast<int>(currentGID));
                if (!data.count("x")) data["x"] = Value(static_cast<float>(x));
                if (!data.count("y")) data["y"] = Value(static_cast<float>(y));

                Configuration config{data, mapLayer->getLayerName(), map, box2dContainer};
                for (auto& callback : gidFactories.at(currentGID)) {
                    callback(config);
                }
            }
        }
    }
}

void TiledMapLoader::loadNamedFactories(cocos2d::TMXTiledMap& map)
{
    for (auto& arrayElement : map.getObjectGroups()) {
        auto objectGroup = dynamic_cast<TMXObjectGroup*>(arrayElement);
        if (!objectGroup) {
            continue;
        }

        for (auto& value : objectGroup->getObjects()) {
            auto valueMap = value.asValueMap();
            if (valueMap.empty())
                continue;

            if (!valueMap.count("name")) {
                continue;
            }

            auto name = valueMap["name"].asString();
            if (!nameFactories.count(name)) {
                continue;
            }

            Configuration config{valueMap, objectGroup->getGroupName(), map, box2dContainer};
            for (auto& callback : nameFactories.at(name)) {
                callback(config);
            }
        }
    }
}

void TiledMapLoader::registerCallbackForName(const std::string& name, const Callback& callback, const std::list<std::string>& layerFilter)
{
    if (!nameFactories.count(name)) {
        nameFactories[name] = CallbackList();
    }

    nameFactories[name].push_back([this, callback, layerFilter](const Configuration& config) {
        if (!isFiltered(config.layer, layerFilter)) {
            callback(config);
        }
    });
}

void TiledMapLoader::registerCallbackForGID(const int gid, const Callback& callback, const std::list<std::string>& layerFilter)
{
    if (!gidFactories.count(gid)) {
        gidFactories[gid] = CallbackList();
    }

    gidFactories[gid].push_back([this, callback, layerFilter](const Configuration& config) {
        if (!isFiltered(config.layer, layerFilter)) {
            callback(config);
        }
    });
}

} // namespace io
} // namespace avalon
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014, Georgia Tech Research Corporation
 * All rights reserved.
 *
 * Author: Luke Tornquist <luke.tornquist@gatech.edu>
 * Date: Jan 2014
 *
 * Humanoid Robotics Lab      Georgia Institute of Technology
 * Director: Mike Stilman     http://www.golems.org
 *
 *
 * This file is provided under the following "BSD-style" License:
 *   Redistribution and use in source and binary forms, with or
 *   without modification, are permitted provided that the following
 *   conditions are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *
 *   * Neither the name of the Humanoid Robotics Lab nor the names of
 *     its contributors may be used to endorse or promote products
 *     derived from this software without specific prior written
 *     permission
 *
 *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 *   CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 *   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 *   MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 *   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 *   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 *   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 *   AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *   LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *   ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *   POSSIBILITY OF SUCH DAMAGE.
 */

#include "main.h"

using namespace std;
using namespace fsp;
using namespace Eigen;

///
/// \brief main
/// \return
///
int main()
{
    // Initialize random seed
    srand(time(NULL));

    // Initialize the feet
    //vector<Foot> feet;
    FEET.push_back(Foot(2.0f, 4.0f, "Left"));
    FEET.push_back(Foot(2.0f, 4.0f, "Right"));

    // Initialize the foot constraints
    vector<FootConstraint> constraints;
    constraints.push_back(FootConstraint(0, 1, 2.0d, 4.0d, -4.0d, 4.0d, -25.0d, 30.0d));
    constraints.push_back(FootConstraint(1, 0, 2.0d, 4.0d, -4.0d, 4.0d, -25.0d, 30.0d));

    // Initialize the current location
    vector<FootLocation> currentLoc;
    currentLoc.push_back(FootLocation(Vector2d(0.0d, 3.0d), 0.0f, 0, &FEET));
    currentLoc.push_back(FootLocation(Vector2d(0.0d, 0.0d), 0.0f, 1, &FEET));

    // Initialize the goal location
    vector<FootLocation> goalLoc;
    goalLoc.push_back(FootLocation(Vector2d(67.0d, 3.0d), 0.0f, 0, &FEET));
    goalLoc.push_back(FootLocation(Vector2d(67.0d, 0.0d), 0.0f, 1, &FEET));

    // Initialize the obstacles
    vector<Line> obs;
    // First obstacle
    obs.push_back(Line(Vector2d(-10.0d, 7.0d), Vector2d(55.0d, 18.0d)));
    obs.push_back(Line(Vector2d(55.0d, 18.0d), Vector2d(0.0d, 23.0d)));
    obs.push_back(Line(Vector2d(0.0d, 23.0d), Vector2d(-10.0d, 7.0d)));
    // Second obstacle
    obs.push_back(Line(Vector2d(20.0d, -7.0d), Vector2d(25.0d, -38.0d)));
    obs.push_back(Line(Vector2d(25.0d, -38.0d), Vector2d(25.0d, -50.0d)));
    obs.push_back(Line(Vector2d(25.0d, -50.0d), Vector2d(10.0d, -17.0d)));
    obs.push_back(Line(Vector2d(10.0d, -17.0d), Vector2d(20.0d, -7.0d)));

    // Initialize the planner
    FootstepPlanner planner(FEET);
    //vector<FootLocation> plan = planner.getStaticPlan();
    vector<FootLocation> plan2 = planner.generatePlan(PLANNER_TYPE_RRT, constraints, currentLoc, goalLoc, obs);
    //vector<FootLocation> plan3 = planner.generatePlan(PLANNER_TYPE_R_STAR, constraints, currentLoc, goalLoc, obs);

    // Initialize the visualizer
    FootstepPlanVisualizer visualizer(FEET);
    visualizer.visualizePlanUsingTransform(currentLoc, goalLoc, obs, plan2);
    //visualizePlan(currentLoc, goalLoc, obs, plan);
    return 0;
}
<commit_msg>-Remove call to RRT planner as it's unfinished<commit_after>/*
 * Copyright (c) 2014, Georgia Tech Research Corporation
 * All rights reserved.
 *
 * Author: Luke Tornquist <luke.tornquist@gatech.edu>
 * Date: Jan 2014
 *
 * Humanoid Robotics Lab      Georgia Institute of Technology
 * Director: Mike Stilman     http://www.golems.org
 *
 *
 * This file is provided under the following "BSD-style" License:
 *   Redistribution and use in source and binary forms, with or
 *   without modification, are permitted provided that the following
 *   conditions are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *
 *   * Neither the name of the Humanoid Robotics Lab nor the names of
 *     its contributors may be used to endorse or promote products
 *     derived from this software without specific prior written
 *     permission
 *
 *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 *   CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 *   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 *   MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 *   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 *   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 *   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 *   AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *   LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *   ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *   POSSIBILITY OF SUCH DAMAGE.
 */

#include "main.h"

using namespace std;
using namespace fsp;
using namespace Eigen;

///
/// \brief main
/// \return
///
int main()
{
    // Initialize random seed
    srand(time(NULL));

    // Initialize the feet
    //vector<Foot> feet;
    FEET.push_back(Foot(2.0f, 4.0f, "Left"));
    FEET.push_back(Foot(2.0f, 4.0f, "Right"));

    // Initialize the foot constraints
    vector<FootConstraint> constraints;
    constraints.push_back(FootConstraint(0, 1, 2.0d, 4.0d, -4.0d, 4.0d, -25.0d, 30.0d));
    constraints.push_back(FootConstraint(1, 0, 2.0d, 4.0d, -4.0d, 4.0d, -25.0d, 30.0d));

    // Initialize the current location
    vector<FootLocation> currentLoc;
    currentLoc.push_back(FootLocation(Vector2d(0.0d, 3.0d), 0.0f, 0, &FEET));
    currentLoc.push_back(FootLocation(Vector2d(0.0d, 0.0d), 0.0f, 1, &FEET));

    // Initialize the goal location
    vector<FootLocation> goalLoc;
    goalLoc.push_back(FootLocation(Vector2d(67.0d, 3.0d), 0.0f, 0, &FEET));
    goalLoc.push_back(FootLocation(Vector2d(67.0d, 0.0d), 0.0f, 1, &FEET));

    // Initialize the obstacles
    vector<Line> obs;
    // First obstacle
    obs.push_back(Line(Vector2d(-10.0d, 7.0d), Vector2d(55.0d, 18.0d)));
    obs.push_back(Line(Vector2d(55.0d, 18.0d), Vector2d(0.0d, 23.0d)));
    obs.push_back(Line(Vector2d(0.0d, 23.0d), Vector2d(-10.0d, 7.0d)));
    // Second obstacle
    obs.push_back(Line(Vector2d(20.0d, -7.0d), Vector2d(25.0d, -38.0d)));
    obs.push_back(Line(Vector2d(25.0d, -38.0d), Vector2d(25.0d, -50.0d)));
    obs.push_back(Line(Vector2d(25.0d, -50.0d), Vector2d(10.0d, -17.0d)));
    obs.push_back(Line(Vector2d(10.0d, -17.0d), Vector2d(20.0d, -7.0d)));

    // Initialize the planner
    FootstepPlanner planner(FEET);
    vector<FootLocation> plan = planner.getStaticPlan();
    //vector<FootLocation> plan = planner.generatePlan(PLANNER_TYPE_RRT, constraints, currentLoc, goalLoc, obs);
    //vector<FootLocation> plan = planner.generatePlan(PLANNER_TYPE_R_STAR, constraints, currentLoc, goalLoc, obs);

    // Initialize the visualizer
    FootstepPlanVisualizer visualizer(FEET);
    visualizer.visualizePlanUsingTransform(currentLoc, goalLoc, obs, plan);
    //visualizePlan(currentLoc, goalLoc, obs, plan);
    return 0;
}
<|endoftext|>


<commit_before>// -------------------------------------------------------------------------
//    @FileName      :    NFCPluginManager.cpp
//    @Author           :    LvSheng.Huang
//    @Date             :    2012-12-15
//    @Module           :    NFCPluginManager
//
// -------------------------------------------------------------------------

//#include "stdafx.h"
#include "NFCPluginManager.h"
#include "NFComm/RapidXML/rapidxml.hpp"
#include "NFComm/RapidXML/rapidxml_iterators.hpp"
#include "NFComm/RapidXML/rapidxml_print.hpp"
#include "NFComm/RapidXML/rapidxml_utils.hpp"
#include "NFComm/NFPluginModule/NFIPlugin.h"
#include "NFComm/NFPluginModule/NFIActorDataModule.h"
#include "NFComm/NFPluginModule/NFPlatform.h"

#pragma comment( lib, "ws2_32.lib" )

#ifdef NF_DEBUG_MODE

#if NF_PLATFORM == NF_PLATFORM_WIN
#pragma comment( lib, "Theron_d.lib" )
#elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID
#pragma comment( lib, "Theron_d.a" )
#elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS
#pragma comment( lib, "Theron_d.a" )
#endif

#else

#if NF_PLATFORM == NF_PLATFORM_WIN
#pragma comment( lib, "Theron.lib" )
#elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID
#pragma comment( lib, "Theron.a" )
#elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS
#pragma comment( lib, "Theron.a" )
#endif

#endif

bool NFCPluginManager::LoadPlugin()
{
    rapidxml::file<> fdoc( "Plugin.xml" );
    rapidxml::xml_document<>  doc;
    doc.parse<0>( fdoc.data() );

    rapidxml::xml_node<>* pRoot = doc.first_node();
    for ( rapidxml::xml_node<>* pPluginNode = pRoot->first_node("Plugin"); pPluginNode; pPluginNode = pPluginNode->next_sibling("Plugin") )
    {
        const char* strPluginName = pPluginNode->first_attribute( "Name" )->value();
        const char* strMain = pPluginNode->first_attribute( "Main" )->value();

		mPluginNameMap.insert(PluginNameMap::value_type(strPluginName, true));

    }

    rapidxml::xml_node<>* pPluginAppNode = pRoot->first_node("APPID");
    if (!pPluginAppNode)
    {
        NFASSERT(0, "There are no App ID", __FILE__, __FUNCTION__);
        return false;
    }

    const char* strAppID = pPluginAppNode->first_attribute( "Name" )->value();
    if (!strAppID)
    {
        NFASSERT(0, "There are no App ID", __FILE__, __FUNCTION__);
        return false;
    }

    if (!NF_StrTo(strAppID, mnAppID))
    {
        NFASSERT(0, "App ID Convert Error", __FILE__, __FUNCTION__);
        return false;
    }

    return true;
}

void NFCPluginManager::Registered(NFIPlugin* plugin)
{
    std::string strPluginName = plugin->GetPluginName();
    if (!FindPlugin(strPluginName))
    {
        bool bFind = false;
        PluginNameMap::iterator it = mPluginNameMap.begin();
        for (it; it != mPluginNameMap.end(); ++it)
        {
            if (strPluginName == it->first)
            {
                bFind = true;
                break;
            }
        }

        if (bFind)
        {
            mPluginInstanceMap.insert(PluginInstanceMap::value_type(strPluginName, plugin));
            plugin->Install();
        }
    }

}

void NFCPluginManager::UnsRegistered(NFIPlugin* plugin)
{
    PluginInstanceMap::iterator it = mPluginInstanceMap.find(plugin->GetPluginName());
    if (it != mPluginInstanceMap.end())
    {
        it->second->Uninstall();
		delete it->second;
        it->second = NULL;
        mPluginInstanceMap.erase(it);
    }
}

NFIPlugin* NFCPluginManager::FindPlugin(const std::string& strPluginName)
{
    PluginInstanceMap::iterator it = mPluginInstanceMap.find(strPluginName);
    if (it != mPluginInstanceMap.end())
    {
        return it->second;
    }

    return NULL;
}

bool NFCPluginManager::Execute(const float fLasFrametime, const float fStartedTime)
{
    bool bRet = true;

    PluginInstanceMap::iterator it = mPluginInstanceMap.begin();
    for (; it != mPluginInstanceMap.end(); ++it)
    {
        bool tembRet = it->second->Execute(fLasFrametime, fStartedTime);
        bRet = bRet && tembRet;
    }

	ExecuteEvent();

    return bRet;
}

void NFCPluginManager::AddModule(const std::string& strModuleName, NFILogicModule* pModule)
{
    if (!FindModule(strModuleName))
    {
        mModuleInstanceMap.insert(ModuleInstanceMap::value_type(strModuleName, pModule));
    }
}

void NFCPluginManager::RemoveModule(const std::string& strModuleName)
{
    ModuleInstanceMap::iterator it = mModuleInstanceMap.find(strModuleName);
    if (it != mModuleInstanceMap.end())
    {
        mModuleInstanceMap.erase(it);
    }
}

NFILogicModule* NFCPluginManager::FindModule(const std::string& strModuleName)
{
    ModuleInstanceMap::iterator it = mModuleInstanceMap.find(strModuleName);
    if (it != mModuleInstanceMap.end())
    {
        return it->second;
    }
    return NULL;
}

bool NFCPluginManager::Init()
{
#ifdef NF_DYNAMIC_PLUGIN
    LoadPlugin();

#if NF_PLATFORM == NF_PLATFORM_WIN || NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_APPLE
    PluginNameMap::iterator it = mPluginNameMap.begin();
    for (it; it != mPluginNameMap.end(); ++it)
    {
        LoadPluginLibrary(it->first);
    }

#endif

#else
    //     PluginNameList::iterator it = mPluginNameList.begin();
    //     for (it; it != mPluginNameList.end(); it++)
    //     {
    //         const std::string& strPluginName = *it;
    //         CREATE_PLUGIN( this, strPluginName );
    //     }

    //     CREATE_PLUGIN(this, NFKernelPlugin)
    //     CREATE_PLUGIN(this, NFEventProcessPlugin)
    //     CREATE_PLUGIN(this, NFConfigPlugin)

#endif

    PluginInstanceMap::iterator itInstance = mPluginInstanceMap.begin();
    for (itInstance; itInstance != mPluginInstanceMap.end(); itInstance++)
    {
        itInstance->second->Init();
    }

    return true;
}

bool NFCPluginManager::AfterInit()
{
    PluginInstanceMap::iterator itAfterInstance = mPluginInstanceMap.begin();
    for (itAfterInstance; itAfterInstance != mPluginInstanceMap.end(); itAfterInstance++)
    {
        itAfterInstance->second->AfterInit();
    }

    return true;
}

bool NFCPluginManager::CheckConfig()
{
    PluginInstanceMap::iterator itCheckInstance = mPluginInstanceMap.begin();
    for (itCheckInstance; itCheckInstance != mPluginInstanceMap.end(); itCheckInstance++)
    {
        itCheckInstance->second->CheckConfig();
    }

    return true;
}

bool NFCPluginManager::BeforeShut()
{
    PluginInstanceMap::iterator itBeforeInstance = mPluginInstanceMap.begin();
    for (itBeforeInstance; itBeforeInstance != mPluginInstanceMap.end(); itBeforeInstance++)
    {
        itBeforeInstance->second->BeforeShut();
    }

    return true;
}

bool NFCPluginManager::Shut()
{

    PluginInstanceMap::iterator itInstance = mPluginInstanceMap.begin();
    for (itInstance; itInstance != mPluginInstanceMap.end(); ++itInstance)
    {
        itInstance->second->Shut();
    }

#ifdef NF_DYNAMIC_PLUGIN

    PluginNameMap::iterator it = mPluginNameMap.begin();
    for (it; it != mPluginNameMap.end(); it++)
    {
        UnLoadPluginLibrary(it->first);
    }

#else

    //     DESTROY_PLUGIN(this, NFConfigPlugin)
    //     DESTROY_PLUGIN(this, NFEventProcessPlugin)
    //     DESTROY_PLUGIN(this, NFKernelPlugin)

#endif
	mPluginInstanceMap.clear();
    mPluginNameMap.clear();
	return true;
}

bool NFCPluginManager::LoadPluginLibrary(const std::string& strPluginDLLName)
{
    PluginLibMap::iterator it = mPluginLibMap.find(strPluginDLLName);
    if (it == mPluginLibMap.end())
    {
        NFCDynLib* pLib = new NFCDynLib(strPluginDLLName);
        bool bLoad = pLib->Load();

        if (bLoad)
        {
            mPluginLibMap.insert(PluginLibMap::value_type(strPluginDLLName, pLib));

            DLL_START_PLUGIN_FUNC pFunc = (DLL_START_PLUGIN_FUNC)pLib->GetSymbol("DllStartPlugin");
            if (!pFunc)
            {
                std::cout << "Find function DllStartPlugin Failed in [" << pLib->GetName() << "]" << std::endl;
                assert(0);
                return false;
            }

            pFunc(this);

            return true;
        }
        else
        {
#if NF_PLATFORM == NF_PLATFORM_LINUX
            char* error = dlerror();
            if (error)
            {
				std::cout << stderr << " Open shared lib failed " << pLib->GetName() << " " << error << std::endl;
                assert(0);
                return false;
            }
#elif NF_PLATFORM == NF_PLATFORM_WIN
            std::cout << stderr << " Open DLL " << pLib->GetName() << " failed, ErrorNo = "<< GetLastError();
#endif // NF_PLATFORM
            std::cout << "Load [" << pLib->GetName() << "] Failed" << std::endl;
            assert(0);
        }
    }

    return false;
}

bool NFCPluginManager::UnLoadPluginLibrary(const std::string& strPluginDLLName)
{
    PluginLibMap::iterator it = mPluginLibMap.find(strPluginDLLName);
    if (it != mPluginLibMap.end())
    {
        NFCDynLib* pLib = it->second;

        DLL_STOP_PLUGIN_FUNC pFunc = (DLL_STOP_PLUGIN_FUNC)pLib->GetSymbol("DllStopPlugin");

        if (pFunc)
        {
            pFunc(this);
        }

        pLib->UnLoad();

        delete pLib;
        pLib = NULL;
        mPluginLibMap.erase(it);

        return true;
    }

    return false;
}

bool NFCPluginManager::ReInitialize()
{
    PluginInstanceMap::iterator itBeforeInstance = mPluginInstanceMap.begin();
    for ( itBeforeInstance; itBeforeInstance != mPluginInstanceMap.end(); itBeforeInstance++ )
    {
        itBeforeInstance->second->BeforeShut();
    }

    PluginInstanceMap::iterator itShutDownInstance = mPluginInstanceMap.begin();
    for ( itShutDownInstance; itShutDownInstance != mPluginInstanceMap.end(); itShutDownInstance++ )
    {
        itShutDownInstance->second->Shut();
    }

    PluginInstanceMap::iterator itInstance = mPluginInstanceMap.begin();
    for ( itInstance; itInstance != mPluginInstanceMap.end(); itInstance++ )
    {
        itInstance->second->Init();
    }

    PluginInstanceMap::iterator itAfterInstance = mPluginInstanceMap.begin();
    for ( ; itAfterInstance != mPluginInstanceMap.end(); itAfterInstance++ )
    {
        itAfterInstance->second->AfterInit();
    }

    PluginInstanceMap::iterator itCheckInstance = mPluginInstanceMap.begin();
    for (itCheckInstance; itCheckInstance != mPluginInstanceMap.end(); itCheckInstance++)
    {
        itCheckInstance->second->CheckConfig();
    }

    return true;
}

void NFCPluginManager::HandlerEx( const NFIActorMessage& message, const Theron::Address from )
{
	//ӵУÿִ֡
	mxQueue.Push(message);
}

bool NFCPluginManager::ExecuteEvent()
{
	NFIActorMessage xMsg;
	bool bRet = false;
	bRet = mxQueue.Pop(xMsg);
	while (bRet)
	{
		if (xMsg.eType == NFIActorMessage::EACTOR_RETURN_EVENT_MSG)
		{
			xMsg.xActorEventFunc->xEndFuncptr->operator()(xMsg.self, xMsg.nFormActor, xMsg.nSubMsgID, xMsg.data);
		}

		bRet = mxQueue.Pop(xMsg);
	}

	return true;
}
<commit_msg>release actor<commit_after>// -------------------------------------------------------------------------
//    @FileName      :    NFCPluginManager.cpp
//    @Author           :    LvSheng.Huang
//    @Date             :    2012-12-15
//    @Module           :    NFCPluginManager
//
// -------------------------------------------------------------------------

//#include "stdafx.h"
#include "NFCPluginManager.h"
#include "NFComm/RapidXML/rapidxml.hpp"
#include "NFComm/RapidXML/rapidxml_iterators.hpp"
#include "NFComm/RapidXML/rapidxml_print.hpp"
#include "NFComm/RapidXML/rapidxml_utils.hpp"
#include "NFComm/NFPluginModule/NFIPlugin.h"
#include "NFComm/NFPluginModule/NFIActorDataModule.h"
#include "NFComm/NFPluginModule/NFPlatform.h"

#pragma comment( lib, "ws2_32.lib" )

#ifdef NF_DEBUG_MODE

#if NF_PLATFORM == NF_PLATFORM_WIN
#pragma comment( lib, "Theron_d.lib" )
#elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID
#pragma comment( lib, "Theron_d.a" )
#elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS
#pragma comment( lib, "Theron_d.a" )
#endif

#else

#if NF_PLATFORM == NF_PLATFORM_WIN
#pragma comment( lib, "Theron.lib" )
#elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID
#pragma comment( lib, "Theron.a" )
#elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS
#pragma comment( lib, "Theron.a" )
#endif

#endif

bool NFCPluginManager::LoadPlugin()
{
    rapidxml::file<> fdoc( "Plugin.xml" );
    rapidxml::xml_document<>  doc;
    doc.parse<0>( fdoc.data() );

    rapidxml::xml_node<>* pRoot = doc.first_node();
    for ( rapidxml::xml_node<>* pPluginNode = pRoot->first_node("Plugin"); pPluginNode; pPluginNode = pPluginNode->next_sibling("Plugin") )
    {
        const char* strPluginName = pPluginNode->first_attribute( "Name" )->value();
        const char* strMain = pPluginNode->first_attribute( "Main" )->value();

		mPluginNameMap.insert(PluginNameMap::value_type(strPluginName, true));

    }

    rapidxml::xml_node<>* pPluginAppNode = pRoot->first_node("APPID");
    if (!pPluginAppNode)
    {
        NFASSERT(0, "There are no App ID", __FILE__, __FUNCTION__);
        return false;
    }

    const char* strAppID = pPluginAppNode->first_attribute( "Name" )->value();
    if (!strAppID)
    {
        NFASSERT(0, "There are no App ID", __FILE__, __FUNCTION__);
        return false;
    }

    if (!NF_StrTo(strAppID, mnAppID))
    {
        NFASSERT(0, "App ID Convert Error", __FILE__, __FUNCTION__);
        return false;
    }

    return true;
}

void NFCPluginManager::Registered(NFIPlugin* plugin)
{
    std::string strPluginName = plugin->GetPluginName();
    if (!FindPlugin(strPluginName))
    {
        bool bFind = false;
        PluginNameMap::iterator it = mPluginNameMap.begin();
        for (it; it != mPluginNameMap.end(); ++it)
        {
            if (strPluginName == it->first)
            {
                bFind = true;
                break;
            }
        }

        if (bFind)
        {
            mPluginInstanceMap.insert(PluginInstanceMap::value_type(strPluginName, plugin));
            plugin->Install();
        }
    }

}

void NFCPluginManager::UnsRegistered(NFIPlugin* plugin)
{
    PluginInstanceMap::iterator it = mPluginInstanceMap.find(plugin->GetPluginName());
    if (it != mPluginInstanceMap.end())
    {
        it->second->Uninstall();
		delete it->second;
        it->second = NULL;
        mPluginInstanceMap.erase(it);
    }
}

NFIPlugin* NFCPluginManager::FindPlugin(const std::string& strPluginName)
{
    PluginInstanceMap::iterator it = mPluginInstanceMap.find(strPluginName);
    if (it != mPluginInstanceMap.end())
    {
        return it->second;
    }

    return NULL;
}

bool NFCPluginManager::Execute(const float fLasFrametime, const float fStartedTime)
{
    bool bRet = true;

    PluginInstanceMap::iterator it = mPluginInstanceMap.begin();
    for (; it != mPluginInstanceMap.end(); ++it)
    {
        bool tembRet = it->second->Execute(fLasFrametime, fStartedTime);
        bRet = bRet && tembRet;
    }

	ExecuteEvent();

    return bRet;
}

void NFCPluginManager::AddModule(const std::string& strModuleName, NFILogicModule* pModule)
{
    if (!FindModule(strModuleName))
    {
        mModuleInstanceMap.insert(ModuleInstanceMap::value_type(strModuleName, pModule));
    }
}

void NFCPluginManager::RemoveModule(const std::string& strModuleName)
{
    ModuleInstanceMap::iterator it = mModuleInstanceMap.find(strModuleName);
    if (it != mModuleInstanceMap.end())
    {
        mModuleInstanceMap.erase(it);
    }
}

NFILogicModule* NFCPluginManager::FindModule(const std::string& strModuleName)
{
    ModuleInstanceMap::iterator it = mModuleInstanceMap.find(strModuleName);
    if (it != mModuleInstanceMap.end())
    {
        return it->second;
    }
    return NULL;
}

bool NFCPluginManager::Init()
{
#ifdef NF_DYNAMIC_PLUGIN
    LoadPlugin();

#if NF_PLATFORM == NF_PLATFORM_WIN || NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_APPLE
    PluginNameMap::iterator it = mPluginNameMap.begin();
    for (it; it != mPluginNameMap.end(); ++it)
    {
        LoadPluginLibrary(it->first);
    }

#endif

#else
    //     PluginNameList::iterator it = mPluginNameList.begin();
    //     for (it; it != mPluginNameList.end(); it++)
    //     {
    //         const std::string& strPluginName = *it;
    //         CREATE_PLUGIN( this, strPluginName );
    //     }

    //     CREATE_PLUGIN(this, NFKernelPlugin)
    //     CREATE_PLUGIN(this, NFEventProcessPlugin)
    //     CREATE_PLUGIN(this, NFConfigPlugin)

#endif

    PluginInstanceMap::iterator itInstance = mPluginInstanceMap.begin();
    for (itInstance; itInstance != mPluginInstanceMap.end(); itInstance++)
    {
        itInstance->second->Init();
    }

    return true;
}

bool NFCPluginManager::AfterInit()
{
    PluginInstanceMap::iterator itAfterInstance = mPluginInstanceMap.begin();
    for (itAfterInstance; itAfterInstance != mPluginInstanceMap.end(); itAfterInstance++)
    {
        itAfterInstance->second->AfterInit();
    }

    return true;
}

bool NFCPluginManager::CheckConfig()
{
    PluginInstanceMap::iterator itCheckInstance = mPluginInstanceMap.begin();
    for (itCheckInstance; itCheckInstance != mPluginInstanceMap.end(); itCheckInstance++)
    {
        itCheckInstance->second->CheckConfig();
    }

    return true;
}

bool NFCPluginManager::BeforeShut()
{
    PluginInstanceMap::iterator itBeforeInstance = mPluginInstanceMap.begin();
    for (itBeforeInstance; itBeforeInstance != mPluginInstanceMap.end(); itBeforeInstance++)
    {
        itBeforeInstance->second->BeforeShut();
    }

    return true;
}

bool NFCPluginManager::Shut()
{

    PluginInstanceMap::iterator itInstance = mPluginInstanceMap.begin();
    for (itInstance; itInstance != mPluginInstanceMap.end(); ++itInstance)
    {
        itInstance->second->Shut();
    }

#ifdef NF_DYNAMIC_PLUGIN

    PluginNameMap::iterator it = mPluginNameMap.begin();
    for (it; it != mPluginNameMap.end(); it++)
    {
        UnLoadPluginLibrary(it->first);
    }

#else

    //     DESTROY_PLUGIN(this, NFConfigPlugin)
    //     DESTROY_PLUGIN(this, NFEventProcessPlugin)
    //     DESTROY_PLUGIN(this, NFKernelPlugin)

#endif
	mPluginInstanceMap.clear();
    mPluginNameMap.clear();
	return true;
}

bool NFCPluginManager::LoadPluginLibrary(const std::string& strPluginDLLName)
{
    PluginLibMap::iterator it = mPluginLibMap.find(strPluginDLLName);
    if (it == mPluginLibMap.end())
    {
        NFCDynLib* pLib = new NFCDynLib(strPluginDLLName);
        bool bLoad = pLib->Load();

        if (bLoad)
        {
            mPluginLibMap.insert(PluginLibMap::value_type(strPluginDLLName, pLib));

            DLL_START_PLUGIN_FUNC pFunc = (DLL_START_PLUGIN_FUNC)pLib->GetSymbol("DllStartPlugin");
            if (!pFunc)
            {
                std::cout << "Find function DllStartPlugin Failed in [" << pLib->GetName() << "]" << std::endl;
                assert(0);
                return false;
            }

            pFunc(this);

            return true;
        }
        else
        {
#if NF_PLATFORM == NF_PLATFORM_LINUX
            char* error = dlerror();
            if (error)
            {
				std::cout << stderr << " Open shared lib failed " << pLib->GetName() << " " << error << std::endl;
                assert(0);
                return false;
            }
#elif NF_PLATFORM == NF_PLATFORM_WIN
            std::cout << stderr << " Open DLL " << pLib->GetName() << " failed, ErrorNo = "<< GetLastError();
#endif // NF_PLATFORM
            std::cout << "Load [" << pLib->GetName() << "] Failed" << std::endl;
            assert(0);
        }
    }

    return false;
}

bool NFCPluginManager::UnLoadPluginLibrary(const std::string& strPluginDLLName)
{
    PluginLibMap::iterator it = mPluginLibMap.find(strPluginDLLName);
    if (it != mPluginLibMap.end())
    {
        NFCDynLib* pLib = it->second;

        DLL_STOP_PLUGIN_FUNC pFunc = (DLL_STOP_PLUGIN_FUNC)pLib->GetSymbol("DllStopPlugin");

        if (pFunc)
        {
            pFunc(this);
        }

        pLib->UnLoad();

        delete pLib;
        pLib = NULL;
        mPluginLibMap.erase(it);

        return true;
    }

    return false;
}

bool NFCPluginManager::ReInitialize()
{
    PluginInstanceMap::iterator itBeforeInstance = mPluginInstanceMap.begin();
    for ( itBeforeInstance; itBeforeInstance != mPluginInstanceMap.end(); itBeforeInstance++ )
    {
        itBeforeInstance->second->BeforeShut();
    }

    PluginInstanceMap::iterator itShutDownInstance = mPluginInstanceMap.begin();
    for ( itShutDownInstance; itShutDownInstance != mPluginInstanceMap.end(); itShutDownInstance++ )
    {
        itShutDownInstance->second->Shut();
    }

    PluginInstanceMap::iterator itInstance = mPluginInstanceMap.begin();
    for ( itInstance; itInstance != mPluginInstanceMap.end(); itInstance++ )
    {
        itInstance->second->Init();
    }

    PluginInstanceMap::iterator itAfterInstance = mPluginInstanceMap.begin();
    for ( ; itAfterInstance != mPluginInstanceMap.end(); itAfterInstance++ )
    {
        itAfterInstance->second->AfterInit();
    }

    PluginInstanceMap::iterator itCheckInstance = mPluginInstanceMap.begin();
    for (itCheckInstance; itCheckInstance != mPluginInstanceMap.end(); itCheckInstance++)
    {
        itCheckInstance->second->CheckConfig();
    }

    return true;
}

void NFCPluginManager::HandlerEx( const NFIActorMessage& message, const Theron::Address from )
{
	//ӵУÿִ֡
	mxQueue.Push(message);
}

bool NFCPluginManager::ExecuteEvent()
{
	NFIActorMessage xMsg;
	bool bRet = false;
	bRet = mxQueue.Pop(xMsg);
	while (bRet)
	{
		if (xMsg.eType == NFIActorMessage::EACTOR_RETURN_EVENT_MSG)
		{
			xMsg.xActorEventFunc->xEndFuncptr->operator()(xMsg.self, xMsg.nFormActor, xMsg.nSubMsgID, xMsg.data);
			m_pActorManager->ReleaseActor(xMsg.nFormActor);
		}

		bRet = mxQueue.Pop(xMsg);
	}

	return true;
}
<|endoftext|>


<commit_before>/***********************************************************************************************************************
 **
 ** Copyright (c) 2011, 2014 ETH Zurich
 ** All rights reserved.
 **
 ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
 ** following conditions are met:
 **
 **    * Redistributions of source code must retain the above copyright notice, this list of conditions and the
 **      following disclaimer.
 **    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
 **      following disclaimer in the documentation and/or other materials provided with the distribution.
 **    * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
 **      derived from this software without specific prior written permission.
 **
 **
 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 **
 **********************************************************************************************************************/
#include "GenericPersistentUnit.h"

#include "GenericNode.h"
#include "GenericTree.h"

namespace FilePersistence {

GenericPersistentUnit::GenericPersistentUnit(GenericTree* tree, QString name, char* data, int dataSize)
: tree_{tree}, name_{name}, data_{data}, dataSize_{dataSize},
  lastNodeIndexInLastChunk_{GenericTree::ALLOCATION_CHUNK_SIZE}
{
	Q_ASSERT(tree_);
}

GenericPersistentUnit::~GenericPersistentUnit()
{
	for (auto c : chunks_) tree_->releaseChunk(c);
	chunks_.clear();

	if (data_) delete [] data_;
	data_ = nullptr;
}

GenericNode* GenericPersistentUnit::nextNode()
{
	++lastNodeIndexInLastChunk_;

	if (chunks_.isEmpty() || lastNodeIndexInLastChunk_ >= GenericTree::ALLOCATION_CHUNK_SIZE)
	{
		// We must get a new chunk
		lastNodeIndexInLastChunk_ = 0;
		chunks_.append( tree_->emptyChunk() );
	}

	return chunks_.last() + lastNodeIndexInLastChunk_;
}

void GenericPersistentUnit::releaseLastNode()
{
	--lastNodeIndexInLastChunk_;
	if (!chunks_.isEmpty() && lastNodeIndexInLastChunk_ < 0)
	{
		// We must release the last chunk
		tree_->releaseChunk(chunks_.takeLast());
		lastNodeIndexInLastChunk_ = GenericTree::ALLOCATION_CHUNK_SIZE - 1;
	}
}

GenericNode* GenericPersistentUnit::newNode()
{
	Q_ASSERT(!data_);

	auto node = nextNode();
	node->reset(this);
	return node;
}

GenericNode* GenericPersistentUnit::newNode(int lineStart, int lineEndEnclusive)
{
	Q_ASSERT(data_);
	Q_ASSERT(lineEndEnclusive < dataSize_);
	Q_ASSERT(!tree_->piecewiseLoader());

	auto node = nextNode();
	node->reset(this, data_+lineStart, lineEndEnclusive - lineStart + 1, true);
	return node;
}

GenericNode* GenericPersistentUnit::newNode(const char* data, int dataLength)
{
	Q_ASSERT(!data_);
	auto node = nextNode();
	node->reset(this, data, dataLength, false);
	return node;
}

GenericNode* GenericPersistentUnit::newNode(const GenericNode* nodeToCopy, bool force, bool deepCopy)
{
	Q_ASSERT(nodeToCopy->tree() != tree());
	if (!force) Q_ASSERT(!tree_->find(nodeToCopy->id()));

	auto node = nextNode();
	node->reset(this, nodeToCopy);

	if (deepCopy)
		for (auto childToCopy : nodeToCopy->children())
		{
			auto child = newNode(childToCopy, true);
			child->setParent(node);
			node->attachChild(child);
		}

	return node;
}

QPair<bool, GenericNode*> GenericPersistentUnit::newOrExistingNode(const char* data, int dataLength)
{
	// NOTE if we could just read the ID from the line, this method could be removed, I think.
	auto newNode = newNode(data, dataLength);

	// Ignore persistence unit nodes
	if (newNode->type() == GenericNode::PERSISTENT_UNIT_TYPE)
	{
		releaseLastNode();
		return {false, nullptr};
	}

	auto oldNode = tree_->find(newNode->id());
	if (oldNode)
	{
		Q_ASSERT(oldNode->label() == newNode->label());
		Q_ASSERT(oldNode->type() == newNode->type());
		Q_ASSERT(oldNode->parentId() == newNode->parentId());
		releaseLastNode();
		return {false, oldNode};
	}
	else
		return {true, newNode};
}

const char* GenericPersistentUnit::setData(const char* data, int dataSize)
{
	Q_ASSERT(!tree_->piecewiseLoader());
	Q_ASSERT(!data_);
	Q_ASSERT(data);
	Q_ASSERT(dataSize > 0);
	data_ = new char[dataSize];
	dataSize_ = dataSize;
	memcpy(data_, data, dataSize);
	return data_;
}

GenericNode* GenericPersistentUnit::unitRootNode() const
{
	if (chunks_.isEmpty())
		return nullptr;
	else
		return &(chunks_.first()[0]);
}

GenericNode* GenericPersistentUnit::nodeWithNullParent() const
{
	for (auto& chunk : chunks_)
	{
		int maxIndex = (chunk == chunks_.last() ? lastNodeIndexInLastChunk_ : GenericTree::ALLOCATION_CHUNK_SIZE-1);
		for (int i = 0; i<= maxIndex; ++i)
			if (chunk[i].parentId().isNull())
				return &chunk[i];
	}

	return nullptr;
}

}
<commit_msg>Fix a name conflict<commit_after>/***********************************************************************************************************************
 **
 ** Copyright (c) 2011, 2014 ETH Zurich
 ** All rights reserved.
 **
 ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
 ** following conditions are met:
 **
 **    * Redistributions of source code must retain the above copyright notice, this list of conditions and the
 **      following disclaimer.
 **    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
 **      following disclaimer in the documentation and/or other materials provided with the distribution.
 **    * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
 **      derived from this software without specific prior written permission.
 **
 **
 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 **
 **********************************************************************************************************************/
#include "GenericPersistentUnit.h"

#include "GenericNode.h"
#include "GenericTree.h"

namespace FilePersistence {

GenericPersistentUnit::GenericPersistentUnit(GenericTree* tree, QString name, char* data, int dataSize)
: tree_{tree}, name_{name}, data_{data}, dataSize_{dataSize},
  lastNodeIndexInLastChunk_{GenericTree::ALLOCATION_CHUNK_SIZE}
{
	Q_ASSERT(tree_);
}

GenericPersistentUnit::~GenericPersistentUnit()
{
	for (auto c : chunks_) tree_->releaseChunk(c);
	chunks_.clear();

	if (data_) delete [] data_;
	data_ = nullptr;
}

GenericNode* GenericPersistentUnit::nextNode()
{
	++lastNodeIndexInLastChunk_;

	if (chunks_.isEmpty() || lastNodeIndexInLastChunk_ >= GenericTree::ALLOCATION_CHUNK_SIZE)
	{
		// We must get a new chunk
		lastNodeIndexInLastChunk_ = 0;
		chunks_.append( tree_->emptyChunk() );
	}

	return chunks_.last() + lastNodeIndexInLastChunk_;
}

void GenericPersistentUnit::releaseLastNode()
{
	--lastNodeIndexInLastChunk_;
	if (!chunks_.isEmpty() && lastNodeIndexInLastChunk_ < 0)
	{
		// We must release the last chunk
		tree_->releaseChunk(chunks_.takeLast());
		lastNodeIndexInLastChunk_ = GenericTree::ALLOCATION_CHUNK_SIZE - 1;
	}
}

GenericNode* GenericPersistentUnit::newNode()
{
	Q_ASSERT(!data_);

	auto node = nextNode();
	node->reset(this);
	return node;
}

GenericNode* GenericPersistentUnit::newNode(int lineStart, int lineEndEnclusive)
{
	Q_ASSERT(data_);
	Q_ASSERT(lineEndEnclusive < dataSize_);
	Q_ASSERT(!tree_->piecewiseLoader());

	auto node = nextNode();
	node->reset(this, data_+lineStart, lineEndEnclusive - lineStart + 1, true);
	return node;
}

GenericNode* GenericPersistentUnit::newNode(const char* data, int dataLength)
{
	Q_ASSERT(!data_);
	auto node = nextNode();
	node->reset(this, data, dataLength, false);
	return node;
}

GenericNode* GenericPersistentUnit::newNode(const GenericNode* nodeToCopy, bool force, bool deepCopy)
{
	Q_ASSERT(nodeToCopy->tree() != tree());
	if (!force) Q_ASSERT(!tree_->find(nodeToCopy->id()));

	auto node = nextNode();
	node->reset(this, nodeToCopy);

	if (deepCopy)
		for (auto childToCopy : nodeToCopy->children())
		{
			auto child = newNode(childToCopy, true);
			child->setParent(node);
			node->attachChild(child);
		}

	return node;
}

QPair<bool, GenericNode*> GenericPersistentUnit::newOrExistingNode(const char* data, int dataLength)
{
	// NOTE if we could just read the ID from the line, this method could be removed, I think.
	auto newlyCreatedNode = newNode(data, dataLength);

	// Ignore persistence unit nodes
	if (newlyCreatedNode->type() == GenericNode::PERSISTENT_UNIT_TYPE)
	{
		releaseLastNode();
		return {false, nullptr};
	}

	auto oldNode = tree_->find(newlyCreatedNode->id());
	if (oldNode)
	{
		Q_ASSERT(oldNode->label() == newlyCreatedNode->label());
		Q_ASSERT(oldNode->type() == newlyCreatedNode->type());
		Q_ASSERT(oldNode->parentId() == newlyCreatedNode->parentId());
		releaseLastNode();
		return {false, oldNode};
	}
	else
		return {true, newlyCreatedNode};
}

const char* GenericPersistentUnit::setData(const char* data, int dataSize)
{
	Q_ASSERT(!tree_->piecewiseLoader());
	Q_ASSERT(!data_);
	Q_ASSERT(data);
	Q_ASSERT(dataSize > 0);
	data_ = new char[dataSize];
	dataSize_ = dataSize;
	memcpy(data_, data, dataSize);
	return data_;
}

GenericNode* GenericPersistentUnit::unitRootNode() const
{
	if (chunks_.isEmpty())
		return nullptr;
	else
		return &(chunks_.first()[0]);
}

GenericNode* GenericPersistentUnit::nodeWithNullParent() const
{
	for (auto& chunk : chunks_)
	{
		int maxIndex = (chunk == chunks_.last() ? lastNodeIndexInLastChunk_ : GenericTree::ALLOCATION_CHUNK_SIZE-1);
		for (int i = 0; i<= maxIndex; ++i)
			if (chunk[i].parentId().isNull())
				return &chunk[i];
	}

	return nullptr;
}

}
<|endoftext|>