<commit_before>/************************************************************************
  This file is part of Freekick.

  Freekick is free software: you can redistribute it and/or modify
  it under the terms of the GNU Affero General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  Freekick 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 Affero General Public License for more details.

  You should have received a copy of the GNU Affero General Public License
  along with Freekick.  If not, see <http://www.gnu.org/licenses/>.

  Copyright Antti Salonen, 2008
**************************************************************************/

#include "tasks/PlaySoccer.h"

namespace freekick
{
    namespace match
    {
        namespace client
        {
            namespace ai_client
            {
                namespace tasks
                {
                    PlaySoccer::PlaySoccer (boost::shared_ptr<MatchStatus> ms, int id)
                        : mMatchStatus(ms),
                          mPlayerID(id)
                    {
                        mPlayer = mMatchStatus->getPlayer(mPlayerID);
                    }

                    bool PlaySoccer::finished() const
                    {
                        const BallState bs = mMatchStatus->getBallState();
                        if(bs.bio_type == HalfFullTime || bs.bio_type == PreKickoff)
                        {
                            return true;
                        }
                        return false;
                    }

                    boost::shared_ptr<messages::PlayerControlMessage> PlaySoccer::process()
                    {
                        if(mPlayer->isSubstitute())
                        {
                            // TODO: replace with BeingASubstituteTask
                            if(emptyTasks())
                            {
                                boost::shared_ptr<Idle> t(new Idle(mPlayerID));
                                addTask(t);
                            }
                        }

                        else
                        {
                            Helpers h(mMatchStatus, mPlayerID);
                            clearTasks();

                            if(!emptyTasks())
                            {
                                // TODO: check if current task should be cleared
                                clearTasks();
                            }

                            if(h.bio == BallIn && mPlayer->getPlayerPosition() == Goalkeeper)
                            {
                                boost::shared_ptr<GoalkeeperAction> t(new GoalkeeperAction(mMatchStatus, mPlayerID));
                                addTask(t);
                            }
                            else
                            {
                                if(h.iskickoff && !h.startplay)       // goto start formation
                                {
                                    boost::shared_ptr<GotoKickoffFormationPosition> t(new GotoKickoffFormationPosition(mMatchStatus, mPlayerID));
                                    addTask(t);
                                }
                                else
                                {
                                    if((h.isnearestplayer || h.ballinmyarea) && h.allowed_to_kick)
                                    {
                                        if(h.abletokick)
                                        {
                                            boost::shared_ptr<KickBall> t(new KickBall(mMatchStatus, mPlayerID));
                                            addTask(t);
                                        }
                                        else
                                        {
                                            if(h.ourclubhasball)         // run to ball
                                            {
                                                boost::shared_ptr<FetchBall> t(new FetchBall(mMatchStatus, mPlayerID));
                                                addTask(t);
                                            }
                                            else                                                    // defensive
                                            {
                                                boost::shared_ptr<FetchBall> t(new FetchBall(mMatchStatus, mPlayerID));
                                                addTask(t);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        addutil::Vector3 future_pos = mMatchStatus->getBall()->getFuturePosition(AIConfig::getInstance()->future_lookup_time);
                                        future_pos.y = 0.0f;
                                        float future_dist = (mPlayer->getPosition() - future_pos).length();
                                        if(future_dist < AIConfig::getInstance()->max_future_fetch_distance)
                                        {
                                            boost::shared_ptr<FetchBall> t(new FetchBall(mMatchStatus, mPlayerID));
                                            addTask(t);
                                        }
                                        else
                                        {
                                            boost::shared_ptr<IdleInFormation> t(new IdleInFormation(mMatchStatus, mPlayerID));
                                            addTask(t);
                                        }
                                    }
                                }
                            }
                        }

                        boost::shared_ptr<Task> nexttask = getNextTask();
                        boost::shared_ptr<messages::PlayerControlMessage> msg = nexttask->process();
                        return msg;
                    }
                }
            }
        }
    }
}
<commit_msg>ai: fixed issue of ai trying to kick ball when not allowed<commit_after>/************************************************************************
  This file is part of Freekick.

  Freekick is free software: you can redistribute it and/or modify
  it under the terms of the GNU Affero General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  Freekick 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 Affero General Public License for more details.

  You should have received a copy of the GNU Affero General Public License
  along with Freekick.  If not, see <http://www.gnu.org/licenses/>.

  Copyright Antti Salonen, 2008
**************************************************************************/

#include "tasks/PlaySoccer.h"

namespace freekick
{
    namespace match
    {
        namespace client
        {
            namespace ai_client
            {
                namespace tasks
                {
                    PlaySoccer::PlaySoccer (boost::shared_ptr<MatchStatus> ms, int id)
                        : mMatchStatus(ms),
                          mPlayerID(id)
                    {
                        mPlayer = mMatchStatus->getPlayer(mPlayerID);
                    }

                    bool PlaySoccer::finished() const
                    {
                        const BallState bs = mMatchStatus->getBallState();
                        if(bs.bio_type == HalfFullTime || bs.bio_type == PreKickoff)
                        {
                            return true;
                        }
                        return false;
                    }

                    boost::shared_ptr<messages::PlayerControlMessage> PlaySoccer::process()
                    {
                        if(mPlayer->isSubstitute())
                        {
                            // TODO: replace with BeingASubstituteTask
                            if(emptyTasks())
                            {
                                boost::shared_ptr<Idle> t(new Idle(mPlayerID));
                                addTask(t);
                            }
                        }

                        else
                        {
                            Helpers h(mMatchStatus, mPlayerID);
                            clearTasks();

                            if(!emptyTasks())
                            {
                                // TODO: check if current task should be cleared
                                clearTasks();
                            }

                            if(h.bio == BallIn && mPlayer->getPlayerPosition() == Goalkeeper)
                            {
                                boost::shared_ptr<GoalkeeperAction> t(new GoalkeeperAction(mMatchStatus, mPlayerID));
                                addTask(t);
                            }
                            else
                            {
                                if(h.iskickoff && !h.startplay)       // goto start formation
                                {
                                    boost::shared_ptr<GotoKickoffFormationPosition> t(new GotoKickoffFormationPosition(mMatchStatus, mPlayerID));
                                    addTask(t);
                                }
                                else
                                {
                                    if((h.isnearestplayer || h.ballinmyarea) && h.allowed_to_kick)
                                    {
                                        if(h.abletokick)
                                        {
                                            boost::shared_ptr<KickBall> t(new KickBall(mMatchStatus, mPlayerID));
                                            addTask(t);
                                        }
                                        else
                                        {
                                            if(h.ourclubhasball)         // run to ball
                                            {
                                                boost::shared_ptr<FetchBall> t(new FetchBall(mMatchStatus, mPlayerID));
                                                addTask(t);
                                            }
                                            else                                                    // defensive
                                            {
                                                boost::shared_ptr<FetchBall> t(new FetchBall(mMatchStatus, mPlayerID));
                                                addTask(t);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        addutil::Vector3 future_pos = mMatchStatus->getBall()->getFuturePosition(AIConfig::getInstance()->future_lookup_time);
                                        future_pos.y = 0.0f;
                                        float future_dist = (mPlayer->getPosition() - future_pos).length();
                                        if(h.allowed_to_kick && future_dist < AIConfig::getInstance()->max_future_fetch_distance)
                                        {
                                            boost::shared_ptr<FetchBall> t(new FetchBall(mMatchStatus, mPlayerID));
                                            addTask(t);
                                        }
                                        else
                                        {
                                            boost::shared_ptr<IdleInFormation> t(new IdleInFormation(mMatchStatus, mPlayerID));
                                            addTask(t);
                                        }
                                    }
                                }
                            }
                        }

                        boost::shared_ptr<Task> nexttask = getNextTask();
                        boost::shared_ptr<messages::PlayerControlMessage> msg = nexttask->process();
                        return msg;
                    }
                }
            }
        }
    }
}
<|endoftext|>


<commit_before>#ifndef STAN_MATH_FWD_SCAL_FUN_GAMMA_P_HPP
#define STAN_MATH_FWD_SCAL_FUN_GAMMA_P_HPP

#include <stan/math/fwd/core.hpp>
#include <stan/math/fwd/scal/fun/value_of_rec.hpp>
#include <stan/math/prim/scal/err/domain_error.hpp>
#include <stan/math/prim/scal/fun/gamma_p.hpp>
#include <stan/math/prim/scal/fun/lgamma.hpp>
#include <stan/math/prim/scal/fun/grad_reg_lower_inc_gamma.hpp>
#include <limits>

namespace stan {
namespace math {

template <typename T>
inline fvar<T> gamma_p(const fvar<T> &x1, const fvar<T> &x2) {
  using boost::math::digamma;
  using std::exp;
  using std::fabs;
  using std::log;
  using std::pow;

  T u = gamma_p(x1.val_, x2.val_);
  if (is_inf(x1.val_))
    return fvar<T>(u, std::numeric_limits<double>::quiet_NaN());
  if (is_inf(x2.val_))
    return fvar<T>(u, std::numeric_limits<double>::quiet_NaN());

  T der1 = grad_reg_lower_inc_gamma(x1.val_, x2.val_, 1.0e-10);
  T der2 = exp(-x2.val_ + (x1.val_ - 1.0) * log(x2.val_) - lgamma(x1.val_));

  return fvar<T>(u, x1.d_ * der1 + x2.d_ * der2);
}

template <typename T>
inline fvar<T> gamma_p(const fvar<T> &x1, double x2) {
  using boost::math::digamma;
  using std::exp;
  using std::fabs;
  using std::log;
  using std::pow;

  T u = gamma_p(x1.val_, x2);
  if (is_inf(x1.val_))
    return fvar<T>(u, std::numeric_limits<double>::quiet_NaN());
  if (is_inf(x2))
    return fvar<T>(u, std::numeric_limits<double>::quiet_NaN());

  T der1 = grad_reg_lower_inc_gamma(x1.val_, x2, 1.0e-10);

  return fvar<T>(u, x1.d_ * der1);
}

template <typename T>
inline fvar<T> gamma_p(double x1, const fvar<T> &x2) {
  using std::exp;
  using std::log;

  T u = gamma_p(x1, x2.val_);
  if (is_inf(x1))
    return fvar<T>(u, std::numeric_limits<double>::quiet_NaN());

  T der2 = exp(-x2.val_ + (x1 - 1.0) * log(x2.val_) - stan::math::lgamma(x1));

  return fvar<T>(u, x2.d_ * der2);
}
}  // namespace math
}  // namespace stan
#endif
<commit_msg>Remove unnecessary namespace qualification<commit_after>#ifndef STAN_MATH_FWD_SCAL_FUN_GAMMA_P_HPP
#define STAN_MATH_FWD_SCAL_FUN_GAMMA_P_HPP

#include <stan/math/fwd/core.hpp>
#include <stan/math/fwd/scal/fun/value_of_rec.hpp>
#include <stan/math/prim/scal/err/domain_error.hpp>
#include <stan/math/prim/scal/fun/gamma_p.hpp>
#include <stan/math/prim/scal/fun/lgamma.hpp>
#include <stan/math/prim/scal/fun/grad_reg_lower_inc_gamma.hpp>
#include <limits>

namespace stan {
namespace math {

template <typename T>
inline fvar<T> gamma_p(const fvar<T> &x1, const fvar<T> &x2) {
  using boost::math::digamma;
  using std::exp;
  using std::fabs;
  using std::log;
  using std::pow;

  T u = gamma_p(x1.val_, x2.val_);
  if (is_inf(x1.val_))
    return fvar<T>(u, std::numeric_limits<double>::quiet_NaN());
  if (is_inf(x2.val_))
    return fvar<T>(u, std::numeric_limits<double>::quiet_NaN());

  T der1 = grad_reg_lower_inc_gamma(x1.val_, x2.val_, 1.0e-10);
  T der2 = exp(-x2.val_ + (x1.val_ - 1.0) * log(x2.val_) - lgamma(x1.val_));

  return fvar<T>(u, x1.d_ * der1 + x2.d_ * der2);
}

template <typename T>
inline fvar<T> gamma_p(const fvar<T> &x1, double x2) {
  using boost::math::digamma;
  using std::exp;
  using std::fabs;
  using std::log;
  using std::pow;

  T u = gamma_p(x1.val_, x2);
  if (is_inf(x1.val_))
    return fvar<T>(u, std::numeric_limits<double>::quiet_NaN());
  if (is_inf(x2))
    return fvar<T>(u, std::numeric_limits<double>::quiet_NaN());

  T der1 = grad_reg_lower_inc_gamma(x1.val_, x2, 1.0e-10);

  return fvar<T>(u, x1.d_ * der1);
}

template <typename T>
inline fvar<T> gamma_p(double x1, const fvar<T> &x2) {
  using std::exp;
  using std::log;

  T u = gamma_p(x1, x2.val_);
  if (is_inf(x1))
    return fvar<T>(u, std::numeric_limits<double>::quiet_NaN());

  T der2 = exp(-x2.val_ + (x1 - 1.0) * log(x2.val_) - lgamma(x1));

  return fvar<T>(u, x2.d_ * der2);
}
}  // namespace math
}  // namespace stan
#endif
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    TestStringToNumeric.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.

=========================================================================*/
/*-------------------------------------------------------------------------
  Copyright 2008 Sandia Corporation.
  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
  the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/

#include "vtkDelimitedTextReader.h"
#include "vtkDoubleArray.h"
#include "vtkIntArray.h"
#include "vtkStringArray.h"
#include "vtkStringToNumeric.h"
#include "vtkTable.h"
#include "vtkTestUtilities.h"
#include "vtkMath.h"

#include "vtkSmartPointer.h"
#define VTK_CREATE(type,name) \
  vtkSmartPointer<type> name = vtkSmartPointer<type>::New()

namespace
{
    int ArrayTypesTest(int argc, char* argv[])
    {
      char* file = vtkTestUtilities::ExpandDataFileName(argc, argv,
                                                        "Data/authors.csv");

      VTK_CREATE(vtkDelimitedTextReader, reader);
      reader->SetFileName(file);
      reader->SetHaveHeaders(true);

      delete [] file;

      VTK_CREATE(vtkStringToNumeric, numeric);
      numeric->SetInputConnection(reader->GetOutputPort());
      numeric->Update();

      vtkTable* table = vtkTable::SafeDownCast(numeric->GetOutput());

      cerr << "Testing array types..." << endl;
      int errors = 0;
      if (!vtkStringArray::SafeDownCast(table->GetColumnByName("Author")))
        {
        cerr << "ERROR: Author array missing" << endl;
        ++errors;
        }
      if (!vtkStringArray::SafeDownCast(table->GetColumnByName("Affiliation")))
        {
        cerr << "ERROR: Affiliation array missing" << endl;
        ++errors;
        }
      if (!vtkStringArray::SafeDownCast(table->GetColumnByName("Alma Mater")))
        {
        cerr << "ERROR: Alma Mater array missing" << endl;
        ++errors;
        }
      if (!vtkStringArray::SafeDownCast(table->GetColumnByName("Categories")))
        {
        cerr << "ERROR: Categories array missing" << endl;
        ++errors;
        }
      if (!vtkIntArray::SafeDownCast(table->GetColumnByName("Age")))
        {
        cerr << "ERROR: Age array missing or not converted to int" << endl;
        ++errors;
        }
      else
        {
        vtkIntArray* age = vtkIntArray::SafeDownCast(table->GetColumnByName("Age"));
        int sum = 0;
        for (vtkIdType i = 0; i < age->GetNumberOfTuples(); i++)
          {
          sum += age->GetValue(i);
          }
        if (sum != 181)
          {
          cerr << "ERROR: Age sum is incorrect" << endl;
          ++errors;
          }
        }
      if (!vtkDoubleArray::SafeDownCast(table->GetColumnByName("Coolness")))
        {
        cerr << "ERROR: Coolness array missing or not converted to double" << endl;
        ++errors;
        }
      else
        {
        vtkDoubleArray* cool = vtkDoubleArray::SafeDownCast(table->GetColumnByName("Coolness"));
        double sum = 0;
        for (vtkIdType i = 0; i < cool->GetNumberOfTuples(); i++)
          {
          sum += cool->GetValue(i);
          }
        double eps = 10e-8;
        double diff = (2.35 > sum) ? (2.35 - sum) : (sum - 2.35);
        if (diff > eps)
          {
          cerr << "ERROR: Coolness sum is incorrect" << endl;
          ++errors;
          }
        }

      return errors;

    }

    int WhitespaceAndEmptyCellsTest()
    {
      // Setup a table of string columns, which is to get converted to numeric
      VTK_CREATE(vtkTable, inputTable);
      VTK_CREATE(vtkStringArray, integerColumn);
      integerColumn->SetName("IntegerColumn");
      integerColumn->SetNumberOfTuples(2);
      integerColumn->SetValue(0, " ");
      integerColumn->SetValue(1, " 1 ");

      VTK_CREATE(vtkStringArray, doubleColumn);
      doubleColumn->SetName("DoubleColumn");
      doubleColumn->SetNumberOfTuples(2);
      doubleColumn->SetValue(0, " ");
      doubleColumn->SetValue(1, " 1.1 ");

      inputTable->AddColumn(integerColumn);
      inputTable->AddColumn(doubleColumn);

      // Setup the vtkStringToNumeric which is under test
      VTK_CREATE(vtkStringToNumeric, numeric);
      int const defaultIntValue = 100;
      numeric->SetDefaultIntegerValue(defaultIntValue);
      numeric->SetDefaultDoubleValue(vtkMath::Nan());
      numeric->SetTrimWhitespacePriorToNumericConversion(true);
      numeric->SetInput(inputTable);
      numeric->Update();
      vtkTable* table = vtkTable::SafeDownCast(numeric->GetOutput());
      table->Dump();

      cerr << "Testing handling whitespace and empty cells..." << endl;
      int errors = 0;
      if (!vtkIntArray::SafeDownCast(table->GetColumnByName("IntegerColumn")))
        {
        cerr << "ERROR: IntegerColumn array missing or not converted to int" << endl;
        ++errors;
        }
      else
        {
        vtkIntArray* column = vtkIntArray::SafeDownCast(table->GetColumnByName("IntegerColumn"));
        if (defaultIntValue != column->GetValue(0))
          {
              cerr << "ERROR: Empty cell value is: " << column->GetValue(0) << ". Expected: " << defaultIntValue;
              ++errors;
          }
        if (1 != column->GetValue(1))
          {
              cerr << "ERROR: Cell with whitespace value is: " << column->GetValue(1) << ". Expected: 1";
              ++errors;
          }
        }

      if (!vtkDoubleArray::SafeDownCast(table->GetColumnByName("DoubleColumn")))
        {
        cerr << "ERROR: DoubleColumn array missing or not converted to double" << endl;
        ++errors;
        }
      else
        {
        vtkDoubleArray* column = vtkDoubleArray::SafeDownCast(table->GetColumnByName("DoubleColumn"));
        if (!vtkMath::IsNan(column->GetValue(0)))
          {
              cerr << "ERROR: Empty cell value is: " << column->GetValue(0) << ". Expected: " << vtkMath::Nan();
              ++errors;
          }
        if (1.1 != column->GetValue(1))
          {
              cerr << "ERROR: Cell with whitespace value is: " << column->GetValue(1) << ". Expected: 1.1";
              ++errors;
          }
        }
      return errors;
    }
}
int TestStringToNumeric(int argc, char* argv[])
{
    int errors = ArrayTypesTest(argc, argv);
    errors += WhitespaceAndEmptyCellsTest();

    cerr << "...done testing" << endl;
    cerr << errors << " errors found." << endl;

    return errors;
}

<commit_msg>Adding back testing for ForceDouble<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    TestStringToNumeric.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.

=========================================================================*/
/*-------------------------------------------------------------------------
  Copyright 2008 Sandia Corporation.
  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
  the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/

#include "vtkDelimitedTextReader.h"
#include "vtkDoubleArray.h"
#include "vtkIntArray.h"
#include "vtkStringArray.h"
#include "vtkStringToNumeric.h"
#include "vtkTable.h"
#include "vtkTestUtilities.h"
#include "vtkMath.h"

#include "vtkSmartPointer.h"
#define VTK_CREATE(type,name) \
  vtkSmartPointer<type> name = vtkSmartPointer<type>::New()

namespace
{
    int ArrayTypesTest(int argc, char* argv[])
    {
      char* file = vtkTestUtilities::ExpandDataFileName(argc, argv,
                                                        "Data/authors.csv");

      VTK_CREATE(vtkDelimitedTextReader, reader);
      reader->SetFileName(file);
      reader->SetHaveHeaders(true);

      delete [] file;

      VTK_CREATE(vtkStringToNumeric, numeric);
      numeric->SetInputConnection(reader->GetOutputPort());
      numeric->Update();

      vtkTable* table = vtkTable::SafeDownCast(numeric->GetOutput());

      cerr << "Testing array types..." << endl;
      int errors = 0;
      if (!vtkStringArray::SafeDownCast(table->GetColumnByName("Author")))
        {
        cerr << "ERROR: Author array missing" << endl;
        ++errors;
        }
      if (!vtkStringArray::SafeDownCast(table->GetColumnByName("Affiliation")))
        {
        cerr << "ERROR: Affiliation array missing" << endl;
        ++errors;
        }
      if (!vtkStringArray::SafeDownCast(table->GetColumnByName("Alma Mater")))
        {
        cerr << "ERROR: Alma Mater array missing" << endl;
        ++errors;
        }
      if (!vtkStringArray::SafeDownCast(table->GetColumnByName("Categories")))
        {
        cerr << "ERROR: Categories array missing" << endl;
        ++errors;
        }
      if (!vtkIntArray::SafeDownCast(table->GetColumnByName("Age")))
        {
        cerr << "ERROR: Age array missing or not converted to int" << endl;
        ++errors;
        }
      else
        {
        vtkIntArray* age = vtkIntArray::SafeDownCast(table->GetColumnByName("Age"));
        int sum = 0;
        for (vtkIdType i = 0; i < age->GetNumberOfTuples(); i++)
          {
          sum += age->GetValue(i);
          }
        if (sum != 181)
          {
          cerr << "ERROR: Age sum is incorrect" << endl;
          ++errors;
          }
        }
      if (!vtkDoubleArray::SafeDownCast(table->GetColumnByName("Coolness")))
        {
        cerr << "ERROR: Coolness array missing or not converted to double" << endl;
        ++errors;
        }
      else
        {
        vtkDoubleArray* cool = vtkDoubleArray::SafeDownCast(table->GetColumnByName("Coolness"));
        double sum = 0;
        for (vtkIdType i = 0; i < cool->GetNumberOfTuples(); i++)
          {
          sum += cool->GetValue(i);
          }
        double eps = 10e-8;
        double diff = (2.35 > sum) ? (2.35 - sum) : (sum - 2.35);
        if (diff > eps)
          {
          cerr << "ERROR: Coolness sum is incorrect" << endl;
          ++errors;
          }
        }

      cerr << "Testing force double..." << endl;
      numeric->ForceDoubleOn();
      numeric->Update();
      table = vtkTable::SafeDownCast(numeric->GetOutput());
      if (!vtkDoubleArray::SafeDownCast(table->GetColumnByName("Age")))
        {
        cerr << "ERROR: Arrays should have been forced to double" << endl;
        ++errors;
        }

      return errors;

    }

    int WhitespaceAndEmptyCellsTest()
    {
      // Setup a table of string columns, which is to get converted to numeric
      VTK_CREATE(vtkTable, inputTable);
      VTK_CREATE(vtkStringArray, integerColumn);
      integerColumn->SetName("IntegerColumn");
      integerColumn->SetNumberOfTuples(2);
      integerColumn->SetValue(0, " ");
      integerColumn->SetValue(1, " 1 ");

      VTK_CREATE(vtkStringArray, doubleColumn);
      doubleColumn->SetName("DoubleColumn");
      doubleColumn->SetNumberOfTuples(2);
      doubleColumn->SetValue(0, " ");
      doubleColumn->SetValue(1, " 1.1 ");

      inputTable->AddColumn(integerColumn);
      inputTable->AddColumn(doubleColumn);

      // Setup the vtkStringToNumeric which is under test
      VTK_CREATE(vtkStringToNumeric, numeric);
      int const defaultIntValue = 100;
      numeric->SetDefaultIntegerValue(defaultIntValue);
      numeric->SetDefaultDoubleValue(vtkMath::Nan());
      numeric->SetTrimWhitespacePriorToNumericConversion(true);
      numeric->SetInput(inputTable);
      numeric->Update();
      vtkTable* table = vtkTable::SafeDownCast(numeric->GetOutput());
      table->Dump();

      cerr << "Testing handling whitespace and empty cells..." << endl;
      int errors = 0;
      if (!vtkIntArray::SafeDownCast(table->GetColumnByName("IntegerColumn")))
        {
        cerr << "ERROR: IntegerColumn array missing or not converted to int" << endl;
        ++errors;
        }
      else
        {
        vtkIntArray* column = vtkIntArray::SafeDownCast(table->GetColumnByName("IntegerColumn"));
        if (defaultIntValue != column->GetValue(0))
          {
              cerr << "ERROR: Empty cell value is: " << column->GetValue(0) << ". Expected: " << defaultIntValue;
              ++errors;
          }
        if (1 != column->GetValue(1))
          {
              cerr << "ERROR: Cell with whitespace value is: " << column->GetValue(1) << ". Expected: 1";
              ++errors;
          }
        }

      if (!vtkDoubleArray::SafeDownCast(table->GetColumnByName("DoubleColumn")))
        {
        cerr << "ERROR: DoubleColumn array missing or not converted to double" << endl;
        ++errors;
        }
      else
        {
        vtkDoubleArray* column = vtkDoubleArray::SafeDownCast(table->GetColumnByName("DoubleColumn"));
        if (!vtkMath::IsNan(column->GetValue(0)))
          {
              cerr << "ERROR: Empty cell value is: " << column->GetValue(0) << ". Expected: " << vtkMath::Nan();
              ++errors;
          }
        if (1.1 != column->GetValue(1))
          {
              cerr << "ERROR: Cell with whitespace value is: " << column->GetValue(1) << ". Expected: 1.1";
              ++errors;
          }
        }
      return errors;
    }
}
int TestStringToNumeric(int argc, char* argv[])
{
    int errors = ArrayTypesTest(argc, argv);
    errors += WhitespaceAndEmptyCellsTest();

    cerr << "...done testing" << endl;
    cerr << errors << " errors found." << endl;

    return errors;
}

<|endoftext|>


<commit_before>// GrowthRegion.cpp
// Implements the GrowthRegion class

#include "GrowthRegion.h"

#include "InputXML.h"
#include "Model.h"
#include "InstModel.h"
#include "SupplyDemand.h"
#include "BuildingManager.h"
#include "SymbolicFunctionFactories.h"
#include "CycException.h"

#include <stdlib.h>
#include <map>
#include <vector>
#include <string>
#include <boost/shared_ptr.hpp>
#include <libxml/xpath.h>

using namespace std;
using namespace boost;

/* --------------------
 * GrowthRegion Class Methods
 * --------------------
 */
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
GrowthRegion::GrowthRegion() {
  builders_ = map<Producer*,Model*>();
  producers_ = map<Producer*,Model*>();
  commodities_ = vector<Commodity>();
  sdmanager_ = SupplyDemandManager();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::init(xmlNodePtr cur, xmlXPathContextPtr context) {
  LOG(LEV_DEBUG2, "greg") << "A Growth Region is being initialized";
  // xml inits
  Model::init(cur); // name_ and model_impl_
  RegionModel::initAllowedFacilities(cur); // allowedFacilities_

  // get path to this model
  xmlNodePtr model_cur =
    XMLinput->get_xpath_element(context,cur,"model/GrowthRegion");

  // get all commodities
  xmlNodeSetPtr commodity_nodes =
    XMLinput->get_xpath_elements(context,model_cur,"gcommodity");\

  // for now we can only handle one commodity
  if (commodity_nodes->nodeNr > 1) {
    stringstream err("");
    err << "GrowthRegion can currently only handle demand for "
        << "one commodity type.";
    throw CycException(err.str());
  }

  // populate supply demand manager info for each commodity
  for (int i=0;i<commodity_nodes->nodeNr;i++) {
    initCommodity(commodity_nodes->nodeTab[i],XMLinput->context());
  }

  // instantiate building manager
  initBuildManager();

  // parent_ and tick listener, model 'born'
  RegionModel::initSimInteraction(this);
  // children->setParent, requires init()
  RegionModel::initChildren(cur);

  // populate producers_, builders_
  populateProducerMaps();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::initBuildManager() {
  buildmanager_ =
    shared_ptr<BuildingManager>(new BuildingManager(sdmanager_));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::init(xmlNodePtr cur) {
  init(cur,XMLinput->context());
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::initCommodity(xmlNodePtr& node,
                                 xmlXPathContextPtr context) {
    // instantiate product
    string name =
      (const char*)XMLinput->get_xpath_content(context,node,"name");
    Commodity commodity(name);
    int position = commodities_.size();
    commodities_.push_back(commodity);

    // instantiate demand
    string type =
      (const char*)XMLinput->get_xpath_content(context,node,"demand/type");
    string params =
      (const char*)XMLinput->get_xpath_content(context,node,"demand/parameters");
    BasicFunctionFactory bff;
    FunctionPtr demand = bff.getFunctionPtr(type,params);

    // set up producers vector
    vector<Producer> producers;
    xmlNodeSetPtr producer_nodes =
      XMLinput->get_xpath_elements(context,node,"demand/metby");

    for (int i=0; i<producer_nodes->nodeNr; i++) {
      xmlNodePtr pnode = producer_nodes->nodeTab[i];
      producers.push_back(getProducer(context,pnode,commodities_.at(position)));
    } // end producer nodes

    // populate info
    sdmanager_.registerCommodity(commodities_.at(position),demand,producers);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Producer GrowthRegion::getProducer(xmlXPathContextPtr& context,
                                   xmlNodePtr& node,
                                   Commodity& commodity) {
  string fac_name =
    (const char*)XMLinput->get_xpath_content(context,node,"facility");
  double capacity =
    atof((const char*)
         XMLinput->get_xpath_content(context,node,"capacity"));
  double cost = capacity; // cost = capacity
  return Producer(fac_name,commodity,capacity,cost);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::copy(GrowthRegion* src) {
  RegionModel::copy(src);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::string GrowthRegion::str() {
  std::string s = RegionModel::str();

  // if ( builders_ == NULL || builders_->empty() ){
  //   s += name() + " has no builders (currently).";
  // } else {
  //   s += name() + " has the following builders: " ;
  //   for(map<Model*, list<Model*>*>::iterator mit=builders_->begin();
  //       mit != builders_->end(); mit++) {
  //     s += " prototype=" + mit->first->name() + "(";
  //     for(list<Model*>::iterator inst = mit->second->begin();
  //         inst != mit->second->end(); inst++) {
  //       s += (*inst)->name() + ", ";
  //     }
  //     s += "), ";
  //   }
  // }
  return s;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::handleTick(int time) {

  // for each commodity
  for (int i = 0; i < commodities_.size(); i++) {
    Commodity c = commodities_.at(i);

    // does demand exist?
    double unmet_demand =
      sdmanager_.supply(c) - sdmanager_.demand(c,time);

    // if so, determine which prototypes to build and build them
    if (unmet_demand > 0) {
      vector<BuildOrder> orders =
        buildmanager_->makeBuildDecision(c,unmet_demand);
      // build the prototypes
      orderBuilds(orders);
    }
  }

  // After we finish building, call the normal handleTick for a region
  RegionModel::handleTick(time);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::populateProducerMaps() {

  // if there are no children, yell
  if ( children_.empty() ) {
    stringstream err("");
    err << "GrowthRegion " << this->name()
        << " cannot populate its list"
        << " of builders because it has no children.";
    throw CycOverrideException(err.str());
  }

  // for each commodity
  for (int i = 0; i < commodities_.size(); i++) {
    Commodity c = commodities_.at(i);

    // map each producer's name to a pointer to it
    map<string,Producer*> producer_names;
    populateProducerNames(c,producer_names);

    // populate the maps with those producer names
    populateMaps(this,producer_names);
  }

  // if there are no builders, yell
  if ( builders_.empty() ) {
    stringstream err("");
    err << "GrowthRegion " << this->name()
        << " has finished populating"
        << " its list of builders, but that list is empty.";
    throw CycOverrideException(err.str());
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::populateProducerNames(Commodity& c,
                                         std::map<std::string,Producer*>&
                                         producer_names) {
  for (int j = 0; j < sdmanager_.nProducers(c); j++) {
    Producer* p = sdmanager_.producer(c,j);
    producer_names[p->name()] = p;
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::populateMaps(Model* node,
                                std::map<std::string,Producer*>&
                                producer_names) {
  // the name to search for
  string model_name = node->name();

  // if the model is in producers, log it as a producer
  // and its parent as a builder
  map<string,Producer*>::iterator it = producer_names.find(model_name);
  if (it != producer_names.end()) {
    producers_[it->second] = node;
    builders_[it->second] = node->parent();
  }

  // perform the same operation for each of this node's children
  for (int i = 0; i < node->nChildren(); i++) {
    populateMaps(node->children(i),producer_names);
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::string GrowthRegion::printMaps() {
  stringstream ss("");
  map<Producer*,Model*>::iterator it;
  ss << "Producer map:" << endl;
  for (it = producers_.begin(); it != producers_.end(); it++) {
    ss << "\t" << it->first->name() << " producer produces model "
       << it->second->name() << endl;
  }
  ss << "Builder map:" << endl;
  for (it = builders_.begin(); it != builders_.end(); it++) {
    ss << "\t" << it->first->name() << " producer is built by model "
       << it->second->name() << endl;
  }
  return ss.str();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::orderBuilds(std::vector<BuildOrder>& orders) {
  // for each order
  for (int i = 0; i < orders.size(); i++) {
    BuildOrder bo = orders.at(i);
    // for each instance of a prototype order
    for (int j = 0; j < bo.number; j++) {
      Model* builder = builders_[bo.producer];
      Model* prototype = producers_[bo.producer];
      orderBuild(builder,prototype);
    }
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::orderBuild(Model* builder, Model* prototype) {
  // build functions must know who is placing the build order
  dynamic_cast<InstModel*>(builder)->build(prototype,this);
}
/* -------------------- */

/* --------------------
 * Model Class Methods
 * --------------------
 */
extern "C" Model* constructGrowthRegion() {
    return new GrowthRegion();
}

/* -------------------- */

<commit_msg>in cyclus pull request https://github.com/cyclus/core/pull/285, the BuildManager constructor was changed to take a pointer. This makes cycamore's GrowthRegion compatible with that change. A previously noted occaisionally failing test 'TestBuildDecision' continues to fail despite this change.<commit_after>// GrowthRegion.cpp
// Implements the GrowthRegion class

#include "GrowthRegion.h"

#include "InputXML.h"
#include "Model.h"
#include "InstModel.h"
#include "SupplyDemand.h"
#include "BuildingManager.h"
#include "SymbolicFunctionFactories.h"
#include "CycException.h"

#include <stdlib.h>
#include <map>
#include <vector>
#include <string>
#include <boost/shared_ptr.hpp>
#include <libxml/xpath.h>

using namespace std;
using namespace boost;

/* --------------------
 * GrowthRegion Class Methods
 * --------------------
 */
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
GrowthRegion::GrowthRegion() {
  builders_ = map<Producer*,Model*>();
  producers_ = map<Producer*,Model*>();
  commodities_ = vector<Commodity>();
  sdmanager_ = SupplyDemandManager();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::init(xmlNodePtr cur, xmlXPathContextPtr context) {
  LOG(LEV_DEBUG2, "greg") << "A Growth Region is being initialized";
  // xml inits
  Model::init(cur); // name_ and model_impl_
  RegionModel::initAllowedFacilities(cur); // allowedFacilities_

  // get path to this model
  xmlNodePtr model_cur =
    XMLinput->get_xpath_element(context,cur,"model/GrowthRegion");

  // get all commodities
  xmlNodeSetPtr commodity_nodes =
    XMLinput->get_xpath_elements(context,model_cur,"gcommodity");\

  // for now we can only handle one commodity
  if (commodity_nodes->nodeNr > 1) {
    stringstream err("");
    err << "GrowthRegion can currently only handle demand for "
        << "one commodity type.";
    throw CycException(err.str());
  }

  // populate supply demand manager info for each commodity
  for (int i=0;i<commodity_nodes->nodeNr;i++) {
    initCommodity(commodity_nodes->nodeTab[i],XMLinput->context());
  }

  // instantiate building manager
  initBuildManager();

  // parent_ and tick listener, model 'born'
  RegionModel::initSimInteraction(this);
  // children->setParent, requires init()
  RegionModel::initChildren(cur);

  // populate producers_, builders_
  populateProducerMaps();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::initBuildManager() {
  buildmanager_ =
    shared_ptr<BuildingManager>(new BuildingManager(&sdmanager_));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::init(xmlNodePtr cur) {
  init(cur,XMLinput->context());
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::initCommodity(xmlNodePtr& node,
                                 xmlXPathContextPtr context) {
    // instantiate product
    string name =
      (const char*)XMLinput->get_xpath_content(context,node,"name");
    Commodity commodity(name);
    int position = commodities_.size();
    commodities_.push_back(commodity);

    // instantiate demand
    string type =
      (const char*)XMLinput->get_xpath_content(context,node,"demand/type");
    string params =
      (const char*)XMLinput->get_xpath_content(context,node,"demand/parameters");
    BasicFunctionFactory bff;
    FunctionPtr demand = bff.getFunctionPtr(type,params);

    // set up producers vector
    vector<Producer> producers;
    xmlNodeSetPtr producer_nodes =
      XMLinput->get_xpath_elements(context,node,"demand/metby");

    for (int i=0; i<producer_nodes->nodeNr; i++) {
      xmlNodePtr pnode = producer_nodes->nodeTab[i];
      producers.push_back(getProducer(context,pnode,commodities_.at(position)));
    } // end producer nodes

    // populate info
    sdmanager_.registerCommodity(commodities_.at(position),demand,producers);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Producer GrowthRegion::getProducer(xmlXPathContextPtr& context,
                                   xmlNodePtr& node,
                                   Commodity& commodity) {
  string fac_name =
    (const char*)XMLinput->get_xpath_content(context,node,"facility");
  double capacity =
    atof((const char*)
         XMLinput->get_xpath_content(context,node,"capacity"));
  double cost = capacity; // cost = capacity
  return Producer(fac_name,commodity,capacity,cost);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::copy(GrowthRegion* src) {
  RegionModel::copy(src);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::string GrowthRegion::str() {
  std::string s = RegionModel::str();

  // if ( builders_ == NULL || builders_->empty() ){
  //   s += name() + " has no builders (currently).";
  // } else {
  //   s += name() + " has the following builders: " ;
  //   for(map<Model*, list<Model*>*>::iterator mit=builders_->begin();
  //       mit != builders_->end(); mit++) {
  //     s += " prototype=" + mit->first->name() + "(";
  //     for(list<Model*>::iterator inst = mit->second->begin();
  //         inst != mit->second->end(); inst++) {
  //       s += (*inst)->name() + ", ";
  //     }
  //     s += "), ";
  //   }
  // }
  return s;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::handleTick(int time) {

  // for each commodity
  for (int i = 0; i < commodities_.size(); i++) {
    Commodity c = commodities_.at(i);

    // does demand exist?
    double unmet_demand =
      sdmanager_.supply(c) - sdmanager_.demand(c,time);

    // if so, determine which prototypes to build and build them
    if (unmet_demand > 0) {
      vector<BuildOrder> orders =
        buildmanager_->makeBuildDecision(c,unmet_demand);
      // build the prototypes
      orderBuilds(orders);
    }
  }

  // After we finish building, call the normal handleTick for a region
  RegionModel::handleTick(time);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::populateProducerMaps() {

  // if there are no children, yell
  if ( children_.empty() ) {
    stringstream err("");
    err << "GrowthRegion " << this->name()
        << " cannot populate its list"
        << " of builders because it has no children.";
    throw CycOverrideException(err.str());
  }

  // for each commodity
  for (int i = 0; i < commodities_.size(); i++) {
    Commodity c = commodities_.at(i);

    // map each producer's name to a pointer to it
    map<string,Producer*> producer_names;
    populateProducerNames(c,producer_names);

    // populate the maps with those producer names
    populateMaps(this,producer_names);
  }

  // if there are no builders, yell
  if ( builders_.empty() ) {
    stringstream err("");
    err << "GrowthRegion " << this->name()
        << " has finished populating"
        << " its list of builders, but that list is empty.";
    throw CycOverrideException(err.str());
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::populateProducerNames(Commodity& c,
                                         std::map<std::string,Producer*>&
                                         producer_names) {
  for (int j = 0; j < sdmanager_.nProducers(c); j++) {
    Producer* p = sdmanager_.producer(c,j);
    producer_names[p->name()] = p;
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::populateMaps(Model* node,
                                std::map<std::string,Producer*>&
                                producer_names) {
  // the name to search for
  string model_name = node->name();

  // if the model is in producers, log it as a producer
  // and its parent as a builder
  map<string,Producer*>::iterator it = producer_names.find(model_name);
  if (it != producer_names.end()) {
    producers_[it->second] = node;
    builders_[it->second] = node->parent();
  }

  // perform the same operation for each of this node's children
  for (int i = 0; i < node->nChildren(); i++) {
    populateMaps(node->children(i),producer_names);
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::string GrowthRegion::printMaps() {
  stringstream ss("");
  map<Producer*,Model*>::iterator it;
  ss << "Producer map:" << endl;
  for (it = producers_.begin(); it != producers_.end(); it++) {
    ss << "\t" << it->first->name() << " producer produces model "
       << it->second->name() << endl;
  }
  ss << "Builder map:" << endl;
  for (it = builders_.begin(); it != builders_.end(); it++) {
    ss << "\t" << it->first->name() << " producer is built by model "
       << it->second->name() << endl;
  }
  return ss.str();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::orderBuilds(std::vector<BuildOrder>& orders) {
  // for each order
  for (int i = 0; i < orders.size(); i++) {
    BuildOrder bo = orders.at(i);
    // for each instance of a prototype order
    for (int j = 0; j < bo.number; j++) {
      Model* builder = builders_[bo.producer];
      Model* prototype = producers_[bo.producer];
      orderBuild(builder,prototype);
    }
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::orderBuild(Model* builder, Model* prototype) {
  // build functions must know who is placing the build order
  dynamic_cast<InstModel*>(builder)->build(prototype,this);
}
/* -------------------- */

/* --------------------
 * Model Class Methods
 * --------------------
 */
extern "C" Model* constructGrowthRegion() {
    return new GrowthRegion();
}

/* -------------------- */

<|endoftext|>


<commit_before>// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"
#include "OgreMaterialResource.h"
#include "OgreParticleResource.h"
#include "OgreTextureResource.h"
#include "OgreRenderingModule.h"
#include "OgreMaterialUtils.h"
#include "ResourceHandler.h"

#include <Ogre.h>

namespace OgreRenderer
{
    OgreParticleResource::OgreParticleResource(const std::string& id) :
        ResourceInterface(id)
    {
    }

    OgreParticleResource::OgreParticleResource(const std::string& id, Foundation::AssetPtr source) :
        ResourceInterface(id)
    {
        SetData(source);
    }

    OgreParticleResource::~OgreParticleResource()
    {
        RemoveTemplates();
    }

    bool OgreParticleResource::SetData(Foundation::AssetPtr source)
    {
        RemoveTemplates();
        references_.clear();

        if (!source)
        {
            OgreRenderingModule::LogError("Null source asset data pointer");
            return false;
        }
        if (!source->GetSize())
        {
            OgreRenderingModule::LogError("Zero sized particle system asset");
            return false;
        }

        // Detected template names
        Core::StringVector new_templates;

        Ogre::DataStreamPtr data = Ogre::DataStreamPtr(new Ogre::MemoryDataStream(const_cast<Core::u8 *>(source->GetData()), source->GetSize()));
        try
        {
            int brace_level = 0;
            bool skip_until_next = false;
            int skip_brace_level = 0;
            // Parsed/modified script
            std::ostringstream output;

            while (!data->eof())
            {
                Ogre::String line = data->getLine();
                // Skip empty lines & comments
                if ((line.length()) && (line.substr(0, 2) != "//"))
                {
                    // Process opening/closing braces
                    if (!ResourceHandler::ProcessBraces(line, brace_level))
                    {
                        // If not a brace and on level 0, it should be a new particlesystem; replace name with resource ID + ordinal
                        if (brace_level == 0)
                        {
                            line = id_ + "_" + Core::ToString<size_t>(new_templates.size());
                            new_templates.push_back(line);
                            // New script compilers need this
                            line = "particle_system " + line;
                        }
                        else
                        {
                            // Check for ColourImage, which is a risky affector and may easily crash if image can't be loaded
                            if (line.substr(0, 8) == "affector")
                            {
                                std::vector<Ogre::String> line_vec = Ogre::StringUtil::split(line, "\t ");
                                if (line_vec.size() >= 2)
                                {
                                    if (line_vec[1] == "ColourImage")
                                    {
                                        skip_until_next = true;
                                        skip_brace_level = brace_level;
                                    }
                                }
                            }
                            // Check for image/material definition
                            else if (line.substr(0, 8) == "material")
                            {
                                std::vector<Ogre::String> line_vec = Ogre::StringUtil::split(line, "\t ");
                                if (line_vec.size() >= 2)
                                {
                                    std::string mat_name = line_vec[1];
                                    // Material script mode
                                    if ((line_vec.size() >= 3) && (line_vec[2].substr(0,6) == "script"))
                                    {
                                        references_.push_back(Foundation::ResourceReference(mat_name, OgreMaterialResource::GetTypeStatic()));
                                        line = "material " + mat_name;
                                    }
                                    // Texture mode
                                    else
                                    {
                                        //! @todo handle legacy material variations
                                        std::string variation;
                                        if (line_vec.size() >= 3)
                                            variation = line_vec[2];

                                        references_.push_back(Foundation::ResourceReference(mat_name, OgreTextureResource::GetTypeStatic()));
                                        line = "material " + mat_name;
                                    }
                                }
                            }
                        }
                        // Write line to the copy
                        if (!skip_until_next)
                            output << line << std::endl;
                        else
                            OgreRenderingModule::LogDebug("Skipping risky particle effect line: " + line);
                    }
                    else
                    {
                        // Write line to the copy
                        if (!skip_until_next)
                            output << line << std::endl;
                        else
                            OgreRenderingModule::LogDebug("Skipping risky particle effect line: " + line);

                        if (brace_level <= skip_brace_level)
                            skip_until_next = false;
                    }
                }
            }

            std::string output_str = output.str();
            Ogre::DataStreamPtr modified_data = Ogre::DataStreamPtr(new Ogre::MemoryDataStream(&output_str[0], output_str.size()));
            Ogre::ParticleSystemManager::getSingleton().parseScript(modified_data, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
        }
        catch (Ogre::Exception& e)
        {
            OgreRenderingModule::LogWarning(e.what());
            OgreRenderingModule::LogWarning("Failed to parse Ogre particle script " + source->GetId() + ".");
        }

        // Check which templates actually succeeded
        for (Core::uint i = 0; i < new_templates.size(); ++i)
        {
            if (Ogre::ParticleSystemManager::getSingleton().getTemplate(new_templates[i]))
            {
                templates_.push_back(new_templates[i]);
                OgreRenderingModule::LogDebug("Ogre particle system template " + new_templates[i] + " created");
            }
        }

        // Theoretical success if at least one template was created
        return IsValid();
    }

    static const std::string type_name("OgreParticle");

    const std::string& OgreParticleResource::GetType() const
    {
        return type_name;
    }

    const std::string& OgreParticleResource::GetTypeStatic()
    {
        return type_name;
    }

    Core::uint OgreParticleResource::GetNumTemplates() const
    {
        return templates_.size();
    }

    const std::string& OgreParticleResource::GetTemplateName(Core::uint index) const
    {
        static const std::string empty;
        if (index >= templates_.size())
            return empty;

        return templates_[index];
    }

    void OgreParticleResource::RemoveTemplates()
    {
        for (unsigned i = 0; i < templates_.size(); ++i)
        {
            try
            {
                Ogre::ParticleSystemManager::getSingleton().removeTemplate(templates_[i]);
            } catch (...) {}
        }
        templates_.clear();
    }

    bool OgreParticleResource::IsValid() const
    {
        return (templates_.size() > 0);
    }
}<commit_msg>[Fix] Should now compile also with latest Ogre and GCC. <commit_after>// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"
#include "OgreMaterialResource.h"
#include "OgreParticleResource.h"
#include "OgreTextureResource.h"
#include "OgreRenderingModule.h"
#include "OgreMaterialUtils.h"
#include "ResourceHandler.h"

#include <Ogre.h>

namespace OgreRenderer
{
    OgreParticleResource::OgreParticleResource(const std::string& id) :
        ResourceInterface(id)
    {
    }

    OgreParticleResource::OgreParticleResource(const std::string& id, Foundation::AssetPtr source) :
        ResourceInterface(id)
    {
        SetData(source);
    }

    OgreParticleResource::~OgreParticleResource()
    {
        RemoveTemplates();
    }

    bool OgreParticleResource::SetData(Foundation::AssetPtr source)
    {
        RemoveTemplates();
        references_.clear();

        if (!source)
        {
            OgreRenderingModule::LogError("Null source asset data pointer");
            return false;
        }
        if (!source->GetSize())
        {
            OgreRenderingModule::LogError("Zero sized particle system asset");
            return false;
        }

        // Detected template names
        Core::StringVector new_templates;

        Ogre::DataStreamPtr data = Ogre::DataStreamPtr(new Ogre::MemoryDataStream(const_cast<Core::u8 *>(source->GetData()), source->GetSize()));
        try
        {
            int brace_level = 0;
            bool skip_until_next = false;
            int skip_brace_level = 0;
            // Parsed/modified script
            std::ostringstream output;

            while (!data->eof())
            {
                Ogre::String line = data->getLine();
                // Skip empty lines & comments
                if ((line.length()) && (line.substr(0, 2) != "//"))
                {
                    // Process opening/closing braces
                    if (!ResourceHandler::ProcessBraces(line, brace_level))
                    {
                        // If not a brace and on level 0, it should be a new particlesystem; replace name with resource ID + ordinal
                        if (brace_level == 0)
                        {
                            line = id_ + "_" + Core::ToString<size_t>(new_templates.size());
                            new_templates.push_back(line);
                            // New script compilers need this
                            line = "particle_system " + line;
                        }
                        else
                        {
                            // Check for ColourImage, which is a risky affector and may easily crash if image can't be loaded
                            if (line.substr(0, 8) == "affector")
                            {
			      std::vector<Ogre::String> line_vec;

#if OGRE_VERSION_MAJOR == 1 && OGRE_VERSION_MINOR == 6
			      line_vec = Ogre::StringUtil::split(line, "\t ");
#else
			      Ogre::vector<Ogre::String>::type vec = Ogre::StringUtil::split(line,"\t ");
			      int size = vec.size();
			      line_vec.resize(size);

			      for (int i = 0; i < size; ++i)
				line_vec[i] = vec[i];
#endif
                               if (line_vec.size() >= 2)
                                {
                                    if (line_vec[1] == "ColourImage")
                                    {
                                        skip_until_next = true;
                                        skip_brace_level = brace_level;
                                    }
                                }
                            }
                            // Check for image/material definition
                            else if (line.substr(0, 8) == "material")
                            {
			      std::vector<Ogre::String> line_vec;
#if OGRE_VERSION_MAJOR == 1 && OGRE_VERSION_MINOR == 6
			      line_vec = Ogre::StringUtil::split(line, "\t ");
#else
			      Ogre::vector<Ogre::String>::type vec = Ogre::StringUtil::split(line,"\t ");
			      int size = vec.size();
			      line_vec.resize(size);

			      for (int i = 0; i < size; ++i)
				line_vec[i] = vec[i];
#endif
				if (line_vec.size() >= 2)
                                {
                                    std::string mat_name = line_vec[1];
                                    // Material script mode
                                    if ((line_vec.size() >= 3) && (line_vec[2].substr(0,6) == "script"))
                                    {
                                        references_.push_back(Foundation::ResourceReference(mat_name, OgreMaterialResource::GetTypeStatic()));
                                        line = "material " + mat_name;
                                    }
                                    // Texture mode
                                    else
                                    {
                                        //! @todo handle legacy material variations
                                        std::string variation;
                                        if (line_vec.size() >= 3)
                                            variation = line_vec[2];

                                        references_.push_back(Foundation::ResourceReference(mat_name, OgreTextureResource::GetTypeStatic()));
                                        line = "material " + mat_name;
                                    }
                                }
                            }
                        }
                        // Write line to the copy
                        if (!skip_until_next)
                            output << line << std::endl;
                        else
                            OgreRenderingModule::LogDebug("Skipping risky particle effect line: " + line);
                    }
                    else
                    {
                        // Write line to the copy
                        if (!skip_until_next)
                            output << line << std::endl;
                        else
                            OgreRenderingModule::LogDebug("Skipping risky particle effect line: " + line);

                        if (brace_level <= skip_brace_level)
                            skip_until_next = false;
                    }
                }
            }

            std::string output_str = output.str();
            Ogre::DataStreamPtr modified_data = Ogre::DataStreamPtr(new Ogre::MemoryDataStream(&output_str[0], output_str.size()));
            Ogre::ParticleSystemManager::getSingleton().parseScript(modified_data, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
        }
        catch (Ogre::Exception& e)
        {
            OgreRenderingModule::LogWarning(e.what());
            OgreRenderingModule::LogWarning("Failed to parse Ogre particle script " + source->GetId() + ".");
        }

        // Check which templates actually succeeded
        for (Core::uint i = 0; i < new_templates.size(); ++i)
        {
            if (Ogre::ParticleSystemManager::getSingleton().getTemplate(new_templates[i]))
            {
                templates_.push_back(new_templates[i]);
                OgreRenderingModule::LogDebug("Ogre particle system template " + new_templates[i] + " created");
            }
        }

        // Theoretical success if at least one template was created
        return IsValid();
    }

    static const std::string type_name("OgreParticle");

    const std::string& OgreParticleResource::GetType() const
    {
        return type_name;
    }

    const std::string& OgreParticleResource::GetTypeStatic()
    {
        return type_name;
    }

    Core::uint OgreParticleResource::GetNumTemplates() const
    {
        return templates_.size();
    }

    const std::string& OgreParticleResource::GetTemplateName(Core::uint index) const
    {
        static const std::string empty;
        if (index >= templates_.size())
            return empty;

        return templates_[index];
    }

    void OgreParticleResource::RemoveTemplates()
    {
        for (unsigned i = 0; i < templates_.size(); ++i)
        {
            try
            {
                Ogre::ParticleSystemManager::getSingleton().removeTemplate(templates_[i]);
            } catch (...) {}
        }
        templates_.clear();
    }

    bool OgreParticleResource::IsValid() const
    {
        return (templates_.size() > 0);
    }
}
<|endoftext|>


<commit_before>/* Copyright (c) 2010, Antonie Jovanoski
 *
 * All rights reserved.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Contact e-mail: Antonie Jovanoski <minimoog77_at_gmail.com>
 */

#include <QtDebug>
#include <QNetworkRequest>
#include <QNetworkReply>
#include "qtweetfriendshipdestroy.h"
#include "qtweetuser.h"
#include "qtweetconvert.h"

/**
 *  Constructor
 */
QTweetFriendshipDestroy::QTweetFriendshipDestroy(QObject *parent) :
    QTweetNetBase(parent)
{
}

/**
 *  Constructor
 *  @param oauthTwitter OAuthTwitter object
 *  @param parent parent QObject
 */
QTweetFriendshipDestroy::QTweetFriendshipDestroy(OAuthTwitter *oauthTwitter, QObject *parent) :
        QTweetNetBase(oauthTwitter, parent)
{
}

/**
 *  Unfollows the specified user
 *  @param userid user id to unfollow
 *  @param includeEntities when set totrue, each tweet will include a node called "entities,".
 */
void QTweetFriendshipDestroy::unfollow(qint64 userid, bool includeEntities)
{
    if (!isAuthenticationEnabled()) {
        qCritical("Needs authentication to be enabled");
        return;
    }

    QUrl url("http://api.twitter.com/1/friendships/destroy.json");

    url.addQueryItem("user_id", QString::number(userid));

    if (includeEntities)
        url.addQueryItem("include_entities", "true");

    QNetworkRequest req(url);

    QByteArray oauthHeader = oauthTwitter()->generateAuthorizationHeader(url, OAuth::GET);
    req.setRawHeader(AUTH_HEADER, oauthHeader);

    QNetworkReply *reply = oauthTwitter()->networkAccessManager()->deleteResource(req);
    connect(reply, SIGNAL(finished()), this, SLOT(reply()));
}

/**
 *  Unfollows the specified user
 *  @param screenName screen name to unfollow
 *  @param includeEntities when set totrue, each tweet will include a node called "entities,".
 */
void QTweetFriendshipDestroy::unfollow(const QString &screenName, bool includeEntities)
{
    if (!isAuthenticationEnabled()) {
        qCritical("Needs authentication to be enabled");
        return;
    }

    QUrl url("http://api.twitter.com/1/friendships/destroy.json");

    url.addQueryItem("screen_name", screenName);

    if (includeEntities)
        url.addQueryItem("include_entities", "true");

    QNetworkRequest req(url);

    QByteArray oauthHeader = oauthTwitter()->generateAuthorizationHeader(url, OAuth::GET);
    req.setRawHeader(AUTH_HEADER, oauthHeader);

    QNetworkReply *reply = oauthTwitter()->networkAccessManager()->deleteResource(req);
    connect(reply, SIGNAL(finished()), this, SLOT(reply()));
}

void QTweetFriendshipDestroy::parsingJsonFinished(const QVariant &json, bool ok, const QString &errorMsg)
{
    if (ok) {
        QTweetUser user = QTweetConvert::variantMapToUserInfo(json.toMap());

        emit parsedUser(user);
    } else {
        qDebug() << "QTweetFriendshipCreate parser error: " << errorMsg;
        setLastErrorMessage(errorMsg);
        emit error(JsonParsingError, errorMsg);
    }
}
<commit_msg>Fixed issue 9.<commit_after>/* Copyright (c) 2010, Antonie Jovanoski
 *
 * All rights reserved.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Contact e-mail: Antonie Jovanoski <minimoog77_at_gmail.com>
 */

#include <QtDebug>
#include <QNetworkRequest>
#include <QNetworkReply>
#include "qtweetfriendshipdestroy.h"
#include "qtweetuser.h"
#include "qtweetconvert.h"

/**
 *  Constructor
 */
QTweetFriendshipDestroy::QTweetFriendshipDestroy(QObject *parent) :
    QTweetNetBase(parent)
{
}

/**
 *  Constructor
 *  @param oauthTwitter OAuthTwitter object
 *  @param parent parent QObject
 */
QTweetFriendshipDestroy::QTweetFriendshipDestroy(OAuthTwitter *oauthTwitter, QObject *parent) :
        QTweetNetBase(oauthTwitter, parent)
{
}

/**
 *  Unfollows the specified user
 *  @param userid user id to unfollow
 *  @param includeEntities when set totrue, each tweet will include a node called "entities,".
 */
void QTweetFriendshipDestroy::unfollow(qint64 userid, bool includeEntities)
{
    if (!isAuthenticationEnabled()) {
        qCritical("Needs authentication to be enabled");
        return;
    }

    QUrl url("http://api.twitter.com/1/friendships/destroy.json");

    url.addQueryItem("user_id", QString::number(userid));

    if (includeEntities)
        url.addQueryItem("include_entities", "true");

    QNetworkRequest req(url);

    QByteArray oauthHeader = oauthTwitter()->generateAuthorizationHeader(url, OAuth::DELETE);
    req.setRawHeader(AUTH_HEADER, oauthHeader);

    QNetworkReply *reply = oauthTwitter()->networkAccessManager()->deleteResource(req);
    connect(reply, SIGNAL(finished()), this, SLOT(reply()));
}

/**
 *  Unfollows the specified user
 *  @param screenName screen name to unfollow
 *  @param includeEntities when set totrue, each tweet will include a node called "entities,".
 */
void QTweetFriendshipDestroy::unfollow(const QString &screenName, bool includeEntities)
{
    if (!isAuthenticationEnabled()) {
        qCritical("Needs authentication to be enabled");
        return;
    }

    QUrl url("http://api.twitter.com/1/friendships/destroy.json");

    url.addQueryItem("screen_name", screenName);

    if (includeEntities)
        url.addQueryItem("include_entities", "true");

    QNetworkRequest req(url);

    QByteArray oauthHeader = oauthTwitter()->generateAuthorizationHeader(url, OAuth::DELETE);
    req.setRawHeader(AUTH_HEADER, oauthHeader);

    QNetworkReply *reply = oauthTwitter()->networkAccessManager()->deleteResource(req);
    connect(reply, SIGNAL(finished()), this, SLOT(reply()));
}

void QTweetFriendshipDestroy::parsingJsonFinished(const QVariant &json, bool ok, const QString &errorMsg)
{
    if (ok) {
        QTweetUser user = QTweetConvert::variantMapToUserInfo(json.toMap());

        emit parsedUser(user);
    } else {
        qDebug() << "QTweetFriendshipCreate parser error: " << errorMsg;
        setLastErrorMessage(errorMsg);
        emit error(JsonParsingError, errorMsg);
    }
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of meegotouch-controlpanelapplets.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "resetapplet.h"
#include "resetwidget.h"
#include "resetbrief.h"

#include <MTheme>
#include <MAction>
#include <QDBusInterface>

#undef DEBUG
#include "../debug.h"

Q_EXPORT_PLUGIN2(resetapplet, ResetApplet)

ResetApplet::ResetApplet() :
    m_ResetBusinessLogic (new ResetBusinessLogic)
{
}

ResetApplet::~ResetApplet()
{
    delete m_ResetBusinessLogic;
}

void
ResetApplet::init()
{
}

DcpWidget *
ResetApplet::pageMain(
        int widgetId)
{
    SYS_DEBUG ("widgetId = %d", widgetId);
    switch (widgetId) {
        case 0:
            if (m_MainWidget == 0)
                m_MainWidget = new ResetWidget (m_ResetBusinessLogic);
            return m_MainWidget;

        default:
            SYS_WARNING ("Unknown widgetId: %d", widgetId);
    }

    return 0;
}

DcpWidget *
ResetApplet::constructWidget (
        int widgetId)
{
    SYS_DEBUG ("-----------------------------------");
    SYS_DEBUG ("*** widgetId = %d", widgetId);
    return pageMain (widgetId);
}

QString
ResetApplet::title() const
{
    //% "Reset settings"
    return qtTrId ("qtn_rset_reset_settings");
}

QVector<MAction*>
ResetApplet::viewMenuItems()
{
    MAction            *helpAction;
    QVector<MAction*>   vector;

    SYS_DEBUG ("");
    helpAction = new MAction (
            //% "User Guide"
            qtTrId ("qtn_comm_userguide"),
            pageMain (0));
    helpAction->setLocation (MAction::ApplicationMenuLocation);

    connect (helpAction, SIGNAL (triggered (bool)),
             this, SLOT (userGuide ()));

    vector.append(helpAction);

    return vector;
}

void
ResetApplet::userGuide ()
{
    QDBusInterface userguide ("com.nokia.userguide", "/",
                              "com.nokia.UserGuideIf");
    userguide.call ("pageByPath", "tips.cfg");
    SYS_DEBUG ("");
}

DcpBrief *
ResetApplet::constructBrief (
        int partId)
{
    Q_UNUSED (partId);
    return new ResetBrief (m_ResetBusinessLogic);
}
<commit_msg>removed menu from reset applet.<commit_after>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of meegotouch-controlpanelapplets.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "resetapplet.h"
#include "resetwidget.h"
#include "resetbrief.h"

#include <MTheme>
#include <MAction>
#include <QDBusInterface>

#undef DEBUG
#include "../debug.h"

Q_EXPORT_PLUGIN2(resetapplet, ResetApplet)

ResetApplet::ResetApplet() :
    m_ResetBusinessLogic (new ResetBusinessLogic)
{
}

ResetApplet::~ResetApplet()
{
    delete m_ResetBusinessLogic;
}

void
ResetApplet::init()
{
}

DcpWidget *
ResetApplet::pageMain(
        int widgetId)
{
    SYS_DEBUG ("widgetId = %d", widgetId);
    switch (widgetId) {
        case 0:
            if (m_MainWidget == 0)
                m_MainWidget = new ResetWidget (m_ResetBusinessLogic);
            return m_MainWidget;

        default:
            SYS_WARNING ("Unknown widgetId: %d", widgetId);
    }

    return 0;
}

DcpWidget *
ResetApplet::constructWidget (
        int widgetId)
{
    SYS_DEBUG ("-----------------------------------");
    SYS_DEBUG ("*** widgetId = %d", widgetId);
    return pageMain (widgetId);
}

QString
ResetApplet::title() const
{
    //% "Reset settings"
    return qtTrId ("qtn_rset_reset_settings");
}

QVector<MAction*>
ResetApplet::viewMenuItems()
{
    QVector<MAction*>   vector;

    return vector;
}

void
ResetApplet::userGuide ()
{
    QDBusInterface userguide ("com.nokia.userguide", "/",
                              "com.nokia.UserGuideIf");
    userguide.call ("pageByPath", "tips.cfg");
    SYS_DEBUG ("");
}

DcpBrief *
ResetApplet::constructBrief (
        int partId)
{
    Q_UNUSED (partId);
    return new ResetBrief (m_ResetBusinessLogic);
}
<|endoftext|>


<commit_before>/*=========================================================================
   Library:   TubeTK

   Copyright 2010 Kitware Inc. 28 Corporate Drive,
   Clifton Park, NY, 12065, USA.

   All rights reserved.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
=========================================================================*/
#include <iostream>
#include <sstream>

#include "itkTimeProbesCollectorBase.h"
#include "tubeMessage.h"

#include "tubeMacro.h"
#include "metaScene.h"

#include "itkSpatialObjectReader.h"
#include "itkSpatialObjectWriter.h"
#include "itkGroupSpatialObject.h"

#include "ClipTubesCLP.h"

template< unsigned int VDimension >
bool isInside (itk::Point<double,VDimension> pointPos, double tubeRadius,
		 std::vector<double> boxPos, std::vector<double> boxSize)
{
  // Return a boolean indicating if any slice of the tube
  // is included in the box.
  // A slice is considered as a point and an associated radius
  bool hasXInside=false;
  bool hasYInside=false,
  bool hasZInside=false;

  if( pointPos[0] + tubeRadius >= boxPos[0] &&
    pointPos[0] - tubeRadius <= boxPos[0] + boxSize[0] )
    {
    hasXInside = true;
    }
  if( pointPos[1] <= boxPos[1] &&
    pointPos[1] >= boxPos[1] - boxSize[1] )
    {
    hasYInside = true;
    }
  switch( VDimension )
    {
    case 2:
      {
      hasZInside = true;
      break;
      }
    case 3:
      {
      if( pointPos[2] + tubeRadius >= boxPos[2] &&
	pointPos[2] - tubeRadius <= boxPos[2] + boxSize[2] )
	{
	hasZInside = true;
	}
      break;
      }
    default:
      {
      tubeErrorMacro(
        << "Error: Only 2D and 3D data is currently supported." );
      return EXIT_FAILURE;
      }
    }

  return (hasXInside && hasYInside && hasZInside);
}

template< unsigned int VDimension >
int DoIt (int argc, char * argv[])
{
  PARSE_ARGS;

  // Ensure that the input image dimension is valid
  // We only support 2D and 3D Images due to the
  // limitation of itkTubeSpatialObject
  if( VDimension != 2 && VDimension != 3 )
    {
    tube::ErrorMessage(
      "Error: Only 2D and 3D data is currently supported.");
    return EXIT_FAILURE;
    }

  // The timeCollector to perform basic profiling of algorithmic components
  itk::TimeProbesCollectorBase timeCollector;

  // Load TRE File
  tubeStandardOutputMacro( << "\n>> Loading TRE File" );

  typedef itk::SpatialObjectReader< VDimension > 	   TubesReaderType;
  typedef itk::GroupSpatialObject< VDimension >  	   TubeGroupType;
//   typedef itk::TubeSpatialObject< VDimension >  TubeType;
/*WARNING :
  dynamic_cast on "typedef itk::TubeSpatialObject< VDimension > TubeType"
  causes SEGFAULT
  so TubeType corresponds to VesselTubeType to prevent issues
  so TubePointType corresponds to VesselTubePointType */
  typedef itk::VesselTubeSpatialObject< VDimension >  	   TubeType;
  typedef itk::VesselTubeSpatialObjectPoint< VDimension >  TubePointType;

  timeCollector.Start( "Loading Input TRE File" );

  typename TubesReaderType::Pointer tubeFileReader = TubesReaderType::New();

  try
    {
    tubeFileReader->SetFileName( inputTREFile.c_str() );
    tubeFileReader->Update();
    }
  catch( itk::ExceptionObject & err )
    {
    tube::ErrorMessage( "Error loading TRE File: "
      + std::string( err.GetDescription() ) );
    timeCollector.Report();
    return EXIT_FAILURE;
    }

  typename TubeGroupType::Pointer pSourceTubeGroup =
    tubeFileReader->GetGroup();
  typename TubeGroupType::ChildrenListPointer pSourceTubeList =
    pSourceTubeGroup->GetChildren();

  timeCollector.Stop( "Loading Input TRE File" );

  // Compute clipping
  tubeStandardOutputMacro( << "\n>> Finding Tubes for Clipping" );

  timeCollector.Start( "Selecting Tubes" );
  //Target Group to save desired tubes
  typename TubeGroupType::Pointer pTargetTubeGroup = TubeGroupType::New();

  int targetTubeId=0;

  for( typename TubeGroupType::ChildrenListType::iterator
    tubeList_it = pSourceTubeList->begin();
    tubeList_it != pSourceTubeList->end(); ++tubeList_it)
    {
    //**** Source Tube **** :
    typename TubeType::Pointer pCurSourceTube =
      dynamic_cast< TubeType* >( tubeList_it->GetPointer() );
    //dynamic_cast verification
    if(!pCurSourceTube)
      {
      return EXIT_FAILURE;
      }
    //Point List for TargetTube
    typename TubeType::PointListType TargetPointList;
    //Get points in current source tube
    typename TubeType::PointListType pointList =
      pCurSourceTube->GetPoints();

    for( typename TubeType::PointListType::const_iterator
      pointList_it = pointList.begin();
      pointList_it != pointList.end(); ++pointList_it )
      {
      TubePointType curSourcePoint = *pointList_it;
      typename TubePointType::PointType curSourcePos =
        curSourcePoint.GetPosition();
      //Save point in target tube if it belongs to the box
      if(isInside(curSourcePos,curSourcePoint.GetRadius(),boxCorner,boxSize))
	{
	if(ClipTubes)
	  {
	  TargetPointList.push_back(curSourcePoint);
	  }
	else
	  {
	  pCurSourceTube->SetId(targetTubeId);
	  ++targetTubeId;
	  pTargetTubeGroup->AddSpatialObject(pCurSourceTube);
	  break;
	  }
	}
      else
	{
	if( TargetPointList.size() > 0 )
	  {
	  //**** Target Tube **** :
	  typename TubeType::Pointer pTargetTube = TubeType::New();
	  pTargetTube->SetId(targetTubeId);
	  ++targetTubeId;
	  //Save clipped tube
	  pTargetTube->SetPoints(TargetPointList);
	  pTargetTubeGroup->AddSpatialObject(pTargetTube);

	  TargetPointList.clear();
	  }
	}
      }
    }
  timeCollector.Stop( "Selecting Tubes" );

  // Write output TRE file
  tubeStandardOutputMacro(
    << "\n>> Writing TRE file" );

  timeCollector.Start( "Writing output TRE file" );

  typedef itk::SpatialObjectWriter< VDimension > TubeWriterType;
  typename TubeWriterType::Pointer tubeWriter = TubeWriterType::New();

  try
    {
    tubeWriter->SetFileName( outputTREFile.c_str() );
    tubeWriter->SetInput(pTargetTubeGroup);
    tubeWriter->Update();
    }
  catch( itk::ExceptionObject & err )
    {
    tube::ErrorMessage( "Error writing TRE file: "
      + std::string( err.GetDescription() ) );
    timeCollector.Report();
    return EXIT_FAILURE;
    }

  timeCollector.Stop( "Writing output TRE file" );
  timeCollector.Report();
  return EXIT_SUCCESS;
}

// Main
int main( int argc, char * argv[] )
{
  try
    {
    PARSE_ARGS;
    }
  catch( const std::exception & err )
    {
    tube::ErrorMessage( err.what() );
    return EXIT_FAILURE;
    }
  PARSE_ARGS;

  if(boxCorner.empty() || boxSize.empty())
    {
    tube::ErrorMessage(
      "Error: longflags --boxCorner and --boxSize are both required");
    return EXIT_FAILURE;
    }

  MetaScene *mScene = new MetaScene;
  mScene->Read( inputTREFile.c_str() );

  if( mScene->GetObjectList()->empty() )
    {
    tubeWarningMacro( << "Input TRE file has no spatial objects" );
    return EXIT_SUCCESS;
    }

  switch( mScene->GetObjectList()->front()->NDims() )
    {
    case 2:
      {
      return DoIt<2>( argc, argv );
      break;
      }

    case 3:
      {
      return DoIt<3>( argc, argv );
      break;
      }

    default:
      {
      tubeErrorMacro(
	<< "Error: Only 2D and 3D data is currently supported.");
      return EXIT_FAILURE;
      }
    }
}<commit_msg>STYLE: KWStyle test OK<commit_after>/*=========================================================================
   Library:   TubeTK

   Copyright 2010 Kitware Inc. 28 Corporate Drive,
   Clifton Park, NY, 12065, USA.

   All rights reserved.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
=========================================================================*/
#include <iostream>
#include <sstream>

#include "itkTimeProbesCollectorBase.h"
#include "tubeMessage.h"

#include "tubeMacro.h"
#include "metaScene.h"

#include "itkSpatialObjectReader.h"
#include "itkSpatialObjectWriter.h"
#include "itkGroupSpatialObject.h"

#include "ClipTubesCLP.h"

template< unsigned int VDimension >
bool isInside (itk::Point<double,VDimension> pointPos, double tubeRadius,
                 std::vector<double> boxPos, std::vector<double> boxSize)
{
  // Return a boolean indicating if any slice of the tube
  // is included in the box.
  // A slice is considered as a point and an associated radius
  bool hasXInside=false;
  bool hasYInside=false,
  bool hasZInside=false;

  if( pointPos[0] + tubeRadius >= boxPos[0] &&
    pointPos[0] - tubeRadius <= boxPos[0] + boxSize[0] )
    {
    hasXInside = true;
    }
  if( pointPos[1] <= boxPos[1] &&
    pointPos[1] >= boxPos[1] - boxSize[1] )
    {
    hasYInside = true;
    }
  switch( VDimension )
    {
    case 2:
      {
      hasZInside = true;
      break;
      }
    case 3:
      {
      if( pointPos[2] + tubeRadius >= boxPos[2] &&
        pointPos[2] - tubeRadius <= boxPos[2] + boxSize[2] )
        {
        hasZInside = true;
        }
      break;
      }
    default:
      {
      tubeErrorMacro(
        << "Error: Only 2D and 3D data is currently supported." );
      return EXIT_FAILURE;
      }
    }

  return (hasXInside && hasYInside && hasZInside);
}

template< unsigned int VDimension >
int DoIt (int argc, char * argv[])
{
  PARSE_ARGS;

  // Ensure that the input image dimension is valid
  // We only support 2D and 3D Images due to the
  // limitation of itkTubeSpatialObject
  if( VDimension != 2 && VDimension != 3 )
    {
    tube::ErrorMessage(
      "Error: Only 2D and 3D data is currently supported.");
    return EXIT_FAILURE;
    }

  // The timeCollector to perform basic profiling of algorithmic components
  itk::TimeProbesCollectorBase timeCollector;

  // Load TRE File
  tubeStandardOutputMacro( << "\n>> Loading TRE File" );

  typedef itk::SpatialObjectReader< VDimension >          TubesReaderType;
  typedef itk::GroupSpatialObject< VDimension >           TubeGroupType;
//typedef itk::TubeSpatialObject< VDimension >            TubeType;
/*WARNING :
  dynamic_cast on "typedef itk::TubeSpatialObject< VDimension > TubeType"
  causes SEGFAULT
  so TubeType corresponds to VesselTubeType to prevent issues
  so TubePointType corresponds to VesselTubePointType */
  typedef itk::VesselTubeSpatialObject< VDimension >      TubeType;
  typedef itk::VesselTubeSpatialObjectPoint< VDimension > TubePointType;

  timeCollector.Start( "Loading Input TRE File" );

  typename TubesReaderType::Pointer tubeFileReader = TubesReaderType::New();

  try
    {
    tubeFileReader->SetFileName( inputTREFile.c_str() );
    tubeFileReader->Update();
    }
  catch( itk::ExceptionObject & err )
    {
    tube::ErrorMessage( "Error loading TRE File: "
      + std::string( err.GetDescription() ) );
    timeCollector.Report();
    return EXIT_FAILURE;
    }

  typename TubeGroupType::Pointer pSourceTubeGroup =
    tubeFileReader->GetGroup();
  typename TubeGroupType::ChildrenListPointer pSourceTubeList =
    pSourceTubeGroup->GetChildren();

  timeCollector.Stop( "Loading Input TRE File" );

  // Compute clipping
  tubeStandardOutputMacro( << "\n>> Finding Tubes for Clipping" );

  timeCollector.Start( "Selecting Tubes" );
  //Target Group to save desired tubes
  typename TubeGroupType::Pointer pTargetTubeGroup = TubeGroupType::New();

  int targetTubeId=0;

  for( typename TubeGroupType::ChildrenListType::iterator
    tubeList_it = pSourceTubeList->begin();
    tubeList_it != pSourceTubeList->end(); ++tubeList_it)
    {
    //**** Source Tube **** :
    typename TubeType::Pointer pCurSourceTube =
      dynamic_cast< TubeType* >( tubeList_it->GetPointer() );
    //dynamic_cast verification
    if(!pCurSourceTube)
      {
      return EXIT_FAILURE;
      }
    //Point List for TargetTube
    typename TubeType::PointListType TargetPointList;
    //Get points in current source tube
    typename TubeType::PointListType pointList =
      pCurSourceTube->GetPoints();

    for( typename TubeType::PointListType::const_iterator
      pointList_it = pointList.begin();
      pointList_it != pointList.end(); ++pointList_it )
      {
      TubePointType curSourcePoint = *pointList_it;
      typename TubePointType::PointType curSourcePos =
        curSourcePoint.GetPosition();
      //Save point in target tube if it belongs to the box
      if(isInside(curSourcePos,curSourcePoint.GetRadius(),boxCorner,boxSize))
        {
        if(ClipTubes)
          {
          TargetPointList.push_back(curSourcePoint);
          }
        else
          {
          pCurSourceTube->SetId(targetTubeId);
          ++targetTubeId;
          pTargetTubeGroup->AddSpatialObject(pCurSourceTube);
          break;
          }
        }
      else
        {
        if( TargetPointList.size() > 0 )
          {
          //**** Target Tube **** :
          typename TubeType::Pointer pTargetTube = TubeType::New();
          pTargetTube->SetId(targetTubeId);
          ++targetTubeId;
          //Save clipped tube
          pTargetTube->SetPoints(TargetPointList);
          pTargetTubeGroup->AddSpatialObject(pTargetTube);

          TargetPointList.clear();
          }
        }
      }
    }
  timeCollector.Stop( "Selecting Tubes" );

  // Write output TRE file
  tubeStandardOutputMacro(
    << "\n>> Writing TRE file" );

  timeCollector.Start( "Writing output TRE file" );

  typedef itk::SpatialObjectWriter< VDimension > TubeWriterType;
  typename TubeWriterType::Pointer tubeWriter = TubeWriterType::New();

  try
    {
    tubeWriter->SetFileName( outputTREFile.c_str() );
    tubeWriter->SetInput(pTargetTubeGroup);
    tubeWriter->Update();
    }
  catch( itk::ExceptionObject & err )
    {
    tube::ErrorMessage( "Error writing TRE file: "
      + std::string( err.GetDescription() ) );
    timeCollector.Report();
    return EXIT_FAILURE;
    }

  timeCollector.Stop( "Writing output TRE file" );
  timeCollector.Report();
  return EXIT_SUCCESS;
}

// Main
int main( int argc, char * argv[] )
{
  try
    {
    PARSE_ARGS;
    }
  catch( const std::exception & err )
    {
    tube::ErrorMessage( err.what() );
    return EXIT_FAILURE;
    }
  PARSE_ARGS;

  if(boxCorner.empty() || boxSize.empty())
    {
    tube::ErrorMessage(
      "Error: longflags --boxCorner and --boxSize are both required");
    return EXIT_FAILURE;
    }

  MetaScene *mScene = new MetaScene;
  mScene->Read( inputTREFile.c_str() );

  if( mScene->GetObjectList()->empty() )
    {
    tubeWarningMacro( << "Input TRE file has no spatial objects" );
    return EXIT_SUCCESS;
    }

  switch( mScene->GetObjectList()->front()->NDims() )
    {
    case 2:
      {
      return DoIt<2>( argc, argv );
      break;
      }

    case 3:
      {
      return DoIt<3>( argc, argv );
      break;
      }

    default:
      {
      tubeErrorMacro(
        << "Error: Only 2D and 3D data is currently supported.");
      return EXIT_FAILURE;
      }
    }
}
<|endoftext|>