<commit_before>#include "iteration/updater/source_updater_gauss_seidel.h"

#include <memory>
#include <iteration/updater/angular_source_updater_gauss_seidel.h>

#include "test_helpers/gmock_wrapper.h"
#include "quadrature/tests/quadrature_set_mock.h"
#include "formulation/tests/angular_stamper_mock.h"

namespace  {

using namespace bart;

template <typename DimensionWrapper>
class IterationUpdaterAngularSourceUpdaterGaussSeidelTest :
    public ::testing::Test {
 public:
  static constexpr int dim = DimensionWrapper::value;
  using UpdaterType = iteration::updater::AngularSourceUpdaterGaussSeidel<formulation::AngularStamperI<dim>>;
  using StamperType = formulation::AngularStamperMock<dim>;
  using QuadratureSetType = quadrature::QuadratureSetMock<dim>;

  std::shared_ptr<StamperType> stamper_ptr_;
  std::shared_ptr<QuadratureSetType> quadrature_set_ptr_;
  std::unique_ptr<UpdaterType> test_updater_;

  void SetUp() override;
};

template <typename DimensionWrapper>
void IterationUpdaterAngularSourceUpdaterGaussSeidelTest<DimensionWrapper>::SetUp() {
  stamper_ptr_ = std::make_shared<StamperType>();
  quadrature_set_ptr_ = std::make_shared<QuadratureSetType>();

  test_updater_ = std::make_unique<UpdaterType>(stamper_ptr_, quadrature_set_ptr_);
}

TYPED_TEST_SUITE(IterationUpdaterAngularSourceUpdaterGaussSeidelTest,
                 bart::testing::AllDimensions);

TYPED_TEST(IterationUpdaterAngularSourceUpdaterGaussSeidelTest, Constructor) {
  constexpr int dim = this->dim;
  using UpdaterType = iteration::updater::AngularSourceUpdaterGaussSeidel<formulation::AngularStamperI<dim>>;
  using StamperType = formulation::AngularStamperMock<dim>;
  auto stamper_ptr = std::make_shared<StamperType>();
  auto quadrature_set_ptr = std::make_shared<quadrature::QuadratureSetMock<dim>>();

  EXPECT_NO_THROW({ UpdaterType test_updater(stamper_ptr, quadrature_set_ptr); });
  EXPECT_ANY_THROW({ UpdaterType test_updater(nullptr, quadrature_set_ptr); });
  EXPECT_ANY_THROW({ UpdaterType test_updater(stamper_ptr, nullptr); });
}

TYPED_TEST(IterationUpdaterAngularSourceUpdaterGaussSeidelTest, Getters) {
  auto quadrature_set_ptr = this->test_updater_->quadrature_set_ptr();
  auto stamper_ptr = this->test_updater_->stamper_ptr();

  EXPECT_EQ(quadrature_set_ptr, this->quadrature_set_ptr_.get());
  EXPECT_EQ(stamper_ptr, this->stamper_ptr_.get());
}

} // namespace
<commit_msg>started adding test to tests for AngularSourceUpdater<commit_after>#include "iteration/updater/source_updater_gauss_seidel.h"

#include <memory>
#include <iteration/updater/angular_source_updater_gauss_seidel.h>
#include <deal.II/base/mpi.h>

#include "test_helpers/gmock_wrapper.h"
#include "quadrature/tests/quadrature_set_mock.h"
#include "formulation/tests/angular_stamper_mock.h"
#include "system/terms/tests/linear_term_mock.h"

namespace  {

using namespace bart;
using ::testing::A, ::testing::Return, ::testing::_;

template <typename DimensionWrapper>
class IterationUpdaterAngularSourceUpdaterGaussSeidelTest :
    public ::testing::Test {
 public:
  static constexpr int dim = DimensionWrapper::value;
  using UpdaterType = iteration::updater::AngularSourceUpdaterGaussSeidel<formulation::AngularStamperI<dim>>;
  using StamperType = formulation::AngularStamperMock<dim>;
  using QuadratureSetType = quadrature::QuadratureSetMock<dim>;
  using RightHandSideType = bart::system::terms::LinearTermMock;

  // Tested object
  std::unique_ptr<UpdaterType> test_updater_;

  // Dependencies
  std::shared_ptr<StamperType> stamper_ptr_;
  std::shared_ptr<QuadratureSetType> quadrature_set_ptr_;

  // Other test objects
  bart::system::System test_system_;
  std::shared_ptr<system::MPIVector> source_vector_ptr_;
  bart::system::MPIVector expected_vector_;
  RightHandSideType* right_hand_side_obs_ptr_;

  void SetUp() override;
  void SetUpTestObject();
  void SetUpSystem();
};

template <typename DimensionWrapper>
void IterationUpdaterAngularSourceUpdaterGaussSeidelTest<DimensionWrapper>::SetUp() {
  SetUpTestObject();
  SetUpSystem();
}

template <typename DimensionWrapper>
void IterationUpdaterAngularSourceUpdaterGaussSeidelTest<DimensionWrapper>::SetUpTestObject() {
  stamper_ptr_ = std::make_shared<StamperType>();
  quadrature_set_ptr_ = std::make_shared<QuadratureSetType>();

  test_updater_ = std::make_unique<UpdaterType>(stamper_ptr_, quadrature_set_ptr_);
}

template <typename DimensionWrapper>
void IterationUpdaterAngularSourceUpdaterGaussSeidelTest<DimensionWrapper>::SetUpSystem() {
  auto mock_right_hand_side_ptr = std::make_unique<RightHandSideType>();
  right_hand_side_obs_ptr_ = mock_right_hand_side_ptr.get();

  source_vector_ptr_ = std::make_shared<system::MPIVector>();
  auto n_processes = dealii::Utilities::MPI::n_mpi_processes(MPI_COMM_WORLD);
  source_vector_ptr_->reinit(MPI_COMM_WORLD, n_processes*5, 5);
  expected_vector_.reinit(*source_vector_ptr_);

  ON_CALL(*mock_right_hand_side_ptr, GetVariableTermPtr(A<system::Index>(), _))
      .WillByDefault(Return(source_vector_ptr_));

  test_system_.right_hand_side_ptr_ = std::move(mock_right_hand_side_ptr);
}

TYPED_TEST_SUITE(IterationUpdaterAngularSourceUpdaterGaussSeidelTest,
                 bart::testing::AllDimensions);

TYPED_TEST(IterationUpdaterAngularSourceUpdaterGaussSeidelTest, Constructor) {
  constexpr int dim = this->dim;
  using UpdaterType = iteration::updater::AngularSourceUpdaterGaussSeidel<formulation::AngularStamperI<dim>>;
  using StamperType = formulation::AngularStamperMock<dim>;
  auto stamper_ptr = std::make_shared<StamperType>();
  auto quadrature_set_ptr = std::make_shared<quadrature::QuadratureSetMock<dim>>();

  EXPECT_NO_THROW({ UpdaterType test_updater(stamper_ptr, quadrature_set_ptr); });
  EXPECT_ANY_THROW({ UpdaterType test_updater(nullptr, quadrature_set_ptr); });
  EXPECT_ANY_THROW({ UpdaterType test_updater(stamper_ptr, nullptr); });
}

TYPED_TEST(IterationUpdaterAngularSourceUpdaterGaussSeidelTest, Getters) {
  auto quadrature_set_ptr = this->test_updater_->quadrature_set_ptr();
  auto stamper_ptr = this->test_updater_->stamper_ptr();

  EXPECT_EQ(quadrature_set_ptr, this->quadrature_set_ptr_.get());
  EXPECT_EQ(stamper_ptr, this->stamper_ptr_.get());
}

} // namespace
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 2006-2008, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

//-----------------------------------------------------------------
//           Implementation of the base Vertex class
//           This class contains the Secondary Vertex
//           of a set of tracks
//           And it is the base class for primary vertices
// Origin: F.Prino, Torino, prino@to.infn.it
//-----------------------------------------------------------------

#include "AliVertex.h"

ClassImp(AliVertex)

//--------------------------------------------------------------------------
AliVertex::AliVertex() :
  TNamed(),
  fSigma(0),
  fNContributors(0),
  fNIndices(0)
{
//
// Default Constructor, set everything to 0
//
  for(Int_t k=0;k<3;k++) fPosition[k]   = 0;
  fIndices = 0;
}

//--------------------------------------------------------------------------
AliVertex::AliVertex(Double_t position[3],Double_t dispersion,
		     Int_t nContributors):
  TNamed(),
  fSigma(dispersion),
  fNContributors(nContributors),
  fNIndices(0)
{
  //
  // Standard Constructor
  //

  for(Int_t k=0;k<3;k++) fPosition[k]   = position[k];
  fIndices = 0;
  SetName("BaseVertex");

}

//--------------------------------------------------------------------------
AliVertex::AliVertex(const AliVertex &source):
  TNamed(source),
  fSigma(source.GetDispersion()),
  fNContributors(source.GetNContributors()),
  fNIndices(source.GetNIndices())
{
  //
  // Copy constructor
  //
  for(Int_t i=0;i<3;i++)fPosition[i] = source.fPosition[i];
  if(source.fNIndices>0) {
    fIndices = new UShort_t[fNIndices];
    memcpy(fIndices,source.fIndices,fNIndices*sizeof(UShort_t));
  }
}

//--------------------------------------------------------------------------
AliVertex &AliVertex::operator=(const AliVertex &source){
  //
  // assignment operator
  //
  if(&source == this) return *this;
  this->SetName(source.GetName());
  this->SetTitle(source.GetTitle());
  for(Int_t i=0;i<3;i++)fPosition[i] = source.fPosition[i];
  fSigma = source.GetDispersion();
  fNContributors = source.GetNContributors();
  fNIndices = source.GetNIndices();
  if(source.fNIndices>0) {
    fIndices = new UShort_t[fNIndices];
    memcpy(fIndices,source.fIndices,fNIndices*sizeof(UShort_t));
  }
  return *this;
}

//--------------------------------------------------------------------------
AliVertex::~AliVertex() {
//
// Default Destructor
//
  delete [] fIndices;
}
//--------------------------------------------------------------------------
void AliVertex::GetXYZ(Double_t position[3]) const {
//
// Return position of the vertex in global frame
//
  position[0] = fPosition[0];
  position[1] = fPosition[1];
  position[2] = fPosition[2];

  return;
}
//--------------------------------------------------------------------------
void AliVertex::SetIndices(Int_t nindices,UShort_t *indices) {
//
// Set indices of tracks used for vertex determination
//
  if(fNContributors<1)  { printf("fNContributors<1"); return; }
  fNIndices = nindices;
  fIndices = new UShort_t[fNIndices];
  for(Int_t i=0;i<fNIndices;i++) fIndices[i] = indices[i];
  return;
}
//--------------------------------------------------------------------------
Bool_t AliVertex::UsesTrack(Int_t index) const {
//
// checks if a track is used for the vertex
//
  if(fNIndices<1)  { printf("fNIndices<1"); return kFALSE; }
  for(Int_t i=0;i<fNIndices;i++) {
    if((Int_t)fIndices[i]==index) return kTRUE;
  }
  return kFALSE;
}
//--------------------------------------------------------------------------
void AliVertex::Print(Option_t* /*option*/) const {
//
// Print out information on all data members
//
  printf("Vertex position:\n");
  printf("   x = %f\n",fPosition[0]);
  printf("   y = %f\n",fPosition[1]);
  printf("   z = %f\n",fPosition[2]);
  printf(" Dispersion = %f\n",fSigma);
  printf(" # tracks = %d\n",fNContributors);

  return;
}

<commit_msg>Corrected initialization of pointers (Solaris x86)<commit_after>/**************************************************************************
 * Copyright(c) 2006-2008, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

//-----------------------------------------------------------------
//           Implementation of the base Vertex class
//           This class contains the Secondary Vertex
//           of a set of tracks
//           And it is the base class for primary vertices
// Origin: F.Prino, Torino, prino@to.infn.it
//-----------------------------------------------------------------

#include "AliVertex.h"

ClassImp(AliVertex)

//--------------------------------------------------------------------------
AliVertex::AliVertex() :
  TNamed(),
  fSigma(0),
  fNContributors(0),
  fNIndices(0)
{
//
// Default Constructor, set everything to 0
//
  for(Int_t k=0;k<3;k++) fPosition[k]   = 0;
  fIndices = 0;
}

//--------------------------------------------------------------------------
AliVertex::AliVertex(Double_t position[3],Double_t dispersion,
		     Int_t nContributors):
  TNamed(),
  fSigma(dispersion),
  fNContributors(nContributors),
  fNIndices(0)
{
  //
  // Standard Constructor
  //

  for(Int_t k=0;k<3;k++) fPosition[k]   = position[k];
  fIndices = 0;
  SetName("BaseVertex");

}

//--------------------------------------------------------------------------
AliVertex::AliVertex(const AliVertex &source):
  TNamed(source),
  fSigma(source.GetDispersion()),
  fNContributors(source.GetNContributors()),
  fNIndices(source.GetNIndices()),
  fIndices(0x0)
{
  //
  // Copy constructor
  //
  for(Int_t i=0;i<3;i++)fPosition[i] = source.fPosition[i];
  if(source.fNIndices>0) {
    fIndices = new UShort_t[fNIndices];
    memcpy(fIndices,source.fIndices,fNIndices*sizeof(UShort_t));
  }
}

//--------------------------------------------------------------------------
AliVertex &AliVertex::operator=(const AliVertex &source){
  //
  // assignment operator
  //
  if(&source == this) return *this;
  this->SetName(source.GetName());
  this->SetTitle(source.GetTitle());
  for(Int_t i=0;i<3;i++)fPosition[i] = source.fPosition[i];
  fSigma = source.GetDispersion();
  fNContributors = source.GetNContributors();
  fNIndices = source.GetNIndices();
  fIndices = 0x0;
  if(source.fNIndices>0) {
    fIndices = new UShort_t[fNIndices];
    memcpy(fIndices,source.fIndices,fNIndices*sizeof(UShort_t));
  }
  return *this;
}

//--------------------------------------------------------------------------
AliVertex::~AliVertex() {
//
// Default Destructor
//
  delete [] fIndices;
}
//--------------------------------------------------------------------------
void AliVertex::GetXYZ(Double_t position[3]) const {
//
// Return position of the vertex in global frame
//
  position[0] = fPosition[0];
  position[1] = fPosition[1];
  position[2] = fPosition[2];

  return;
}
//--------------------------------------------------------------------------
void AliVertex::SetIndices(Int_t nindices,UShort_t *indices) {
//
// Set indices of tracks used for vertex determination
//
  if(fNContributors<1)  { printf("fNContributors<1"); return; }
  fNIndices = nindices;
  delete [] fIndices;
  fIndices = new UShort_t[fNIndices];
  for(Int_t i=0;i<fNIndices;i++) fIndices[i] = indices[i];
  return;
}
//--------------------------------------------------------------------------
Bool_t AliVertex::UsesTrack(Int_t index) const {
//
// checks if a track is used for the vertex
//
  if(fNIndices<1)  { printf("fNIndices<1"); return kFALSE; }
  for(Int_t i=0;i<fNIndices;i++) {
    if((Int_t)fIndices[i]==index) return kTRUE;
  }
  return kFALSE;
}
//--------------------------------------------------------------------------
void AliVertex::Print(Option_t* /*option*/) const {
//
// Print out information on all data members
//
  printf("Vertex position:\n");
  printf("   x = %f\n",fPosition[0]);
  printf("   y = %f\n",fPosition[1]);
  printf("   z = %f\n",fPosition[2]);
  printf(" Dispersion = %f\n",fSigma);
  printf(" # tracks = %d\n",fNContributors);

  return;
}

<|endoftext|>


<commit_before>
/*
 *            kPPP: A front end for pppd for the KDE project
 *
 * $Id$
 *
 *              Copyright (C) 1997 Bernd Johannes Wuebben
 *                      wuebben@math.cornell.edu
 *
 * based on EzPPP:
 * Copyright (C) 1997  Jay Painter
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this program; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

#include "scriptedit.h"
#include <qlayout.h>
#include <qcombobox.h>
#include <qlineedit.h>
//Added by qt3to4:
#include <QHBoxLayout>

ScriptEdit::ScriptEdit( QWidget *parent )
  : QWidget(parent)
{
  QHBoxLayout *tl = new QHBoxLayout(this);
  tl->setSpacing(10);
  tl->setMargin(0);

  st = new QComboBox(this, "st");
  st->addItem("Expect");
  st->addItem("Send");
  st->addItem("Pause (sec)");
  st->addItem("Hangup");
  st->addItem("Answer");
  st->addItem("Timeout (sec)");
  st->addItem("Password");
  st->addItem("ID");
  st->addItem("Prompt");
  st->addItem("PWPrompt");
  st->addItem("LoopStart");
  st->addItem("LoopEnd");
  st->addItem("Scan");
  st->addItem("Save");
  st->addItem("SendNoEcho");
  connect(st, SIGNAL(activated(int)), SLOT(setType(int)));

  se = new QLineEdit(this, "se");
  se->setGeometry(120, 5, 140, 25);
  se->setMaxLength(50);
  connect(se, SIGNAL(returnPressed()), SLOT(seReturnPressed()));

  tl->addWidget(st, 3);
  tl->addWidget(se, 7);

  setType(0);

  tl->activate();
}

void ScriptEdit::setEnabled(bool b) {
  se->setEnabled(b);
  st->setEnabled(b);
}

void ScriptEdit::seReturnPressed() {
  emit returnPressed();
}

QString ScriptEdit::text()const {
  return se->text();
}

void ScriptEdit::setText(const QString &t) {
  se->setText(t);
}

int ScriptEdit::type()const {
  return st->currentIndex();
}

void ScriptEdit::setType(int i) {
  switch(i) {
  case Expect:
    se->setText("");
    se->setEnabled(TRUE);
    break;

  case Send:
    se->setText("");
    se->setEnabled(TRUE);
    break;

  case Pause:
    se->setText("");
    se->setEnabled(TRUE);
    break;

  case Hangup:
    se->setText("");
    se->setEnabled(FALSE);
    break;

  case Answer:
    se->setText("");
    se->setEnabled(FALSE);
    break;

  case Timeout:
    se->setText("");
    se->setEnabled(TRUE);
    break;

  case Password:
    se->setText("");
    se->setEnabled(TRUE);
    break;

  case ID:
    se->setText("");
    se->setEnabled(TRUE);
    break;

  case Prompt:
    se->setText("");
    se->setEnabled(TRUE);
    break;

  case PWPrompt:
    se->setText("");
    se->setEnabled(TRUE);
    break;

  case LoopStart:
    se->setText("");
    se->setEnabled(TRUE);
    break;

  case LoopEnd:
    se->setText("");
    se->setEnabled(TRUE);
    break;

  case Scan:
    se->setText("");
    se->setEnabled(TRUE);
    break;

  case Save:
    se->setText("password");
    se->setEnabled(FALSE);
    break;

  default: break;
  }
}

#include "scriptedit.moc"

<commit_msg>replace deprecated functions<commit_after>
/*
 *            kPPP: A front end for pppd for the KDE project
 *
 * $Id$
 *
 *              Copyright (C) 1997 Bernd Johannes Wuebben
 *                      wuebben@math.cornell.edu
 *
 * based on EzPPP:
 * Copyright (C) 1997  Jay Painter
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this program; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

#include "scriptedit.h"
#include <qlayout.h>
#include <qcombobox.h>
#include <qlineedit.h>
//Added by qt3to4:
#include <QHBoxLayout>

ScriptEdit::ScriptEdit( QWidget *parent )
  : QWidget(parent)
{
  QHBoxLayout *tl = new QHBoxLayout(this);
  tl->setSpacing(10);
  tl->setMargin(0);

  st = new QComboBox(this);
  st->setObjectName("st");
  st->addItem("Expect");
  st->addItem("Send");
  st->addItem("Pause (sec)");
  st->addItem("Hangup");
  st->addItem("Answer");
  st->addItem("Timeout (sec)");
  st->addItem("Password");
  st->addItem("ID");
  st->addItem("Prompt");
  st->addItem("PWPrompt");
  st->addItem("LoopStart");
  st->addItem("LoopEnd");
  st->addItem("Scan");
  st->addItem("Save");
  st->addItem("SendNoEcho");
  connect(st, SIGNAL(activated(int)), SLOT(setType(int)));

  se = new QLineEdit(this, "se");
  se->setGeometry(120, 5, 140, 25);
  se->setMaxLength(50);
  connect(se, SIGNAL(returnPressed()), SLOT(seReturnPressed()));

  tl->addWidget(st, 3);
  tl->addWidget(se, 7);

  setType(0);

  tl->activate();
}

void ScriptEdit::setEnabled(bool b) {
  se->setEnabled(b);
  st->setEnabled(b);
}

void ScriptEdit::seReturnPressed() {
  emit returnPressed();
}

QString ScriptEdit::text()const {
  return se->text();
}

void ScriptEdit::setText(const QString &t) {
  se->setText(t);
}

int ScriptEdit::type()const {
  return st->currentIndex();
}

void ScriptEdit::setType(int i) {
  switch(i) {
  case Expect:
    se->setText("");
    se->setEnabled(TRUE);
    break;

  case Send:
    se->setText("");
    se->setEnabled(TRUE);
    break;

  case Pause:
    se->setText("");
    se->setEnabled(TRUE);
    break;

  case Hangup:
    se->setText("");
    se->setEnabled(FALSE);
    break;

  case Answer:
    se->setText("");
    se->setEnabled(FALSE);
    break;

  case Timeout:
    se->setText("");
    se->setEnabled(TRUE);
    break;

  case Password:
    se->setText("");
    se->setEnabled(TRUE);
    break;

  case ID:
    se->setText("");
    se->setEnabled(TRUE);
    break;

  case Prompt:
    se->setText("");
    se->setEnabled(TRUE);
    break;

  case PWPrompt:
    se->setText("");
    se->setEnabled(TRUE);
    break;

  case LoopStart:
    se->setText("");
    se->setEnabled(TRUE);
    break;

  case LoopEnd:
    se->setText("");
    se->setEnabled(TRUE);
    break;

  case Scan:
    se->setText("");
    se->setEnabled(TRUE);
    break;

  case Save:
    se->setText("password");
    se->setEnabled(FALSE);
    break;

  default: break;
  }
}

#include "scriptedit.moc"

<|endoftext|>


<commit_before>#include <inttypes.h>

#include "constants.h"
#include "main.h"
#include "types.h"

#include "GetNextTargetRequired.h"

compact_target_t GetNextTargetRequired(CBlockIndex const * pindexTail0, bool fProofOfStake)
{
    target_t initialTarget = POW_INITIAL_TARGET;

    if (pindexTail0 == NULL)
        return initialTarget.GetCompact(); // genesis block

    CBlockIndex const * pindexTail1 = GetLastBlockIndex(pindexTail0, fProofOfStake);

    if (pindexTail1->pprev == NULL)
        return initialTarget.GetCompact(); // first block

    CBlockIndex const * pindexTail2 = GetLastBlockIndex(pindexTail1->pprev, fProofOfStake);

    if (pindexTail2->pprev == NULL)
        return initialTarget.GetCompact(); // second block

    timestamp_t actualSpacing = pindexTail1->GetBlockTime() - pindexTail2->GetBlockTime();
    timestamp_t targetSpacing = fProofOfStake ? POS_TARGET_SPACING : POW_TARGET_SPACING;
    timestamp_t targetInterval = TARGET_TIMESPAN / targetSpacing;

    // ppcoin: target change every block
    // ppcoin: retarget with exponential moving toward target spacing

    target_t currentTarget = CBigNum().SetCompact(pindexTail1->nBits);
    target_t newTarget = currentTarget;

    newTarget *= ((targetInterval - 1) * targetSpacing + actualSpacing + actualSpacing);
    newTarget /= ((targetInterval + 1) * targetSpacing);

    target_t maxTarget = fProofOfStake ? POS_MAX_TARGET : POW_MAX_TARGET;

    if (newTarget > maxTarget)
        newTarget = maxTarget;

    printf("Expecting: %llis Actual: %llis Old Difficulty: %x New Difficulty: %x (%s)\n", targetSpacing, actualSpacing, currentTarget.GetCompact(), newTarget.GetCompact(), fProofOfStake ? "PoS" : "PoW");

    return newTarget.GetCompact();
}
<commit_msg>Comments out debug informations<commit_after>#include <inttypes.h>

#include "constants.h"
#include "main.h"
#include "types.h"

#include "GetNextTargetRequired.h"

compact_target_t GetNextTargetRequired(CBlockIndex const * pindexTail0, bool fProofOfStake)
{
    target_t initialTarget = POW_INITIAL_TARGET;

    if (pindexTail0 == NULL)
        return initialTarget.GetCompact(); // genesis block

    CBlockIndex const * pindexTail1 = GetLastBlockIndex(pindexTail0, fProofOfStake);

    if (pindexTail1->pprev == NULL)
        return initialTarget.GetCompact(); // first block

    CBlockIndex const * pindexTail2 = GetLastBlockIndex(pindexTail1->pprev, fProofOfStake);

    if (pindexTail2->pprev == NULL)
        return initialTarget.GetCompact(); // second block

    timestamp_t actualSpacing = pindexTail1->GetBlockTime() - pindexTail2->GetBlockTime();
    timestamp_t targetSpacing = fProofOfStake ? POS_TARGET_SPACING : POW_TARGET_SPACING;
    timestamp_t targetInterval = TARGET_TIMESPAN / targetSpacing;

    // ppcoin: target change every block
    // ppcoin: retarget with exponential moving toward target spacing

    target_t currentTarget = CBigNum().SetCompact(pindexTail1->nBits);
    target_t newTarget = currentTarget;

    newTarget *= ((targetInterval - 1) * targetSpacing + actualSpacing + actualSpacing);
    newTarget /= ((targetInterval + 1) * targetSpacing);

    target_t maxTarget = fProofOfStake ? POS_MAX_TARGET : POW_MAX_TARGET;

    if (newTarget > maxTarget)
        newTarget = maxTarget;

    //printf("Expecting: %llis Actual: %llis Old Difficulty: %x New Difficulty: %x (%s)\n", targetSpacing, actualSpacing, currentTarget.GetCompact(), newTarget.GetCompact(), fProofOfStake ? "PoS" : "PoW");

    return newTarget.GetCompact();
}
<|endoftext|>


<commit_before><commit_msg>Add Workbench name as Tab item tooltip<commit_after><|endoftext|>


<commit_before>/*
 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/modules/audio_coding/neteq4/decoder_database.h"

#include <assert.h>
#include <stdlib.h>

#include <string>

#include "gmock/gmock.h"
#include "gtest/gtest.h"

#include "webrtc/modules/audio_coding/neteq4/mock/mock_audio_decoder.h"
#include "webrtc/test/testsupport/gtest_disable.h"

namespace webrtc {

TEST(DecoderDatabase, CreateAndDestroy) {
  DecoderDatabase db;
  EXPECT_EQ(0, db.Size());
  EXPECT_TRUE(db.Empty());
}

TEST(DecoderDatabase, InsertAndRemove) {
  DecoderDatabase db;
  const uint8_t kPayloadType = 0;
  EXPECT_EQ(DecoderDatabase::kOK,
            db.RegisterPayload(kPayloadType, kDecoderPCMu));
  EXPECT_EQ(1, db.Size());
  EXPECT_FALSE(db.Empty());
  EXPECT_EQ(DecoderDatabase::kOK, db.Remove(kPayloadType));
  EXPECT_EQ(0, db.Size());
  EXPECT_TRUE(db.Empty());
}

TEST(DecoderDatabase, GetDecoderInfo) {
  DecoderDatabase db;
  const uint8_t kPayloadType = 0;
  EXPECT_EQ(DecoderDatabase::kOK,
            db.RegisterPayload(kPayloadType, kDecoderPCMu));
  const DecoderDatabase::DecoderInfo* info;
  info = db.GetDecoderInfo(kPayloadType);
  ASSERT_TRUE(info != NULL);
  EXPECT_EQ(kDecoderPCMu, info->codec_type);
  EXPECT_EQ(NULL, info->decoder);
  EXPECT_EQ(8000, info->fs_hz);
  EXPECT_FALSE(info->external);
  info = db.GetDecoderInfo(kPayloadType + 1);  // Other payload type.
  EXPECT_TRUE(info == NULL);  // Should not be found.
}

TEST(DecoderDatabase, GetRtpPayloadType) {
  DecoderDatabase db;
  const uint8_t kPayloadType = 0;
  EXPECT_EQ(DecoderDatabase::kOK,
            db.RegisterPayload(kPayloadType, kDecoderPCMu));
  EXPECT_EQ(kPayloadType, db.GetRtpPayloadType(kDecoderPCMu));
  const uint8_t expected_value = DecoderDatabase::kRtpPayloadTypeError;
  EXPECT_EQ(expected_value,
            db.GetRtpPayloadType(kDecoderISAC));  // iSAC is not registered.
}

TEST(DecoderDatabase, DISABLED_ON_ANDROID(GetDecoder)) {
  DecoderDatabase db;
  const uint8_t kPayloadType = 0;
  EXPECT_EQ(DecoderDatabase::kOK,
            db.RegisterPayload(kPayloadType, kDecoderILBC));
  AudioDecoder* dec = db.GetDecoder(kPayloadType);
  ASSERT_TRUE(dec != NULL);
}

TEST(DecoderDatabase, TypeTests) {
  DecoderDatabase db;
  const uint8_t kPayloadTypePcmU = 0;
  const uint8_t kPayloadTypeCng = 13;
  const uint8_t kPayloadTypeDtmf = 100;
  const uint8_t kPayloadTypeRed = 101;
  const uint8_t kPayloadNotUsed = 102;
  // Load into database.
  EXPECT_EQ(DecoderDatabase::kOK,
            db.RegisterPayload(kPayloadTypePcmU, kDecoderPCMu));
  EXPECT_EQ(DecoderDatabase::kOK,
            db.RegisterPayload(kPayloadTypeCng, kDecoderCNGnb));
  EXPECT_EQ(DecoderDatabase::kOK,
            db.RegisterPayload(kPayloadTypeDtmf, kDecoderAVT));
  EXPECT_EQ(DecoderDatabase::kOK,
            db.RegisterPayload(kPayloadTypeRed, kDecoderRED));
  EXPECT_EQ(4, db.Size());
  // Test.
  EXPECT_FALSE(db.IsComfortNoise(kPayloadNotUsed));
  EXPECT_FALSE(db.IsDtmf(kPayloadNotUsed));
  EXPECT_FALSE(db.IsRed(kPayloadNotUsed));
  EXPECT_FALSE(db.IsComfortNoise(kPayloadTypePcmU));
  EXPECT_FALSE(db.IsDtmf(kPayloadTypePcmU));
  EXPECT_FALSE(db.IsRed(kPayloadTypePcmU));
  EXPECT_FALSE(db.IsType(kPayloadTypePcmU, kDecoderISAC));
  EXPECT_TRUE(db.IsType(kPayloadTypePcmU, kDecoderPCMu));
  EXPECT_TRUE(db.IsComfortNoise(kPayloadTypeCng));
  EXPECT_TRUE(db.IsDtmf(kPayloadTypeDtmf));
  EXPECT_TRUE(db.IsRed(kPayloadTypeRed));
}

TEST(DecoderDatabase, ExternalDecoder) {
  DecoderDatabase db;
  const uint8_t kPayloadType = 0;
  MockAudioDecoder decoder;
  // Load into database.
  EXPECT_EQ(DecoderDatabase::kOK,
            db.InsertExternal(kPayloadType, kDecoderPCMu, 8000,
                               &decoder));
  EXPECT_EQ(1, db.Size());
  // Get decoder and make sure we get the external one.
  EXPECT_EQ(&decoder, db.GetDecoder(kPayloadType));
  // Get the decoder info struct and check it too.
  const DecoderDatabase::DecoderInfo* info;
  info = db.GetDecoderInfo(kPayloadType);
  ASSERT_TRUE(info != NULL);
  EXPECT_EQ(kDecoderPCMu, info->codec_type);
  EXPECT_EQ(&decoder, info->decoder);
  EXPECT_EQ(8000, info->fs_hz);
  EXPECT_TRUE(info->external);
  // Expect not to delete the decoder when removing it from the database, since
  // it was declared externally.
  EXPECT_CALL(decoder, Die()).Times(0);
  EXPECT_EQ(DecoderDatabase::kOK, db.Remove(kPayloadType));
  EXPECT_TRUE(db.Empty());

  EXPECT_CALL(decoder, Die()).Times(1);  // Will be called when |db| is deleted.
}

TEST(DecoderDatabase, CheckPayloadTypes) {
  DecoderDatabase db;
  // Load a number of payloads into the database. Payload types are 0, 1, ...,
  // while the decoder type is the same for all payload types (this does not
  // matter for the test).
  const int kNumPayloads = 10;
  for (uint8_t payload_type = 0; payload_type < kNumPayloads; ++payload_type) {
    EXPECT_EQ(DecoderDatabase::kOK,
              db.RegisterPayload(payload_type, kDecoderArbitrary));
  }
  PacketList packet_list;
  for (int i = 0; i < kNumPayloads + 1; ++i) {
    // Create packet with payload type |i|. The last packet will have a payload
    // type that is not registered in the decoder database.
    Packet* packet = new Packet;
    packet->header.payloadType = i;
    packet_list.push_back(packet);
  }

  // Expect to return false, since the last packet is of an unknown type.
  EXPECT_EQ(DecoderDatabase::kDecoderNotFound,
            db.CheckPayloadTypes(packet_list));

  delete packet_list.back();
  packet_list.pop_back();  // Remove the unknown one.

  EXPECT_EQ(DecoderDatabase::kOK, db.CheckPayloadTypes(packet_list));

  // Delete all packets.
  PacketList::iterator it = packet_list.begin();
  while (it != packet_list.end()) {
    delete packet_list.front();
    it = packet_list.erase(it);
  }
}

// Test the methods for setting and getting active speech and CNG decoders.
TEST(DecoderDatabase, ActiveDecoders) {
  DecoderDatabase db;
  // Load payload types.
  ASSERT_EQ(DecoderDatabase::kOK, db.RegisterPayload(0, kDecoderPCMu));
  ASSERT_EQ(DecoderDatabase::kOK, db.RegisterPayload(103, kDecoderISAC));
  ASSERT_EQ(DecoderDatabase::kOK, db.RegisterPayload(13, kDecoderCNGnb));
  // Verify that no decoders are active from the start.
  EXPECT_EQ(NULL, db.GetActiveDecoder());
  EXPECT_EQ(NULL, db.GetActiveCngDecoder());

  // Set active speech codec.
  bool changed;  // Should be true when the active decoder changed.
  EXPECT_EQ(DecoderDatabase::kOK, db.SetActiveDecoder(0, &changed));
  EXPECT_TRUE(changed);
  AudioDecoder* decoder = db.GetActiveDecoder();
  ASSERT_FALSE(decoder == NULL);  // Should get a decoder here.
  EXPECT_EQ(kDecoderPCMu, decoder->codec_type());

  // Set the same again. Expect no change.
  EXPECT_EQ(DecoderDatabase::kOK, db.SetActiveDecoder(0, &changed));
  EXPECT_FALSE(changed);
  decoder = db.GetActiveDecoder();
  ASSERT_FALSE(decoder == NULL);  // Should get a decoder here.
  EXPECT_EQ(kDecoderPCMu, decoder->codec_type());

  // Change active decoder.
  EXPECT_EQ(DecoderDatabase::kOK, db.SetActiveDecoder(103, &changed));
  EXPECT_TRUE(changed);
  decoder = db.GetActiveDecoder();
  ASSERT_FALSE(decoder == NULL);  // Should get a decoder here.
  EXPECT_EQ(kDecoderISAC, decoder->codec_type());

  // Remove the active decoder, and verify that the active becomes NULL.
  EXPECT_EQ(DecoderDatabase::kOK, db.Remove(103));
  EXPECT_EQ(NULL, db.GetActiveDecoder());

  // Set active CNG codec.
  EXPECT_EQ(DecoderDatabase::kOK, db.SetActiveCngDecoder(13));
  decoder = db.GetActiveCngDecoder();
  ASSERT_FALSE(decoder == NULL);  // Should get a decoder here.
  EXPECT_EQ(kDecoderCNGnb, decoder->codec_type());

  // Remove the active CNG decoder, and verify that the active becomes NULL.
  EXPECT_EQ(DecoderDatabase::kOK, db.Remove(13));
  EXPECT_EQ(NULL, db.GetActiveCngDecoder());

  // Try to set non-existing codecs as active.
  EXPECT_EQ(DecoderDatabase::kDecoderNotFound,
            db.SetActiveDecoder(17, &changed));
  EXPECT_EQ(DecoderDatabase::kDecoderNotFound,
            db.SetActiveCngDecoder(17));
}
}  // namespace webrtc
<commit_msg>Re-enable NetEQ DecoderDatabase test for Android<commit_after>/*
 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/modules/audio_coding/neteq4/decoder_database.h"

#include <assert.h>
#include <stdlib.h>

#include <string>

#include "gmock/gmock.h"
#include "gtest/gtest.h"

#include "webrtc/modules/audio_coding/neteq4/mock/mock_audio_decoder.h"
#include "webrtc/test/testsupport/gtest_disable.h"

namespace webrtc {

TEST(DecoderDatabase, CreateAndDestroy) {
  DecoderDatabase db;
  EXPECT_EQ(0, db.Size());
  EXPECT_TRUE(db.Empty());
}

TEST(DecoderDatabase, InsertAndRemove) {
  DecoderDatabase db;
  const uint8_t kPayloadType = 0;
  EXPECT_EQ(DecoderDatabase::kOK,
            db.RegisterPayload(kPayloadType, kDecoderPCMu));
  EXPECT_EQ(1, db.Size());
  EXPECT_FALSE(db.Empty());
  EXPECT_EQ(DecoderDatabase::kOK, db.Remove(kPayloadType));
  EXPECT_EQ(0, db.Size());
  EXPECT_TRUE(db.Empty());
}

TEST(DecoderDatabase, GetDecoderInfo) {
  DecoderDatabase db;
  const uint8_t kPayloadType = 0;
  EXPECT_EQ(DecoderDatabase::kOK,
            db.RegisterPayload(kPayloadType, kDecoderPCMu));
  const DecoderDatabase::DecoderInfo* info;
  info = db.GetDecoderInfo(kPayloadType);
  ASSERT_TRUE(info != NULL);
  EXPECT_EQ(kDecoderPCMu, info->codec_type);
  EXPECT_EQ(NULL, info->decoder);
  EXPECT_EQ(8000, info->fs_hz);
  EXPECT_FALSE(info->external);
  info = db.GetDecoderInfo(kPayloadType + 1);  // Other payload type.
  EXPECT_TRUE(info == NULL);  // Should not be found.
}

TEST(DecoderDatabase, GetRtpPayloadType) {
  DecoderDatabase db;
  const uint8_t kPayloadType = 0;
  EXPECT_EQ(DecoderDatabase::kOK,
            db.RegisterPayload(kPayloadType, kDecoderPCMu));
  EXPECT_EQ(kPayloadType, db.GetRtpPayloadType(kDecoderPCMu));
  const uint8_t expected_value = DecoderDatabase::kRtpPayloadTypeError;
  EXPECT_EQ(expected_value,
            db.GetRtpPayloadType(kDecoderISAC));  // iSAC is not registered.
}

TEST(DecoderDatabase, GetDecoder) {
  DecoderDatabase db;
  const uint8_t kPayloadType = 0;
  EXPECT_EQ(DecoderDatabase::kOK,
            db.RegisterPayload(kPayloadType, kDecoderPCM16B));
  AudioDecoder* dec = db.GetDecoder(kPayloadType);
  ASSERT_TRUE(dec != NULL);
}

TEST(DecoderDatabase, TypeTests) {
  DecoderDatabase db;
  const uint8_t kPayloadTypePcmU = 0;
  const uint8_t kPayloadTypeCng = 13;
  const uint8_t kPayloadTypeDtmf = 100;
  const uint8_t kPayloadTypeRed = 101;
  const uint8_t kPayloadNotUsed = 102;
  // Load into database.
  EXPECT_EQ(DecoderDatabase::kOK,
            db.RegisterPayload(kPayloadTypePcmU, kDecoderPCMu));
  EXPECT_EQ(DecoderDatabase::kOK,
            db.RegisterPayload(kPayloadTypeCng, kDecoderCNGnb));
  EXPECT_EQ(DecoderDatabase::kOK,
            db.RegisterPayload(kPayloadTypeDtmf, kDecoderAVT));
  EXPECT_EQ(DecoderDatabase::kOK,
            db.RegisterPayload(kPayloadTypeRed, kDecoderRED));
  EXPECT_EQ(4, db.Size());
  // Test.
  EXPECT_FALSE(db.IsComfortNoise(kPayloadNotUsed));
  EXPECT_FALSE(db.IsDtmf(kPayloadNotUsed));
  EXPECT_FALSE(db.IsRed(kPayloadNotUsed));
  EXPECT_FALSE(db.IsComfortNoise(kPayloadTypePcmU));
  EXPECT_FALSE(db.IsDtmf(kPayloadTypePcmU));
  EXPECT_FALSE(db.IsRed(kPayloadTypePcmU));
  EXPECT_FALSE(db.IsType(kPayloadTypePcmU, kDecoderISAC));
  EXPECT_TRUE(db.IsType(kPayloadTypePcmU, kDecoderPCMu));
  EXPECT_TRUE(db.IsComfortNoise(kPayloadTypeCng));
  EXPECT_TRUE(db.IsDtmf(kPayloadTypeDtmf));
  EXPECT_TRUE(db.IsRed(kPayloadTypeRed));
}

TEST(DecoderDatabase, ExternalDecoder) {
  DecoderDatabase db;
  const uint8_t kPayloadType = 0;
  MockAudioDecoder decoder;
  // Load into database.
  EXPECT_EQ(DecoderDatabase::kOK,
            db.InsertExternal(kPayloadType, kDecoderPCMu, 8000,
                               &decoder));
  EXPECT_EQ(1, db.Size());
  // Get decoder and make sure we get the external one.
  EXPECT_EQ(&decoder, db.GetDecoder(kPayloadType));
  // Get the decoder info struct and check it too.
  const DecoderDatabase::DecoderInfo* info;
  info = db.GetDecoderInfo(kPayloadType);
  ASSERT_TRUE(info != NULL);
  EXPECT_EQ(kDecoderPCMu, info->codec_type);
  EXPECT_EQ(&decoder, info->decoder);
  EXPECT_EQ(8000, info->fs_hz);
  EXPECT_TRUE(info->external);
  // Expect not to delete the decoder when removing it from the database, since
  // it was declared externally.
  EXPECT_CALL(decoder, Die()).Times(0);
  EXPECT_EQ(DecoderDatabase::kOK, db.Remove(kPayloadType));
  EXPECT_TRUE(db.Empty());

  EXPECT_CALL(decoder, Die()).Times(1);  // Will be called when |db| is deleted.
}

TEST(DecoderDatabase, CheckPayloadTypes) {
  DecoderDatabase db;
  // Load a number of payloads into the database. Payload types are 0, 1, ...,
  // while the decoder type is the same for all payload types (this does not
  // matter for the test).
  const int kNumPayloads = 10;
  for (uint8_t payload_type = 0; payload_type < kNumPayloads; ++payload_type) {
    EXPECT_EQ(DecoderDatabase::kOK,
              db.RegisterPayload(payload_type, kDecoderArbitrary));
  }
  PacketList packet_list;
  for (int i = 0; i < kNumPayloads + 1; ++i) {
    // Create packet with payload type |i|. The last packet will have a payload
    // type that is not registered in the decoder database.
    Packet* packet = new Packet;
    packet->header.payloadType = i;
    packet_list.push_back(packet);
  }

  // Expect to return false, since the last packet is of an unknown type.
  EXPECT_EQ(DecoderDatabase::kDecoderNotFound,
            db.CheckPayloadTypes(packet_list));

  delete packet_list.back();
  packet_list.pop_back();  // Remove the unknown one.

  EXPECT_EQ(DecoderDatabase::kOK, db.CheckPayloadTypes(packet_list));

  // Delete all packets.
  PacketList::iterator it = packet_list.begin();
  while (it != packet_list.end()) {
    delete packet_list.front();
    it = packet_list.erase(it);
  }
}

// Test the methods for setting and getting active speech and CNG decoders.
TEST(DecoderDatabase, ActiveDecoders) {
  DecoderDatabase db;
  // Load payload types.
  ASSERT_EQ(DecoderDatabase::kOK, db.RegisterPayload(0, kDecoderPCMu));
  ASSERT_EQ(DecoderDatabase::kOK, db.RegisterPayload(103, kDecoderISAC));
  ASSERT_EQ(DecoderDatabase::kOK, db.RegisterPayload(13, kDecoderCNGnb));
  // Verify that no decoders are active from the start.
  EXPECT_EQ(NULL, db.GetActiveDecoder());
  EXPECT_EQ(NULL, db.GetActiveCngDecoder());

  // Set active speech codec.
  bool changed;  // Should be true when the active decoder changed.
  EXPECT_EQ(DecoderDatabase::kOK, db.SetActiveDecoder(0, &changed));
  EXPECT_TRUE(changed);
  AudioDecoder* decoder = db.GetActiveDecoder();
  ASSERT_FALSE(decoder == NULL);  // Should get a decoder here.
  EXPECT_EQ(kDecoderPCMu, decoder->codec_type());

  // Set the same again. Expect no change.
  EXPECT_EQ(DecoderDatabase::kOK, db.SetActiveDecoder(0, &changed));
  EXPECT_FALSE(changed);
  decoder = db.GetActiveDecoder();
  ASSERT_FALSE(decoder == NULL);  // Should get a decoder here.
  EXPECT_EQ(kDecoderPCMu, decoder->codec_type());

  // Change active decoder.
  EXPECT_EQ(DecoderDatabase::kOK, db.SetActiveDecoder(103, &changed));
  EXPECT_TRUE(changed);
  decoder = db.GetActiveDecoder();
  ASSERT_FALSE(decoder == NULL);  // Should get a decoder here.
  EXPECT_EQ(kDecoderISAC, decoder->codec_type());

  // Remove the active decoder, and verify that the active becomes NULL.
  EXPECT_EQ(DecoderDatabase::kOK, db.Remove(103));
  EXPECT_EQ(NULL, db.GetActiveDecoder());

  // Set active CNG codec.
  EXPECT_EQ(DecoderDatabase::kOK, db.SetActiveCngDecoder(13));
  decoder = db.GetActiveCngDecoder();
  ASSERT_FALSE(decoder == NULL);  // Should get a decoder here.
  EXPECT_EQ(kDecoderCNGnb, decoder->codec_type());

  // Remove the active CNG decoder, and verify that the active becomes NULL.
  EXPECT_EQ(DecoderDatabase::kOK, db.Remove(13));
  EXPECT_EQ(NULL, db.GetActiveCngDecoder());

  // Try to set non-existing codecs as active.
  EXPECT_EQ(DecoderDatabase::kDecoderNotFound,
            db.SetActiveDecoder(17, &changed));
  EXPECT_EQ(DecoderDatabase::kDecoderNotFound,
            db.SetActiveCngDecoder(17));
}
}  // namespace webrtc
<|endoftext|>


<commit_before>/* dlvhex -- Answer-Set Programming with external interfaces.
 * Copyright (C) 2005-2007 Roman Schindlauer
 * Copyright (C) 2006-2015 Thomas Krennwallner
 * Copyright (C) 2009-2016 Peter Schüller
 * Copyright (C) 2011-2016 Christoph Redl
 * Copyright (C) 2015-2016 Tobias Kaminski
 * Copyright (C) 2015-2016 Antonius Weinzierl
 *
 * This file is part of dlvhex.
 *
 * dlvhex is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * dlvhex is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with dlvhex; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 */

/**
 * @file   InconsistencyAnalyzer.cpp
 * @author Christoph Redl
 * @date Wed April 20 2016
 *
 * @brief  Computes a reason for the inconsistency in a program unit.
 *
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "dlvhex2/BaseModelGenerator.h"
#include "dlvhex2/InconsistencyAnalyzer.h"
#include "dlvhex2/Printer.h"
#include "dlvhex2/ProgramCtx.h"
#include "dlvhex2/Benchmarking.h"
#include "dlvhex2/Benchmarking.h"
#include "dlvhex2/InternalGrounder.h"
#include "dlvhex2/SATSolver.h"

#include <boost/graph/breadth_first_search.hpp>
#include <boost/graph/visitors.hpp>
#include <boost/graph/strong_components.hpp>
#include <boost/graph/filtered_graph.hpp>

#include <boost/foreach.hpp>

DLVHEX_NAMESPACE_BEGIN

InconsistencyAnalyzer::InconsistencyAnalyzer(ProgramCtx& ctx) : ctx(ctx){
}

ID InconsistencyAnalyzer::getAuxiliaryAtom(char type, ID id){
    OrdinaryAtom oatom(ID::MAINKIND_ATOM | ID::SUBKIND_ATOM_ORDINARYG | ID::PROPERTY_AUX);
    oatom.tuple.push_back(ctx.registry()->getAuxiliaryConstantSymbol(type, id));
    return ctx.registry()->storeOrdinaryAtom(oatom);
}

Nogood InconsistencyAnalyzer::getInconsistencyReason(BaseModelGenerator* mg, InterpretationConstPtr explAtoms, std::vector<ID>& innerEatoms, OrdinaryASPProgram& program, AnnotatedGroundProgram& annotatedOptimizedProgram, bool* haveInconsistencyReason){

#ifndef NDEBUG
    DBGLOG(DBG, "Performing inconsistency analyzis for program:" << std::endl << *program.edb << std::endl << printManyToString<RawPrinter>(program.idb, "\n", ctx.registry()));
#endif

    // ground the program without optimization
    InternalGrounder grounder(ctx, program, InternalGrounder::builtin);
    OrdinaryASPProgram gp = grounder.getGroundProgram();

#ifndef NDEBUG
    DBGLOG(DBG, "Unoptimized grounded program:" << std::endl << *gp.edb << std::endl << printManyToString<RawPrinter>(gp.idb, "\n", ctx.registry()));
#endif
    InterpretationPtr programAtoms(new Interpretation(*gp.edb));
    BOOST_FOREACH (ID ruleID, gp.idb) {
        const Rule& rule = ctx.registry()->rules.getByID(ruleID);
        BOOST_FOREACH (ID h, rule.head) programAtoms->setFact(h.address);
        BOOST_FOREACH (ID b, rule.body) programAtoms->setFact(b.address);
    }

    // construct analysis program
    InterpretationPtr analysisProgramEdb(new Interpretation(ctx.registry()));
    OrdinaryASPProgram analysisProgram(ctx.registry(), std::vector<ID>(), analysisProgramEdb, ctx.maxint);
    bm::bvector<>::enumerator en, en_end;
    int nextAtomID = 0;
    ID satAtom = getAuxiliaryAtom('x', ID::termFromInteger(nextAtomID++));

    // explanation guess
    DBGLOG(DBG, "Adding guessing rules for explanation atoms " << *explAtoms);
    InterpretationPtr negExplAtoms(new Interpretation(ctx.registry()));
    en = explAtoms->getStorage().first();
    en_end = explAtoms->getStorage().end();
    while (en < en_end) {
        Rule explanationGuess(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR | ID::PROPERTY_RULE_DISJ);
        ID eAtomID = ctx.registry()->ogatoms.getIDByAddress(*en);
        ID neAtomID = getAuxiliaryAtom('x', eAtomID);
        negExplAtoms->setFact(neAtomID.address);
        explanationGuess.head.push_back(eAtomID);                           // atom is in R+
        explanationGuess.head.push_back(neAtomID);                          // atom is in R-
        explanationGuess.head.push_back(getAuxiliaryAtom('y', eAtomID));    // atom is neither in R+ nor in R-
        analysisProgram.idb.push_back(ctx.registry()->storeRule(explanationGuess));
        en++;
    }

    // interpretation guess and saturation
    DBGLOG(DBG, "Adding guessing and saturation rules for program atoms " << *programAtoms);
    en = programAtoms->getStorage().first();
    en_end = programAtoms->getStorage().end();
    while (en < en_end) {
        // interpretation guess
        Rule interpretationGuess(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR | ID::PROPERTY_RULE_DISJ);
        ID atomID = ctx.registry()->ogatoms.getIDByAddress(*en);
        interpretationGuess.head.push_back(getAuxiliaryAtom('p', atomID));    // atom in interpretation
        interpretationGuess.head.push_back(getAuxiliaryAtom('n', atomID));    // -atom in interpretation
        analysisProgram.idb.push_back(ctx.registry()->storeRule(interpretationGuess));

        // saturation on discrepancy of interpretation guess from explanation guess
        {
            Rule discrepancy(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR);
            discrepancy.head.push_back(satAtom);
            discrepancy.body.push_back(ID::posLiteralFromAtom(atomID));                                   // atom in explanation guess
            discrepancy.body.push_back(ID::posLiteralFromAtom(getAuxiliaryAtom('n', atomID)));            // -atom in interpretation
            analysisProgram.idb.push_back(ctx.registry()->storeRule(discrepancy));
        }{
            Rule discrepancy(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR);
            discrepancy.head.push_back(satAtom);
            discrepancy.body.push_back(ID::posLiteralFromAtom(getAuxiliaryAtom('x', atomID)));            // atom in explanation guess
            discrepancy.body.push_back(ID::posLiteralFromAtom(getAuxiliaryAtom('p', atomID)));            // -atom in interpretation
            analysisProgram.idb.push_back(ctx.registry()->storeRule(discrepancy));
        }
        {
            Rule satInterpretation(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR);
            satInterpretation.head.push_back(getAuxiliaryAtom('p', atomID));                              // -atom in interpretation
            satInterpretation.body.push_back(ID::posLiteralFromAtom(satAtom));
            analysisProgram.idb.push_back(ctx.registry()->storeRule(satInterpretation));
        }{
            Rule satInterpretation(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR);
            satInterpretation.head.push_back(getAuxiliaryAtom('n', atomID));                              // -atom in interpretation
            satInterpretation.body.push_back(ID::posLiteralFromAtom(satAtom));
            analysisProgram.idb.push_back(ctx.registry()->storeRule(satInterpretation));
        }

        en++;
    }

    // saturation for non-models
    en = gp.edb->getStorage().first();
    en_end = gp.edb->getStorage().end();
    while (en < en_end) {
        // explanation atoms cannot be part of the EDB
	    if (!explAtoms->getFact(*en)) {
                Rule satOnModelRule(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR);
	        satOnModelRule.head.push_back(satAtom);
	        satOnModelRule.body.push_back(ID::posLiteralFromAtom(getAuxiliaryAtom('n', ctx.registry()->ogatoms.getIDByAddress(*en))));
                analysisProgram.idb.push_back(ctx.registry()->storeRule(satOnModelRule));
	    }
        en++;
    }
    BOOST_FOREACH (ID ruleID, gp.idb) {
        DBGLOG(DBG, "Adding saturation rule for program rule " << printToString<RawPrinter>(ruleID, ctx.registry()));
        const Rule& rule = ctx.registry()->rules.getByID(ruleID);
        Rule satOnModelRule(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR);
        satOnModelRule.head.push_back(satAtom);
        BOOST_FOREACH (ID h, rule.head) { satOnModelRule.body.push_back(getAuxiliaryAtom('n', h)); }
        BOOST_FOREACH (ID b, rule.body) {
            if (!b.isNaf()) {
                satOnModelRule.body.push_back(ID::posLiteralFromAtom(getAuxiliaryAtom('p', ID::atomFromLiteral(b))));
            }else{
                satOnModelRule.body.push_back(ID::posLiteralFromAtom(getAuxiliaryAtom('n', ID::atomFromLiteral(b))));
            }
        }
        analysisProgram.idb.push_back(ctx.registry()->storeRule(satOnModelRule));
    }

    // restrict search to models with atom sat
    {
        DBGLOG(DBG, "Adding sat constraint");
        Rule satConstraint(ID::MAINKIND_RULE | ID::SUBKIND_RULE_CONSTRAINT);
        satConstraint.body.push_back(ID::nafLiteralFromAtom(satAtom));
        analysisProgram.idb.push_back(ctx.registry()->storeRule(satConstraint));
    }

#ifndef NDEBUG
    if (!!gp.edb) {
        DBGLOG(DBG, "Analysis program:" << std::endl << *gp.edb << std::endl << printManyToString<RawPrinter>(analysisProgram.idb, "\n", ctx.registry()));
    }else{
        DBGLOG(DBG, "Analysis program:" << std::endl << printManyToString<RawPrinter>(analysisProgram.idb, "\n", ctx.registry()));
    }
#endif

    // solve the instance
    GenuineGroundSolverPtr analysisSolver = GenuineGroundSolver::getInstance(ctx, analysisProgram);
    InterpretationConstPtr model;
    while ( (model = analysisSolver->getNextModel()) != InterpretationConstPtr() ) {
        DBGLOG(DBG, "Answer set of analysis program: " << *model);

        // extract explanation
        Nogood explanation;
        en = model->getStorage().first();
        en_end = model->getStorage().end();
        while (en < en_end) {
            if (explAtoms->getFact(*en)) explanation.insert(NogoodContainer::createLiteral(*en, true));
            else if (negExplAtoms->getFact(*en)) explanation.insert(NogoodContainer::createLiteral(ctx.registry()->getIDByAuxiliaryConstantSymbol(ctx.registry()->ogatoms.getByAddress(*en).tuple[0]).address, false));
            en++;
        }
        DBGLOG(DBG, "Explanation: " << explanation.getStringRepresentation(ctx.registry()));
        if (ctx.config.getOption("UserInconsistencyAnalysis")) {
            std::cout << "Inconsistency explanation: " << explanation.getStringRepresentation(ctx.registry()) << std::endl;
        }
    }

    return Nogood();
}

DLVHEX_NAMESPACE_END

// vim:expandtab:ts=4:sw=4:
// mode: C++
// End:
<commit_msg>fix debug output<commit_after>/* dlvhex -- Answer-Set Programming with external interfaces.
 * Copyright (C) 2005-2007 Roman Schindlauer
 * Copyright (C) 2006-2015 Thomas Krennwallner
 * Copyright (C) 2009-2016 Peter Schüller
 * Copyright (C) 2011-2016 Christoph Redl
 * Copyright (C) 2015-2016 Tobias Kaminski
 * Copyright (C) 2015-2016 Antonius Weinzierl
 *
 * This file is part of dlvhex.
 *
 * dlvhex is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * dlvhex is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with dlvhex; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 */

/**
 * @file   InconsistencyAnalyzer.cpp
 * @author Christoph Redl
 * @date Wed April 20 2016
 *
 * @brief  Computes a reason for the inconsistency in a program unit.
 *
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "dlvhex2/BaseModelGenerator.h"
#include "dlvhex2/InconsistencyAnalyzer.h"
#include "dlvhex2/Printer.h"
#include "dlvhex2/ProgramCtx.h"
#include "dlvhex2/Benchmarking.h"
#include "dlvhex2/Benchmarking.h"
#include "dlvhex2/InternalGrounder.h"
#include "dlvhex2/SATSolver.h"

#include <boost/graph/breadth_first_search.hpp>
#include <boost/graph/visitors.hpp>
#include <boost/graph/strong_components.hpp>
#include <boost/graph/filtered_graph.hpp>

#include <boost/foreach.hpp>

DLVHEX_NAMESPACE_BEGIN

InconsistencyAnalyzer::InconsistencyAnalyzer(ProgramCtx& ctx) : ctx(ctx){
}

ID InconsistencyAnalyzer::getAuxiliaryAtom(char type, ID id){
    OrdinaryAtom oatom(ID::MAINKIND_ATOM | ID::SUBKIND_ATOM_ORDINARYG | ID::PROPERTY_AUX);
    oatom.tuple.push_back(ctx.registry()->getAuxiliaryConstantSymbol(type, id));
    return ctx.registry()->storeOrdinaryAtom(oatom);
}

Nogood InconsistencyAnalyzer::getInconsistencyReason(BaseModelGenerator* mg, InterpretationConstPtr explAtoms, std::vector<ID>& innerEatoms, OrdinaryASPProgram& program, AnnotatedGroundProgram& annotatedOptimizedProgram, bool* haveInconsistencyReason){

#ifndef NDEBUG
    DBGLOG(DBG, "Performing inconsistency analyzis for program:" << std::endl << *program.edb << std::endl << printManyToString<RawPrinter>(program.idb, "\n", ctx.registry()));
#endif

    // ground the program without optimization
    InternalGrounder grounder(ctx, program, InternalGrounder::builtin);
    OrdinaryASPProgram gp = grounder.getGroundProgram();

#ifndef NDEBUG
    DBGLOG(DBG, "Unoptimized grounded program:" << std::endl << *gp.edb << std::endl << printManyToString<RawPrinter>(gp.idb, "\n", ctx.registry()));
#endif
    InterpretationPtr programAtoms(new Interpretation(*gp.edb));
    BOOST_FOREACH (ID ruleID, gp.idb) {
        const Rule& rule = ctx.registry()->rules.getByID(ruleID);
        BOOST_FOREACH (ID h, rule.head) programAtoms->setFact(h.address);
        BOOST_FOREACH (ID b, rule.body) programAtoms->setFact(b.address);
    }

    // construct analysis program
    InterpretationPtr analysisProgramEdb(new Interpretation(ctx.registry()));
    OrdinaryASPProgram analysisProgram(ctx.registry(), std::vector<ID>(), analysisProgramEdb, ctx.maxint);
    bm::bvector<>::enumerator en, en_end;
    int nextAtomID = 0;
    ID satAtom = getAuxiliaryAtom('x', ID::termFromInteger(nextAtomID++));

    // explanation guess
    DBGLOG(DBG, "Adding guessing rules for explanation atoms " << *explAtoms);
    InterpretationPtr negExplAtoms(new Interpretation(ctx.registry()));
    en = explAtoms->getStorage().first();
    en_end = explAtoms->getStorage().end();
    while (en < en_end) {
        Rule explanationGuess(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR | ID::PROPERTY_RULE_DISJ);
        ID eAtomID = ctx.registry()->ogatoms.getIDByAddress(*en);
        ID neAtomID = getAuxiliaryAtom('x', eAtomID);
        negExplAtoms->setFact(neAtomID.address);
        explanationGuess.head.push_back(eAtomID);                           // atom is in R+
        explanationGuess.head.push_back(neAtomID);                          // atom is in R-
        explanationGuess.head.push_back(getAuxiliaryAtom('y', eAtomID));    // atom is neither in R+ nor in R-
        analysisProgram.idb.push_back(ctx.registry()->storeRule(explanationGuess));
        en++;
    }

    // interpretation guess and saturation
    DBGLOG(DBG, "Adding guessing and saturation rules for program atoms " << *programAtoms);
    en = programAtoms->getStorage().first();
    en_end = programAtoms->getStorage().end();
    while (en < en_end) {
        // interpretation guess
        Rule interpretationGuess(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR | ID::PROPERTY_RULE_DISJ);
        ID atomID = ctx.registry()->ogatoms.getIDByAddress(*en);
        interpretationGuess.head.push_back(getAuxiliaryAtom('p', atomID));    // atom in interpretation
        interpretationGuess.head.push_back(getAuxiliaryAtom('n', atomID));    // -atom in interpretation
        analysisProgram.idb.push_back(ctx.registry()->storeRule(interpretationGuess));

        // saturation on discrepancy of interpretation guess from explanation guess
        {
            Rule discrepancy(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR);
            discrepancy.head.push_back(satAtom);
            discrepancy.body.push_back(ID::posLiteralFromAtom(atomID));                                   // atom in explanation guess
            discrepancy.body.push_back(ID::posLiteralFromAtom(getAuxiliaryAtom('n', atomID)));            // -atom in interpretation
            analysisProgram.idb.push_back(ctx.registry()->storeRule(discrepancy));
        }{
            Rule discrepancy(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR);
            discrepancy.head.push_back(satAtom);
            discrepancy.body.push_back(ID::posLiteralFromAtom(getAuxiliaryAtom('x', atomID)));            // atom in explanation guess
            discrepancy.body.push_back(ID::posLiteralFromAtom(getAuxiliaryAtom('p', atomID)));            // -atom in interpretation
            analysisProgram.idb.push_back(ctx.registry()->storeRule(discrepancy));
        }
        {
            Rule satInterpretation(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR);
            satInterpretation.head.push_back(getAuxiliaryAtom('p', atomID));                              // -atom in interpretation
            satInterpretation.body.push_back(ID::posLiteralFromAtom(satAtom));
            analysisProgram.idb.push_back(ctx.registry()->storeRule(satInterpretation));
        }{
            Rule satInterpretation(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR);
            satInterpretation.head.push_back(getAuxiliaryAtom('n', atomID));                              // -atom in interpretation
            satInterpretation.body.push_back(ID::posLiteralFromAtom(satAtom));
            analysisProgram.idb.push_back(ctx.registry()->storeRule(satInterpretation));
        }

        en++;
    }

    // saturation for non-models
    en = gp.edb->getStorage().first();
    en_end = gp.edb->getStorage().end();
    while (en < en_end) {
        // explanation atoms cannot be part of the EDB
//	    if (!explAtoms->getFact(*en)) {
                Rule satOnModelRule(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR);
	        satOnModelRule.head.push_back(satAtom);
	        satOnModelRule.body.push_back(ID::posLiteralFromAtom(getAuxiliaryAtom('n', ctx.registry()->ogatoms.getIDByAddress(*en))));
                analysisProgram.idb.push_back(ctx.registry()->storeRule(satOnModelRule));
//	    }
        en++;
    }
    BOOST_FOREACH (ID ruleID, gp.idb) {
        DBGLOG(DBG, "Adding saturation rule for program rule " << printToString<RawPrinter>(ruleID, ctx.registry()));
        const Rule& rule = ctx.registry()->rules.getByID(ruleID);
        Rule satOnModelRule(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR);
        satOnModelRule.head.push_back(satAtom);
        BOOST_FOREACH (ID h, rule.head) { satOnModelRule.body.push_back(getAuxiliaryAtom('n', h)); }
        BOOST_FOREACH (ID b, rule.body) {
            if (!b.isNaf()) {
                satOnModelRule.body.push_back(ID::posLiteralFromAtom(getAuxiliaryAtom('p', ID::atomFromLiteral(b))));
            }else{
                satOnModelRule.body.push_back(ID::posLiteralFromAtom(getAuxiliaryAtom('n', ID::atomFromLiteral(b))));
            }
        }
        analysisProgram.idb.push_back(ctx.registry()->storeRule(satOnModelRule));
    }

    // restrict search to models with atom sat
    {
        DBGLOG(DBG, "Adding sat constraint");
        Rule satConstraint(ID::MAINKIND_RULE | ID::SUBKIND_RULE_CONSTRAINT);
        satConstraint.body.push_back(ID::nafLiteralFromAtom(satAtom));
        analysisProgram.idb.push_back(ctx.registry()->storeRule(satConstraint));
    }

#ifndef NDEBUG
    if (!!gp.edb) {
        DBGLOG(DBG, "Analysis program:" << std::endl << *analysisProgramEdb.edb << std::endl << printManyToString<RawPrinter>(analysisProgram.idb, "\n", ctx.registry()));
    }else{
        DBGLOG(DBG, "Analysis program:" << std::endl << printManyToString<RawPrinter>(analysisProgram.idb, "\n", ctx.registry()));
    }
#endif

    // solve the instance
    GenuineGroundSolverPtr analysisSolver = GenuineGroundSolver::getInstance(ctx, analysisProgram);
    InterpretationConstPtr model;
    while ( (model = analysisSolver->getNextModel()) != InterpretationConstPtr() ) {
        DBGLOG(DBG, "Answer set of analysis program: " << *model);

        // extract explanation
        Nogood explanation;
        en = model->getStorage().first();
        en_end = model->getStorage().end();
        while (en < en_end) {
            if (explAtoms->getFact(*en)) explanation.insert(NogoodContainer::createLiteral(*en, true));
            else if (negExplAtoms->getFact(*en)) explanation.insert(NogoodContainer::createLiteral(ctx.registry()->getIDByAuxiliaryConstantSymbol(ctx.registry()->ogatoms.getByAddress(*en).tuple[0]).address, false));
            en++;
        }
        DBGLOG(DBG, "Explanation: " << explanation.getStringRepresentation(ctx.registry()));
        if (ctx.config.getOption("UserInconsistencyAnalysis")) {
            std::cout << "Inconsistency explanation: " << explanation.getStringRepresentation(ctx.registry()) << std::endl;
        }
    }

    return Nogood();
}

DLVHEX_NAMESPACE_END

// vim:expandtab:ts=4:sw=4:
// mode: C++
// End:
<|endoftext|>


<commit_before>/***********************************************************************
    filename:   CEGUIIrrlichtTexture.cpp
    created:    Tue Mar 3 2009
    author:     Paul D Turner (based on original code by Thomas Suter)
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include "CEGUIIrrlichtTexture.h"
#include "CEGUISystem.h"
#include "CEGUIExceptions.h"
#include "CEGUIImageCodec.h"
#include <irrlicht.h>

// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
uint32 IrrlichtTexture::d_textureNumber = 0;

//----------------------------------------------------------------------------//
void IrrlichtTexture::setIrrlichtTexture(irr::video::ITexture* tex)
{
    d_texture = tex;

    if (d_texture)
    {
        d_size = d_dataSize = Size<>(
                static_cast<float>(d_texture->getSize().Width),
                static_cast<float>(d_texture->getSize().Height));

        updateCachedScaleValues();
    }
}

//----------------------------------------------------------------------------//
irr::video::ITexture* IrrlichtTexture::getIrrlichtTexture() const
{
    return d_texture;
}

//----------------------------------------------------------------------------//
const String& IrrlichtTexture::getName() const
{
    return d_name;
}

//----------------------------------------------------------------------------//
const Size<>& IrrlichtTexture::getSize() const
{
    return d_size;
}

//----------------------------------------------------------------------------//
const Size<>& IrrlichtTexture::getOriginalDataSize() const
{
    return d_dataSize;
}

//----------------------------------------------------------------------------//
const Vector2<>& IrrlichtTexture::getTexelScaling() const
{
    return d_texelScaling;
}

//----------------------------------------------------------------------------//
void IrrlichtTexture::loadFromFile(const String& filename,
                                   const String& resourceGroup)
{
    // get and check existence of CEGUI::System object
    System* sys = System::getSingletonPtr();
    if (!sys)
        CEGUI_THROW(RendererException("IrrlichtTexture::loadFromFile: "
            "CEGUI::System object has not been created!"));

    // load file to memory via resource provider
    RawDataContainer texFile;
    sys->getResourceProvider()->loadRawDataContainer(filename, texFile,
                                                     resourceGroup);

    Texture* res = sys->getImageCodec().load(texFile, this);

    // unload file data buffer
    sys->getResourceProvider()->unloadRawDataContainer(texFile);

    // throw exception if data was load loaded to texture.
    if (!res)
        CEGUI_THROW(RendererException("IrrlichtTexture::loadFromFile: " +
            sys->getImageCodec().getIdentifierString() +
            " failed to load image '" + filename + "'."));
}

//----------------------------------------------------------------------------//
void IrrlichtTexture::loadFromMemory(const void* buffer,
                                     const Size<>& buffer_size,
                                     PixelFormat pixel_format)
{
    using namespace irr;

    freeIrrlichtTexture();
    createIrrlichtTexture(buffer_size);

    d_size.d_width = static_cast<float>(d_texture->getSize().Width);
    d_size.d_height = static_cast<float>(d_texture->getSize().Height);
    d_dataSize = buffer_size;

    updateCachedScaleValues();

    const size_t pix_sz = (pixel_format == PF_RGB) ? 3 : 4;
    const char* src = static_cast<const char*>(buffer);
    char* dest = static_cast<char*>(d_texture->lock());

    // copy data into texture, swapping red & blue and creating alpha channel
    // values as needed.
    for (int j = 0; j < buffer_size.d_height; ++j)
    {
        for (int i = 0; i < buffer_size.d_width; ++i)
        {
            dest[i * 4 + 0] = src[i * pix_sz + 2];
            dest[i * 4 + 1] = src[i * pix_sz + 1];
            dest[i * 4 + 2] = src[i * pix_sz + 0];
            dest[i * 4 + 3] = (pix_sz == 3) ? 0xFF : src[i * pix_sz + 3];
        }

        src += static_cast<int>(buffer_size.d_width * pix_sz);
        dest += static_cast<int>(d_size.d_width * 4);
    }

    d_texture->unlock();
}

//----------------------------------------------------------------------------//
void IrrlichtTexture::blitFromMemory(void* sourceData, const Rect<>& area)
{
    CEGUI_THROW(InvalidRequestException("IrrlichtTexture::blitFromMemory: "
        "Function is unimplemented!"));
}

//----------------------------------------------------------------------------//
void IrrlichtTexture::blitToMemory(void* targetData)
{
    if (!d_texture)
        return;

    const size_t sz = static_cast<size_t>(d_size.d_width * d_size.d_height) * 4;
    memcpy(targetData, d_texture->lock(), sz);
    d_texture->unlock();
}

//----------------------------------------------------------------------------//
IrrlichtTexture::IrrlichtTexture(IrrlichtRenderer& owner,
                                 irr::video::IVideoDriver& driver,
                                 const String& name) :
    d_driver(driver),
    d_texture(0),
    d_size(0, 0),
    d_dataSize(0, 0),
    d_texelScaling(0, 0),
    d_owner(owner),
    d_name(name)
{
}

//----------------------------------------------------------------------------//
IrrlichtTexture::IrrlichtTexture(IrrlichtRenderer& owner,
                                 irr::video::IVideoDriver& driver,
                                 const String& name,
                                 const String& filename,
                                 const String& resourceGroup) :
    d_driver(driver),
    d_texture(0),
    d_owner(owner),
    d_name(name)
{
    loadFromFile(filename, resourceGroup);
}

//----------------------------------------------------------------------------//
IrrlichtTexture::IrrlichtTexture(IrrlichtRenderer& owner,
                                 irr::video::IVideoDriver& driver,
                                 const String& name,
                                 const Size<>& size) :
    d_driver(driver),
    d_dataSize(size),
    d_owner(owner),
    d_name(name)

{
    createIrrlichtTexture(size);

    d_size.d_width = static_cast<float>(d_texture->getSize().Width);
    d_size.d_height = static_cast<float>(d_texture->getSize().Height);

    updateCachedScaleValues();
}

//----------------------------------------------------------------------------//
IrrlichtTexture::~IrrlichtTexture()
{
    freeIrrlichtTexture();
}

//----------------------------------------------------------------------------//
void IrrlichtTexture::createIrrlichtTexture(const Size<>& sz)
{
    using namespace irr;

    const Size<> tex_sz(d_owner.getAdjustedTextureSize(sz));

    #if CEGUI_IRR_SDK_VERSION >= 16
        const core::dimension2d<u32> irr_sz(
            static_cast<u32>(tex_sz.d_width),
            static_cast<u32>(tex_sz.d_height));
    #else
        const core::dimension2d<s32> irr_sz(
            static_cast<s32>(tex_sz.d_width),
            static_cast<s32>(tex_sz.d_height));
    #endif

    // save texture creation state
    video::E_TEXTURE_CREATION_FLAG fmtflg;

    if (d_driver.getTextureCreationFlag(video::ETCF_ALWAYS_32_BIT))
        fmtflg = video::ETCF_ALWAYS_32_BIT;
    else if (d_driver.getTextureCreationFlag(video::ETCF_OPTIMIZED_FOR_QUALITY))
        fmtflg = video::ETCF_OPTIMIZED_FOR_QUALITY;
    else if (d_driver.getTextureCreationFlag(video::ETCF_OPTIMIZED_FOR_SPEED))
        fmtflg = video::ETCF_OPTIMIZED_FOR_SPEED;
    else
        fmtflg = video::ETCF_ALWAYS_16_BIT;

    const bool tfmips =
        d_driver.getTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS);
    const bool tfalpha =
        d_driver.getTextureCreationFlag(video::ETCF_NO_ALPHA_CHANNEL);
    const bool tfnpot =
        d_driver.getTextureCreationFlag(video::ETCF_ALLOW_NON_POWER_2);

    // explicitly set all states to what we want
    d_driver.setTextureCreationFlag(video::ETCF_ALWAYS_32_BIT, true);
    d_driver.setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, false);
    d_driver.setTextureCreationFlag(video::ETCF_NO_ALPHA_CHANNEL, false);
    d_driver.setTextureCreationFlag(video::ETCF_ALLOW_NON_POWER_2, true);

    d_texture = d_driver.addTexture(irr_sz, getUniqueName().c_str(),
                                    irr::video::ECF_A8R8G8B8);

    // restore previous texture creation state
    d_driver.setTextureCreationFlag(fmtflg, true);
    d_driver.setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, tfmips);
    d_driver.setTextureCreationFlag(video::ETCF_NO_ALPHA_CHANNEL, tfalpha);
    d_driver.setTextureCreationFlag(video::ETCF_ALLOW_NON_POWER_2, tfnpot);

    // we use ARGB all the time for now, so throw if we gut something else!
    if(video::ECF_A8R8G8B8 != d_texture->getColorFormat())
        CEGUI_THROW(RendererException(
            "IrrlichtTexture::loadFromMemory: texture did "
            "not have the correct format (ARGB)"));
}

//----------------------------------------------------------------------------//
void IrrlichtTexture::freeIrrlichtTexture()
{
    if (!d_texture)
        return;

    d_driver.removeTexture(d_texture);
    d_texture = 0;
}

//----------------------------------------------------------------------------//
std::string IrrlichtTexture::getUniqueName()
{
    char tmp[32];
    sprintf(tmp, "irr_tex_%d", d_textureNumber++);

    return std::string(tmp);
}

//----------------------------------------------------------------------------//
void IrrlichtTexture::setOriginalDataSize(const Size<>& sz)
{
    d_dataSize = sz;
    updateCachedScaleValues();
}

//----------------------------------------------------------------------------//
void IrrlichtTexture::updateCachedScaleValues()
{
    //
    // calculate what to use for x scale
    //
    const float orgW = d_dataSize.d_width;
    const float texW = d_size.d_width;

    // if texture and original data width are the same, scale is based
    // on the original size.
    // if texture is wider (and source data was not stretched), scale
    // is based on the size of the resulting texture.
    d_texelScaling.d_x = 1.0f / ((orgW == texW) ? orgW : texW);

    //
    // calculate what to use for y scale
    //
    const float orgH = d_dataSize.d_height;
    const float texH = d_size.d_height;

    // if texture and original data height are the same, scale is based
    // on the original size.
    // if texture is taller (and source data was not stretched), scale
    // is based on the size of the resulting texture.
    d_texelScaling.d_y = 1.0f / ((orgH == texH) ? orgH : texH);
}

//----------------------------------------------------------------------------//

} // End of  CEGUI namespace section
<commit_msg>Implement blit functions for Irrlicht renderer.  Currently these seem to not work when copying to a render target.<commit_after>/***********************************************************************
    filename:   CEGUIIrrlichtTexture.cpp
    created:    Tue Mar 3 2009
    author:     Paul D Turner (based on original code by Thomas Suter)
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include "CEGUIIrrlichtTexture.h"
#include "CEGUISystem.h"
#include "CEGUIExceptions.h"
#include "CEGUIImageCodec.h"
#include <irrlicht.h>

// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
uint32 IrrlichtTexture::d_textureNumber = 0;

//----------------------------------------------------------------------------//
void IrrlichtTexture::setIrrlichtTexture(irr::video::ITexture* tex)
{
    d_texture = tex;

    if (d_texture)
    {
        d_size = d_dataSize = Size<>(
                static_cast<float>(d_texture->getSize().Width),
                static_cast<float>(d_texture->getSize().Height));

        updateCachedScaleValues();
    }
}

//----------------------------------------------------------------------------//
irr::video::ITexture* IrrlichtTexture::getIrrlichtTexture() const
{
    return d_texture;
}

//----------------------------------------------------------------------------//
const String& IrrlichtTexture::getName() const
{
    return d_name;
}

//----------------------------------------------------------------------------//
const Size<>& IrrlichtTexture::getSize() const
{
    return d_size;
}

//----------------------------------------------------------------------------//
const Size<>& IrrlichtTexture::getOriginalDataSize() const
{
    return d_dataSize;
}

//----------------------------------------------------------------------------//
const Vector2<>& IrrlichtTexture::getTexelScaling() const
{
    return d_texelScaling;
}

//----------------------------------------------------------------------------//
void IrrlichtTexture::loadFromFile(const String& filename,
                                   const String& resourceGroup)
{
    // get and check existence of CEGUI::System object
    System* sys = System::getSingletonPtr();
    if (!sys)
        CEGUI_THROW(RendererException("IrrlichtTexture::loadFromFile: "
            "CEGUI::System object has not been created!"));

    // load file to memory via resource provider
    RawDataContainer texFile;
    sys->getResourceProvider()->loadRawDataContainer(filename, texFile,
                                                     resourceGroup);

    Texture* res = sys->getImageCodec().load(texFile, this);

    // unload file data buffer
    sys->getResourceProvider()->unloadRawDataContainer(texFile);

    // throw exception if data was load loaded to texture.
    if (!res)
        CEGUI_THROW(RendererException("IrrlichtTexture::loadFromFile: " +
            sys->getImageCodec().getIdentifierString() +
            " failed to load image '" + filename + "'."));
}

//----------------------------------------------------------------------------//
void IrrlichtTexture::loadFromMemory(const void* buffer,
                                     const Size<>& buffer_size,
                                     PixelFormat pixel_format)
{
    using namespace irr;

    freeIrrlichtTexture();
    createIrrlichtTexture(buffer_size);

    d_size.d_width = static_cast<float>(d_texture->getSize().Width);
    d_size.d_height = static_cast<float>(d_texture->getSize().Height);
    d_dataSize = buffer_size;

    updateCachedScaleValues();

    const size_t pix_sz = (pixel_format == PF_RGB) ? 3 : 4;
    const char* src = static_cast<const char*>(buffer);
    char* dest = static_cast<char*>(d_texture->lock());

    // copy data into texture, swapping red & blue and creating alpha channel
    // values as needed.
    for (int j = 0; j < buffer_size.d_height; ++j)
    {
        for (int i = 0; i < buffer_size.d_width; ++i)
        {
            dest[i * 4 + 0] = src[i * pix_sz + 2];
            dest[i * 4 + 1] = src[i * pix_sz + 1];
            dest[i * 4 + 2] = src[i * pix_sz + 0];
            dest[i * 4 + 3] = (pix_sz == 3) ? 0xFF : src[i * pix_sz + 3];
        }

        src += static_cast<int>(buffer_size.d_width * pix_sz);
        dest += static_cast<int>(d_size.d_width * 4);
    }

    d_texture->unlock();
}

//----------------------------------------------------------------------------//
void IrrlichtTexture::blitFromMemory(void* sourceData, const Rect<>& area)
{
    if (!d_texture)
        return;

    const size_t pitch = d_texture->getPitch();
    const uint32* src = static_cast<uint32*>(sourceData);
    uint32* dst = static_cast<uint32*>(d_texture->lock());

    if (!dst)
        CEGUI_THROW(RendererException(
            "[IrrlichtRenderer] ITexture::lock failed."));

    dst += static_cast<size_t>(area.top()) * (pitch / 4) +
        static_cast<size_t>(area.left());

    const Size<> sz(area.getSize());

    for (int j = 0; j < sz.d_height; ++j)
    {
        for (int i = 0; i < sz.d_width; ++i)
        {
            dst[i] = src[i];
        }

        src += static_cast<int>(sz.d_width);
        dst += pitch / 4;
    }

    d_texture->unlock();
}

//----------------------------------------------------------------------------//
void IrrlichtTexture::blitToMemory(void* targetData)
{
    if (!d_texture)
        return;

    const void* src = d_texture->lock(true);
    if (!src)
        CEGUI_THROW(RendererException(
            "[IrrlichtRenderer] ITexture::lock failed."));

    memcpy(targetData, src,
           static_cast<size_t>(d_size.d_width * d_size.d_height) * 4);

    d_texture->unlock();
}

//----------------------------------------------------------------------------//
IrrlichtTexture::IrrlichtTexture(IrrlichtRenderer& owner,
                                 irr::video::IVideoDriver& driver,
                                 const String& name) :
    d_driver(driver),
    d_texture(0),
    d_size(0, 0),
    d_dataSize(0, 0),
    d_texelScaling(0, 0),
    d_owner(owner),
    d_name(name)
{
}

//----------------------------------------------------------------------------//
IrrlichtTexture::IrrlichtTexture(IrrlichtRenderer& owner,
                                 irr::video::IVideoDriver& driver,
                                 const String& name,
                                 const String& filename,
                                 const String& resourceGroup) :
    d_driver(driver),
    d_texture(0),
    d_owner(owner),
    d_name(name)
{
    loadFromFile(filename, resourceGroup);
}

//----------------------------------------------------------------------------//
IrrlichtTexture::IrrlichtTexture(IrrlichtRenderer& owner,
                                 irr::video::IVideoDriver& driver,
                                 const String& name,
                                 const Size<>& size) :
    d_driver(driver),
    d_dataSize(size),
    d_owner(owner),
    d_name(name)

{
    createIrrlichtTexture(size);

    d_size.d_width = static_cast<float>(d_texture->getSize().Width);
    d_size.d_height = static_cast<float>(d_texture->getSize().Height);

    updateCachedScaleValues();
}

//----------------------------------------------------------------------------//
IrrlichtTexture::~IrrlichtTexture()
{
    freeIrrlichtTexture();
}

//----------------------------------------------------------------------------//
void IrrlichtTexture::createIrrlichtTexture(const Size<>& sz)
{
    using namespace irr;

    const Size<> tex_sz(d_owner.getAdjustedTextureSize(sz));

    #if CEGUI_IRR_SDK_VERSION >= 16
        const core::dimension2d<u32> irr_sz(
            static_cast<u32>(tex_sz.d_width),
            static_cast<u32>(tex_sz.d_height));
    #else
        const core::dimension2d<s32> irr_sz(
            static_cast<s32>(tex_sz.d_width),
            static_cast<s32>(tex_sz.d_height));
    #endif

    // save texture creation state
    video::E_TEXTURE_CREATION_FLAG fmtflg;

    if (d_driver.getTextureCreationFlag(video::ETCF_ALWAYS_32_BIT))
        fmtflg = video::ETCF_ALWAYS_32_BIT;
    else if (d_driver.getTextureCreationFlag(video::ETCF_OPTIMIZED_FOR_QUALITY))
        fmtflg = video::ETCF_OPTIMIZED_FOR_QUALITY;
    else if (d_driver.getTextureCreationFlag(video::ETCF_OPTIMIZED_FOR_SPEED))
        fmtflg = video::ETCF_OPTIMIZED_FOR_SPEED;
    else
        fmtflg = video::ETCF_ALWAYS_16_BIT;

    const bool tfmips =
        d_driver.getTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS);
    const bool tfalpha =
        d_driver.getTextureCreationFlag(video::ETCF_NO_ALPHA_CHANNEL);
    const bool tfnpot =
        d_driver.getTextureCreationFlag(video::ETCF_ALLOW_NON_POWER_2);

    // explicitly set all states to what we want
    d_driver.setTextureCreationFlag(video::ETCF_ALWAYS_32_BIT, true);
    d_driver.setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, false);
    d_driver.setTextureCreationFlag(video::ETCF_NO_ALPHA_CHANNEL, false);
    d_driver.setTextureCreationFlag(video::ETCF_ALLOW_NON_POWER_2, true);

    d_texture = d_driver.addTexture(irr_sz, getUniqueName().c_str(),
                                    irr::video::ECF_A8R8G8B8);

    // restore previous texture creation state
    d_driver.setTextureCreationFlag(fmtflg, true);
    d_driver.setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, tfmips);
    d_driver.setTextureCreationFlag(video::ETCF_NO_ALPHA_CHANNEL, tfalpha);
    d_driver.setTextureCreationFlag(video::ETCF_ALLOW_NON_POWER_2, tfnpot);

    // we use ARGB all the time for now, so throw if we gut something else!
    if(video::ECF_A8R8G8B8 != d_texture->getColorFormat())
        CEGUI_THROW(RendererException(
            "IrrlichtTexture::loadFromMemory: texture did "
            "not have the correct format (ARGB)"));
}

//----------------------------------------------------------------------------//
void IrrlichtTexture::freeIrrlichtTexture()
{
    if (!d_texture)
        return;

    d_driver.removeTexture(d_texture);
    d_texture = 0;
}

//----------------------------------------------------------------------------//
std::string IrrlichtTexture::getUniqueName()
{
    char tmp[32];
    sprintf(tmp, "irr_tex_%d", d_textureNumber++);

    return std::string(tmp);
}

//----------------------------------------------------------------------------//
void IrrlichtTexture::setOriginalDataSize(const Size<>& sz)
{
    d_dataSize = sz;
    updateCachedScaleValues();
}

//----------------------------------------------------------------------------//
void IrrlichtTexture::updateCachedScaleValues()
{
    //
    // calculate what to use for x scale
    //
    const float orgW = d_dataSize.d_width;
    const float texW = d_size.d_width;

    // if texture and original data width are the same, scale is based
    // on the original size.
    // if texture is wider (and source data was not stretched), scale
    // is based on the size of the resulting texture.
    d_texelScaling.d_x = 1.0f / ((orgW == texW) ? orgW : texW);

    //
    // calculate what to use for y scale
    //
    const float orgH = d_dataSize.d_height;
    const float texH = d_size.d_height;

    // if texture and original data height are the same, scale is based
    // on the original size.
    // if texture is taller (and source data was not stretched), scale
    // is based on the size of the resulting texture.
    d_texelScaling.d_y = 1.0f / ((orgH == texH) ? orgH : texH);
}

//----------------------------------------------------------------------------//

} // End of  CEGUI namespace section
<|endoftext|>


<commit_before>#include <string.h>
#include <signal.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <thread>
#include <set>
#include "msg_filter.hpp"
#include "io_policy/line.hpp"
#include "io_policy/length.hpp"
#include "io_policy/sysv_mq.hpp"
#include "io_policy/tcp.hpp"
#include "sub_entry.hpp"
#include "util.hpp"
#include "logger.hpp"

using namespace std;
using namespace wissbi;

bool run = true;

void exit_signal_handler(int signum) {
    run = false;
}

template<class OutputWriter>
void run_sub(const std::string& src) {
    int serv = socket(AF_INET, SOCK_STREAM, 0);
    sockaddr serv_addr;
    util::ConnectStringToSockaddr("0.0.0.0:0", reinterpret_cast<sockaddr_in*>(&serv_addr));
    if(-1 == ::bind(serv, &serv_addr, sizeof(serv_addr))) {
        logger::log("bind error");
        throw std::runtime_error("bind error");
    }
    if(-1 == listen(serv, 10)) {
        logger::log("listen error");
        throw std::runtime_error("listen error");
    }
    socklen_t len = sizeof(serv_addr);;
    getsockname(serv, &serv_addr, &len);
    logger::log("wissbi-sub is listening on port {}", ntohs(((sockaddr_in*)&serv_addr)->sin_port));

    ostringstream tmp;
    tmp << util::GetHostIP() << ":" << ntohs(((sockaddr_in*)&serv_addr)->sin_port);

    SubEntry sub_entry(getenv("WISSBI_META_DIR") != NULL ? getenv("WISSBI_META_DIR") : "/var/lib/wissbi", src, tmp.str());

    OutputWriter output_writer;
    output_writer.mq_init("");
    output_writer.auto_flush();
    thread* output_th = new thread([&output_writer](){
        output_writer.FilterLoop();
    });

    struct timeval tv;
    tv.tv_sec = 1;
    tv.tv_usec = 0;
    setsockopt(serv, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));

    while(run) {
        sockaddr other_addr;
        socklen_t len = sizeof(other_addr);
        int res = accept(serv, &other_addr, &len);
        if(res > 0){
            logger::log("wissbi-pub connected from {}", util::SockaddrToConnectString(reinterpret_cast<const sockaddr_in&>(other_addr)));
            struct timeval tv;
            tv.tv_sec = 0;
            tv.tv_usec = 0;
            setsockopt(res, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
            thread([res]{
                MsgFilter<io_policy::TCP, io_policy::SysvMq> filter;
                filter.mq_init("");
                filter.set_cleanup(false);
                filter.AttachConnectedSock(res);
                filter.FilterLoop();
            }).detach();
        }
        sub_entry.renew();
    }
}

int main(int argc, char* argv[]){
    if(argc < 2) {
        std::cerr << "Usage: " << argv[0] << " SOURCE_NAME" << std::endl;
        return 1;
    }
    signal(SIGINT, exit_signal_handler);
    signal(SIGTERM, exit_signal_handler);
    signal(SIGPIPE, exit_signal_handler);

    std::string src(argv[1]);

    if(getenv("WISSBI_PID_FILE") != NULL) {
        ofstream ofs(getenv("WISSBI_PID_FILE"));
        ofs << getpid() << endl;
    }

    char* msg_format = getenv("WISSBI_MESSAGE_FORMAT");
    if(msg_format) {
        if(std::string(msg_format) == "line") {
            run_sub<MsgFilter<io_policy::SysvMq, io_policy::Line>>(src);
        }
        else if(std::string(msg_format) == "length") {
            run_sub<MsgFilter<io_policy::SysvMq, io_policy::Length>>(src);
        }
        else {
            logger::log("unknown message format: {}", msg_format);
            return 1;
        }
    }
    else {
        run_sub<MsgFilter<io_policy::SysvMq, io_policy::Line>>(src);
    }
    logger::log("wissbi-sub exited normally");
    return 0;
}

<commit_msg>force sub to reset the connection when it exits<commit_after>#include <string.h>
#include <signal.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <thread>
#include <set>
#include "msg_filter.hpp"
#include "io_policy/line.hpp"
#include "io_policy/length.hpp"
#include "io_policy/sysv_mq.hpp"
#include "io_policy/tcp.hpp"
#include "sub_entry.hpp"
#include "util.hpp"
#include "logger.hpp"

using namespace std;
using namespace wissbi;

bool run = true;

void exit_signal_handler(int signum) {
    run = false;
}

template<class OutputWriter>
void run_sub(const std::string& src) {
    int serv = socket(AF_INET, SOCK_STREAM, 0);
    sockaddr serv_addr;
    util::ConnectStringToSockaddr("0.0.0.0:0", reinterpret_cast<sockaddr_in*>(&serv_addr));
    if(-1 == ::bind(serv, &serv_addr, sizeof(serv_addr))) {
        logger::log("bind error");
        throw std::runtime_error("bind error");
    }
    if(-1 == listen(serv, 10)) {
        logger::log("listen error");
        throw std::runtime_error("listen error");
    }
    socklen_t len = sizeof(serv_addr);;
    getsockname(serv, &serv_addr, &len);
    logger::log("wissbi-sub is listening on port {}", ntohs(((sockaddr_in*)&serv_addr)->sin_port));

    ostringstream tmp;
    tmp << util::GetHostIP() << ":" << ntohs(((sockaddr_in*)&serv_addr)->sin_port);

    SubEntry sub_entry(getenv("WISSBI_META_DIR") != NULL ? getenv("WISSBI_META_DIR") : "/var/lib/wissbi", src, tmp.str());

    OutputWriter output_writer;
    output_writer.mq_init("");
    output_writer.auto_flush();
    thread* output_th = new thread([&output_writer](){
        output_writer.FilterLoop();
    });

    struct timeval tv;
    tv.tv_sec = 1;
    tv.tv_usec = 0;
    setsockopt(serv, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));

    while(run) {
        sockaddr other_addr;
        socklen_t len = sizeof(other_addr);
        int res = accept(serv, &other_addr, &len);
        if(res > 0){
            logger::log("wissbi-pub connected from {}", util::SockaddrToConnectString(reinterpret_cast<const sockaddr_in&>(other_addr)));
            struct timeval tv;
            tv.tv_sec = 0;
            tv.tv_usec = 0;
            setsockopt(res, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
            struct linger lo = {1, 0};
            setsockopt(res, SOL_SOCKET, SO_LINGER, &lo, sizeof(lo));
            thread([res]{
                MsgFilter<io_policy::TCP, io_policy::SysvMq> filter;
                filter.mq_init("");
                filter.set_cleanup(false);
                filter.AttachConnectedSock(res);
                filter.FilterLoop();
            }).detach();
        }
        sub_entry.renew();
    }
}

int main(int argc, char* argv[]){
    if(argc < 2) {
        std::cerr << "Usage: " << argv[0] << " SOURCE_NAME" << std::endl;
        return 1;
    }
    signal(SIGINT, exit_signal_handler);
    signal(SIGTERM, exit_signal_handler);
    signal(SIGPIPE, exit_signal_handler);

    std::string src(argv[1]);

    if(getenv("WISSBI_PID_FILE") != NULL) {
        ofstream ofs(getenv("WISSBI_PID_FILE"));
        ofs << getpid() << endl;
    }

    char* msg_format = getenv("WISSBI_MESSAGE_FORMAT");
    if(msg_format) {
        if(std::string(msg_format) == "line") {
            run_sub<MsgFilter<io_policy::SysvMq, io_policy::Line>>(src);
        }
        else if(std::string(msg_format) == "length") {
            run_sub<MsgFilter<io_policy::SysvMq, io_policy::Length>>(src);
        }
        else {
            logger::log("unknown message format: {}", msg_format);
            return 1;
        }
    }
    else {
        run_sub<MsgFilter<io_policy::SysvMq, io_policy::Line>>(src);
    }
    logger::log("wissbi-sub exited normally");
    return 0;
}

<|endoftext|>