<commit_before>//----------------------------  mglocal.cc  ---------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 1998, 1999, 2000 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//----------------------------  mglocal.cc  ---------------------------

#include <base/function.h>
#include <base/quadrature_lib.h>
#include <base/logstream.h>
#include <lac/vector.h>
#include <lac/sparse_matrix.h>
#include <lac/solver_cg.h>
#include <lac/solver_richardson.h>
#include <lac/vector_memory.h>
#include <lac/precondition.h>
#include <grid/tria.h>
#include <grid/tria_iterator.h>
#include <grid/grid_out.h>
#include <multigrid/mg_dof_handler.h>
#include <dofs/dof_constraints.h>
#include <dofs/dof_accessor.h>
#include <multigrid/mg_dof_accessor.h>
#include <grid/grid_generator.h>
#include <numerics/data_out.h>
#include <fe/fe_lib.lagrange.h>
#include <fe/fe_values.h>
#include <multigrid/multigrid.h>
#include <multigrid/mg_smoother.h>
#include <dofs/dof_tools.h>
#include <multigrid/mg_dof_tools.h>

#include <fstream>

MGSmoother* smoother_object;

// Does anybody know why cmath does not do this?

#ifndef M_PI_2
#define	M_PI_2		1.57079632679489661923
#endif

int step_counter = 0;

#include "helmholtz.h"

template<int dim>
class RHSFunction
  :
  public Function<dim>
{
  public:
    virtual double value (const Point<dim>&,
			  const unsigned int ) const;
};

extern void write_gnuplot (const MGDoFHandler<2>& dofs,
			   const Vector<double>& v,
			   unsigned int level,
			   ostream &out);

int main()
{
  ofstream logfile("mglocal.output");
  logfile.setf(ios::fixed);
  logfile.precision (3);
  deallog.attach(logfile);
//  deallog.log_execution_time(true);
  deallog.depth_console(10);

  Helmholtz equation;
  RHSFunction<2> rhs;
  QGauss5<2> quadrature;

  FEQ1<2> fe1;
  FEQ2<2> fe2;
  FEQ3<2> fe3;
  FEQ4<2> fe4;
  for (unsigned int degree=1;degree<=1;degree++)
    {
      Triangulation<2> tr(Triangulation<2>::maximum_smoothing);
      MGDoFHandler<2> mgdof(tr);
      DoFHandler<2>& dof(mgdof);

      GridGenerator::hyper_cube(tr,-M_PI_2,M_PI_2);

      FiniteElement<2>* fe;
      switch(degree)
	{
	  case 1: fe = &fe1; deallog.push("Q1"); break;
	  case 2: fe = &fe2; deallog.push("Q2"); break;
	  case 3: fe = &fe3; deallog.push("Q3"); break;
	  case 4: fe = &fe4; deallog.push("Q4"); break;
	}

      tr.refine_global(1);

      Triangulation<2>::active_cell_iterator cell, endc;
      for (int i=0; i<8; ++i)
	{
	  int n_levels = tr.n_levels();
	  cell = tr.begin_active();
	  endc = tr.end();

	  for (; cell!=endc; ++cell)
	    {
	      double r      = rand()*1.0/RAND_MAX,
		     weight = 1.*
			      (cell->level()*cell->level()) /
			      (n_levels*n_levels);

	      if (r <= 0.5*weight)
		cell->set_refine_flag ();
	    };

	  tr.execute_coarsening_and_refinement ();
	};
//        Triangulation<2>::active_cell_iterator cell = tr.begin_active();
//        cell->set_refine_flag();
      tr.execute_coarsening_and_refinement();

//      tr.refine_global(4);
      if (true)
	{
	  ofstream x ("T");
	  GridOut().write_eps (tr, x);
	};

      dof.distribute_dofs(*fe);
      const unsigned int size = dof.n_dofs();
      deallog << "DoFs " << size << endl;
      deallog << "Levels: " << tr.n_levels() << endl;
      for (unsigned int step=1;step < 3; ++step)
	{
	  deallog << "smoothing-steps" << step << endl;
	  SparsityPattern structure(size, dof.max_couplings_between_dofs());
	  DoFTools::make_sparsity_pattern(dof, structure);

	  ConstraintMatrix hanging_nodes;
	  DoFTools::make_hanging_node_constraints (dof, hanging_nodes);
	  hanging_nodes.close();
	  hanging_nodes.condense(structure);

	  structure.compress();

	  SparseMatrix<double> A(structure);
	  Vector<double> f(size);

	  equation.build_all(A,f,dof, quadrature, rhs);

	  hanging_nodes.condense(A);
	  hanging_nodes.condense(f);

	  if (false)
	    {
	      ofstream out_file("MGf");
	      DataOut<2> out;
	      out.attach_dof_handler(dof);
	      out.add_data_vector(f, "v");
	      out.build_patches(5);
	      out.write_gnuplot(out_file);
	    }

	  Vector<double> u;
	  u.reinit(f);
	  PrimitiveVectorMemory<> mem;

	  SolverControl control(20, 1.e-12, false);
	  SolverCG<> solver(control, mem);

	  MGLevelObject<SparsityPattern> mgstruct(0, tr.n_levels()-1);
	  MGLevelObject<SparseMatrix<double> > mgA(0,tr.n_levels()-1);
	  for (unsigned int i=0;i<tr.n_levels();++i)
	    {
	      mgstruct[i].reinit(mgdof.n_dofs(i), mgdof.n_dofs(i),
				 mgdof.max_couplings_between_dofs());
	      MGDoFTools::make_sparsity_pattern(mgdof, mgstruct[i], i);
	      mgstruct[i].compress();

	      mgA[i].reinit(mgstruct[i]);
	    }
	  equation.build_mgmatrix(mgA, mgdof, quadrature);

	  SolverControl cgcontrol(2000,1.e-14, false, false);
	  PrimitiveVectorMemory<> cgmem;
	  SolverCG<> cgsolver(cgcontrol, cgmem);
	  PreconditionIdentity cgprec;
	  MGCoarseGridLACIteration<SolverCG<>, SparseMatrix<double>, PreconditionIdentity>
	    coarse(cgsolver, mgA[0], cgprec);

	  MGSmootherRelaxation<double>
	    smoother(mgdof, mgA, &SparseMatrix<double>::template precondition_SSOR<double>,
		     step, 1.);
	  smoother_object = &smoother;

	  MGTransferPrebuilt transfer;
	  transfer.build_matrices(mgdof);

Multigrid<2> multigrid(mgdof, hanging_nodes, mgstruct, mgA, transfer, 0);
	  PreconditionMG<Multigrid<2> >
	    mgprecondition(multigrid, smoother, smoother, coarse);

	   u = 0.;

	  solver.solve(A, u, f, mgprecondition);
	  hanging_nodes.distribute(u);

	  if (false)
	    {
	      DataOut<2> out;
	      char* name = new char[100];

	      sprintf(name, "MG-Q%d-%d", degree, step);

	      ofstream ofile(name);
	      out.attach_dof_handler(dof);
	      out.add_data_vector(u,"u");
	      out.add_data_vector(f,"f");
	      out.build_patches(5);
	      out.write_gnuplot(ofile);
	      delete[] name;
	    }
	}
      deallog.pop();
    }
}

template<int dim>
double
RHSFunction<dim>::value (const Point<dim>&p,
			 const unsigned int) const
{
  return 1.;

  return p(0)*p(0)+p(1)*p(1);

  return (2.1)*(sin(p(0))* sin(p(1)));
}
<commit_msg>Revert unintended change to mglocal.cc<commit_after>//----------------------------  mglocal.cc  ---------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 1998, 1999, 2000 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//----------------------------  mglocal.cc  ---------------------------

#include <base/function.h>
#include <base/quadrature_lib.h>
#include <base/logstream.h>
#include <lac/vector.h>
#include <lac/sparse_matrix.h>
#include <lac/solver_cg.h>
#include <lac/solver_richardson.h>
#include <lac/vector_memory.h>
#include <lac/precondition.h>
#include <grid/tria.h>
#include <grid/tria_iterator.h>
#include <multigrid/mg_dof_handler.h>
#include <dofs/dof_constraints.h>
#include <dofs/dof_accessor.h>
#include <multigrid/mg_dof_accessor.h>
#include <grid/grid_generator.h>
#include <numerics/data_out.h>
#include <fe/fe_lib.lagrange.h>
#include <fe/fe_values.h>
#include <multigrid/multigrid.h>
#include <multigrid/mg_smoother.h>
#include <dofs/dof_tools.h>
#include <multigrid/mg_dof_tools.h>

#include <fstream>

MGSmoother* smoother_object;

// Does anybody know why cmath does not do this?

#ifndef M_PI_2
#define	M_PI_2		1.57079632679489661923
#endif

int step_counter = 0;

#include "helmholtz.h"

template<int dim>
class RHSFunction
  :
  public Function<dim>
{
  public:
    virtual double value (const Point<dim>&,
			  const unsigned int ) const;
};

extern void write_gnuplot (const MGDoFHandler<2>& dofs,
			   const Vector<double>& v,
			   unsigned int level,
			   ostream &out);

int main()
{
  ofstream logfile("mglocal.output");
  logfile.setf(ios::fixed);
  logfile.precision (3);
  deallog.attach(logfile);
//  deallog.log_execution_time(true);
  deallog.depth_console(0);

  Helmholtz equation;
  RHSFunction<2> rhs;
  QGauss5<2> quadrature;

  FEQ1<2> fe1;
  FEQ2<2> fe2;
  FEQ3<2> fe3;
  FEQ4<2> fe4;
  for (unsigned int degree=1;degree<=3;degree++)
    {
      Triangulation<2> tr;
      MGDoFHandler<2> mgdof(tr);
      DoFHandler<2>& dof(mgdof);

      GridGenerator::hyper_cube(tr,-M_PI_2,M_PI_2);

      FiniteElement<2>* fe;
      switch(degree)
	{
	  case 1: fe = &fe1; deallog.push("Q1"); break;
	  case 2: fe = &fe2; deallog.push("Q2"); break;
	  case 3: fe = &fe3; deallog.push("Q3"); break;
	  case 4: fe = &fe4; deallog.push("Q4"); break;
	}

      tr.refine_global(1);
      Triangulation<2>::active_cell_iterator cell = tr.begin_active();
      cell->set_refine_flag();
      tr.execute_coarsening_and_refinement();

      tr.refine_global(1);
      dof.distribute_dofs(*fe);
      const unsigned int size = dof.n_dofs();
      deallog << "DoFs " << size << endl;
      deallog << "Levels: " << tr.n_levels() << endl;
      for (unsigned int step=1;step < 3; ++step)
	{
	  deallog << "smoothing-steps" << step << endl;
	  SparsityPattern structure(size, dof.max_couplings_between_dofs());
	  DoFTools::make_sparsity_pattern(dof, structure);

	  ConstraintMatrix hanging_nodes;
	  DoFTools::make_hanging_node_constraints (dof, hanging_nodes);
	  hanging_nodes.close();
	  hanging_nodes.condense(structure);

	  structure.compress();

	  SparseMatrix<double> A(structure);
	  Vector<double> f(size);

	  equation.build_all(A,f,dof, quadrature, rhs);

	  hanging_nodes.condense(A);
	  hanging_nodes.condense(f);

	  if (false)
	    {
	      ofstream out_file("MGf");
	      DataOut<2> out;
	      out.attach_dof_handler(dof);
	      out.add_data_vector(f, "v");
	      out.build_patches(5);
	      out.write_gnuplot(out_file);
	    }

	  Vector<double> u;
	  u.reinit(f);
	  PrimitiveVectorMemory<> mem;

	  SolverControl control(20, 1.e-12, false);
	  SolverCG<> solver(control, mem);

	  MGLevelObject<SparsityPattern> mgstruct(0, tr.n_levels()-1);
	  MGLevelObject<SparseMatrix<double> > mgA(0,tr.n_levels()-1);
	  for (unsigned int i=0;i<tr.n_levels();++i)
	    {
	      mgstruct[i].reinit(mgdof.n_dofs(i), mgdof.n_dofs(i),
				 mgdof.max_couplings_between_dofs());
	      MGDoFTools::make_sparsity_pattern(mgdof, mgstruct[i], i);
	      mgstruct[i].compress();

	      mgA[i].reinit(mgstruct[i]);
	    }
	  equation.build_mgmatrix(mgA, mgdof, quadrature);

	  SolverControl cgcontrol(2000,1.e-14, false, false);
	  PrimitiveVectorMemory<> cgmem;
	  SolverCG<> cgsolver(cgcontrol, cgmem);
	  PreconditionIdentity cgprec;
	  MGCoarseGridLACIteration<SolverCG<>, SparseMatrix<double>, PreconditionIdentity>
	    coarse(cgsolver, mgA[tr.n_levels()-2], cgprec);

	  MGSmootherRelaxation<double>
	    smoother(mgdof, mgA, &SparseMatrix<double>::template precondition_SSOR<double>,
		     step, 1.);
	  smoother_object = &smoother;

	  MGTransferPrebuilt transfer;
	  transfer.build_matrices(mgdof);

Multigrid<2> multigrid(mgdof, hanging_nodes, mgstruct, mgA, transfer, tr.n_levels()-2);
	  PreconditionMG<Multigrid<2> >
	    mgprecondition(multigrid, smoother, smoother, coarse);

	   u = 0.;

	  solver.solve(A, u, f, mgprecondition);
	  hanging_nodes.distribute(u);

	  if (false)
	    {
	      DataOut<2> out;
	      char* name = new char[100];

	      sprintf(name, "MG-Q%d-%d", degree, step);

	      ofstream ofile(name);
	      out.attach_dof_handler(dof);
	      out.add_data_vector(u,"u");
	      out.add_data_vector(f,"f");
	      out.build_patches(5);
	      out.write_gnuplot(ofile);
	      delete[] name;
	    }
	}
      deallog.pop();
    }
}

template<int dim>
double
RHSFunction<dim>::value (const Point<dim>&p,
			 const unsigned int) const
{
  return 1.;

  return p(0)*p(0)+p(1)*p(1);

  return (2.1)*(sin(p(0))* sin(p(1)));
}
<|endoftext|>


<commit_before>#include "catch.hpp"
#include <SQLiteXX.h>

TEST_CASE("Initialization with non empty database", "[Backup]") {
    sqlite::dbconnection src = sqlite::dbconnection::memory();
    sqlite::execute(src, "CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT)");

    REQUIRE(sqlite::execute(src, "INSERT INTO test VALUES (1, \"one\")") == 1);
    REQUIRE(sqlite::execute(src, "INSERT INTO test VALUES (2, \"two\")") == 1);

    SECTION("Backup to self") {
        REQUIRE_THROWS_AS(sqlite::backup(src, src), sqlite::exception);
    }

    SECTION("Backup to read-only file") {
        sqlite::dbconnection destination("TestBackup.db", sqlite::openmode::read_only);
        sqlite::backup backup(src, destination);
        REQUIRE_THROWS_AS(backup.step(), sqlite::exception);
    }
}

TEST_CASE("Backup process", "[Backup]") {
    sqlite::dbconnection src = sqlite::dbconnection::memory();
    sqlite::execute(src, "CREATE TABLE test (id INTEGER PRIMARY KEY, integerValue TEXT, doubleValue REAL)");
    REQUIRE(sqlite::execute(src, "INSERT INTO test VALUES (1, \"one\", 1.0)") == 1);
    REQUIRE(sqlite::execute(src, "INSERT INTO test VALUES (2, \"two\", 2.0)") == 1);

    sqlite::dbconnection dest = sqlite::dbconnection::memory();

    SECTION("Backup one page at a time") {
        sqlite::backup backup(src, dest);

        REQUIRE(backup.step(1) == true);
        REQUIRE(backup.total_page_count() == 2);
        REQUIRE(backup.remaining_page_count() == 1);
        REQUIRE(backup.step(1) == false);
        REQUIRE(backup.remaining_page_count() == 0);

        sqlite::statement query(dest, "SELECT * FROM test ORDER BY id ASC");
        REQUIRE(query.step() == true);
        REQUIRE(query.get_int(0) == 1);
        REQUIRE(query.get_string(1) == std::string("one"));
        REQUIRE(query.get_double(2) == 1.0);
        REQUIRE(query.step() == true);
        REQUIRE(query.get_int(0) == 2);
        REQUIRE(query.get_string(1) == std::string("two"));
        REQUIRE(query.get_double(2) == 2.0);
        REQUIRE(query.step() == false);
    }

    SECTION("Backup all at once") {
        sqlite::backup backup(src, dest);

        REQUIRE(backup.step() == false);
        REQUIRE(backup.total_page_count() == 2);
        REQUIRE(backup.remaining_page_count() == 0);

        sqlite::statement query(dest, "SELECT * FROM test ORDER BY id ASC");
        REQUIRE(query.step() == true);
        REQUIRE(query.get_int(0) == 1);
        REQUIRE(query.get_string(1) == std::string("one"));
        REQUIRE(query.get_double(2) == 1.0);
        REQUIRE(query.step() == true);
        REQUIRE(query.get_int(0) == 2);
        REQUIRE(query.get_string(1) == std::string("two"));
        REQUIRE(query.get_double(2) == 2.0);
        REQUIRE(query.step() == false);
    }

    SECTION("Save to disk") {
        remove("SaveToDiskResults.db");
        sqlite::save(src, "SaveToDiskResults.db");

        sqlite::dbconnection connection("SaveToDiskResults.db");

        sqlite::statement query(connection, "SELECT * FROM test ORDER BY id ASC");
        REQUIRE(query.step() == true);
        REQUIRE(query.get_int(0) == 1);
        REQUIRE(query.get_string(1) == std::string("one"));
        REQUIRE(query.get_double(2) == 1.0);
        REQUIRE(query.step() == true);
        REQUIRE(query.get_int(0) == 2);
        REQUIRE(query.get_string(1) == std::string("two"));
        REQUIRE(query.get_double(2) == 2.0);
        REQUIRE(query.step() == false);
    }
}
<commit_msg>Fixing test when file does not exist<commit_after>#include "catch.hpp"
#include <SQLiteXX.h>

TEST_CASE("Initialization with non empty database", "[Backup]") {
    sqlite::dbconnection src = sqlite::dbconnection::memory();
    sqlite::execute(src, "CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT)");

    REQUIRE(sqlite::execute(src, "INSERT INTO test VALUES (1, \"one\")") == 1);
    REQUIRE(sqlite::execute(src, "INSERT INTO test VALUES (2, \"two\")") == 1);

    SECTION("Backup to self") {
        REQUIRE_THROWS_AS(sqlite::backup(src, src), sqlite::exception);
    }

    SECTION("Backup to read-only file") {
        remove("TestBackup.db");
        sqlite::dbconnection create_database("TestBackup.db");

        sqlite::dbconnection destination("TestBackup.db", sqlite::openmode::read_only);
        sqlite::backup backup(src, destination);
        REQUIRE_THROWS_AS(backup.step(), sqlite::exception);
    }
}

TEST_CASE("Backup process", "[Backup]") {
    sqlite::dbconnection src = sqlite::dbconnection::memory();
    sqlite::execute(src, "CREATE TABLE test (id INTEGER PRIMARY KEY, integerValue TEXT, doubleValue REAL)");
    REQUIRE(sqlite::execute(src, "INSERT INTO test VALUES (1, \"one\", 1.0)") == 1);
    REQUIRE(sqlite::execute(src, "INSERT INTO test VALUES (2, \"two\", 2.0)") == 1);

    sqlite::dbconnection dest = sqlite::dbconnection::memory();

    SECTION("Backup one page at a time") {
        sqlite::backup backup(src, dest);

        REQUIRE(backup.step(1) == true);
        REQUIRE(backup.total_page_count() == 2);
        REQUIRE(backup.remaining_page_count() == 1);
        REQUIRE(backup.step(1) == false);
        REQUIRE(backup.remaining_page_count() == 0);

        sqlite::statement query(dest, "SELECT * FROM test ORDER BY id ASC");
        REQUIRE(query.step() == true);
        REQUIRE(query.get_int(0) == 1);
        REQUIRE(query.get_string(1) == std::string("one"));
        REQUIRE(query.get_double(2) == 1.0);
        REQUIRE(query.step() == true);
        REQUIRE(query.get_int(0) == 2);
        REQUIRE(query.get_string(1) == std::string("two"));
        REQUIRE(query.get_double(2) == 2.0);
        REQUIRE(query.step() == false);
    }

    SECTION("Backup all at once") {
        sqlite::backup backup(src, dest);

        REQUIRE(backup.step() == false);
        REQUIRE(backup.total_page_count() == 2);
        REQUIRE(backup.remaining_page_count() == 0);

        sqlite::statement query(dest, "SELECT * FROM test ORDER BY id ASC");
        REQUIRE(query.step() == true);
        REQUIRE(query.get_int(0) == 1);
        REQUIRE(query.get_string(1) == std::string("one"));
        REQUIRE(query.get_double(2) == 1.0);
        REQUIRE(query.step() == true);
        REQUIRE(query.get_int(0) == 2);
        REQUIRE(query.get_string(1) == std::string("two"));
        REQUIRE(query.get_double(2) == 2.0);
        REQUIRE(query.step() == false);
    }

    SECTION("Save to disk") {
        remove("SaveToDiskResults.db");
        sqlite::save(src, "SaveToDiskResults.db");

        sqlite::dbconnection connection("SaveToDiskResults.db");

        sqlite::statement query(connection, "SELECT * FROM test ORDER BY id ASC");
        REQUIRE(query.step() == true);
        REQUIRE(query.get_int(0) == 1);
        REQUIRE(query.get_string(1) == std::string("one"));
        REQUIRE(query.get_double(2) == 1.0);
        REQUIRE(query.step() == true);
        REQUIRE(query.get_int(0) == 2);
        REQUIRE(query.get_string(1) == std::string("two"));
        REQUIRE(query.get_double(2) == 2.0);
        REQUIRE(query.step() == false);
    }
}
<|endoftext|>


<commit_before>#include <cmath>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include "StateSpace3.h"
#include "PriorityQueue.h"
#include "State3.h"
#include "environment.h"

template<typename T> std::string to_string(T x) {
	return static_cast<std::ostringstream&>((std::ostringstream() << std::dec << x)).str();
}

//function to calculate a temperature for the select action function as a function of time
double temperature(unsigned long t);

//function to select next action
float selectAction(PriorityQueue<float, double>& a_queue, unsigned long int iterations);

//function to update a q value
void updateQ(StateSpace & space, float  action, State & new_state, State & old_state, double alpha, double gamma);

int main()
{
	//learning factor
	const double alpha = 0.5;
	//discount factor
	const double gamma = 0.5;
	const double deltatime = 0.1;
	const double mass = 0.5;
	const double length = 0.08;

	const int angle_bins = 100;
	const int velocity_bins = 50;
	const int torque_bins = 9;
	const double maxangle = 4;
	const double maxvelocity = 4;
	const double maxtorque = 4;

	/*for (int i = 0; i < torque_bins; ++i) {
		const int t_i = -maxtorque + i;
	}*/

	environment* env = new environment(0, 0, 0, maxtorque, 0, deltatime, mass, length, gamma);

	//seed rng
	std::srand(static_cast<unsigned int>(std::time(NULL)));

	//create pointers to the possible actions as well as a pointer to hold the chosen action
	float chosen_action = 1.0f;	// THE F MUST NOT BE DELETED UNDER ANY CIRCUMSTANCES
	float actions[torque_bins];
	for (int i = 0; i < (maxtorque*2)+1 ; ++i) {
		actions[i] = static_cast<float>(-maxtorque+i);
	}

	//create a priority queue to copy to all the state space priority queues
	PriorityQueue<float, double> initiator_queue(MAX);
	for (int i = 0; i < torque_bins; ++i) {
		initiator_queue.enqueueWithPriority(actions[i], 0);
	}

	//create the state space
	StateSpace space(initiator_queue, angle_bins, velocity_bins, torque_bins, maxangle, maxvelocity, maxtorque);

	//state objects
	State current_state(0, 0, 0);
	State old_state(0, 0, 0);

	std::ofstream file("output.txt");
	file.precision(16);

	file << "Trialno" << "	" << "Time" << "		" << "Theta" << "	" << "Thetadot" << "		" << "Torque" << std::endl;

	double trialno = 1;
	unsigned long i=0UL;
	while (true)
	{
		current_state.theta = env->getTheta();
		current_state.theta_dot = env->getThetadot();
		current_state.torque = env->getTorque();
		std::cout << "State Read" << std::endl;

		updateQ(space, chosen_action, old_state, current_state, alpha, gamma);
		std::cout << "Q Updated" << std::endl;

		if (current_state.theta>2 * 3.1415 && current_state.theta_dot>2 * 3.1415 && env->getTime() >= 10) {
			env->resetPendulum();
			std::domain_error("unsuccessful trial");
			trialno++;
			i = 0;
		}

		old_state = current_state;

		chosen_action = selectAction(space[current_state],i);
		std::cout << "Action Selected" << std::endl;
		env->setTorque(chosen_action);

		env->propagate();
		std::cout << "Environment Propogated\n" << std::endl;

		file << trialno << "	  " << env->getTime() << "	  " << current_state.theta << "	  " << current_state.theta_dot << "	   " << current_state.torque << std::endl;
		++i;
	}

	file.close();
	delete env;
	return 1;
}

double temperature(unsigned long t) {
	return 100000.0*std::exp((-8.0*t*t) / (26000.0*26000.0)) + 0.1;//0.1 is an offset
	//	^
	//	|
	//make this large
}

int selectAction(PriorityQueue<int, double>& a_queue, unsigned long iterations) {

	typedef std::vector<std::pair<int, double> > VecPair ;

	//turn priority queue into a vector of pairs
	VecPair vec = a_queue.saveOrderedQueueAsVector();

    //sum for partition function
	double sum = 0.0;

	// calculate partition function by iterating over action-values
	for (VecPair::iterator iter = vec.begin(), end = vec.end(); iter < end; ++iter) {
		sum += std::exp((iter->second) / temperature(iterations));
	}

	// compute Boltzmann factors for action-values and enqueue to vec
	for (VecPair::iterator iter = vec.begin(); iter < vec.end(); ++iter) {
		iter->second = std::exp(iter->second / temperature(iterations)) / sum;
	}

	// calculate cumulative probability distribution
	for (VecPair::iterator iter = vec.begin()++, end = vec.end(); iter < end; ++iter) {
        //second member of pair becomes addition of its current value
        //and that of the index before it
		iter->second += (iter-1)->second;
	}

	//generate RN between 0 and 1
	double rand_num = static_cast<double>(rand()) / RAND_MAX;

	// choose action based on random number relation to priorities within action queue
	for (VecPair::iterator iter = vec.begin(), end = vec.end(); iter < end; ++iter) {
		if (rand_num < iter->second)
			return iter->first;
	}

	return -1; //note that this line should never be reached
}

void updateQ(StateSpace & space, float action, State & new_state, State & old_state, double alpha, double gamma)
{
	//std::cout << action << std::endl;
	//std::cout << space[old_state].toString() << std::endl << "-----------";

	//oldQ value reference
	double oldQ = space[old_state].search(action).second;

	//reward given to current state
	double R = new_state.getReward();
	std::cout << "Reward: " << R << std::endl;
	//optimal Q value for new state i.e. first element
	double maxQ = space[new_state].peekFront().second;

	//new Q value determined by Q learning algorithm
	double newQ = oldQ + alpha * (R + (gamma * maxQ) - oldQ);
	//std::cout << "New Q-Value: " << newQ << std::endl;
	space[old_state].changePriority(action, newQ);
}

<commit_msg>Update main.cpp<commit_after>#include <cmath>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include "StateSpace3.h"
#include "PriorityQueue.h"
#include "State3.h"
#include "environment.h"

template<typename T> std::string to_string(T x) {
	return static_cast<std::ostringstream&>((std::ostringstream() << std::dec << x)).str();
}

//function to calculate a temperature for the select action function as a function of time
double temperature(unsigned long t);

//function to select next action
float selectAction(PriorityQueue<float, double>& a_queue, unsigned long int iterations);

//function to update a q value
void updateQ(StateSpace & space, float  action, State & new_state, State & old_state, double alpha, double gamma);

int main()
{
	//learning factor
	const double alpha = 0.5;
	//discount factor
	const double gamma = 0.5;
	const double deltatime = 0.1;
	const double mass = 0.5;
	const double length = 0.08;

	const int angle_bins = 100;
	const int velocity_bins = 50;
	const int torque_bins = 9;
	const double maxangle = 4;
	const double maxvelocity = 4;
	const double maxtorque = 4;

	/*for (int i = 0; i < torque_bins; ++i) {
		const int t_i = -maxtorque + i;
	}*/

	environment* env = new environment(0, 0, 0, maxtorque, 0, deltatime, mass, length, gamma);

	//seed rng
	std::srand(static_cast<unsigned int>(std::time(NULL)));

	//create pointers to the possible actions as well as a pointer to hold the chosen action
	float chosen_action = 1.0f;	// THE F MUST NOT BE DELETED UNDER ANY CIRCUMSTANCES
	float actions[torque_bins];
	for (int i = 0; i < (maxtorque*2)+1 ; ++i) {
		actions[i] = static_cast<float>(-maxtorque+i);
	}

	//create a priority queue to copy to all the state space priority queues
	PriorityQueue<float, double> initiator_queue(MAX);
	for (int i = 0; i < torque_bins; ++i) {
		initiator_queue.enqueueWithPriority(actions[i], 0);
	}

	//create the state space
	StateSpace space(initiator_queue, angle_bins, velocity_bins, torque_bins, maxangle, maxvelocity, maxtorque);

	//state objects
	State current_state(0, 0, 0);
	State old_state(0, 0, 0);

	std::ofstream file("output.txt");
	file.precision(16);

	file << "Trialno" << "	" << "Time" << "		" << "Theta" << "	" << "Thetadot" << "		" << "Torque" << std::endl;

	double trialno = 1;
	unsigned long i=0UL;
	while (true)
	{
		current_state.theta = env->getTheta();
		current_state.theta_dot = env->getThetadot();
		current_state.torque = env->getTorque();
		std::cout << "State Read" << std::endl;

		updateQ(space, chosen_action, old_state, current_state, alpha, gamma);
		std::cout << "Q Updated" << std::endl;

		if (current_state.theta>2 * 3.1415 && current_state.theta_dot>2 * 3.1415 && env->getTime() >= 10) {
			env->resetPendulum();
			std::domain_error("unsuccessful trial");
			trialno++;
			i = 0;
		}

		old_state = current_state;

		chosen_action = selectAction(space[current_state],i);
		std::cout << "Action Selected" << std::endl;
		env->setTorque(chosen_action);

		env->propagate();
		std::cout << "Environment Propogated\n" << std::endl;

		file << trialno << "	  " << env->getTime() << "	  " << current_state.theta << "	  " << current_state.theta_dot << "	   " << current_state.torque << std::endl;
		++i;
	}

	file.close();
	delete env;
	return 1;
}

double temperature(unsigned long t) {
	return 100.0*std::exp((-8.0*t*t) / (2600.0*2600.0)) + 0.1;//0.1 is an offset
}

int selectAction(PriorityQueue<int, double>& a_queue, unsigned long iterations) {

	typedef std::vector<std::pair<int, double> > VecPair ;

	//turn priority queue into a vector of pairs
	VecPair vec = a_queue.saveOrderedQueueAsVector();

    //sum for partition function
	double sum = 0.0;

	// calculate partition function by iterating over action-values
	for (VecPair::iterator iter = vec.begin(), end = vec.end(); iter < end; ++iter) {
		sum += std::exp((iter->second) / temperature(iterations));
	}

	// compute Boltzmann factors for action-values and enqueue to vec
	for (VecPair::iterator iter = vec.begin(); iter < vec.end(); ++iter) {
		iter->second = std::exp(iter->second / temperature(iterations)) / sum;
	}

	// calculate cumulative probability distribution
	for (VecPair::iterator iter = vec.begin()++, end = vec.end(); iter < end; ++iter) {
        //second member of pair becomes addition of its current value
        //and that of the index before it
		iter->second += (iter-1)->second;
	}

	//generate RN between 0 and 1
	double rand_num = static_cast<double>(rand()) / RAND_MAX;

	// choose action based on random number relation to priorities within action queue
	for (VecPair::iterator iter = vec.begin(), end = vec.end(); iter < end; ++iter) {
		if (rand_num < iter->second)
			return iter->first;
	}

	return -1; //note that this line should never be reached
}

void updateQ(StateSpace & space, float action, State & new_state, State & old_state, double alpha, double gamma)
{
	//std::cout << action << std::endl;
	//std::cout << space[old_state].toString() << std::endl << "-----------";

	//oldQ value reference
	double oldQ = space[old_state].search(action).second;

	//reward given to current state
	double R = new_state.getReward();
	std::cout << "Reward: " << R << std::endl;
	//optimal Q value for new state i.e. first element
	double maxQ = space[new_state].peekFront().second;

	//new Q value determined by Q learning algorithm
	double newQ = oldQ + alpha * (R + (gamma * maxQ) - oldQ);
	//std::cout << "New Q-Value: " << newQ << std::endl;
	space[old_state].changePriority(action, newQ);
}

<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <string>

int main()
{
	std::std::vector<std::string> words;
	std::string sentence;
	boost::split(words, sentence, boost::is_any_of(", "), boost::token_compress_on);
}
<commit_msg>Delete tokenizer2.cpp<commit_after><|endoftext|>


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

/*

	what if scenarios:
		1) singal enabled to e.g button and button object is deleted, does get_signal work anymore due to tasserver cannot retrieve button object?

*/

#include <QtPlugin>
#include <QDebug>
#include <QMetaObject>
#include <QMetaMethod>
#include <QHash>
#include <QApplication>
#include <QGraphicsItem>
#include <QGraphicsWidget>
#include <tasqtdatamodel.h>
#include <taslogger.h>
#include <tasconstants.h>
#include <tascoreutils.h>
#include <testabilityutils.h>

#include "tassignalplugin.h"

static QString CONTAINER_ID = "1";

static QString CHILD_SIGNAL = "child_signal";
static QString CHILD_CLASS  = "child_class";
static QString TRAVERSE_SENDER = "traverse_sender";

/*!
  \class TasFixturePlugin
  \brief TasDuiTraverse traverse DUI components for adding custom details to them

  Using standard qt objects it is not always possible to get specific details from the
  components. This TasHelperInterface implementation will allow us to add details from
  the wanted dui components that are not accesible through the property or other
  generic way.
*/

/*!
  Constructor
*/
    TasSignalPlugin::TasSignalPlugin(QObject* parent)
        :QObject(parent)
{
    mOccuredSignals = new TasDataModel();
}

/*!
  Destructor
*/
TasSignalPlugin::~TasSignalPlugin()
{
    QString s;
    clearSignals(s);
    delete mOccuredSignals;
}

/*!
  Execute the given action. Possible actions are: list_signals, get_signal, enable_signal and remove_signals.
*/
bool TasSignalPlugin::execute(void * objectInstance, QString actionName, QHash<QString, QString> parameters, QString & stdOut)
{
    TasLogger::logger()->debug("TasSignalPlugin::execute action: " + actionName );
    bool result = true;
    // set the stdOut if you wish to pass information back to Testability Driver
    if (actionName == "list_signals") {
    	result = listSignals( objectInstance, parameters.value(OBJECT_TYPE), stdOut);
    }
    else if (actionName == "get_signal") {
        result = printSignals(stdOut);
    }
    else if (actionName == "enable_signal") {
        result = enableSignal(objectInstance, parameters, stdOut);
    }
    else if (actionName == "remove_signals") {
        result = clearSignals(stdOut);
    }
    else {
        printErrorMsg(parameters, stdOut);
        result =  false;
    }
    return result;
}

/*!
  Print error message.
 */
void TasSignalPlugin::printErrorMsg(QHash<QString, QString> parameters, QString& stdOut)
{
    QHash<QString, QString>::const_iterator i = parameters.constBegin();
    stdOut.append("(");
    while (i != parameters.constEnd()) {
        stdOut.append(i.key());
        stdOut.append("=>");
        stdOut.append(i.value());
        stdOut.append(")");
        ++i;
        }
    stdOut.append("}");
}

/*!
  Serialize the model used by TasSignalSpies to report
  occured signals.
*/

bool TasSignalPlugin::printSignals(QString& stdOut)
{
    QByteArray xml;
    mOccuredSignals->serializeModel(xml);
    stdOut.append(QString::fromUtf8(xml.data()));
    return true;
}

/*!
  Clear signal model.
 */
bool TasSignalPlugin::clearSignals(QString& stdOut)
{
    QHash<QString, TasSignalSpy*>::const_iterator i = spyContainerHash.constBegin();
    while (i != spyContainerHash.constEnd()) {
        TasSignalSpy *tasSpy = i.value();
        delete tasSpy;
        ++i;
    }
    spyContainerHash.clear();
    mOccuredSignals->clearModel();
    stdOut = "Signals removed OK";
    return true;
}

/*!
  List all signals from the target object.
 */
bool TasSignalPlugin::listSignals(void* objectInstance, QString ptrType, QString & stdOut)
{
    QObject *target = castToObject(objectInstance, ptrType);
    bool result = false;
    if(target){
        TasDataModel* model = new TasDataModel();
        TasObjectContainer& container = model->addNewObjectContainer(CONTAINER_ID.toInt(), "QtSignals", "QtSignals");

        for(int i = 0; i < target->metaObject()->methodCount(); ++i) {
            if (target->metaObject()->method(i).methodType() == QMetaMethod::Signal)
                container.addNewObject(QString::number(i), QString::fromLatin1(target->metaObject()->method(i).methodSignature()), "QtSignal");
        }
        QByteArray xml;
        model->serializeModel(xml);
        stdOut.append(QString::fromUtf8(xml.data()));
        delete model;
        result =  true;
    }
    else{
        stdOut = "No target object could be found.";
    }
    return result;
}

/*!
  Start listening to the given signal and report occurences to the model.
 */
bool TasSignalPlugin::enableSignal(void *objectInstance, QHash<QString, QString> parameters, QString & stdOut)
{
    bool result = false;
    if(parameters.contains(SIGNAL_KEY)){
        QString signalName = parameters.value(SIGNAL_KEY);
        QObject* target = castToObject(objectInstance, parameters.value(OBJECT_TYPE));
        //the object which we really want the changes related to the emitted signal
        QObject* owner = target;
        if(target && parameters[CHILD_SIGNAL] == "true"){
            owner = target;
            QObject* obj = target->findChild<QObject*>(parameters[CHILD_CLASS]);
            target = obj;
        }
        if(target){
            int signalId = target->metaObject()->indexOfMethod(signalName.toLatin1().data());
            if(signalId != -1){
                QByteArray signature = target->metaObject()->method(signalId).methodSignature();
                QString hashIdentificator = TasCoreUtils::objectId(target);
                TasObjectContainer* container = mOccuredSignals->findObjectContainer(CONTAINER_ID);
                if(!container){
                    container = &(mOccuredSignals->addNewObjectContainer(CONTAINER_ID.toInt(), "QtSignals", "QtSignals"));
                    if(parameters.contains(PROCESS_START_TIME)){
                        QString timeStamp = parameters.value(PROCESS_START_TIME);
                        TasObject& eventObj = container->addNewObject(TasCoreUtils::pointerId(&timeStamp), PROCESS_START_TIME, "event");
                        eventObj.addAttribute("timeStamp", parameters.value(PROCESS_START_TIME));
                    }
                }
                bool traverseSender = false;
                if(parameters[TRAVERSE_SENDER] == "true"){
                    traverseSender = true;
                }
                TasSignalSpy *tasSpy = new TasSignalSpy(target, (QString::number(QSIGNAL_CODE)+signature).toLatin1().data(),
                                                        *container, traverseSender);
                tasSpy->setTarget(owner);
                spyContainerHash.insert(QString(hashIdentificator + signature), tasSpy);
                stdOut = "Enable signal called";
                result = true;
            }
            else{
                stdOut = "Signal " + signalName + " not found on object " + QString(target->metaObject()->className());
            }
        }
        else{
            stdOut = "No target object could be found!";
        }
    }
    else{
        stdOut = "No signal defined in parameters";
    }
    return result;
}

QObject* TasSignalPlugin::castToObject(void* objectInstance, QString ptrType)
{
    QObject* target = 0;
    if( ptrType == WIDGET_TYPE ){
        target = reinterpret_cast<QWidget*>(objectInstance);
    }
    else if( ptrType == GRAPHICS_ITEM_TYPE ){
        QGraphicsItem* item = reinterpret_cast<QGraphicsItem*>(objectInstance);
        target = item->toGraphicsObject();
    }
    else if( ptrType == APPLICATION_TYPE ){
        target = qApp;
    }
    return target;
}
<commit_msg>Cosmethic<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (testabilitydriver@nokia.com)
**
** This file is part of Testability Driver Qt Agent
**
** If you have questions regarding the use of this file, please contact
** Nokia at testabilitydriver@nokia.com .
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

/*

	what if scenarios:
		1) singal enabled to e.g button and button object is deleted, does get_signal work anymore due to tasserver cannot retrieve button object?

*/

#include <QtPlugin>
#include <QDebug>
#include <QMetaObject>
#include <QMetaMethod>
#include <QHash>
#include <QApplication>
#include <QGraphicsItem>
#include <QGraphicsWidget>
#include <tasqtdatamodel.h>
#include <taslogger.h>
#include <tasconstants.h>
#include <tascoreutils.h>
#include <testabilityutils.h>

#include "tassignalplugin.h"

static QString CONTAINER_ID = "1";

static QString CHILD_SIGNAL = "child_signal";
static QString CHILD_CLASS  = "child_class";
static QString TRAVERSE_SENDER = "traverse_sender";

/*!
  \class TasFixturePlugin
  \brief TasDuiTraverse traverse DUI components for adding custom details to them

  Using standard qt objects it is not always possible to get specific details from the
  components. This TasHelperInterface implementation will allow us to add details from
  the wanted dui components that are not accesible through the property or other
  generic way.
*/

/*!
  Constructor
*/
    TasSignalPlugin::TasSignalPlugin(QObject* parent)
        :QObject(parent)
{
    mOccuredSignals = new TasDataModel();
}

/*!
  Destructor
*/
TasSignalPlugin::~TasSignalPlugin()
{
    QString s;
    clearSignals(s);
    delete mOccuredSignals;
}

/*!
  Execute the given action. Possible actions are: list_signals, get_signal, enable_signal and remove_signals.
*/
bool TasSignalPlugin::execute(void * objectInstance, QString actionName, QHash<QString, QString> parameters, QString & stdOut)
{
    TasLogger::logger()->debug("TasSignalPlugin::execute action: " + actionName );
    bool result = true;
    // set the stdOut if you wish to pass information back to Testability Driver
    if (actionName == "list_signals") {
    	result = listSignals( objectInstance, parameters.value(OBJECT_TYPE), stdOut);
    }
    else if (actionName == "get_signal") {
        result = printSignals(stdOut);
    }
    else if (actionName == "enable_signal") {
        result = enableSignal(objectInstance, parameters, stdOut);
    }
    else if (actionName == "remove_signals") {
        result = clearSignals(stdOut);
    }
    else {
        printErrorMsg(parameters, stdOut);
        result =  false;
    }
    return result;
}

/*!
  Print error message.
 */
void TasSignalPlugin::printErrorMsg(QHash<QString, QString> parameters, QString& stdOut)
{
    QHash<QString, QString>::const_iterator i = parameters.constBegin();
    stdOut.append("(");
    while (i != parameters.constEnd()) {
        stdOut.append(i.key());
        stdOut.append("=>");
        stdOut.append(i.value());
        stdOut.append(")");
        ++i;
        }
    stdOut.append("}");
}

/*!
  Serialize the model used by TasSignalSpies to report
  occured signals.
*/

bool TasSignalPlugin::printSignals(QString& stdOut)
{
    QByteArray xml;
    mOccuredSignals->serializeModel(xml);
    stdOut.append(QString::fromUtf8(xml.data()));
    return true;
}

/*!
  Clear signal model.
 */
bool TasSignalPlugin::clearSignals(QString& stdOut)
{
    QHash<QString, TasSignalSpy*>::const_iterator i = spyContainerHash.constBegin();
    while (i != spyContainerHash.constEnd()) {
        TasSignalSpy *tasSpy = i.value();
        delete tasSpy;
        ++i;
    }
    spyContainerHash.clear();
    mOccuredSignals->clearModel();
    stdOut = "Signals removed OK";
    return true;
}

/*!
  List all signals from the target object.
 */
bool TasSignalPlugin::listSignals(void* objectInstance, QString ptrType, QString & stdOut)
{
    QObject *target = castToObject(objectInstance, ptrType);
    bool result = false;
    if(target){
        TasDataModel* model = new TasDataModel();
        TasObjectContainer& container = model->addNewObjectContainer(CONTAINER_ID.toInt(), "QtSignals", "QtSignals");

        for(int i = 0; i < target->metaObject()->methodCount(); ++i) {
            if (target->metaObject()->method(i).methodType() == QMetaMethod::Signal)
                container.addNewObject(QString::number(i), QString::fromLatin1(target->metaObject()->method(i).methodSignature()), "QtSignal");
        }
        QByteArray xml;
        model->serializeModel(xml);
        stdOut.append(QString::fromUtf8(xml.data()));
        delete model;
        result =  true;
    }
    else{
        stdOut = "No target object could be found.";
    }
    return result;
}

/*!
  Start listening to the given signal and report occurences to the model.
 */
bool TasSignalPlugin::enableSignal(void *objectInstance, QHash<QString, QString> parameters, QString & stdOut)
{
    bool result = false;
    if(parameters.contains(SIGNAL_KEY)){
        QString signalName = parameters.value(SIGNAL_KEY);
        QObject* target = castToObject(objectInstance, parameters.value(OBJECT_TYPE));
        //the object which we really want the changes related to the emitted signal
        QObject* owner = target;
        if(target && parameters[CHILD_SIGNAL] == "true"){
            owner = target;
            QObject* obj = target->findChild<QObject*>(parameters[CHILD_CLASS]);
            target = obj;
        }
        if(target){
            int signalId = target->metaObject()->indexOfMethod(signalName.toLatin1().data());
            if(signalId != -1){
                QByteArray signature = target->metaObject()->method(signalId).methodSignature();
                QString hashIdentificator = TasCoreUtils::objectId(target);
                TasObjectContainer* container = mOccuredSignals->findObjectContainer(CONTAINER_ID);
                if(!container){
                    container = &(mOccuredSignals->addNewObjectContainer(CONTAINER_ID.toInt(), "QtSignals", "QtSignals"));
                    if(parameters.contains(PROCESS_START_TIME)){
                        QString timeStamp = parameters.value(PROCESS_START_TIME);
                        TasObject& eventObj = container->addNewObject(TasCoreUtils::pointerId(&timeStamp), PROCESS_START_TIME, "event");
                        eventObj.addAttribute("timeStamp", parameters.value(PROCESS_START_TIME));
                    }
                }
                bool traverseSender = false;
                if(parameters[TRAVERSE_SENDER] == "true"){
                    traverseSender = true;
                }
                TasSignalSpy *tasSpy = new TasSignalSpy(target, (QString::number(QSIGNAL_CODE)+signature).toLatin1().data(),
                                                        *container, traverseSender);
                tasSpy->setTarget(owner);
                spyContainerHash.insert(QString(hashIdentificator + signature), tasSpy);
                stdOut = "Enable signal called";
                result = true;
            }
            else{
                stdOut = "Signal " + signalName + " not found on object " + QString(target->metaObject()->className());
            }
        }
        else{
            stdOut = "No target object could be found!";
        }
    }
    else{
        stdOut = "No signal defined in parameters";
    }
    return result;
}

QObject* TasSignalPlugin::castToObject(void* objectInstance, QString ptrType)
{
    QObject* target = 0;
    if( ptrType == WIDGET_TYPE ){
        target = reinterpret_cast<QWidget*>(objectInstance);
    }
    else if( ptrType == GRAPHICS_ITEM_TYPE ){
        QGraphicsItem* item = reinterpret_cast<QGraphicsItem*>(objectInstance);
        target = item->toGraphicsObject();
    }
    else if( ptrType == APPLICATION_TYPE ){
        target = qApp;
    }
    return target;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: computedexpression.cxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_forms.hxx"

#include "computedexpression.hxx"
#include "unohelper.hxx"
#include "evaluationcontext.hxx"
#include "NameContainer.hxx"

#include <com/sun/star/container/XNameContainer.hpp>
#include <com/sun/star/uno/Sequence.hxx>
#include <com/sun/star/xml/dom/NodeType.hpp>
#include <com/sun/star/xml/dom/XNode.hpp>
#include <com/sun/star/xml/xpath/XXPathAPI.hpp>
#include <com/sun/star/xml/xpath/XXPathObject.hpp>
#include <com/sun/star/xml/xpath/XXPathExtension.hpp>
#include <com/sun/star/beans/NamedValue.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/util/SearchAlgorithms.hpp>

#include <unotools/textsearch.hxx>
#include <comphelper/processfactory.hxx>

using rtl::OUString;
using com::sun::star::beans::NamedValue;
using com::sun::star::uno::Any;
using com::sun::star::uno::Reference;
using com::sun::star::uno::Sequence;
using com::sun::star::lang::XInitialization;
using com::sun::star::lang::XMultiServiceFactory;
using com::sun::star::xml::dom::XNode;
using com::sun::star::container::XNameContainer;
using com::sun::star::xml::xpath::XXPathAPI;
using com::sun::star::xml::xpath::XXPathExtension;
using com::sun::star::xml::xpath::XXPathObject;
using com::sun::star::uno::RuntimeException;
using com::sun::star::uno::UNO_QUERY_THROW;
using com::sun::star::xml::xpath::XPathObjectType_XPATH_UNDEFINED;
using com::sun::star::util::SearchOptions;
using com::sun::star::util::SearchAlgorithms_REGEXP;

namespace xforms
{

ComputedExpression::ComputedExpression()
    : msExpression(),
      mbIsEmpty( true ),
      mbIsSimple( true ),
      mxResult()
{
}

ComputedExpression::~ComputedExpression()
{
}

OUString ComputedExpression::getExpression() const
{
    return msExpression;
}

void ComputedExpression::setExpression( const OUString& rExpression )
{
    // set new expression, and clear pre-computed results
    msExpression = rExpression;
    mbIsEmpty = _checkExpression( " *" );
    mbIsSimple = false;
    mxResult.clear();
}

bool ComputedExpression::_checkExpression( const sal_Char* pExpression ) const
{
    OSL_ENSURE( pExpression != NULL, "no expression?" );

    // call RegExp engine
    SearchOptions aSearchOptions;
    aSearchOptions.algorithmType = SearchAlgorithms_REGEXP;
    aSearchOptions.searchString = String( pExpression, RTL_TEXTENCODING_ASCII_US );
    utl::TextSearch aTextSearch( aSearchOptions );

    xub_StrLen nLength =
        static_cast<xub_StrLen>( msExpression.getLength() );
    xub_StrLen nStart = 0;
    xub_StrLen nEnd = nLength;
    int nSearch = aTextSearch.SearchFrwrd( msExpression, &nStart, &nEnd );

    // our expression is static only if 1) we found our regexp, and 2)
    // the regexp goes from beginning to end.
    return ( nLength == 0  ||  nSearch != 0 )
        && ( nStart == 0  &&  nEnd == nLength );
}

/// do we have an actual expression?
bool ComputedExpression::isEmptyExpression() const
{
    return mbIsEmpty;
}

bool ComputedExpression::isSimpleExpression() const
{
    // actual work is done by setExpression
    return mbIsEmpty || mbIsSimple;
}

const OUString ComputedExpression::_getExpressionForEvaluation() const
{
    // the default implementation is to do nothing...
    return msExpression;
}

bool ComputedExpression::_evaluate(
    const xforms::EvaluationContext& rContext,
    const OUString& sExpression )
{
    OSL_ENSURE( rContext.mxContextNode.is(), "no context node in context" );

    // obtain value by evaluating XPath expression
    mxResult.clear();
    try
    {
        mxResult = _getXPathAPI(rContext)->eval( rContext.mxContextNode,
                                                 sExpression );
    }
    catch( const RuntimeException& )
    {
        ; // ignore exception -> mxResult will be empty
    }

    return hasValue();
}

bool ComputedExpression::evaluate( const EvaluationContext& rContext )
{
    // for simple expression we don't need to re-evaluate (if we have
    // an older result); neither for empty expressions
    if( mbIsEmpty  ||  mxResult.is() && mbIsSimple )
        return true;

    return _evaluate( rContext, _getExpressionForEvaluation() );
}

bool ComputedExpression::hasValue() const
{
    return mxResult.is() &&
           mxResult->getObjectType() != XPathObjectType_XPATH_UNDEFINED;
}

void ComputedExpression::clear()
{
    mxResult.clear();
}

Reference<XXPathObject> ComputedExpression::getXPath()
{
    return mxResult;
}

OUString ComputedExpression::getString( const rtl::OUString& rDefault ) const
{
    return mxResult.is() ? mxResult->getString() : rDefault;
}

bool ComputedExpression::getBool( bool bDefault ) const
{
    return mxResult.is() ? mxResult->getBoolean() : bDefault;
}

Reference<XXPathAPI> ComputedExpression::_getXPathAPI(const xforms::EvaluationContext& aContext)
{
    // create XPath API, then register namespaces
    Reference<XXPathAPI> xXPath( createInstance(
                            OUSTRING( "com.sun.star.xml.xpath.XPathAPI" ) ),
                                 UNO_QUERY_THROW );
    OSL_ENSURE( xXPath.is(), "cannot get XPath API" );

    // register xforms extension#
    Sequence< Any > aSequence(2);
    NamedValue aValue;
    aValue.Name = OUSTRING("Model");
    aValue.Value <<= aContext.mxModel;
    aSequence[0] <<= aValue;
    aValue.Name = OUSTRING("ContextNode");
    aValue.Value <<= aContext.mxContextNode;
    aSequence[1] <<= aValue;
    Reference<XMultiServiceFactory> aFactory = comphelper::getProcessServiceFactory();
    Reference< XXPathExtension > aExtension( aFactory->createInstanceWithArguments(
        OUSTRING( "com.sun.star.comp.xml.xpath.XFormsExtension"), aSequence), UNO_QUERY_THROW);
    xXPath->registerExtensionInstance(aExtension);

    // register namespaces
    if( aContext.mxNamespaces.is() )
    {
        Sequence<OUString> aPrefixes =aContext.mxNamespaces->getElementNames();
        sal_Int32 nCount = aPrefixes.getLength();
        const OUString* pPrefixes = aPrefixes.getConstArray();
        for( sal_Int32 i = 0; i < nCount; i++ )
        {
            const OUString* pNamePrefix = &pPrefixes[i];
            OUString sNameURL;
            aContext.mxNamespaces->getByName( *pNamePrefix ) >>= sNameURL;
            xXPath->registerNS( *pNamePrefix, sNameURL );
        }
    }

    // done, so return xXPath-object
    return xXPath;
}

} // namespace xforms
<commit_msg>INTEGRATION: CWS xmlfix2 (1.6.132); FILE MERGED 2008/05/15 17:04:29 mst 1.6.132.2: RESYNC: (1.6-1.7); FILE MERGED 2008/03/31 14:24:28 mst 1.6.132.1: #i81678#: interface change: XXPathAPI - forms/source/xforms/{computedexpression.cxx,pathexpression.cxx,binding.cxx}:   + adapt to changes in css.xml.xpath.XXPathAPI<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: computedexpression.cxx,v $
 * $Revision: 1.8 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_forms.hxx"

#include "computedexpression.hxx"
#include "unohelper.hxx"
#include "evaluationcontext.hxx"
#include "NameContainer.hxx"

#include <com/sun/star/container/XNameContainer.hpp>
#include <com/sun/star/uno/Sequence.hxx>
#include <com/sun/star/xml/dom/NodeType.hpp>
#include <com/sun/star/xml/dom/XNode.hpp>
#include <com/sun/star/xml/xpath/XXPathAPI.hpp>
#include <com/sun/star/xml/xpath/XXPathObject.hpp>
#include <com/sun/star/xml/xpath/XXPathExtension.hpp>
#include <com/sun/star/beans/NamedValue.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/util/SearchAlgorithms.hpp>

#include <unotools/textsearch.hxx>
#include <comphelper/processfactory.hxx>

using rtl::OUString;
using com::sun::star::beans::NamedValue;
using com::sun::star::uno::Any;
using com::sun::star::uno::Reference;
using com::sun::star::uno::Sequence;
using com::sun::star::lang::XInitialization;
using com::sun::star::lang::XMultiServiceFactory;
using com::sun::star::xml::dom::XNode;
using com::sun::star::container::XNameContainer;
using com::sun::star::xml::xpath::XXPathAPI;
using com::sun::star::xml::xpath::XXPathExtension;
using com::sun::star::xml::xpath::XXPathObject;
using com::sun::star::uno::RuntimeException;
using com::sun::star::uno::Exception;
using com::sun::star::uno::UNO_QUERY_THROW;
using com::sun::star::xml::xpath::XPathObjectType_XPATH_UNDEFINED;
using com::sun::star::util::SearchOptions;
using com::sun::star::util::SearchAlgorithms_REGEXP;

namespace xforms
{

ComputedExpression::ComputedExpression()
    : msExpression(),
      mbIsEmpty( true ),
      mbIsSimple( true ),
      mxResult()
{
}

ComputedExpression::~ComputedExpression()
{
}

OUString ComputedExpression::getExpression() const
{
    return msExpression;
}

void ComputedExpression::setExpression( const OUString& rExpression )
{
    // set new expression, and clear pre-computed results
    msExpression = rExpression;
    mbIsEmpty = _checkExpression( " *" );
    mbIsSimple = false;
    mxResult.clear();
}

bool ComputedExpression::_checkExpression( const sal_Char* pExpression ) const
{
    OSL_ENSURE( pExpression != NULL, "no expression?" );

    // call RegExp engine
    SearchOptions aSearchOptions;
    aSearchOptions.algorithmType = SearchAlgorithms_REGEXP;
    aSearchOptions.searchString = String( pExpression, RTL_TEXTENCODING_ASCII_US );
    utl::TextSearch aTextSearch( aSearchOptions );

    xub_StrLen nLength =
        static_cast<xub_StrLen>( msExpression.getLength() );
    xub_StrLen nStart = 0;
    xub_StrLen nEnd = nLength;
    int nSearch = aTextSearch.SearchFrwrd( msExpression, &nStart, &nEnd );

    // our expression is static only if 1) we found our regexp, and 2)
    // the regexp goes from beginning to end.
    return ( nLength == 0  ||  nSearch != 0 )
        && ( nStart == 0  &&  nEnd == nLength );
}

/// do we have an actual expression?
bool ComputedExpression::isEmptyExpression() const
{
    return mbIsEmpty;
}

bool ComputedExpression::isSimpleExpression() const
{
    // actual work is done by setExpression
    return mbIsEmpty || mbIsSimple;
}

const OUString ComputedExpression::_getExpressionForEvaluation() const
{
    // the default implementation is to do nothing...
    return msExpression;
}

bool ComputedExpression::_evaluate(
    const xforms::EvaluationContext& rContext,
    const OUString& sExpression )
{
    OSL_ENSURE( rContext.mxContextNode.is(), "no context node in context" );

    // obtain value by evaluating XPath expression
    mxResult.clear();
    try
    {
        mxResult = _getXPathAPI(rContext)->eval( rContext.mxContextNode,
                                                 sExpression );
    }
    catch( const Exception& )
    {
        ; // ignore exception -> mxResult will be empty
    }

    return hasValue();
}

bool ComputedExpression::evaluate( const EvaluationContext& rContext )
{
    // for simple expression we don't need to re-evaluate (if we have
    // an older result); neither for empty expressions
    if( mbIsEmpty  ||  mxResult.is() && mbIsSimple )
        return true;

    return _evaluate( rContext, _getExpressionForEvaluation() );
}

bool ComputedExpression::hasValue() const
{
    return mxResult.is() &&
           mxResult->getObjectType() != XPathObjectType_XPATH_UNDEFINED;
}

void ComputedExpression::clear()
{
    mxResult.clear();
}

Reference<XXPathObject> ComputedExpression::getXPath()
{
    return mxResult;
}

OUString ComputedExpression::getString( const rtl::OUString& rDefault ) const
{
    return mxResult.is() ? mxResult->getString() : rDefault;
}

bool ComputedExpression::getBool( bool bDefault ) const
{
    return mxResult.is() ? mxResult->getBoolean() : bDefault;
}

Reference<XXPathAPI> ComputedExpression::_getXPathAPI(const xforms::EvaluationContext& aContext)
{
    // create XPath API, then register namespaces
    Reference<XXPathAPI> xXPath( createInstance(
                            OUSTRING( "com.sun.star.xml.xpath.XPathAPI" ) ),
                                 UNO_QUERY_THROW );
    OSL_ENSURE( xXPath.is(), "cannot get XPath API" );

    // register xforms extension#
    Sequence< Any > aSequence(2);
    NamedValue aValue;
    aValue.Name = OUSTRING("Model");
    aValue.Value <<= aContext.mxModel;
    aSequence[0] <<= aValue;
    aValue.Name = OUSTRING("ContextNode");
    aValue.Value <<= aContext.mxContextNode;
    aSequence[1] <<= aValue;
    Reference<XMultiServiceFactory> aFactory = comphelper::getProcessServiceFactory();
    Reference< XXPathExtension > aExtension( aFactory->createInstanceWithArguments(
        OUSTRING( "com.sun.star.comp.xml.xpath.XFormsExtension"), aSequence), UNO_QUERY_THROW);
    xXPath->registerExtensionInstance(aExtension);

    // register namespaces
    if( aContext.mxNamespaces.is() )
    {
        Sequence<OUString> aPrefixes =aContext.mxNamespaces->getElementNames();
        sal_Int32 nCount = aPrefixes.getLength();
        const OUString* pPrefixes = aPrefixes.getConstArray();
        for( sal_Int32 i = 0; i < nCount; i++ )
        {
            const OUString* pNamePrefix = &pPrefixes[i];
            OUString sNameURL;
            aContext.mxNamespaces->getByName( *pNamePrefix ) >>= sNameURL;
            xXPath->registerNS( *pNamePrefix, sNameURL );
        }
    }

    // done, so return xXPath-object
    return xXPath;
}

} // namespace xforms
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: replace.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-10-24 07:38:20 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include "submission.hxx"

#include <rtl/ustring.hxx>
#include <rtl/string.hxx>

#include <unotools/processfactory.hxx>
#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/xml/dom/XDocument.hpp>
#include <com/sun/star/xml/dom/XDocumentBuilder.hpp>
#include <com/sun/star/frame/XComponentLoader.hpp>
#include <com/sun/star/frame/FrameSearchFlag.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>

using namespace rtl;
using namespace com::sun::star::uno;
using namespace com::sun::star::frame;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::xml::dom;

CSubmission::SubmissionResult CSubmission::replace(const OUString& aReplace, const Reference<XDocument>& aDocument, const Reference<XFrame>& aFrame)
{
    if (!m_aResultStream.is())
        return CSubmission::UNKNOWN_ERROR;

    try {
        Reference< XMultiServiceFactory > xFactory = utl::getProcessServiceFactory();
        if (aReplace.equalsIgnoreAsciiCaseAscii("all") || aReplace.equalsIgnoreAsciiCaseAscii("document")) {
            Reference< XComponentLoader > xLoader;
            if (aFrame.is())
                xLoader = Reference< XComponentLoader >(aFrame, UNO_QUERY);

            if (!xLoader.is())
                xLoader = Reference< XComponentLoader >(xFactory->createInstance(
                    OUString::createFromAscii("com.sun.star.frame.Desktop")), UNO_QUERY_THROW);

            // open the stream from the result...
            // build media descriptor
            Sequence< PropertyValue > descriptor(2);
            descriptor[0] = PropertyValue(OUString::createFromAscii(
                "InputStream"), -1, makeAny(m_aResultStream), PropertyState_DIRECT_VALUE);
            descriptor[1] = PropertyValue(OUString::createFromAscii(
                "ReadOnly"), -1, makeAny(sal_True), PropertyState_DIRECT_VALUE);

            //OUString aURL = OUString::createFromAscii("private:stream");
            OUString aURL = m_aURLObj.GetMainURL(INetURLObject::NO_DECODE);
            OUString aTarget = OUString::createFromAscii("_default");
            xLoader->loadComponentFromURL(aURL, aTarget, FrameSearchFlag::ALL, descriptor);

            return CSubmission::SUCCESS;

        } else if (aReplace.equalsIgnoreAsciiCaseAscii("instance")) {
            if (aDocument.is()) {
                // parse the result stream into a new document
                Reference< XDocumentBuilder > xBuilder(xFactory->createInstance(
                    OUString::createFromAscii("com.sun.star.xml.dom.DocumentBuilder")), UNO_QUERY_THROW);
                Reference< XDocument > aNewDocument = xBuilder->parse(m_aResultStream);

                if (aNewDocument.is()) {
                    // and replace the content of the current instance
                    Reference< XElement > oldRoot = aDocument->getDocumentElement();
                    Reference< XElement > newRoot = aNewDocument->getDocumentElement();

                    // aDocument->removeChild(Reference< XNode >(oldRoot, UNO_QUERY_THROW));
                    Reference< XNode > aImportedNode = aDocument->importNode(Reference< XNode >(newRoot, UNO_QUERY_THROW), sal_True);
                    Reference< XNode >(aDocument, UNO_QUERY_THROW)->replaceChild(aImportedNode, Reference< XNode >(oldRoot, UNO_QUERY_THROW));
                    return CSubmission::SUCCESS;
                } else {
                    return CSubmission::UNKNOWN_ERROR;
                }
            } else {
                // nothing to replace
                return CSubmission::UNKNOWN_ERROR;
            }
        } else if (aReplace.equalsIgnoreAsciiCaseAscii("none")) {
            // do nothing \o/
            return CSubmission::SUCCESS;
        }
    } catch (Exception& e) {
        OString aMsg("Exception during replace:\n");
        aMsg += OUStringToOString(e.Message, RTL_TEXTENCODING_UTF8);
        OSL_ENSURE(sal_False, aMsg.getStr());
    }
    return CSubmission::UNKNOWN_ERROR;
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.4.98); FILE MERGED 2006/09/01 17:27:48 kaib 1.4.98.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: replace.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 00:06:48 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_forms.hxx"

#include "submission.hxx"

#include <rtl/ustring.hxx>
#include <rtl/string.hxx>

#include <unotools/processfactory.hxx>
#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/xml/dom/XDocument.hpp>
#include <com/sun/star/xml/dom/XDocumentBuilder.hpp>
#include <com/sun/star/frame/XComponentLoader.hpp>
#include <com/sun/star/frame/FrameSearchFlag.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>

using namespace rtl;
using namespace com::sun::star::uno;
using namespace com::sun::star::frame;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::xml::dom;

CSubmission::SubmissionResult CSubmission::replace(const OUString& aReplace, const Reference<XDocument>& aDocument, const Reference<XFrame>& aFrame)
{
    if (!m_aResultStream.is())
        return CSubmission::UNKNOWN_ERROR;

    try {
        Reference< XMultiServiceFactory > xFactory = utl::getProcessServiceFactory();
        if (aReplace.equalsIgnoreAsciiCaseAscii("all") || aReplace.equalsIgnoreAsciiCaseAscii("document")) {
            Reference< XComponentLoader > xLoader;
            if (aFrame.is())
                xLoader = Reference< XComponentLoader >(aFrame, UNO_QUERY);

            if (!xLoader.is())
                xLoader = Reference< XComponentLoader >(xFactory->createInstance(
                    OUString::createFromAscii("com.sun.star.frame.Desktop")), UNO_QUERY_THROW);

            // open the stream from the result...
            // build media descriptor
            Sequence< PropertyValue > descriptor(2);
            descriptor[0] = PropertyValue(OUString::createFromAscii(
                "InputStream"), -1, makeAny(m_aResultStream), PropertyState_DIRECT_VALUE);
            descriptor[1] = PropertyValue(OUString::createFromAscii(
                "ReadOnly"), -1, makeAny(sal_True), PropertyState_DIRECT_VALUE);

            //OUString aURL = OUString::createFromAscii("private:stream");
            OUString aURL = m_aURLObj.GetMainURL(INetURLObject::NO_DECODE);
            OUString aTarget = OUString::createFromAscii("_default");
            xLoader->loadComponentFromURL(aURL, aTarget, FrameSearchFlag::ALL, descriptor);

            return CSubmission::SUCCESS;

        } else if (aReplace.equalsIgnoreAsciiCaseAscii("instance")) {
            if (aDocument.is()) {
                // parse the result stream into a new document
                Reference< XDocumentBuilder > xBuilder(xFactory->createInstance(
                    OUString::createFromAscii("com.sun.star.xml.dom.DocumentBuilder")), UNO_QUERY_THROW);
                Reference< XDocument > aNewDocument = xBuilder->parse(m_aResultStream);

                if (aNewDocument.is()) {
                    // and replace the content of the current instance
                    Reference< XElement > oldRoot = aDocument->getDocumentElement();
                    Reference< XElement > newRoot = aNewDocument->getDocumentElement();

                    // aDocument->removeChild(Reference< XNode >(oldRoot, UNO_QUERY_THROW));
                    Reference< XNode > aImportedNode = aDocument->importNode(Reference< XNode >(newRoot, UNO_QUERY_THROW), sal_True);
                    Reference< XNode >(aDocument, UNO_QUERY_THROW)->replaceChild(aImportedNode, Reference< XNode >(oldRoot, UNO_QUERY_THROW));
                    return CSubmission::SUCCESS;
                } else {
                    return CSubmission::UNKNOWN_ERROR;
                }
            } else {
                // nothing to replace
                return CSubmission::UNKNOWN_ERROR;
            }
        } else if (aReplace.equalsIgnoreAsciiCaseAscii("none")) {
            // do nothing \o/
            return CSubmission::SUCCESS;
        }
    } catch (Exception& e) {
        OString aMsg("Exception during replace:\n");
        aMsg += OUStringToOString(e.Message, RTL_TEXTENCODING_UTF8);
        OSL_ENSURE(sal_False, aMsg.getStr());
    }
    return CSubmission::UNKNOWN_ERROR;
}
<|endoftext|>


<commit_before>// File_Mpeg4_TimeCode - Info for MPEG-4 TimeCode  files
// Copyright (C) 2009-2011 MediaArea.net SARL, Info@MediaArea.net
//
// This library is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library. If not, see <http://www.gnu.org/licenses/>.
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//---------------------------------------------------------------------------
// Compilation conditions
#include "MediaInfo/Setup.h"
#ifdef __BORLANDC__
    #pragma hdrstop
#endif
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#if defined(MEDIAINFO_MPEG4_YES)
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Multiple/File_Mpeg4_TimeCode.h"
//---------------------------------------------------------------------------

namespace MediaInfoLib
{

//***************************************************************************
// Format
//***************************************************************************

//---------------------------------------------------------------------------
void File_Mpeg4_TimeCode::FileHeader_Parse()
{
    if (Element_Offset>=Element_Size)
        return;

    //Parsing
    int32u Position;
    while (Element_Offset<Element_Size)
        Get_B4 (Position,                                       "Position");

    //Filling
    Accept("TimeCode");

    if (FrameRate)
    {
        int64s Pos=Position;
        if (NegativeTimes)
            Pos=(int32s)Position;
        if (StreamKind==Stream_General)
        {
            //No link with a track, we do all
            Stream_Prepare(Stream_Video);
            Fill(Stream_Video, 0, Video_Delay, Pos*1000/FrameRate, 0);
            Fill(Stream_Video, 0, Video_Delay_Source, "Container");

            Stream_Prepare(Stream_Audio);
            Fill(Stream_Audio, 0, Audio_Delay, Pos*1000/FrameRate, 0);
            Fill(Stream_Video, 0, Video_Delay_Source, "Container");
        }
        else
        {
            Stream_Prepare(StreamKind);
            Fill(StreamKind, 0, Fill_Parameter(StreamKind_Last, Generic_Delay), Pos*1000/FrameRate, 0);
            Fill(StreamKind, 0, Fill_Parameter(StreamKind_Last, Generic_Delay_Source), "Container");
        }
    }

    Finish("TimeCode");
}

}

#endif //MEDIAINFO_MPEG4_YES
<commit_msg>x Compiler warning<commit_after>// File_Mpeg4_TimeCode - Info for MPEG-4 TimeCode  files
// Copyright (C) 2009-2011 MediaArea.net SARL, Info@MediaArea.net
//
// This library is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library. If not, see <http://www.gnu.org/licenses/>.
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//---------------------------------------------------------------------------
// Compilation conditions
#include "MediaInfo/Setup.h"
#ifdef __BORLANDC__
    #pragma hdrstop
#endif
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#if defined(MEDIAINFO_MPEG4_YES)
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Multiple/File_Mpeg4_TimeCode.h"
//---------------------------------------------------------------------------

namespace MediaInfoLib
{

//***************************************************************************
// Format
//***************************************************************************

//---------------------------------------------------------------------------
void File_Mpeg4_TimeCode::FileHeader_Parse()
{
    //Parsing
    int32u Position=0;
    while (Element_Offset<Element_Size)
        Get_B4 (Position,                                       "Position");

    FILLING_BEGIN();
        Accept("TimeCode");

        if (FrameRate)
        {
            int64s Pos=Position;
            if (NegativeTimes)
                Pos=(int32s)Position;
            if (StreamKind==Stream_General)
            {
                //No link with a track, we do all
                Stream_Prepare(Stream_Video);
                Fill(Stream_Video, 0, Video_Delay, Pos*1000/FrameRate, 0);
                Fill(Stream_Video, 0, Video_Delay_Source, "Container");

                Stream_Prepare(Stream_Audio);
                Fill(Stream_Audio, 0, Audio_Delay, Pos*1000/FrameRate, 0);
                Fill(Stream_Video, 0, Video_Delay_Source, "Container");
            }
            else
            {
                Stream_Prepare(StreamKind);
                Fill(StreamKind, 0, Fill_Parameter(StreamKind_Last, Generic_Delay), Pos*1000/FrameRate, 0);
                Fill(StreamKind, 0, Fill_Parameter(StreamKind_Last, Generic_Delay_Source), "Container");
            }
        }

        Finish("TimeCode");
    FILLING_END();
}

}

#endif //MEDIAINFO_MPEG4_YES
<|endoftext|>


<commit_before>/*---------------------------------------------------------------------------*\
 *                                OpenSG                                     *
 *                                                                           *
 *                                                                           *
 *           Copyright (C) 2000,2001,2002 by the OpenSG Forum                *
 *                                                                           *
 *                            www.opensg.org                                 *
 *                                                                           *
 *   contact: dirk@opensg.org, gerrit.voss@vossg.org, jbehr@zgdv.de          *
 *                                                                           *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
 *                                License                                    *
 *                                                                           *
 * This library 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, version 2.                               *
 *                                                                           *
 * This library is distributed in the hope that it will be useful, but       *
 * WITHOUT ANY WARRANTY; without even the implied warranty of                *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU         *
 * Library General Public License for more details.                          *
 *                                                                           *
 * You should have received a copy of the GNU Library General Public         *
 * License along with this library; if not, write to the Free Software       *
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.                 *
 *                                                                           *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
 *                                Changes                                    *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
\*---------------------------------------------------------------------------*/

//---------------------------------------------------------------------------
//  Includes
//---------------------------------------------------------------------------

#include <cstdlib>
#include <cstdio>

#include "OSGConfig.h"

#include "OSGRenderActionBase.h"
//#include "OSGRenderTraversalAction.h"

#include "OSGStatCollector.h"
#include "OSGDrawable.h"
#include "OSGVolumeDraw.h"
#include "OSGStageValidator.h"
#include "OSGWindow.h"

OSG_USING_NAMESPACE

StatElemDesc<StatTimeElem>
RenderActionBase::statTravTime       ("RT-TravTime",
                                      "time for traversal"       );

/*
StatElemDesc<StatIntElem>
   RenderTraversalActionBase::statCullTestedNodes("rtCullTestedNodes",
                                                  "nodes tested"             );

StatElemDesc<StatIntElem>
   RenderTraversalActionBase::statCulledNodes    ("rtCulledNodes",
                                                  "nodes culled from frustum");
 */

/*-------------------------------------------------------------------------*/
/*                            Constructors                                 */

RenderActionBase::RenderActionBase(void) :
     Inherited       (     ),
    _pCamera         (NULL ),
    _pBackground     (NULL ),
    _pWindow         (NULL ),
    _pViewport       (NULL ),
    _pGlobalOverride (NULL ),
    _pStatistics     (NULL ),
    _pStageValidator (NULL ),

    _bFrustumCulling (true ),
    _bVolumeDrawing  (false),
    _bAutoFrustum    (true ),
    _oFrustum        (     ),
    _uiFrameTravCount(0    ),
    _iDrawerId       (-1   ),
    _iDrawableId     (-1   )
{
    _pStageValidator = new StageValidator();
}

RenderActionBase::RenderActionBase(const RenderActionBase &source) :

     Inherited       (source                  ),
    _pCamera         (source._pCamera         ),
    _pBackground     (source._pBackground     ),
    _pWindow         (source._pWindow         ),
    _pViewport       (source._pViewport       ),
    _pGlobalOverride (source._pGlobalOverride ),
    _pStageValidator (NULL                    ),
    _pStatistics     (NULL                    ),
    _bFrustumCulling (source._bFrustumCulling ),
    _bVolumeDrawing  (source._bVolumeDrawing  ),
    _bAutoFrustum    (source._bAutoFrustum    ),
    _oFrustum        (source._oFrustum        ),
    _uiFrameTravCount(source._uiFrameTravCount),
    _iDrawerId       (source._iDrawerId       ),
    _iDrawableId     (source._iDrawableId     )
{
    OSG::setRefd(_pStatistics, source._pStatistics);

    _pStageValidator = new StageValidator();
}

/*-------------------------------------------------------------------------*/
/*                             Destructor                                  */

RenderActionBase::~RenderActionBase(void)
{
    OSG::subRef(_pStatistics);

    delete _pStageValidator;
}

ActionBase::ResultE RenderActionBase::start(void)
{
    if(_bFrustumCulling   == true &&
       _bAutoFrustum      == true &&
        getCamera      () != NULL &&
        getViewport    () != NULL)
    {
        getCamera()->getFrustum(_oFrustum, *getViewport());
    }

    if(_pStatistics != NULL)
    {
        _pStatistics->reset();

        _pStatistics->getElem(statTravTime       )->start();
//    getStatistics()->getElem(statCullTestedNodes)->reset();
//    getStatistics()->getElem(statCulledNodes    )->reset();
    //getStatistics()->getElem(RenderAction::statNTextures)->reset();
    //getStatistics()->getElem(RenderAction::statNTexBytes)->reset();

    // this really doesn't belong here, but don't know a better place to put it
        if(_pStatistics->getElem(Drawable::statNTriangles,false) != NULL)
        {
            _pStatistics->getElem(Drawable::statNTriangles )->set(0);
            _pStatistics->getElem(Drawable::statNLines     )->set(0);
            _pStatistics->getElem(Drawable::statNPoints    )->set(0);
            _pStatistics->getElem(Drawable::statNVertices  )->set(0);
            _pStatistics->getElem(Drawable::statNPrimitives)->set(0);
        }
    }

    _pStageValidator->incEventCounter();

//    _iDrawerId   = (_pWindow   != NULL) ? _pWindow  ->getDrawerId  () : 0;
//    _iDrawableId = (_pViewport != NULL) ? _pViewport->getDrawableId() : 0;

    return Action::Continue;
}

ActionBase::ResultE RenderActionBase::stop(ActionBase::ResultE res)
{
    if(_pStatistics != NULL)
    {
        _pStatistics->getElem(statTravTime)->stop();
    }

    ++_uiFrameTravCount;

    return res;
}

void RenderActionBase::frameInit(void)
{
    _uiFrameTravCount = 0;
}

void RenderActionBase::setViewport(Viewport *pViewport)
{
    _pViewport = pViewport;
}

void RenderActionBase::setCamera(Camera *pCamera)
{
    _pCamera = pCamera;
}

void RenderActionBase::setBackground(Background *pBackground)
{
    _pBackground = pBackground;
}

void RenderActionBase::setWindow(Window *pWindow)
{
    _pWindow = pWindow;
}

void RenderActionBase::setStatCollector(StatCollector *pStatistics)
{
    OSG::setRefd(_pStatistics, pStatistics);
}

void RenderActionBase::setGlobalOverride(Material *pMat)
{
    _pGlobalOverride = pMat;
}

// do frustum culling at all?
// default true

void RenderActionBase::setFrustumCulling(bool val)
{
    _bFrustumCulling = val;
}

// automatically calc the frustum at the beginning of the traversal
// default true

void RenderActionBase::setAutoFrustum(bool val)
{
    _bAutoFrustum = val;
}

// draw the tested volumes
// default false

void RenderActionBase::setVolumeDrawing(bool val)
{
    _bVolumeDrawing = val;
}

// explicitly set the frustum

void RenderActionBase::setFrustum(FrustumVolume &oFrustum)
{
    _oFrustum = oFrustum;
}

#if 0
// select all visible nodes
UInt32 RenderActionBase::selectVisibles(void)
{
    if(getFrustumCulling() == false)
        return getNNodes();

    useNodeList();

    Color3f col;

    UInt32 count = 0;

    for(UInt32 i = 0; i < getNNodes(); i++)
    {
        if(isVisible(getCPtr(getNode(i))))
        {
            col.setValuesRGB(0,1,0);

            addNode(getNode(i));

            ++count;
        }
        else
        {
            col.setValuesRGB(1,0,0);
        }

        if(getVolumeDrawing())
        {
            dropVolume(this, getNode(i), col);
        }
    }

    return count;
}
#endif
<commit_msg>try to fix the OS X link problem<commit_after>/*---------------------------------------------------------------------------*\
 *                                OpenSG                                     *
 *                                                                           *
 *                                                                           *
 *           Copyright (C) 2000,2001,2002 by the OpenSG Forum                *
 *                                                                           *
 *                            www.opensg.org                                 *
 *                                                                           *
 *   contact: dirk@opensg.org, gerrit.voss@vossg.org, jbehr@zgdv.de          *
 *                                                                           *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
 *                                License                                    *
 *                                                                           *
 * This library 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, version 2.                               *
 *                                                                           *
 * This library is distributed in the hope that it will be useful, but       *
 * WITHOUT ANY WARRANTY; without even the implied warranty of                *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU         *
 * Library General Public License for more details.                          *
 *                                                                           *
 * You should have received a copy of the GNU Library General Public         *
 * License along with this library; if not, write to the Free Software       *
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.                 *
 *                                                                           *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
 *                                Changes                                    *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
\*---------------------------------------------------------------------------*/

//---------------------------------------------------------------------------
//  Includes
//---------------------------------------------------------------------------

#include <cstdlib>
#include <cstdio>

#include "OSGConfig.h"

#include "OSGRenderActionBase.h"
//#include "OSGRenderTraversalAction.h"

#include "OSGStatCollector.h"
#include "OSGDrawable.h"
#include "OSGVolumeDraw.h"
#include "OSGStageValidator.h"
#include "OSGWindow.h"

OSG_BEGIN_NAMESPACE

StatElemDesc<StatTimeElem>
RenderActionBase::statTravTime       ("RT-TravTime",
                                      "time for traversal"       );
# if defined(__APPLE__)
template class DataSlotMixin< MixinHead < RenderDataSlotDesc > >;
#endif

/*
StatElemDesc<StatIntElem>
   RenderTraversalActionBase::statCullTestedNodes("rtCullTestedNodes",
                                                  "nodes tested"             );

StatElemDesc<StatIntElem>
   RenderTraversalActionBase::statCulledNodes    ("rtCulledNodes",
                                                  "nodes culled from frustum");
 */

/*-------------------------------------------------------------------------*/
/*                            Constructors                                 */

RenderActionBase::RenderActionBase(void) :
     Inherited       (     ),
    _pCamera         (NULL ),
    _pBackground     (NULL ),
    _pWindow         (NULL ),
    _pViewport       (NULL ),
    _pGlobalOverride (NULL ),
    _pStatistics     (NULL ),
    _pStageValidator (NULL ),

    _bFrustumCulling (true ),
    _bVolumeDrawing  (false),
    _bAutoFrustum    (true ),
    _oFrustum        (     ),
    _uiFrameTravCount(0    ),
    _iDrawerId       (-1   ),
    _iDrawableId     (-1   )
{
    _pStageValidator = new StageValidator();
}

RenderActionBase::RenderActionBase(const RenderActionBase &source) :

     Inherited       (source                  ),
    _pCamera         (source._pCamera         ),
    _pBackground     (source._pBackground     ),
    _pWindow         (source._pWindow         ),
    _pViewport       (source._pViewport       ),
    _pGlobalOverride (source._pGlobalOverride ),
    _pStageValidator (NULL                    ),
    _pStatistics     (NULL                    ),
    _bFrustumCulling (source._bFrustumCulling ),
    _bVolumeDrawing  (source._bVolumeDrawing  ),
    _bAutoFrustum    (source._bAutoFrustum    ),
    _oFrustum        (source._oFrustum        ),
    _uiFrameTravCount(source._uiFrameTravCount),
    _iDrawerId       (source._iDrawerId       ),
    _iDrawableId     (source._iDrawableId     )
{
    OSG::setRefd(_pStatistics, source._pStatistics);

    _pStageValidator = new StageValidator();
}

/*-------------------------------------------------------------------------*/
/*                             Destructor                                  */

RenderActionBase::~RenderActionBase(void)
{
    OSG::subRef(_pStatistics);

    delete _pStageValidator;
}

ActionBase::ResultE RenderActionBase::start(void)
{
    if(_bFrustumCulling   == true &&
       _bAutoFrustum      == true &&
        getCamera      () != NULL &&
        getViewport    () != NULL)
    {
        getCamera()->getFrustum(_oFrustum, *getViewport());
    }

    if(_pStatistics != NULL)
    {
        _pStatistics->reset();

        _pStatistics->getElem(statTravTime       )->start();
//    getStatistics()->getElem(statCullTestedNodes)->reset();
//    getStatistics()->getElem(statCulledNodes    )->reset();
    //getStatistics()->getElem(RenderAction::statNTextures)->reset();
    //getStatistics()->getElem(RenderAction::statNTexBytes)->reset();

    // this really doesn't belong here, but don't know a better place to put it
        if(_pStatistics->getElem(Drawable::statNTriangles,false) != NULL)
        {
            _pStatistics->getElem(Drawable::statNTriangles )->set(0);
            _pStatistics->getElem(Drawable::statNLines     )->set(0);
            _pStatistics->getElem(Drawable::statNPoints    )->set(0);
            _pStatistics->getElem(Drawable::statNVertices  )->set(0);
            _pStatistics->getElem(Drawable::statNPrimitives)->set(0);
        }
    }

    _pStageValidator->incEventCounter();

//    _iDrawerId   = (_pWindow   != NULL) ? _pWindow  ->getDrawerId  () : 0;
//    _iDrawableId = (_pViewport != NULL) ? _pViewport->getDrawableId() : 0;

    return Action::Continue;
}

ActionBase::ResultE RenderActionBase::stop(ActionBase::ResultE res)
{
    if(_pStatistics != NULL)
    {
        _pStatistics->getElem(statTravTime)->stop();
    }

    ++_uiFrameTravCount;

    return res;
}

void RenderActionBase::frameInit(void)
{
    _uiFrameTravCount = 0;
}

void RenderActionBase::setViewport(Viewport *pViewport)
{
    _pViewport = pViewport;
}

void RenderActionBase::setCamera(Camera *pCamera)
{
    _pCamera = pCamera;
}

void RenderActionBase::setBackground(Background *pBackground)
{
    _pBackground = pBackground;
}

void RenderActionBase::setWindow(Window *pWindow)
{
    _pWindow = pWindow;
}

void RenderActionBase::setStatCollector(StatCollector *pStatistics)
{
    OSG::setRefd(_pStatistics, pStatistics);
}

void RenderActionBase::setGlobalOverride(Material *pMat)
{
    _pGlobalOverride = pMat;
}

// do frustum culling at all?
// default true

void RenderActionBase::setFrustumCulling(bool val)
{
    _bFrustumCulling = val;
}

// automatically calc the frustum at the beginning of the traversal
// default true

void RenderActionBase::setAutoFrustum(bool val)
{
    _bAutoFrustum = val;
}

// draw the tested volumes
// default false

void RenderActionBase::setVolumeDrawing(bool val)
{
    _bVolumeDrawing = val;
}

// explicitly set the frustum

void RenderActionBase::setFrustum(FrustumVolume &oFrustum)
{
    _oFrustum = oFrustum;
}

#if 0
// select all visible nodes
UInt32 RenderActionBase::selectVisibles(void)
{
    if(getFrustumCulling() == false)
        return getNNodes();

    useNodeList();

    Color3f col;

    UInt32 count = 0;

    for(UInt32 i = 0; i < getNNodes(); i++)
    {
        if(isVisible(getCPtr(getNode(i))))
        {
            col.setValuesRGB(0,1,0);

            addNode(getNode(i));

            ++count;
        }
        else
        {
            col.setValuesRGB(1,0,0);
        }

        if(getVolumeDrawing())
        {
            dropVolume(this, getNode(i), col);
        }
    }

    return count;
}
#endif

OSG_END_NAMESPACE
<|endoftext|>