<commit_before>#include <cstdlib>
#include <iostream>
#include <vector>

#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/program_options.hpp>

#include <mettle/driver/cmd_line.hpp>
#include <mettle/driver/log/child.hpp>
#include <mettle/driver/log/summary.hpp>
#include <mettle/driver/log/term.hpp>
#include <mettle/driver/posix/subprocess.hpp>

#include "cmd_line.hpp"
#include "run_test_files.hpp"
#include "test_compiler.hpp"

namespace caliber {

namespace {
  struct all_options : mettle::generic_options, mettle::driver_options,
                       mettle::output_options {
    all_options() {
      auto cxx = getenv("CXX");
      tool = cxx ? cxx : "c++";
    }

    std::string suite_name = "compilation tests";
    std::string tool;
    METTLE_OPTIONAL_NS::optional<int> child_fd;
    std::vector<std::string> files;
  };

  const char program_name[] = "caliber";
  void report_error(const std::string &message) {
    std::cerr << program_name << ": " << message << std::endl;
  }
}

} // namespace caliber

int main(int argc, const char *argv[]) {
  using namespace mettle;
  using namespace mettle::posix;
  namespace opts = boost::program_options;

  auto factory = make_logger_factory();

  caliber::all_options args;
  auto generic = make_generic_options(args);
  auto driver = make_driver_options(args);
  auto output = make_output_options(args, factory);

  driver.add_options()
    ("suite-name,S", opts::value(&args.suite_name)->value_name("NAME"),
     "the name of the suite containing these tests")
    ("tool", opts::value(&args.tool)->value_name("TOOL"),
     "the tool to use for these tests")
  ;

  opts::options_description hidden("Hidden options");
  hidden.add_options()
    ("child", opts::value(&args.child_fd), "run this file as a child process")
    ("file", opts::value(&args.files), "input file")
  ;
  opts::positional_options_description pos;
  pos.add("file", -1);

  opts::variables_map vm;
  try {
    opts::options_description all;
    all.add(generic).add(driver).add(output).add(hidden);
    auto parsed = opts::command_line_parser(argc, argv)
      .options(all).positional(pos).run();

    opts::store(parsed, vm);
    opts::notify(vm);
  } catch(const std::exception &e) {
    caliber::report_error(e.what());
    return 2;
  }

  if(args.show_help) {
    caliber::per_file_options tmp;
    auto per_file = caliber::make_per_file_options(tmp);
    per_file.add(caliber::make_compiler_options());

    opts::options_description displayed;
    displayed.add(generic).add(driver).add(output).add(per_file);
    std::cout << displayed << std::endl;
    return 0;
  }

  if(args.files.empty()) {
    caliber::report_error("no inputs specified");
    return 1;
  }

  try {
    caliber::test_compiler compiler(args.tool, args.timeout);

    if(args.child_fd) {
      if(auto output_opt = has_option(output, vm)) {
        using namespace opts::command_line_style;
        caliber::report_error(output_opt->canonical_display_name(allow_long) +
                              " can't be used with --child");
        return 2;
      }

      close_fd_on_fork(*args.child_fd);
      namespace io = boost::iostreams;
      io::stream<io::file_descriptor_sink> fds(
        *args.child_fd, io::never_close_handle
      );
      log::child logger(fds);
      caliber::run_test_files(args.suite_name, args.files, logger, compiler,
                              args.filters);
      return 0;
    }

    term::enable(std::cout, args.color);
    indenting_ostream out(std::cout);

    log::summary logger(
      out, factory.make(args.output, out, args), args.show_time,
      args.show_terminal
    );
    caliber::run_test_files(args.suite_name, args.files, logger, compiler,
                            args.filters);

    logger.summarize();
    return !logger.good();
  }
  catch(const std::exception &e) {
    caliber::report_error(e.what());
    return 3;
  }
}
<commit_msg>Use --output-fd instead of --child<commit_after>#include <cstdlib>
#include <iostream>
#include <vector>

#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/program_options.hpp>

#include <mettle/driver/cmd_line.hpp>
#include <mettle/driver/log/child.hpp>
#include <mettle/driver/log/summary.hpp>
#include <mettle/driver/log/term.hpp>
#include <mettle/driver/posix/subprocess.hpp>

#include "cmd_line.hpp"
#include "run_test_files.hpp"
#include "test_compiler.hpp"

namespace caliber {

namespace {
  struct all_options : mettle::generic_options, mettle::driver_options,
                       mettle::output_options {
    all_options() {
      auto cxx = getenv("CXX");
      tool = cxx ? cxx : "c++";
    }

    std::string suite_name = "compilation tests";
    std::string tool;
    METTLE_OPTIONAL_NS::optional<int> output_fd;
    std::vector<std::string> files;
  };

  const char program_name[] = "caliber";
  void report_error(const std::string &message) {
    std::cerr << program_name << ": " << message << std::endl;
  }
}

} // namespace caliber

int main(int argc, const char *argv[]) {
  using namespace mettle;
  using namespace mettle::posix;
  namespace opts = boost::program_options;

  auto factory = make_logger_factory();

  caliber::all_options args;
  auto generic = make_generic_options(args);
  auto driver = make_driver_options(args);
  auto output = make_output_options(args, factory);

  driver.add_options()
    ("suite-name,S", opts::value(&args.suite_name)->value_name("NAME"),
     "the name of the suite containing these tests")
    ("tool", opts::value(&args.tool)->value_name("TOOL"),
     "the tool to use for these tests")
  ;

  opts::options_description hidden("Hidden options");
  hidden.add_options()
    ("output-fd", opts::value(&args.output_fd),
     "pipe the results to this file descriptor")
    ("file", opts::value(&args.files), "input file")
  ;
  opts::positional_options_description pos;
  pos.add("file", -1);

  opts::variables_map vm;
  try {
    opts::options_description all;
    all.add(generic).add(driver).add(output).add(hidden);
    auto parsed = opts::command_line_parser(argc, argv)
      .options(all).positional(pos).run();

    opts::store(parsed, vm);
    opts::notify(vm);
  } catch(const std::exception &e) {
    caliber::report_error(e.what());
    return 2;
  }

  if(args.show_help) {
    caliber::per_file_options tmp;
    auto per_file = caliber::make_per_file_options(tmp);
    per_file.add(caliber::make_compiler_options());

    opts::options_description displayed;
    displayed.add(generic).add(driver).add(output).add(per_file);
    std::cout << displayed << std::endl;
    return 0;
  }

  if(args.files.empty()) {
    caliber::report_error("no inputs specified");
    return 1;
  }

  try {
    caliber::test_compiler compiler(args.tool, args.timeout);

    if(args.output_fd) {
      if(auto output_opt = has_option(output, vm)) {
        using namespace opts::command_line_style;
        caliber::report_error(output_opt->canonical_display_name(allow_long) +
                              " can't be used with --output-fd");
        return 2;
      }

      close_fd_on_fork(*args.output_fd);
      namespace io = boost::iostreams;
      io::stream<io::file_descriptor_sink> fds(
        *args.output_fd, io::never_close_handle
      );
      log::child logger(fds);
      caliber::run_test_files(args.suite_name, args.files, logger, compiler,
                              args.filters);
      return 0;
    }

    term::enable(std::cout, args.color);
    indenting_ostream out(std::cout);

    log::summary logger(
      out, factory.make(args.output, out, args), args.show_time,
      args.show_terminal
    );
    caliber::run_test_files(args.suite_name, args.files, logger, compiler,
                            args.filters);

    logger.summarize();
    return !logger.good();
  }
  catch(const std::exception &e) {
    caliber::report_error(e.what());
    return 3;
  }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: implbitmapcanvas.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 08:25:56 $
 *
 *  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
 *
 ************************************************************************/

#ifndef _CPPCANVAS_IMPLBITMAPCANVAS_HXX
#define _CPPCANVAS_IMPLBITMAPCANVAS_HXX

#ifndef _COM_SUN_STAR_RENDERING_XBITMAPCANVAS_HPP__
#include <com/sun/star/rendering/XBitmapCanvas.hpp>
#endif
#ifndef _COM_SUN_STAR_RENDERING_XBITMAP_HPP__
#include <com/sun/star/rendering/XBitmap.hpp>
#endif

#ifndef BOOST_SHARED_PTR_HPP_INCLUDED
#include <boost/shared_ptr.hpp>
#endif

#ifndef _BGFX_VECTOR_B2DSIZE_HXX
#include <basegfx/vector/b2dsize.hxx>
#endif

#ifndef _CPPCANVAS_BITMAPCANVAS_HXX
#include <cppcanvas/bitmapcanvas.hxx>
#endif

#include <implcanvas.hxx>

namespace cppcanvas
{
    namespace internal
    {
        // share Canvas implementation from ImplCanvas
        class ImplBitmapCanvas : public virtual BitmapCanvas, protected virtual ImplCanvas
        {
        public:
            ImplBitmapCanvas( const ::com::sun::star::uno::Reference<
                                  ::com::sun::star::rendering::XBitmapCanvas >& rCanvas );
            virtual ~ImplBitmapCanvas();

            virtual ::basegfx::B2ISize      getSize() const;

            virtual CanvasSharedPtr         clone() const;

            // take compiler-provided default copy constructor
            //ImplBitmapCanvas(const ImplBitmapCanvas&);

        private:
            // default: disabled assignment
            ImplBitmapCanvas& operator=( const ImplBitmapCanvas& );

            const ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XBitmapCanvas >    mxBitmapCanvas;
            const ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XBitmap >          mxBitmap;
        };
    }
}

#endif /* _CPPCANVAS_IMPLBITMAPCANVAS_HXX */
<commit_msg>INTEGRATION: CWS changefileheader (1.6.80); FILE MERGED 2008/04/01 15:10:06 thb 1.6.80.3: #i85898# Stripping all external header guards 2008/04/01 12:27:51 thb 1.6.80.2: #i85898# Stripping all external header guards 2008/03/31 13:07:09 rt 1.6.80.1: #i87441# Change license header to LPGL v3.<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: implbitmapcanvas.hxx,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.
 *
 ************************************************************************/

#ifndef _CPPCANVAS_IMPLBITMAPCANVAS_HXX
#define _CPPCANVAS_IMPLBITMAPCANVAS_HXX

#ifndef _COM_SUN_STAR_RENDERING_XBITMAPCANVAS_HPP__
#include <com/sun/star/rendering/XBitmapCanvas.hpp>
#endif
#ifndef _COM_SUN_STAR_RENDERING_XBITMAP_HPP__
#include <com/sun/star/rendering/XBitmap.hpp>
#endif

#ifndef BOOST_SHARED_PTR_HPP_INCLUDED
#include <boost/shared_ptr.hpp>
#endif
#include <basegfx/vector/b2dsize.hxx>
#include <cppcanvas/bitmapcanvas.hxx>

#include <implcanvas.hxx>

namespace cppcanvas
{
    namespace internal
    {
        // share Canvas implementation from ImplCanvas
        class ImplBitmapCanvas : public virtual BitmapCanvas, protected virtual ImplCanvas
        {
        public:
            ImplBitmapCanvas( const ::com::sun::star::uno::Reference<
                                  ::com::sun::star::rendering::XBitmapCanvas >& rCanvas );
            virtual ~ImplBitmapCanvas();

            virtual ::basegfx::B2ISize      getSize() const;

            virtual CanvasSharedPtr         clone() const;

            // take compiler-provided default copy constructor
            //ImplBitmapCanvas(const ImplBitmapCanvas&);

        private:
            // default: disabled assignment
            ImplBitmapCanvas& operator=( const ImplBitmapCanvas& );

            const ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XBitmapCanvas >    mxBitmapCanvas;
            const ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XBitmap >          mxBitmap;
        };
    }
}

#endif /* _CPPCANVAS_IMPLBITMAPCANVAS_HXX */
<|endoftext|>


<commit_before>#include "Engine.h"
#include "Game.h"
#include "ObjectDummy.h"
#include "BodyRigid.h"
#include "BodyDummy.h"
#include "Physics.h"
#include "ShapeCapsule.h"
#include "ActorBase.h"
#include "Visualizer.h"
#include "sys/SysControl.h"

using namespace MathLib;

#ifdef MEMORY_INFO
#define new new(__FILE__, __LINE__)
#endif // MEMORY_INFO

/*
*/
#define ACTOR_BASE_IFPS             (1.0f / 60.0f)
#define ACTOR_BASE_CLAMP            89.9f
#define ACTOR_BASE_COLLISIONS       4

/*
*/
CActorBase::CActorBase()
{
	m_vUp = vec3(0.0f, 0.0f, 1.0f);
	m_pObject = new CObjectDummy();
	m_pDummy = new CBodyDummy();
	m_pShape = new CShapeCapsule(1.0f, 1.0f);

	m_nFlush = 0;
	m_vPosition = Vec3_zero;
	m_vVelocity = Vec3_zero;
	m_fPhiAngle = 0.0f;			//倾斜角		二维平面坐标系中，直线向Y周延伸的方向与X轴正向之间的夹角
	m_fThetaAngle = 0.0f;			//方位角，正北方那条线与当前线条按照顺时针走过的角度

	for (int i = 0; i < NUM_STATES; i++)
	{
		m_pStates[i] = 0;
		m_pTimes[i] = 0.0f;
	}
	m_pDummy->SetEnabled(1);
	m_pObject->SetBody(NULL);
	m_pObject->SetBody(m_pDummy);
	m_pShape->SetBody(NULL);
	m_pShape->SetBody(m_pDummy);

	m_pObject->SetWorldTransform(Get_Body_Transform());
	m_pShape->SetRestitution(0.0f);
	m_pShape->SetCollisionMask(2);

	SetEnabled(1);
	SetViewDirection(vec3(0.0f, 1.0f, 0.0f));
	SetCollision(1);
	SetCollisionRadius(0.3f);
	SetCollisionHeight(1.0f);
	SetFriction(2.0f);
	SetMinVelocity(2.0f);
	SetMaxVelocity(4.0f);
	SetAcceleration(8.0f);
	SetDamping(8.0f);
	SetJumping(1.5f);

	SetGround(0);
	SetCeiling(0);
}

<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "Engine.h"
#include "Game.h"
#include "ObjectDummy.h"
#include "BodyRigid.h"
#include "BodyDummy.h"
#include "Physics.h"
#include "ShapeCapsule.h"
#include "ActorBase.h"
#include "Visualizer.h"
#include "sys/SysControl.h"

using namespace MathLib;

#ifdef MEMORY_INFO
#define new new(__FILE__, __LINE__)
#endif // MEMORY_INFO

/*
*/
#define ACTOR_BASE_IFPS             (1.0f / 60.0f)
#define ACTOR_BASE_CLAMP            89.9f
#define ACTOR_BASE_COLLISIONS       4

/*
*/
CActorBase::CActorBase()
{
	m_vUp = vec3(0.0f, 0.0f, 1.0f);
	m_pObject = new CObjectDummy();
	m_pDummy = new CBodyDummy();
	m_pShape = new CShapeCapsule(1.0f, 1.0f);

	m_nFlush = 0;
	m_vPosition = Vec3_zero;
	m_vVelocity = Vec3_zero;
	m_fPhiAngle = 0.0f;			//倾斜角		二维平面坐标系中，直线向Y周延伸的方向与X轴正向之间的夹角
	m_fThetaAngle = 0.0f;			//方位角，正北方那条线与当前线条按照顺时针走过的角度

	for (int i = 0; i < NUM_STATES; i++)
	{
		m_pStates[i] = 0;
		m_pTimes[i] = 0.0f;
	}
	m_pDummy->SetEnabled(1);
	m_pObject->SetBody(NULL);
	m_pObject->SetBody(m_pDummy);
	m_pShape->SetBody(NULL);
	m_pShape->SetBody(m_pDummy);

	m_pObject->SetWorldTransform(Get_Body_Transform());
	m_pShape->SetRestitution(0.0f);
	m_pShape->SetCollisionMask(2);

	SetEnabled(1);
	SetViewDirection(vec3(0.0f, 1.0f, 0.0f));
	SetCollision(1);
	SetCollisionRadius(0.3f);
	SetCollisionHeight(1.0f);
	SetFriction(2.0f);
	SetMinVelocity(2.0f);
	SetMaxVelocity(4.0f);
	SetAcceleration(8.0f);
	SetDamping(8.0f);
	SetJumping(1.5f);

	SetGround(0);
	SetCeiling(0);
}

CActorBase::~CActorBase()
{
	m_pDummy->SetObject(NULL);
	delete m_pObject;
	delete m_pDummy;
}<|endoftext|>


<commit_before>#include "Engine.h"
#include "Game.h"
#include "ObjectDummy.h"
#include "BodyRigid.h"
#include "BodyDummy.h"
#include "Physics.h"
#include "ShapeCapsule.h"
#include "ActorBase.h"
#include "Visualizer.h"
#include "sys/SysControl.h"

using namespace MathLib;

#ifdef MEMORY_INFO
#define new new(__FILE__, __LINE__)
#endif // MEMORY_INFO

/*
*/
#define ACTOR_BASE_IFPS             (1.0f / 60.0f)
#define ACTOR_BASE_CLAMP            89.9f
#define ACTOR_BASE_COLLISIONS       4

/*
*/
CActorBase::CActorBase()
{
	m_vUp = vec3(0.0f, 0.0f, 1.0f);
	m_pObject = new CObjectDummy();
	m_pDummy = new CBodyDummy();
	m_pShape = new CShapeCapsule(1.0f, 1.0f);

	m_nFlush = 0;
	m_vPosition = Vec3_zero;
	m_vVelocity = Vec3_zero;
	m_fPhiAngle = 0.0f;			//倾斜角		二维平面坐标系中，直线向Y周延伸的方向与X轴正向之间的夹角
	m_fThetaAngle = 0.0f;			//方位角，正北方那条线与当前线条按照顺时针走过的角度

	for (int i = 0; i < NUM_STATES; i++)
	{
		m_pStates[i] = 0;
		m_pTimes[i] = 0.0f;
	}
	m_pDummy->SetEnabled(1);
	m_pObject->SetBody(NULL);
	m_pObject->SetBody(m_pDummy);
	m_pShape->SetBody(NULL);
	m_pShape->SetBody(m_pDummy);

	m_pObject->SetWorldTransform(Get_Body_Transform());
	m_pShape->SetRestitution(0.0f);
	m_pShape->SetCollisionMask(2);

	SetEnabled(1);
	SetViewDirection(vec3(0.0f, 1.0f, 0.0f));
	SetCollision(1);
	SetCollisionRadius(0.3f);
	SetCollisionHeight(1.0f);
	SetFriction(2.0f);
	SetMinVelocity(2.0f);
	SetMaxVelocity(4.0f);
	SetAcceleration(8.0f);
	SetDamping(8.0f);
	SetJumping(1.5f);

	SetGround(0);
	SetCeiling(0);
}

CActorBase::~CActorBase()
{
	m_pDummy->SetObject(NULL);
	delete m_pObject;
	delete m_pDummy;
}

void CActorBase::SetEnabled(int enable)
{
	m_nEnable = enable;
	m_pDummy->SetEnabled(m_nEnable);
}

int CActorBase::IsEnabled() const
{
	return m_nEnable;
}
void CActorBase::Update(float ifps)
{
	if (!m_nEnable)
	{
		return;
	}

	// impulse
	vec3 impulse = vec3_zero;

	// ortho basis
	vec3 tangent, binormal;
	OrthoBasis(m_vUp, tangent, binormal);

	// current basis
	vec3 x = quat(m_vUp, -m_fPhiAngle) * binormal;
	vec3 y = Normalize(Cross(m_vUp, x));
	vec3 z = Normalize(Cross(x, y));

	handle states
		Update_States(1, ifps);

	// old velocity
	float x_velocity = Dot(x, m_vVelocity);
	float y_velocity = Dot(y, m_vVelocity);
	float z_velocity = Dot(z, m_vVelocity);
	// movement
	if (m_pStates[STATE_FORWARD]) impulse += x;
	if (m_pStates[STATE_BACKWARD]) impulse -= x;
	if (m_pStates[STATE_MOVE_LEFT]) impulse += y;
	if (m_pStates[STATE_MOVE_RIGHT]) impulse -= y;
	impulse.normalize();
	//velocity
	if (m_pStates[STATE_RUN])
		impulse *= m_fMaxVelocity;
	else
		impulse *= m_fMinVelocity;
	// jump
	if (m_pStates[STATE_JUMP] == STATE_BEGIN)
	{
		impulse += z * CMathCore::Sqrt(2.0f * 9.8f * m_fJumping) / (m_fAcceleration * ifps);
	}

	// rotate velocity
	if (GetGround())
	{
		m_vVelocity = x * x_velocity + y * y_velocity + z * z_velocity;
	}

	// time
	float time = ifps * g_Engine.pPhysics->GetScale();

	// target velocity
	float target_velocity = Length(vec2(Dot(x, impulse), Dot(y, impulse)));

	// penetration tolerance
	float penetration = g_Engine.pPhysics->GetPenetrationTolerance();
	float penetration_2 = penetration * 2.0f;

	// frozen linear velocity
	float frozen_velocity = g_Engine.pPhysics->GetFrozenLinearVelocity();

	// friction
	float friction = 0.0f;
	if (target_velocity < EPSILON)
	{
		friction = m_fFriction;
	}

	//clear collision flags
	if (GetCollision())
	{
		m_nGround = 0;
		m_nCeiling = 0;
	}
	// movement
	do
	{
		// adaptive time step
		float ifps = Min(time, ACTOR_BASE_IFPS);
		time -= ifps;

		// save old velocity
		float old_velocity = Length(vec2(Dot(x, m_vVelocity), Dot(y, m_vVelocity)));

		// integrate velocity
		m_vVelocity += impulse * (m_fAcceleration * ifps);
		m_vVelocity += g_Engine.pPhysics->GetGravity() * ifps;

		// damping
		float current_velocity = Length(vec2(Dot(x, m_vVelocity), Dot(y, m_vVelocity)));
		if (target_velocity < EPSILON || current_velocity > target_velocity)
		{
			m_vVelocity = (x * Dot(x, m_vVelocity) + y * Dot(y, m_vVelocity)) * CMathCore::Exp(-m_fDamping * ifps) + z * Dot(z, m_vVelocity);
		}

		// clamp maximum velocity
		current_velocity = Length(vec2(Dot(x, m_vVelocity), Dot(y, m_vVelocity)));
		if (current_velocity > old_velocity)
		{
			if (current_velocity > target_velocity)
			{
				m_vVelocity = (x * Dot(x, m_vVelocity) + y * Dot(y, m_vVelocity)) * target_velocity / current_velocity + z * Dot(z, m_vVelocity);
			}
		}

	}

}<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "Engine.h"
#include "Game.h"
#include "ObjectDummy.h"
#include "BodyRigid.h"
#include "BodyDummy.h"
#include "Physics.h"
#include "ShapeCapsule.h"
#include "ActorBase.h"
#include "Visualizer.h"
#include "sys/SysControl.h"

using namespace MathLib;

#ifdef MEMORY_INFO
#define new new(__FILE__, __LINE__)
#endif // MEMORY_INFO

/*
*/
#define ACTOR_BASE_IFPS             (1.0f / 60.0f)
#define ACTOR_BASE_CLAMP            89.9f
#define ACTOR_BASE_COLLISIONS       4

/*
*/
CActorBase::CActorBase()
{
	m_vUp = vec3(0.0f, 0.0f, 1.0f);
	m_pObject = new CObjectDummy();
	m_pDummy = new CBodyDummy();
	m_pShape = new CShapeCapsule(1.0f, 1.0f);

	m_nFlush = 0;
	m_vPosition = Vec3_zero;
	m_vVelocity = Vec3_zero;
	m_fPhiAngle = 0.0f;			//倾斜角		二维平面坐标系中，直线向Y周延伸的方向与X轴正向之间的夹角
	m_fThetaAngle = 0.0f;			//方位角，正北方那条线与当前线条按照顺时针走过的角度

	for (int i = 0; i < NUM_STATES; i++)
	{
		m_pStates[i] = 0;
		m_pTimes[i] = 0.0f;
	}
	m_pDummy->SetEnabled(1);
	m_pObject->SetBody(NULL);
	m_pObject->SetBody(m_pDummy);
	m_pShape->SetBody(NULL);
	m_pShape->SetBody(m_pDummy);

	m_pObject->SetWorldTransform(Get_Body_Transform());
	m_pShape->SetRestitution(0.0f);
	m_pShape->SetCollisionMask(2);

	SetEnabled(1);
	SetViewDirection(vec3(0.0f, 1.0f, 0.0f));
	SetCollision(1);
	SetCollisionRadius(0.3f);
	SetCollisionHeight(1.0f);
	SetFriction(2.0f);
	SetMinVelocity(2.0f);
	SetMaxVelocity(4.0f);
	SetAcceleration(8.0f);
	SetDamping(8.0f);
	SetJumping(1.5f);

	SetGround(0);
	SetCeiling(0);
}

CActorBase::~CActorBase()
{
	m_pDummy->SetObject(NULL);
	delete m_pObject;
	delete m_pDummy;
}

void CActorBase::SetEnabled(int enable)
{
	m_nEnable = enable;
	m_pDummy->SetEnabled(m_nEnable);
}

int CActorBase::IsEnabled() const
{
	return m_nEnable;
}
void CActorBase::Update(float ifps)
{
	if (!m_nEnable)
	{
		return;
	}

	// impulse
	vec3 impulse = vec3_zero;

	// ortho basis
	vec3 tangent, binormal;
	OrthoBasis(m_vUp, tangent, binormal);

	// current basis
	vec3 x = quat(m_vUp, -m_fPhiAngle) * binormal;
	vec3 y = Normalize(Cross(m_vUp, x));
	vec3 z = Normalize(Cross(x, y));

	handle states
		Update_States(1, ifps);

	// old velocity
	float x_velocity = Dot(x, m_vVelocity);
	float y_velocity = Dot(y, m_vVelocity);
	float z_velocity = Dot(z, m_vVelocity);
	// movement
	if (m_pStates[STATE_FORWARD]) impulse += x;
	if (m_pStates[STATE_BACKWARD]) impulse -= x;
	if (m_pStates[STATE_MOVE_LEFT]) impulse += y;
	if (m_pStates[STATE_MOVE_RIGHT]) impulse -= y;
	impulse.normalize();
	//velocity
	if (m_pStates[STATE_RUN])
		impulse *= m_fMaxVelocity;
	else
		impulse *= m_fMinVelocity;
	// jump
	if (m_pStates[STATE_JUMP] == STATE_BEGIN)
	{
		impulse += z * CMathCore::Sqrt(2.0f * 9.8f * m_fJumping) / (m_fAcceleration * ifps);
	}

	// rotate velocity
	if (GetGround())
	{
		m_vVelocity = x * x_velocity + y * y_velocity + z * z_velocity;
	}

	// time
	float time = ifps * g_Engine.pPhysics->GetScale();

	// target velocity
	float target_velocity = Length(vec2(Dot(x, impulse), Dot(y, impulse)));

	// penetration tolerance
	float penetration = g_Engine.pPhysics->GetPenetrationTolerance();
	float penetration_2 = penetration * 2.0f;

	// frozen linear velocity
	float frozen_velocity = g_Engine.pPhysics->GetFrozenLinearVelocity();

	// friction
	float friction = 0.0f;
	if (target_velocity < EPSILON)
	{
		friction = m_fFriction;
	}

	//clear collision flags
	if (GetCollision())
	{
		m_nGround = 0;
		m_nCeiling = 0;
	}
	// movement
	do
	{
		// adaptive time step
		float ifps = Min(time, ACTOR_BASE_IFPS);
		time -= ifps;

		// save old velocity
		float old_velocity = Length(vec2(Dot(x, m_vVelocity), Dot(y, m_vVelocity)));

		// integrate velocity
		m_vVelocity += impulse * (m_fAcceleration * ifps);
		m_vVelocity += g_Engine.pPhysics->GetGravity() * ifps;

		// damping
		float current_velocity = Length(vec2(Dot(x, m_vVelocity), Dot(y, m_vVelocity)));
		if (target_velocity < EPSILON || current_velocity > target_velocity)
		{
			m_vVelocity = (x * Dot(x, m_vVelocity) + y * Dot(y, m_vVelocity)) * CMathCore::Exp(-m_fDamping * ifps) + z * Dot(z, m_vVelocity);
		}

		// clamp maximum velocity
		current_velocity = Length(vec2(Dot(x, m_vVelocity), Dot(y, m_vVelocity)));
		if (current_velocity > old_velocity)
		{
			if (current_velocity > target_velocity)
			{
				m_vVelocity = (x * Dot(x, m_vVelocity) + y * Dot(y, m_vVelocity)) * target_velocity / current_velocity + z * Dot(z, m_vVelocity);
			}
		}

		// frozen velocity
		int is_frozen = 0;
		if (current_velocity < frozen_velocity)
		{
			m_vVelocity = z * Dot(z, m_vVelocity);
			is_frozen = 1;
		}

	}

}<|endoftext|>


<commit_before>/*
 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
 *           (C) 1999 Antti Koivisto (koivisto@kde.org)
 *           (C) 2001 Dirk Mueller (mueller@kde.org)
 * Copyright (C) 2003, 2010 Apple Inc. All rights reserved.
 *
 * 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; either
 * version 2 of the License, or (at your option) 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "config.h"
#include "core/html/HTMLTitleElement.h"

#include "HTMLNames.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "core/dom/Document.h"
#include "core/dom/Text.h"
#include "core/rendering/style/RenderStyle.h"
#include "core/rendering/style/StyleInheritedData.h"
#include "wtf/text/StringBuilder.h"

namespace WebCore {

using namespace HTMLNames;

inline HTMLTitleElement::HTMLTitleElement(const QualifiedName& tagName, Document* document)
    : HTMLElement(tagName, document)
{
    ASSERT(hasTagName(titleTag));
    setHasCustomStyleCallbacks();
    ScriptWrappable::init(this);
}

PassRefPtr<HTMLTitleElement> HTMLTitleElement::create(const QualifiedName& tagName, Document* document)
{
    return adoptRef(new HTMLTitleElement(tagName, document));
}

Node::InsertionNotificationRequest HTMLTitleElement::insertedInto(ContainerNode* insertionPoint)
{
    HTMLElement::insertedInto(insertionPoint);
    if (inDocument() && !isInShadowTree())
        document()->setTitleElement(textWithDirection(), this);
    return InsertionDone;
}

void HTMLTitleElement::removedFrom(ContainerNode* insertionPoint)
{
    HTMLElement::removedFrom(insertionPoint);
    if (insertionPoint->inDocument() && !insertionPoint->isInShadowTree())
        document()->removeTitle(this);
}

void HTMLTitleElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
{
    HTMLElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
    if (inDocument() && !isInShadowTree())
        document()->setTitleElement(textWithDirection(), this);
}

void HTMLTitleElement::attach(const AttachContext& context)
{
    HTMLElement::attach(context);
    // If after attaching nothing called styleForRenderer() on this node we
    // manually cache the value. This happens if our parent doesn't have a
    // renderer like <optgroup> or if it doesn't allow children like <select>.
    if (!m_style)
        updateNonRenderStyle();
}

void HTMLTitleElement::detach(const AttachContext& context)
{
    m_style.clear();
    HTMLElement::detach(context);
}

void HTMLTitleElement::updateNonRenderStyle()
{
    m_style = document()->styleForElementIgnoringPendingStylesheets(this);
}

RenderStyle* HTMLTitleElement::nonRendererStyle() const
{
    return m_style.get();
}

PassRefPtr<RenderStyle> HTMLTitleElement::customStyleForRenderer()
{
    // styleForRenderer is called whenever a new style should be associated
    // with an Element so now is a good time to update our cached style.
    updateNonRenderStyle();
    return m_style;
}

void HTMLTitleElement::didRecalcStyle(StyleChange)
{
    if (isInShadowTree())
        return;

    document()->setTitleElement(textWithDirection(), this);
}

String HTMLTitleElement::text() const
{
    StringBuilder result;

    for (Node *n = firstChild(); n; n = n->nextSibling()) {
        if (n->isTextNode())
            result.append(toText(n)->data());
    }

    return result.toString();
}

StringWithDirection HTMLTitleElement::textWithDirection()
{
    TextDirection direction = LTR;
    if (m_style)
        direction = m_style->direction();
    return StringWithDirection(text(), direction);
}

void HTMLTitleElement::setText(const String &value)
{
    RefPtr<Node> protectFromMutationEvents(this);

    int numChildren = childNodeCount();

    if (numChildren == 1 && firstChild()->isTextNode())
        toText(firstChild())->setData(value);
    else {
        // We make a copy here because entity of "value" argument can be Document::m_title,
        // which goes empty during removeChildren() invocation below,
        // which causes HTMLTitleElement::childrenChanged(), which ends up Document::setTitle().
        String valueCopy(value);

        if (numChildren > 0)
            removeChildren();

        appendChild(document()->createTextNode(valueCopy.impl()), IGNORE_EXCEPTION, DeprecatedAttachNow);
    }
}

}
<commit_msg>HTMLTitleElement should AttachLazily.<commit_after>/*
 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
 *           (C) 1999 Antti Koivisto (koivisto@kde.org)
 *           (C) 2001 Dirk Mueller (mueller@kde.org)
 * Copyright (C) 2003, 2010 Apple Inc. All rights reserved.
 *
 * 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; either
 * version 2 of the License, or (at your option) 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "config.h"
#include "core/html/HTMLTitleElement.h"

#include "HTMLNames.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "core/dom/Document.h"
#include "core/dom/Text.h"
#include "core/rendering/style/RenderStyle.h"
#include "core/rendering/style/StyleInheritedData.h"
#include "wtf/text/StringBuilder.h"

namespace WebCore {

using namespace HTMLNames;

inline HTMLTitleElement::HTMLTitleElement(const QualifiedName& tagName, Document* document)
    : HTMLElement(tagName, document)
{
    ASSERT(hasTagName(titleTag));
    setHasCustomStyleCallbacks();
    ScriptWrappable::init(this);
}

PassRefPtr<HTMLTitleElement> HTMLTitleElement::create(const QualifiedName& tagName, Document* document)
{
    return adoptRef(new HTMLTitleElement(tagName, document));
}

Node::InsertionNotificationRequest HTMLTitleElement::insertedInto(ContainerNode* insertionPoint)
{
    HTMLElement::insertedInto(insertionPoint);
    if (inDocument() && !isInShadowTree())
        document()->setTitleElement(textWithDirection(), this);
    return InsertionDone;
}

void HTMLTitleElement::removedFrom(ContainerNode* insertionPoint)
{
    HTMLElement::removedFrom(insertionPoint);
    if (insertionPoint->inDocument() && !insertionPoint->isInShadowTree())
        document()->removeTitle(this);
}

void HTMLTitleElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
{
    HTMLElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
    if (inDocument() && !isInShadowTree())
        document()->setTitleElement(textWithDirection(), this);
}

void HTMLTitleElement::attach(const AttachContext& context)
{
    HTMLElement::attach(context);
    // If after attaching nothing called styleForRenderer() on this node we
    // manually cache the value. This happens if our parent doesn't have a
    // renderer like <optgroup> or if it doesn't allow children like <select>.
    if (!m_style)
        updateNonRenderStyle();
}

void HTMLTitleElement::detach(const AttachContext& context)
{
    m_style.clear();
    HTMLElement::detach(context);
}

void HTMLTitleElement::updateNonRenderStyle()
{
    m_style = document()->styleForElementIgnoringPendingStylesheets(this);
}

RenderStyle* HTMLTitleElement::nonRendererStyle() const
{
    return m_style.get();
}

PassRefPtr<RenderStyle> HTMLTitleElement::customStyleForRenderer()
{
    // styleForRenderer is called whenever a new style should be associated
    // with an Element so now is a good time to update our cached style.
    updateNonRenderStyle();
    return m_style;
}

void HTMLTitleElement::didRecalcStyle(StyleChange)
{
    if (isInShadowTree())
        return;

    document()->setTitleElement(textWithDirection(), this);
}

String HTMLTitleElement::text() const
{
    StringBuilder result;

    for (Node *n = firstChild(); n; n = n->nextSibling()) {
        if (n->isTextNode())
            result.append(toText(n)->data());
    }

    return result.toString();
}

StringWithDirection HTMLTitleElement::textWithDirection()
{
    TextDirection direction = LTR;
    if (m_style)
        direction = m_style->direction();
    return StringWithDirection(text(), direction);
}

void HTMLTitleElement::setText(const String &value)
{
    RefPtr<Node> protectFromMutationEvents(this);

    int numChildren = childNodeCount();

    if (numChildren == 1 && firstChild()->isTextNode())
        toText(firstChild())->setData(value);
    else {
        // We make a copy here because entity of "value" argument can be Document::m_title,
        // which goes empty during removeChildren() invocation below,
        // which causes HTMLTitleElement::childrenChanged(), which ends up Document::setTitle().
        String valueCopy(value);

        if (numChildren > 0)
            removeChildren();

        appendChild(document()->createTextNode(valueCopy.impl()), IGNORE_EXCEPTION);
    }
}

}
<|endoftext|>


<commit_before>// ----------------------------------------------------------------------------
// PSP Player Emulation Suite
// Copyright (C) 2006 Ben Vanik (noxa)
// Licensed under the LGPL - see License.txt in the project root for details
// ----------------------------------------------------------------------------

#include "Stdafx.h"
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>

#include "sceCtrl.h"
#include "Kernel.h"

using namespace System;
using namespace System::Diagnostics;
using namespace Noxa::Emulation::Psp;
using namespace Noxa::Emulation::Psp::Bios;
using namespace Noxa::Emulation::Psp::Bios::Modules;
using namespace Noxa::Emulation::Psp::Input;

void sceCtrl::Start()
{
	if( _threadRunning == true )
		this->Stop();

	_threadRunning = true;
	_thread = gcnew Thread( gcnew ThreadStart( this, &sceCtrl::InputThread ) );
	_thread->IsBackground = true;
	_thread->Name = "Kernel Input Thread";
	_thread->Priority = ThreadPriority::Normal;
	_thread->Start();
}

void sceCtrl::Stop()
{
	_threadRunning = false;
	if( _thread != nullptr )
		_thread->Join();
	_thread = nullptr;
}

void sceCtrl::Clear()
{
	if( _threadRunning == true )
		this->Stop();

	_sampleCycle = 0;
	_sampleMode = ControlSamplingMode::AnalogAndDigital;
	_buffer = gcnew CircularList<ControlSample^>( 100 );
	_dataPresent = gcnew AutoResetEvent( false );
}

void sceCtrl::InputThread()
{
	try
	{
		IInputDevice^ device = _kernel->_emu->Input;
		Debug::Assert( device != nullptr );
		if( device == nullptr )
		{
			_threadRunning = false;
			return;
		}

		while( _threadRunning == true )
		{
			ControlSample^ sample = gcnew ControlSample();
			sample->Timestamp = ( uint )( _kernel->RunTime * 1000 );

			device->Poll();
			sample->Buttons = device->Buttons;
			float max = ushort::MaxValue;
			if( sample->AnalogX == 0 )
				sample->AnalogX = ( int )( ( ( ( float )device->AnalogX / max ) + 0.5f ) * 256 );
			if( sample->AnalogY == 0 )
				sample->AnalogY = ( int )( ( ( -( float )device->AnalogY / max ) + 0.5f ) * 256 );

			Monitor::Enter( this );
			{
				_buffer->Add( sample );
				if( _buffer->Count == 1 )
					_dataPresent->Set();

				// Set pressed buttons list
				uint oldPressed = _pressedButtons;
				_pressedButtons = ( uint )sample->Buttons;
				uint stillPressed = _pressedButtons & oldPressed;

				// Set maked/breaked (pressed/released) buttons this last sample
				_makedButtons = _pressedButtons & ~stillPressed;
				_breakedButtons = oldPressed & ~stillPressed;
			}
			Monitor::Exit( this );

			Thread::Sleep( InputPollInterval );
		}
	}
	catch( ThreadAbortException^ )
	{
	}
	catch( ThreadInterruptedException^ )
	{
	}
}

// int sceCtrlSetSamplingCycle(int cycle); (/ctrl/pspctrl.h:119)
int sceCtrl::sceCtrlSetSamplingCycle( int cycle )
{
	int old = _sampleCycle;
	_sampleCycle = cycle;
	Debug::WriteLine( String::Format( "sceCtrlSetSamplingCycle: set to {0} (was {1})", cycle, old ) );

	return old;
}

// int sceCtrlGetSamplingCycle(int *pcycle); (/ctrl/pspctrl.h:128)
int sceCtrl::sceCtrlGetSamplingCycle( IMemory^ memory, int pcycle )
{
	if( pcycle != 0x0 )
		memory->WriteWord( pcycle, 4, _sampleCycle );

	return 0;
}

// int sceCtrlSetSamplingMode(int mode); (/ctrl/pspctrl.h:137)
int sceCtrl::sceCtrlSetSamplingMode( int mode )
{
	int old = ( int )_sampleMode;
	_sampleMode = ( ControlSamplingMode )mode;

	return old;
}

// int sceCtrlGetSamplingMode(int *pmode); (/ctrl/pspctrl.h:146)
int sceCtrl::sceCtrlGetSamplingMode( IMemory^ memory, int pmode )
{
	if( pmode != 0x0 )
		memory->WriteWord( pmode, 4, ( int )_sampleMode );

	return 0;
}

// int sceCtrlPeekBufferPositive(SceCtrlData *pad_data, int count); (/ctrl/pspctrl.h:148)
int sceCtrl::sceCtrlPeekBufferPositive( IMemory^ memory, int pad_data, int count )
{
	array<ControlSample^>^ samples;
	int toRead;
	Monitor::Enter( this );
	{
		toRead = MIN2( count, _buffer->Count );
		samples = gcnew array<ControlSample^>( toRead );
		for( int n = 0; n < toRead; n++ )
			samples[ n ] = _buffer->PeekAhead( n );
	}
	Monitor::Exit( this );

	if( pad_data != 0x0 )
	{
		int addr = pad_data;
		for( int n = 0; n < toRead; n++ )
		{
			ControlSample^ sample = samples[ n ];
			memory->WriteWord( addr + 0, 4, ( int )sample->Timestamp );
			memory->WriteWord( addr + 4, 4, ( int )sample->Buttons );
			memory->WriteWord( addr + 8, 1, ( byte )sample->AnalogX );
			memory->WriteWord( addr + 9, 1, ( byte )sample->AnalogY );
			// 6 bytes of junk
			addr += 16;
		}
	}

	return toRead;
}

// int sceCtrlPeekBufferNegative(SceCtrlData *pad_data, int count); (/ctrl/pspctrl.h:150)
int sceCtrl::sceCtrlPeekBufferNegative( IMemory^ memory, int pad_data, int count )
{
	// Same as above, but complement button mask

	array<ControlSample^>^ samples;
	int toRead;
	Monitor::Enter( this );
	{
		toRead = MIN2( count, _buffer->Count );
		samples = gcnew array<ControlSample^>( toRead );
		for( int n = 0; n < toRead; n++ )
			samples[ n ] = _buffer->PeekAhead( n );
	}
	Monitor::Exit( this );

	if( pad_data != 0x0 )
	{
		int addr = pad_data;
		for( int n = 0; n < toRead; n++ )
		{
			ControlSample^ sample = samples[ n ];
			memory->WriteWord( addr + 0, 4, ( int )sample->Timestamp );
			memory->WriteWord( addr + 4, 4, ~( int )sample->Buttons );
			memory->WriteWord( addr + 8, 1, ( byte )sample->AnalogX );
			memory->WriteWord( addr + 9, 1, ( byte )sample->AnalogY );
			// 6 bytes of junk
			addr += 16;
		}
	}

	return toRead;
}

// int sceCtrlReadBufferPositive(SceCtrlData *pad_data, int count); (/ctrl/pspctrl.h:168)
int sceCtrl::sceCtrlReadBufferPositive( IMemory^ memory, int pad_data, int count )
{
	array<ControlSample^>^ samples = gcnew array<ControlSample^>( count );
	int read = 0;
	while( read < count )
	{
		Monitor::Enter( this );
		if( _buffer->Count == 0 )
			_dataPresent->WaitOne( InputPollInterval * 2, true );
		while( ( _buffer->Count > 0 ) && ( read < count ) )
			samples[ read++ ] = _buffer->Dequeue();
		Monitor::Exit( this );
	}

	if( pad_data != 0x0 )
	{
		int addr = pad_data;
		for( int n = 0; n < read; n++ )
		{
			ControlSample^ sample = samples[ n ];
			memory->WriteWord( addr + 0, 4, ( int )sample->Timestamp );
			memory->WriteWord( addr + 4, 4, ( int )sample->Buttons );
			memory->WriteWord( addr + 8, 1, ( byte )sample->AnalogX );
			memory->WriteWord( addr + 9, 1, ( byte )sample->AnalogY );
			// 6 bytes of junk
			addr += 16;
		}
	}

	return read;
}

// int sceCtrlReadBufferNegative(SceCtrlData *pad_data, int count); (/ctrl/pspctrl.h:170)
int sceCtrl::sceCtrlReadBufferNegative( IMemory^ memory, int pad_data, int count )
{
	array<ControlSample^>^ samples = gcnew array<ControlSample^>( count );
	int read = 0;
	while( read < count )
	{
		Monitor::Enter( this );
		if( _buffer->Count == 0 )
			_dataPresent->WaitOne( InputPollInterval * 2, true );
		while( _buffer->Count > 0 )
			samples[ read++ ] = _buffer->Dequeue();
		Monitor::Exit( this );
	}

	if( pad_data != 0x0 )
	{
		int addr = pad_data;
		for( int n = 0; n < read; n++ )
		{
			ControlSample^ sample = samples[ n ];
			memory->WriteWord( addr + 0, 4, ( int )sample->Timestamp );
			memory->WriteWord( addr + 4, 4, ~( int )sample->Buttons );
			memory->WriteWord( addr + 8, 1, ( byte )sample->AnalogX );
			memory->WriteWord( addr + 9, 1, ( byte )sample->AnalogY );
			// 6 bytes of junk
			addr += 16;
		}
	}

	return read;
}

//typedef struct SceCtrlLatch {
//	unsigned int 	uiMake;		// keys pressed since last reading
//	unsigned int 	uiBreak;	// keys released since last reading
//	unsigned int 	uiPress;	// bitmask of pressed keys?
//	unsigned int 	uiRelease;	// bitmask of released keys?
//} SceCtrlLatch;

// int sceCtrlPeekLatch(SceCtrlLatch *latch_data); (/ctrl/pspctrl.h:172)
int sceCtrl::sceCtrlPeekLatch( IMemory^ memory, int latch_data )
{
	memory->WriteWord( latch_data + 0, 4, _makedButtons );
	memory->WriteWord( latch_data + 4, 4, _breakedButtons );
	memory->WriteWord( latch_data + 8, 4, _pressedButtons );
	memory->WriteWord( latch_data + 12, 4, ~_pressedButtons );

	return 0;
}

// int sceCtrlReadLatch(SceCtrlLatch *latch_data); (/ctrl/pspctrl.h:174)
int sceCtrl::sceCtrlReadLatch( IMemory^ memory, int latch_data )
{
	memory->WriteWord( latch_data + 0, 4, _makedButtons );
	memory->WriteWord( latch_data + 4, 4, _breakedButtons );
	memory->WriteWord( latch_data + 8, 4, _pressedButtons );
	memory->WriteWord( latch_data + 12, 4, ~_pressedButtons );

	_makedButtons = 0;
	_breakedButtons = 0;

	return 0;
}
<commit_msg>Quick fix for the input library so that it only buffers 3 events. I'm looking to rewrite this so that it only buffers 2 (alternating) and does so quickly (as opposed to using the CircularList<> type I wrote). I'll can also implement some native methods that grab them so that the sceCtrl calls are faster.<commit_after>// ----------------------------------------------------------------------------
// PSP Player Emulation Suite
// Copyright (C) 2006 Ben Vanik (noxa)
// Licensed under the LGPL - see License.txt in the project root for details
// ----------------------------------------------------------------------------

#include "Stdafx.h"
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>

#include "sceCtrl.h"
#include "Kernel.h"

using namespace System;
using namespace System::Diagnostics;
using namespace Noxa::Emulation::Psp;
using namespace Noxa::Emulation::Psp::Bios;
using namespace Noxa::Emulation::Psp::Bios::Modules;
using namespace Noxa::Emulation::Psp::Input;

void sceCtrl::Start()
{
	if( _threadRunning == true )
		this->Stop();

	_threadRunning = true;
	_thread = gcnew Thread( gcnew ThreadStart( this, &sceCtrl::InputThread ) );
	_thread->IsBackground = true;
	_thread->Name = "Kernel Input Thread";
	_thread->Priority = ThreadPriority::Normal;
	_thread->Start();
}

void sceCtrl::Stop()
{
	_threadRunning = false;
	if( _thread != nullptr )
		_thread->Join();
	_thread = nullptr;
}

void sceCtrl::Clear()
{
	if( _threadRunning == true )
		this->Stop();

	_sampleCycle = 0;
	_sampleMode = ControlSamplingMode::AnalogAndDigital;
	_buffer = gcnew CircularList<ControlSample^>( 3 );
	_dataPresent = gcnew AutoResetEvent( false );
}

void sceCtrl::InputThread()
{
	try
	{
		IInputDevice^ device = _kernel->_emu->Input;
		Debug::Assert( device != nullptr );
		if( device == nullptr )
		{
			_threadRunning = false;
			return;
		}

		while( _threadRunning == true )
		{
			ControlSample^ sample = gcnew ControlSample();
			sample->Timestamp = ( uint )( _kernel->RunTime * 1000 );

			device->Poll();
			sample->Buttons = device->Buttons;
			float max = ushort::MaxValue;
			if( sample->AnalogX == 0 )
				sample->AnalogX = ( int )( ( ( ( float )device->AnalogX / max ) + 0.5f ) * 256 );
			if( sample->AnalogY == 0 )
				sample->AnalogY = ( int )( ( ( -( float )device->AnalogY / max ) + 0.5f ) * 256 );

			Monitor::Enter( this );
			{
				_buffer->Add( sample );
				if( _buffer->Count == 1 )
					_dataPresent->Set();

				// Set pressed buttons list
				uint oldPressed = _pressedButtons;
				_pressedButtons = ( uint )sample->Buttons;
				uint stillPressed = _pressedButtons & oldPressed;

				// Set maked/breaked (pressed/released) buttons this last sample
				_makedButtons = _pressedButtons & ~stillPressed;
				_breakedButtons = oldPressed & ~stillPressed;
			}
			Monitor::Exit( this );

			Thread::Sleep( InputPollInterval );
		}
	}
	catch( ThreadAbortException^ )
	{
	}
	catch( ThreadInterruptedException^ )
	{
	}
}

// int sceCtrlSetSamplingCycle(int cycle); (/ctrl/pspctrl.h:119)
int sceCtrl::sceCtrlSetSamplingCycle( int cycle )
{
	int old = _sampleCycle;
	_sampleCycle = cycle;
	Debug::WriteLine( String::Format( "sceCtrlSetSamplingCycle: set to {0} (was {1})", cycle, old ) );

	return old;
}

// int sceCtrlGetSamplingCycle(int *pcycle); (/ctrl/pspctrl.h:128)
int sceCtrl::sceCtrlGetSamplingCycle( IMemory^ memory, int pcycle )
{
	if( pcycle != 0x0 )
		memory->WriteWord( pcycle, 4, _sampleCycle );

	return 0;
}

// int sceCtrlSetSamplingMode(int mode); (/ctrl/pspctrl.h:137)
int sceCtrl::sceCtrlSetSamplingMode( int mode )
{
	int old = ( int )_sampleMode;
	_sampleMode = ( ControlSamplingMode )mode;

	return old;
}

// int sceCtrlGetSamplingMode(int *pmode); (/ctrl/pspctrl.h:146)
int sceCtrl::sceCtrlGetSamplingMode( IMemory^ memory, int pmode )
{
	if( pmode != 0x0 )
		memory->WriteWord( pmode, 4, ( int )_sampleMode );

	return 0;
}

// int sceCtrlPeekBufferPositive(SceCtrlData *pad_data, int count); (/ctrl/pspctrl.h:148)
int sceCtrl::sceCtrlPeekBufferPositive( IMemory^ memory, int pad_data, int count )
{
	array<ControlSample^>^ samples;
	int toRead;
	Monitor::Enter( this );
	{
		toRead = MIN2( count, _buffer->Count );
		samples = gcnew array<ControlSample^>( toRead );
		for( int n = 0; n < toRead; n++ )
			samples[ n ] = _buffer->PeekAhead( n );
	}
	Monitor::Exit( this );

	if( pad_data != 0x0 )
	{
		int addr = pad_data;
		for( int n = 0; n < toRead; n++ )
		{
			ControlSample^ sample = samples[ n ];
			memory->WriteWord( addr + 0, 4, ( int )sample->Timestamp );
			memory->WriteWord( addr + 4, 4, ( int )sample->Buttons );
			memory->WriteWord( addr + 8, 1, ( byte )sample->AnalogX );
			memory->WriteWord( addr + 9, 1, ( byte )sample->AnalogY );
			// 6 bytes of junk
			addr += 16;
		}
	}

	return toRead;
}

// int sceCtrlPeekBufferNegative(SceCtrlData *pad_data, int count); (/ctrl/pspctrl.h:150)
int sceCtrl::sceCtrlPeekBufferNegative( IMemory^ memory, int pad_data, int count )
{
	// Same as above, but complement button mask

	array<ControlSample^>^ samples;
	int toRead;
	Monitor::Enter( this );
	{
		toRead = MIN2( count, _buffer->Count );
		samples = gcnew array<ControlSample^>( toRead );
		for( int n = 0; n < toRead; n++ )
			samples[ n ] = _buffer->PeekAhead( n );
	}
	Monitor::Exit( this );

	if( pad_data != 0x0 )
	{
		int addr = pad_data;
		for( int n = 0; n < toRead; n++ )
		{
			ControlSample^ sample = samples[ n ];
			memory->WriteWord( addr + 0, 4, ( int )sample->Timestamp );
			memory->WriteWord( addr + 4, 4, ~( int )sample->Buttons );
			memory->WriteWord( addr + 8, 1, ( byte )sample->AnalogX );
			memory->WriteWord( addr + 9, 1, ( byte )sample->AnalogY );
			// 6 bytes of junk
			addr += 16;
		}
	}

	return toRead;
}

// int sceCtrlReadBufferPositive(SceCtrlData *pad_data, int count); (/ctrl/pspctrl.h:168)
int sceCtrl::sceCtrlReadBufferPositive( IMemory^ memory, int pad_data, int count )
{
	array<ControlSample^>^ samples = gcnew array<ControlSample^>( count );
	int read = 0;
	while( read < count )
	{
		Monitor::Enter( this );
		if( _buffer->Count == 0 )
			_dataPresent->WaitOne( InputPollInterval * 2, true );
		while( ( _buffer->Count > 0 ) && ( read < count ) )
			samples[ read++ ] = _buffer->Dequeue();
		Monitor::Exit( this );
	}

	if( pad_data != 0x0 )
	{
		int addr = pad_data;
		for( int n = 0; n < read; n++ )
		{
			ControlSample^ sample = samples[ n ];
			memory->WriteWord( addr + 0, 4, ( int )sample->Timestamp );
			memory->WriteWord( addr + 4, 4, ( int )sample->Buttons );
			memory->WriteWord( addr + 8, 1, ( byte )sample->AnalogX );
			memory->WriteWord( addr + 9, 1, ( byte )sample->AnalogY );
			// 6 bytes of junk
			addr += 16;
		}
	}

	return read;
}

// int sceCtrlReadBufferNegative(SceCtrlData *pad_data, int count); (/ctrl/pspctrl.h:170)
int sceCtrl::sceCtrlReadBufferNegative( IMemory^ memory, int pad_data, int count )
{
	array<ControlSample^>^ samples = gcnew array<ControlSample^>( count );
	int read = 0;
	while( read < count )
	{
		Monitor::Enter( this );
		if( _buffer->Count == 0 )
			_dataPresent->WaitOne( InputPollInterval * 2, true );
		while( _buffer->Count > 0 )
			samples[ read++ ] = _buffer->Dequeue();
		Monitor::Exit( this );
	}

	if( pad_data != 0x0 )
	{
		int addr = pad_data;
		for( int n = 0; n < read; n++ )
		{
			ControlSample^ sample = samples[ n ];
			memory->WriteWord( addr + 0, 4, ( int )sample->Timestamp );
			memory->WriteWord( addr + 4, 4, ~( int )sample->Buttons );
			memory->WriteWord( addr + 8, 1, ( byte )sample->AnalogX );
			memory->WriteWord( addr + 9, 1, ( byte )sample->AnalogY );
			// 6 bytes of junk
			addr += 16;
		}
	}

	return read;
}

//typedef struct SceCtrlLatch {
//	unsigned int 	uiMake;		// keys pressed since last reading
//	unsigned int 	uiBreak;	// keys released since last reading
//	unsigned int 	uiPress;	// bitmask of pressed keys?
//	unsigned int 	uiRelease;	// bitmask of released keys?
//} SceCtrlLatch;

// int sceCtrlPeekLatch(SceCtrlLatch *latch_data); (/ctrl/pspctrl.h:172)
int sceCtrl::sceCtrlPeekLatch( IMemory^ memory, int latch_data )
{
	memory->WriteWord( latch_data + 0, 4, _makedButtons );
	memory->WriteWord( latch_data + 4, 4, _breakedButtons );
	memory->WriteWord( latch_data + 8, 4, _pressedButtons );
	memory->WriteWord( latch_data + 12, 4, ~_pressedButtons );

	return 0;
}

// int sceCtrlReadLatch(SceCtrlLatch *latch_data); (/ctrl/pspctrl.h:174)
int sceCtrl::sceCtrlReadLatch( IMemory^ memory, int latch_data )
{
	memory->WriteWord( latch_data + 0, 4, _makedButtons );
	memory->WriteWord( latch_data + 4, 4, _breakedButtons );
	memory->WriteWord( latch_data + 8, 4, _pressedButtons );
	memory->WriteWord( latch_data + 12, 4, ~_pressedButtons );

	_makedButtons = 0;
	_breakedButtons = 0;

	return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xmlStyleImport.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 14:09:16 $
 *
 *  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
 *
 ************************************************************************/

#ifndef DBA_XMLSTYLEIMPORT_HXX
#define DBA_XMLSTYLEIMPORT_HXX

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _XMLOFF_XMLIMP_HXX
#include <xmloff/xmlimp.hxx>
#endif
#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif
#ifndef _XMLOFF_PROPMAPPINGTYPES_HXX
#include <xmloff/maptype.hxx>
#endif
#ifndef _XMLOFF_PRSTYLEI_HXX_
#include <xmloff/prstylei.hxx>
#endif
#ifndef _XMLOFF_XMLIMPPR_HXX
#include <xmloff/xmlimppr.hxx>
#endif
#ifndef _XMLTEXTMASTERPAGECONTEXT_HXX
#include <xmloff/XMLTextMasterPageContext.hxx>
#endif
#ifndef _XMLTEXTMASTERSTYLESCONTEXT_HXX
#include <xmloff/XMLTextMasterStylesContext.hxx>
#endif
#ifndef _XMLOFF_CONTEXTID_HXX_
#include <xmloff/contextid.hxx>
#endif
#ifndef _XMLOFF_FORMS_CONTROLPROPERTYHDL_HXX_
#include <xmloff/controlpropertyhdl.hxx>
#endif
#include <vector>

namespace dbaxml
{
    class ODBFilter;

    class OTableStyleContext : public XMLPropStyleContext
    {
        ::rtl::OUString             m_sDataStyleName;
        ::rtl::OUString             sPageStyle;
        const rtl::OUString         sNumberFormat;
        SvXMLStylesContext*         pStyles;
        //  std::vector<ScXMLMapContent>    aMaps;
        com::sun::star::uno::Any    aConditionalFormat;
        sal_Int32                   m_nNumberFormat;
        sal_Bool                    bConditionalFormatCreated : 1;
        sal_Bool                    bParentSet : 1;

        ODBFilter& GetOwnImport();

    protected:

        virtual void SetAttribute( sal_uInt16 nPrefixKey,
                                const ::rtl::OUString& rLocalName,
                                const ::rtl::OUString& rValue );

    public:

        TYPEINFO();

        OTableStyleContext( ODBFilter& rImport, sal_uInt16 nPrfx,
                const ::rtl::OUString& rLName,
                const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList,
                SvXMLStylesContext& rStyles, sal_uInt16 nFamily, sal_Bool bDefaultStyle = sal_False );

        virtual ~OTableStyleContext();

        virtual void FillPropertySet(const ::com::sun::star::uno::Reference<
                    ::com::sun::star::beans::XPropertySet > & rPropSet );

        virtual void SetDefaults();

          void AddProperty(sal_Int16 nContextID, const com::sun::star::uno::Any& aValue);

        sal_Int32 GetNumberFormat() { return m_nNumberFormat; }
    };

    class OTableStylesContext : public SvXMLStylesContext
    {
        const ::rtl::OUString sColumnStyleServiceName;
        const ::rtl::OUString sTableStyleServiceName;
        sal_Int32 m_nNumberFormatIndex;
        sal_Int32 nMasterPageNameIndex;
        sal_Bool bAutoStyles : 1;

        mutable UniReference < SvXMLImportPropertyMapper > m_xColumnImpPropMapper;
        mutable UniReference < SvXMLImportPropertyMapper > m_xTableImpPropMapper;

        ODBFilter& GetOwnImport();

    protected:

        // Create a style context.
        virtual SvXMLStyleContext *CreateStyleStyleChildContext(
                sal_uInt16 nFamily,
                sal_uInt16 nPrefix,
                const ::rtl::OUString& rLocalName,
                const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList );

    public:

        TYPEINFO();

        OTableStylesContext( SvXMLImport& rImport, sal_uInt16 nPrfx ,
                const ::rtl::OUString& rLName ,
                const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList,
                const sal_Bool bAutoStyles );
        virtual ~OTableStylesContext();

        virtual void EndElement();

        virtual UniReference < SvXMLImportPropertyMapper > GetImportPropertyMapper(
                            sal_uInt16 nFamily ) const;
        virtual ::com::sun::star::uno::Reference <
                        ::com::sun::star::container::XNameContainer >
            GetStylesContainer( sal_uInt16 nFamily ) const;
        virtual ::rtl::OUString GetServiceName( sal_uInt16 nFamily ) const;

        sal_Int32 GetIndex(const sal_Int16 nContextID);
    };
// -----------------------------------------------------------------------------
} // dbaxml
// -----------------------------------------------------------------------------
#endif // DBA_XMLSTYLEIMPORT_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.3.432); FILE MERGED 2008/03/31 13:26:56 rt 1.3.432.1: #i87441# Change license header to LPGL v3.<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: xmlStyleImport.hxx,v $
 * $Revision: 1.4 $
 *
 * 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.
 *
 ************************************************************************/

#ifndef DBA_XMLSTYLEIMPORT_HXX
#define DBA_XMLSTYLEIMPORT_HXX

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _XMLOFF_XMLIMP_HXX
#include <xmloff/xmlimp.hxx>
#endif
#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif
#ifndef _XMLOFF_PROPMAPPINGTYPES_HXX
#include <xmloff/maptype.hxx>
#endif
#ifndef _XMLOFF_PRSTYLEI_HXX_
#include <xmloff/prstylei.hxx>
#endif
#ifndef _XMLOFF_XMLIMPPR_HXX
#include <xmloff/xmlimppr.hxx>
#endif
#ifndef _XMLTEXTMASTERPAGECONTEXT_HXX
#include <xmloff/XMLTextMasterPageContext.hxx>
#endif
#ifndef _XMLTEXTMASTERSTYLESCONTEXT_HXX
#include <xmloff/XMLTextMasterStylesContext.hxx>
#endif
#ifndef _XMLOFF_CONTEXTID_HXX_
#include <xmloff/contextid.hxx>
#endif
#ifndef _XMLOFF_FORMS_CONTROLPROPERTYHDL_HXX_
#include <xmloff/controlpropertyhdl.hxx>
#endif
#include <vector>

namespace dbaxml
{
    class ODBFilter;

    class OTableStyleContext : public XMLPropStyleContext
    {
        ::rtl::OUString             m_sDataStyleName;
        ::rtl::OUString             sPageStyle;
        const rtl::OUString         sNumberFormat;
        SvXMLStylesContext*         pStyles;
        //  std::vector<ScXMLMapContent>    aMaps;
        com::sun::star::uno::Any    aConditionalFormat;
        sal_Int32                   m_nNumberFormat;
        sal_Bool                    bConditionalFormatCreated : 1;
        sal_Bool                    bParentSet : 1;

        ODBFilter& GetOwnImport();

    protected:

        virtual void SetAttribute( sal_uInt16 nPrefixKey,
                                const ::rtl::OUString& rLocalName,
                                const ::rtl::OUString& rValue );

    public:

        TYPEINFO();

        OTableStyleContext( ODBFilter& rImport, sal_uInt16 nPrfx,
                const ::rtl::OUString& rLName,
                const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList,
                SvXMLStylesContext& rStyles, sal_uInt16 nFamily, sal_Bool bDefaultStyle = sal_False );

        virtual ~OTableStyleContext();

        virtual void FillPropertySet(const ::com::sun::star::uno::Reference<
                    ::com::sun::star::beans::XPropertySet > & rPropSet );

        virtual void SetDefaults();

          void AddProperty(sal_Int16 nContextID, const com::sun::star::uno::Any& aValue);

        sal_Int32 GetNumberFormat() { return m_nNumberFormat; }
    };

    class OTableStylesContext : public SvXMLStylesContext
    {
        const ::rtl::OUString sColumnStyleServiceName;
        const ::rtl::OUString sTableStyleServiceName;
        sal_Int32 m_nNumberFormatIndex;
        sal_Int32 nMasterPageNameIndex;
        sal_Bool bAutoStyles : 1;

        mutable UniReference < SvXMLImportPropertyMapper > m_xColumnImpPropMapper;
        mutable UniReference < SvXMLImportPropertyMapper > m_xTableImpPropMapper;

        ODBFilter& GetOwnImport();

    protected:

        // Create a style context.
        virtual SvXMLStyleContext *CreateStyleStyleChildContext(
                sal_uInt16 nFamily,
                sal_uInt16 nPrefix,
                const ::rtl::OUString& rLocalName,
                const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList );

    public:

        TYPEINFO();

        OTableStylesContext( SvXMLImport& rImport, sal_uInt16 nPrfx ,
                const ::rtl::OUString& rLName ,
                const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList,
                const sal_Bool bAutoStyles );
        virtual ~OTableStylesContext();

        virtual void EndElement();

        virtual UniReference < SvXMLImportPropertyMapper > GetImportPropertyMapper(
                            sal_uInt16 nFamily ) const;
        virtual ::com::sun::star::uno::Reference <
                        ::com::sun::star::container::XNameContainer >
            GetStylesContainer( sal_uInt16 nFamily ) const;
        virtual ::rtl::OUString GetServiceName( sal_uInt16 nFamily ) const;

        sal_Int32 GetIndex(const sal_Int16 nContextID);
    };
// -----------------------------------------------------------------------------
} // dbaxml
// -----------------------------------------------------------------------------
#endif // DBA_XMLSTYLEIMPORT_HXX
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: TableDesignControl.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 03:13: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
 *
 ************************************************************************/
#ifndef DBAUI_TABLEDESIGNCONTROL_HXX
#define DBAUI_TABLEDESIGNCONTROL_HXX

#ifndef _TABBAR_HXX //autogen
#include <svtools/tabbar.hxx>
#endif
#ifndef _SVTOOLS_EDITBROWSEBOX_HXX_
#include <svtools/editbrowsebox.hxx>
#endif

#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef DBACCESS_TABLEDESIGN_ICLIPBOARDTEST_HXX
#include "IClipBoardTest.hxx"
#endif
#ifndef DBAUI_TYPEINFO_HXX
#include "TypeInfo.hxx"
#endif

#define TABPAGESIZE 70
namespace dbaui
{
    class OTableDesignView;
    class OTypeInfo;
    //==================================================================
    class OTableRowView : public ::svt::EditBrowseBox
                        ,public IClipboardTest
    {
        friend class OTableDesignUndoAct;

    protected:
        long    m_nDataPos;             // derzeit benoetigte Zeile
        long    m_nCurrentPos;          // Aktuelle Position der ausgewaehlten Column
    private:
        USHORT  m_nCurUndoActId;
    protected:
        BOOL    m_bCurrentModified;
        BOOL    m_bUpdatable;
        BOOL    m_bClipboardFilled;

    public:
        OTableRowView(Window* pParent);
        virtual ~OTableRowView();

        virtual void                SetCellData( long nRow, USHORT nColId, const TOTypeInfoSP& _pTypeInfo ) = 0;
        virtual void                SetCellData( long nRow, USHORT nColId, const ::com::sun::star::uno::Any& _rNewData ) = 0;
        virtual ::com::sun::star::uno::Any          GetCellData( long nRow, USHORT nColId ) = 0;
        virtual void                SetControlText( long nRow, USHORT nColId, const String& rText ) = 0;
        virtual String              GetControlText( long nRow, USHORT nColId ) = 0;

        virtual OTableDesignView* GetView() const = 0;

        USHORT  GetCurUndoActId(){ return m_nCurUndoActId; }

        // IClipboardTest
        virtual void cut();
        virtual void copy();
        virtual void paste();

    protected:
        void Paste( long nRow );

        virtual void CopyRows()                             = 0;
        virtual void DeleteRows()                           = 0;
        virtual void InsertRows( long nRow )                = 0;
        virtual void InsertNewRows( long nRow )             = 0;

        virtual sal_Bool IsPrimaryKeyAllowed( long nRow )   = 0;
        virtual sal_Bool IsInsertNewAllowed( long nRow )    = 0;
        virtual sal_Bool IsDeleteAllowed( long nRow )       = 0;

        virtual BOOL IsUpdatable() const {return m_bUpdatable;}
        virtual void SetUpdatable( BOOL bUpdate=TRUE );

        virtual RowStatus GetRowStatus(long nRow) const;
        virtual void KeyInput(const KeyEvent& rEvt);
        virtual void Command( const CommandEvent& rEvt );

        virtual void Init();
    };
}
#endif // DBAUI_TABLEDESIGNCONTROL_HXX

<commit_msg>INTEGRATION: CWS oj14 (1.7.8); FILE MERGED 2006/07/04 08:05:05 oj 1.7.8.4: RESYNC: (1.7-1.8); FILE MERGED 2006/04/25 13:03:06 oj 1.7.8.3: new include 2006/03/20 07:48:37 oj 1.7.8.2: use of module client helper 2006/01/03 07:49:14 oj 1.7.8.1: changed module client<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: TableDesignControl.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: rt $ $Date: 2007-07-06 08:24:54 $
 *
 *  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
 *
 ************************************************************************/
#ifndef DBAUI_TABLEDESIGNCONTROL_HXX
#define DBAUI_TABLEDESIGNCONTROL_HXX

#ifndef _TABBAR_HXX //autogen
#include <svtools/tabbar.hxx>
#endif
#ifndef _SVTOOLS_EDITBROWSEBOX_HXX_
#include <svtools/editbrowsebox.hxx>
#endif

#ifndef DBACCESS_TABLEDESIGN_ICLIPBOARDTEST_HXX
#include "IClipBoardTest.hxx"
#endif
#ifndef DBAUI_TYPEINFO_HXX
#include "TypeInfo.hxx"
#endif

#define TABPAGESIZE 70
namespace dbaui
{
    class OTableDesignView;
    class OTypeInfo;
    //==================================================================
    class OTableRowView : public ::svt::EditBrowseBox
                        ,public IClipboardTest
    {
        friend class OTableDesignUndoAct;

    protected:
        long    m_nDataPos;             // derzeit benoetigte Zeile
        long    m_nCurrentPos;          // Aktuelle Position der ausgewaehlten Column
    private:
        USHORT  m_nCurUndoActId;
    protected:
        BOOL    m_bCurrentModified;
        BOOL    m_bUpdatable;
        BOOL    m_bClipboardFilled;

    public:
        OTableRowView(Window* pParent);
        virtual ~OTableRowView();

        virtual void                SetCellData( long nRow, USHORT nColId, const TOTypeInfoSP& _pTypeInfo ) = 0;
        virtual void                SetCellData( long nRow, USHORT nColId, const ::com::sun::star::uno::Any& _rNewData ) = 0;
        virtual ::com::sun::star::uno::Any          GetCellData( long nRow, USHORT nColId ) = 0;
        virtual void                SetControlText( long nRow, USHORT nColId, const String& rText ) = 0;
        virtual String              GetControlText( long nRow, USHORT nColId ) = 0;

        virtual OTableDesignView* GetView() const = 0;

        USHORT  GetCurUndoActId(){ return m_nCurUndoActId; }

        // IClipboardTest
        virtual void cut();
        virtual void copy();
        virtual void paste();

    protected:
        void Paste( long nRow );

        virtual void CopyRows()                             = 0;
        virtual void DeleteRows()                           = 0;
        virtual void InsertRows( long nRow )                = 0;
        virtual void InsertNewRows( long nRow )             = 0;

        virtual sal_Bool IsPrimaryKeyAllowed( long nRow )   = 0;
        virtual sal_Bool IsInsertNewAllowed( long nRow )    = 0;
        virtual sal_Bool IsDeleteAllowed( long nRow )       = 0;

        virtual BOOL IsUpdatable() const {return m_bUpdatable;}
        virtual void SetUpdatable( BOOL bUpdate=TRUE );

        virtual RowStatus GetRowStatus(long nRow) const;
        virtual void KeyInput(const KeyEvent& rEvt);
        virtual void Command( const CommandEvent& rEvt );

        virtual void Init();
    };
}
#endif // DBAUI_TABLEDESIGNCONTROL_HXX

<|endoftext|>


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

////////////////////////////////////////////////////
// AliAnalysisTaskFlowEvent:
//
// analysis task for filling the flow event
// from MCEvent, ESD, AOD ....
// and put it in an output stream so it can
// be used by the various flow analysis methods
// for cuts the correction framework is used
// which also outputs QA histograms to view
// the effects of the cuts
////////////////////////////////////////////////////

#include "Riostream.h" //needed as include
#include "TChain.h"
#include "TTree.h"
#include "TFile.h" //needed as include
#include "TList.h"
#include "TRandom3.h"
#include "TTimeStamp.h"

// ALICE Analysis Framework
#include "AliAnalysisManager.h"
#include "AliAnalysisTaskSE.h"

// ESD interface
#include "AliESDEvent.h"
#include "AliESDInputHandler.h"

// AOD interface
#include "AliAODEvent.h"
#include "AliAODInputHandler.h"

// Monte Carlo Event
#include "AliMCEventHandler.h"
#include "AliMCEvent.h"

// ALICE Correction Framework
#include "AliCFManager.h"

// Interface to Event generators to get Reaction Plane Angle
#include "AliGenCocktailEventHeader.h"
#include "AliGenHijingEventHeader.h"
#include "AliGenGeVSimEventHeader.h"
#include "AliGenEposEventHeader.h"

// Interface to make the Flow Event Simple used in the flow analysis methods
#include "AliFlowEvent.h"

#include "AliAnalysisTaskFlowEvent.h"

#include "AliLog.h"

ClassImp(AliAnalysisTaskFlowEvent)

//________________________________________________________________________
AliAnalysisTaskFlowEvent::AliAnalysisTaskFlowEvent() :
  AliAnalysisTaskSE(),
  //  fOutputFile(NULL),
  fAnalysisType("ESD"),
  fCFManager1(NULL),
  fCFManager2(NULL),
  fQAInt(NULL),
  fQADiff(NULL),
  fMinMult(0),
  fMaxMult(10000000),
  fMinA(-1.0),
  fMaxA(-0.01),
  fMinB(0.01),
  fMaxB(1.0),
  fQA(kFALSE),
  fMCReactionPlaneAngle(0.),
  fCount(0),
  fNoOfLoops(1),
  fEllipticFlowValue(0.),
  fSigmaEllipticFlowValue(0.),
  fMultiplicityOfEvent(1000000000),
  fSigmaMultiplicityOfEvent(0),
  fMyTRandom3(NULL),
  fbAfterburnerOn(kFALSE)
{
  // Constructor
  cout<<"AliAnalysisTaskFlowEvent::AliAnalysisTaskFlowEvent()"<<endl;
}

//________________________________________________________________________
AliAnalysisTaskFlowEvent::AliAnalysisTaskFlowEvent(const char *name, Bool_t on, UInt_t iseed) :
  AliAnalysisTaskSE(name),
  //  fOutputFile(NULL),
  fAnalysisType("ESD"),
  fCFManager1(NULL),
  fCFManager2(NULL),
  fQAInt(NULL),
  fQADiff(NULL),
  fMinMult(0),
  fMaxMult(10000000),
  fMinA(-1.0),
  fMaxA(-0.01),
  fMinB(0.01),
  fMaxB(1.0),
  fQA(on),
  fMCReactionPlaneAngle(0.),
  fCount(0),
  fNoOfLoops(1),
  fEllipticFlowValue(0.),
  fSigmaEllipticFlowValue(0.),
  fMultiplicityOfEvent(1000000000),
  fSigmaMultiplicityOfEvent(0),
  fMyTRandom3(NULL),
  fbAfterburnerOn(kFALSE)
{
  // Constructor
  cout<<"AliAnalysisTaskFlowEvent::AliAnalysisTaskFlowEvent(const char *name, Bool_t on, UInt_t iseed)"<<endl;
  fMyTRandom3 = new TRandom3(iseed);
  gRandom->SetSeed(fMyTRandom3->Integer(65539));

  // Define output slots here
  // Define here the flow event output
  DefineOutput(1, AliFlowEventSimple::Class());
  if(on)
  {
    DefineOutput(2, TList::Class());
    DefineOutput(3, TList::Class());
  }
  // and for testing open an output file
  //  fOutputFile = new TFile("FlowEvents.root","RECREATE");

}

//________________________________________________________________________
AliAnalysisTaskFlowEvent::~AliAnalysisTaskFlowEvent()
{
  //
  // Destructor
  //
  if (fMyTRandom3) delete fMyTRandom3;
  // objects in the output list are deleted
  // by the TSelector dtor (I hope)

}

//________________________________________________________________________
void AliAnalysisTaskFlowEvent::UserCreateOutputObjects()
{
  // Called at every worker node to initialize
  cout<<"AliAnalysisTaskFlowEvent::CreateOutputObjects()"<<endl;

  if (!(fAnalysisType == "AOD" || fAnalysisType == "ESD" || fAnalysisType == "ESDMCkineESD"  || fAnalysisType == "ESDMCkineMC" || fAnalysisType == "MC"))
  {
    AliError("WRONG ANALYSIS TYPE! only ESD, ESDMCkineESD, ESDMCkineMC, AOD and MC are allowed.");
    exit(1);
  }
}

//________________________________________________________________________
void AliAnalysisTaskFlowEvent::UserExec(Option_t *)
{
  // Main loop
  // Called for each event
  AliFlowEvent* flowEvent = NULL;
  AliMCEvent*  mcEvent = MCEvent();                              // from TaskSE
  AliESDEvent* myESD = dynamic_cast<AliESDEvent*>(InputEvent()); // from TaskSE
  AliAODEvent* myAOD = dynamic_cast<AliAODEvent*>(InputEvent()); // from TaskSE

  // Make the FlowEvent for MC input
  if (fAnalysisType == "MC")
  {
    // Process MC truth, therefore we receive the AliAnalysisManager and ask it for the AliMCEventHandler
    // This handler can return the current MC event
    if (!(fCFManager1&&fCFManager2))
    {
      AliError("ERROR: No pointer to correction framework cuts! ");
      return;
    }
    if (!mcEvent)
    {
      AliError("ERROR: Could not retrieve MC event");
      return;
    }

    fCFManager1->SetMCEventInfo(mcEvent);
    fCFManager2->SetMCEventInfo(mcEvent);

    AliInfo(Form("Number of MC particles: %d", mcEvent->GetNumberOfTracks()));

    //check multiplicity
    if (!fCFManager1->CheckEventCuts(AliCFManager::kEvtGenCuts,mcEvent))
    {
      AliWarning("Event does not pass multiplicity cuts"); return;
    }
    //make event
    flowEvent = new AliFlowEvent(mcEvent,fCFManager1,fCFManager2);
  }
  // Make the FlowEvent for ESD input
  else if (fAnalysisType == "ESD")
  {
    if (!(fCFManager1&&fCFManager2))
    {
      AliError("ERROR: No pointer to correction framework cuts!");
      return;
    }
    if (!myESD)
    {
      AliError("ERROR: ESD not available");
      return;
    }

    //check the offline trigger (check if the event has the correct trigger)
    AliInfo(Form("There are %d tracks in this event", fInputEvent->GetNumberOfTracks()));

    //check multiplicity
    if (!fCFManager1->CheckEventCuts(AliCFManager::kEvtRecCuts,myESD))
    {
      AliWarning("Event does not pass multiplicity cuts"); return;
    }

    //make event
    flowEvent = new AliFlowEvent(myESD,fCFManager1,fCFManager2);
  }
  // Make the FlowEvent for ESD input combined with MC info
  else if (fAnalysisType == "ESDMCkineESD" || fAnalysisType == "ESDMCkineMC" )
  {
    if (!(fCFManager1&&fCFManager2))
    {
      AliError("ERROR: No pointer to correction framework cuts! ");
      return;
    }
    if (!myESD)
    {
      AliError("ERROR: ESD not available");
      return;
    }
    AliInfo(Form("There are %d tracks in this event", fInputEvent->GetNumberOfTracks()));

    if (!mcEvent)
    {
      AliError("ERROR: Could not retrieve MC event");
      return;
    }

    fCFManager1->SetMCEventInfo(mcEvent);
    fCFManager2->SetMCEventInfo(mcEvent);

    //check multiplicity
    if (!fCFManager1->CheckEventCuts(AliCFManager::kEvtRecCuts,myESD))
    {
      AliWarning("Event does not pass multiplicity cuts"); return;
    }

    //make event
    if (fAnalysisType == "ESDMCkineESD")
    {
      flowEvent = new AliFlowEvent(myESD, mcEvent, AliFlowEvent::kESDkine, fCFManager1, fCFManager2 );
    }
    else if (fAnalysisType == "ESDMCkineMC")
    {
      flowEvent = new AliFlowEvent(myESD, mcEvent, AliFlowEvent::kMCkine, fCFManager1, fCFManager2 );
    }
  }
  // Make the FlowEventSimple for AOD input
  else if (fAnalysisType == "AOD")
  {
    if (!myAOD)
    {
      AliError("ERROR: AOD not available");
      return;
    }
    AliInfo(Form("There are %d tracks in this event", myAOD->GetNumberOfTracks()));
    flowEvent = new AliFlowEvent(myAOD);
  }

  //check final event cuts
  Int_t mult = flowEvent->NumberOfTracks();
  if (mult<fMinMult && mult>fMaxMult)
  {
    AliWarning("FlowEvent cut on multiplicity"); return;
  }

  //tag subevents
  flowEvent->TagSubeventsInEta(fMinA,fMaxA,fMinB,fMaxB);

  ////TODO afterburner
  //if (fbAfterburnerOn && fMyTRandom3) {
  //  // set the new value of the values using a after burner
  //  cout << "settings for afterburner in TaskFlowEvent.cxx:" << endl;
  //  cout << "fCount = " << fCount << endl;
  //  cout << "fNoOfLoops = " << fNoOfLoops << endl;
  //  cout << "fEllipticFlowValue = " << fEllipticFlowValue << endl;
  //  cout << "fSigmaEllipticFlowValue = " << fSigmaEllipticFlowValue << endl;
  //  cout << "fMultiplicityOflowEvent = " << fMultiplicityOflowEvent << endl;
  //  cout << "fSigmaMultiplicityOflowEvent = " << fSigmaMultiplicityOflowEvent << endl;
  //  Double_t xRPangle;
  //  if (!mcEvent) { xRPangle = TMath::TwoPi()*(fMyTRandom3->Rndm()); }
  //  else { xRPangle = fRP; }
  //  Double_t xNewFlowValue = fMyTRandom3->Gaus(fEllipticFlowValue,fSigmaEllipticFlowValue);
  //  Int_t nNewMultOflowEvent =  TMath::Nint(fMyTRandom3->Gaus(fMultiplicityOflowEvent,fSigmaMultiplicityOflowEvent));
  //  cout << "xRPangle = " << xRPangle << endl;
  //  cout << "xNewFlowValue = " << xNewFlowValue << endl;
  //  cout << "nNewMultOflowEvent = " << nNewMultOflowEvent << endl;
  //  cout << "settings for after burner" << endl;
  //  flowEventMaker->SetMCReactionPlaneAngle(xRPangle);
  //  flowEventMaker->SetNoOfLoops(fNoOfLoops);
  //  flowEventMaker->SetEllipticFlowValue(xNewFlowValue);
  //  flowEventMaker->SetMultiplicityOflowEvent(nNewMultOflowEvent);
  //  //end settings afterburner
  //}

  // if monte carlo event get reaction plane from monte carlo (depends on generator)
  if (mcEvent && mcEvent->GenEventHeader()) flowEvent->SetMCReactionPlaneAngle(mcEvent);

  //fListHistos->Print();
  //  fOutputFile->WriteObject(flowEvent,"myFlowEventSimple");
  PostData(1,flowEvent);
  if (fQA)
  {
    PostData(2,fQAInt);
    PostData(3,fQADiff);
  }
}

//________________________________________________________________________
void AliAnalysisTaskFlowEvent::Terminate(Option_t *)
{
  // Called once at the end of the query -- do not call in case of CAF
}

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

////////////////////////////////////////////////////
// AliAnalysisTaskFlowEvent:
//
// analysis task for filling the flow event
// from MCEvent, ESD, AOD ....
// and put it in an output stream so it can
// be used by the various flow analysis methods
// for cuts the correction framework is used
// which also outputs QA histograms to view
// the effects of the cuts
////////////////////////////////////////////////////

#include "Riostream.h" //needed as include
#include "TChain.h"
#include "TTree.h"
#include "TFile.h" //needed as include
#include "TList.h"
#include "TRandom3.h"
#include "TTimeStamp.h"

// ALICE Analysis Framework
#include "AliAnalysisManager.h"
#include "AliAnalysisTaskSE.h"

// ESD interface
#include "AliESDEvent.h"
#include "AliESDInputHandler.h"

// AOD interface
#include "AliAODEvent.h"
#include "AliAODInputHandler.h"

// Monte Carlo Event
#include "AliMCEventHandler.h"
#include "AliMCEvent.h"

// ALICE Correction Framework
#include "AliCFManager.h"

// Interface to Event generators to get Reaction Plane Angle
#include "AliGenCocktailEventHeader.h"
#include "AliGenHijingEventHeader.h"
#include "AliGenGeVSimEventHeader.h"
#include "AliGenEposEventHeader.h"

// Interface to make the Flow Event Simple used in the flow analysis methods
#include "AliFlowEvent.h"

#include "AliAnalysisTaskFlowEvent.h"

#include "AliLog.h"

ClassImp(AliAnalysisTaskFlowEvent)

//________________________________________________________________________
AliAnalysisTaskFlowEvent::AliAnalysisTaskFlowEvent() :
  AliAnalysisTaskSE(),
  //  fOutputFile(NULL),
  fAnalysisType("ESD"),
  fCFManager1(NULL),
  fCFManager2(NULL),
  fQAInt(NULL),
  fQADiff(NULL),
  fMinMult(0),
  fMaxMult(10000000),
  fMinA(-1.0),
  fMaxA(-0.01),
  fMinB(0.01),
  fMaxB(1.0),
  fQA(kFALSE),
  fMCReactionPlaneAngle(0.),
  fCount(0),
  fNoOfLoops(1),
  fEllipticFlowValue(0.),
  fSigmaEllipticFlowValue(0.),
  fMultiplicityOfEvent(1000000000),
  fSigmaMultiplicityOfEvent(0),
  fMyTRandom3(NULL),
  fbAfterburnerOn(kFALSE)
{
  // Constructor
  cout<<"AliAnalysisTaskFlowEvent::AliAnalysisTaskFlowEvent()"<<endl;
}

//________________________________________________________________________
AliAnalysisTaskFlowEvent::AliAnalysisTaskFlowEvent(const char *name, Bool_t on, UInt_t iseed) :
  AliAnalysisTaskSE(name),
  //  fOutputFile(NULL),
  fAnalysisType("ESD"),
  fCFManager1(NULL),
  fCFManager2(NULL),
  fQAInt(NULL),
  fQADiff(NULL),
  fMinMult(0),
  fMaxMult(10000000),
  fMinA(-1.0),
  fMaxA(-0.01),
  fMinB(0.01),
  fMaxB(1.0),
  fQA(on),
  fMCReactionPlaneAngle(0.),
  fCount(0),
  fNoOfLoops(1),
  fEllipticFlowValue(0.),
  fSigmaEllipticFlowValue(0.),
  fMultiplicityOfEvent(1000000000),
  fSigmaMultiplicityOfEvent(0),
  fMyTRandom3(NULL),
  fbAfterburnerOn(kFALSE)
{
  // Constructor
  cout<<"AliAnalysisTaskFlowEvent::AliAnalysisTaskFlowEvent(const char *name, Bool_t on, UInt_t iseed)"<<endl;
  fMyTRandom3 = new TRandom3(iseed);
  gRandom->SetSeed(fMyTRandom3->Integer(65539));

  // Define output slots here
  // Define here the flow event output
  DefineOutput(1, AliFlowEventSimple::Class());
  if(on)
  {
    DefineOutput(2, TList::Class());
    DefineOutput(3, TList::Class());
  }
  // and for testing open an output file
  //  fOutputFile = new TFile("FlowEvents.root","RECREATE");

}

//________________________________________________________________________
AliAnalysisTaskFlowEvent::~AliAnalysisTaskFlowEvent()
{
  //
  // Destructor
  //
  if (fMyTRandom3) delete fMyTRandom3;
  // objects in the output list are deleted
  // by the TSelector dtor (I hope)

}

//________________________________________________________________________
void AliAnalysisTaskFlowEvent::UserCreateOutputObjects()
{
  // Called at every worker node to initialize
  cout<<"AliAnalysisTaskFlowEvent::CreateOutputObjects()"<<endl;

  if (!(fAnalysisType == "AOD" || fAnalysisType == "ESD" || fAnalysisType == "ESDMCkineESD"  || fAnalysisType == "ESDMCkineMC" || fAnalysisType == "MC"))
  {
    AliError("WRONG ANALYSIS TYPE! only ESD, ESDMCkineESD, ESDMCkineMC, AOD and MC are allowed.");
    exit(1);
  }
}

//________________________________________________________________________
void AliAnalysisTaskFlowEvent::UserExec(Option_t *)
{
  // Main loop
  // Called for each event
  AliFlowEvent* flowEvent = NULL;
  AliMCEvent*  mcEvent = MCEvent();                              // from TaskSE
  AliESDEvent* myESD = dynamic_cast<AliESDEvent*>(InputEvent()); // from TaskSE
  AliAODEvent* myAOD = dynamic_cast<AliAODEvent*>(InputEvent()); // from TaskSE

  // Make the FlowEvent for MC input
  if (fAnalysisType == "MC")
  {
    // Process MC truth, therefore we receive the AliAnalysisManager and ask it for the AliMCEventHandler
    // This handler can return the current MC event
    if (!(fCFManager1&&fCFManager2))
    {
      AliError("ERROR: No pointer to correction framework cuts! ");
      return;
    }
    if (!mcEvent)
    {
      AliError("ERROR: Could not retrieve MC event");
      return;
    }

    fCFManager1->SetMCEventInfo(mcEvent);
    fCFManager2->SetMCEventInfo(mcEvent);

    AliInfo(Form("Number of MC particles: %d", mcEvent->GetNumberOfTracks()));

    //check multiplicity
    if (!fCFManager1->CheckEventCuts(AliCFManager::kEvtGenCuts,mcEvent))
    {
      AliWarning("Event does not pass multiplicity cuts"); return;
    }
    //make event
    flowEvent = new AliFlowEvent(mcEvent,fCFManager1,fCFManager2);
  }
  // Make the FlowEvent for ESD input
  else if (fAnalysisType == "ESD")
  {
    if (!(fCFManager1&&fCFManager2))
    {
      AliError("ERROR: No pointer to correction framework cuts!");
      return;
    }
    if (!myESD)
    {
      AliError("ERROR: ESD not available");
      return;
    }

    //check the offline trigger (check if the event has the correct trigger)
    AliInfo(Form("ESD has %d tracks", fInputEvent->GetNumberOfTracks()));

    //check multiplicity
    if (!fCFManager1->CheckEventCuts(AliCFManager::kEvtRecCuts,myESD))
    {
      AliWarning("Event does not pass multiplicity cuts"); return;
    }

    //make event
    flowEvent = new AliFlowEvent(myESD,fCFManager1,fCFManager2);
  }
  // Make the FlowEvent for ESD input combined with MC info
  else if (fAnalysisType == "ESDMCkineESD" || fAnalysisType == "ESDMCkineMC" )
  {
    if (!(fCFManager1&&fCFManager2))
    {
      AliError("ERROR: No pointer to correction framework cuts! ");
      return;
    }
    if (!myESD)
    {
      AliError("ERROR: ESD not available");
      return;
    }
    AliInfo(Form("There are %d tracks in this event", fInputEvent->GetNumberOfTracks()));

    if (!mcEvent)
    {
      AliError("ERROR: Could not retrieve MC event");
      return;
    }

    fCFManager1->SetMCEventInfo(mcEvent);
    fCFManager2->SetMCEventInfo(mcEvent);

    //check multiplicity
    if (!fCFManager1->CheckEventCuts(AliCFManager::kEvtRecCuts,myESD))
    {
      AliWarning("Event does not pass multiplicity cuts"); return;
    }

    //make event
    if (fAnalysisType == "ESDMCkineESD")
    {
      flowEvent = new AliFlowEvent(myESD, mcEvent, AliFlowEvent::kESDkine, fCFManager1, fCFManager2 );
    }
    else if (fAnalysisType == "ESDMCkineMC")
    {
      flowEvent = new AliFlowEvent(myESD, mcEvent, AliFlowEvent::kMCkine, fCFManager1, fCFManager2 );
    }
  }
  // Make the FlowEventSimple for AOD input
  else if (fAnalysisType == "AOD")
  {
    if (!myAOD)
    {
      AliError("ERROR: AOD not available");
      return;
    }
    AliInfo(Form("AOD has %d tracks", myAOD->GetNumberOfTracks()));
    flowEvent = new AliFlowEvent(myAOD);
  }

  //check final event cuts
  Int_t mult = flowEvent->NumberOfTracks();
  AliInfo(Form("FlowEvent has %i tracks",mult));
  if (mult<fMinMult || mult>fMaxMult)
  {
    AliWarning("FlowEvent cut on multiplicity"); return;
  }

  //tag subevents
  flowEvent->TagSubeventsInEta(fMinA,fMaxA,fMinB,fMaxB);

  ////TODO afterburner
  //if (fbAfterburnerOn && fMyTRandom3) {
  //  // set the new value of the values using a after burner
  //  cout << "settings for afterburner in TaskFlowEvent.cxx:" << endl;
  //  cout << "fCount = " << fCount << endl;
  //  cout << "fNoOfLoops = " << fNoOfLoops << endl;
  //  cout << "fEllipticFlowValue = " << fEllipticFlowValue << endl;
  //  cout << "fSigmaEllipticFlowValue = " << fSigmaEllipticFlowValue << endl;
  //  cout << "fMultiplicityOflowEvent = " << fMultiplicityOflowEvent << endl;
  //  cout << "fSigmaMultiplicityOflowEvent = " << fSigmaMultiplicityOflowEvent << endl;
  //  Double_t xRPangle;
  //  if (!mcEvent) { xRPangle = TMath::TwoPi()*(fMyTRandom3->Rndm()); }
  //  else { xRPangle = fRP; }
  //  Double_t xNewFlowValue = fMyTRandom3->Gaus(fEllipticFlowValue,fSigmaEllipticFlowValue);
  //  Int_t nNewMultOflowEvent =  TMath::Nint(fMyTRandom3->Gaus(fMultiplicityOflowEvent,fSigmaMultiplicityOflowEvent));
  //  cout << "xRPangle = " << xRPangle << endl;
  //  cout << "xNewFlowValue = " << xNewFlowValue << endl;
  //  cout << "nNewMultOflowEvent = " << nNewMultOflowEvent << endl;
  //  cout << "settings for after burner" << endl;
  //  flowEventMaker->SetMCReactionPlaneAngle(xRPangle);
  //  flowEventMaker->SetNoOfLoops(fNoOfLoops);
  //  flowEventMaker->SetEllipticFlowValue(xNewFlowValue);
  //  flowEventMaker->SetMultiplicityOflowEvent(nNewMultOflowEvent);
  //  //end settings afterburner
  //}

  // if monte carlo event get reaction plane from monte carlo (depends on generator)
  if (mcEvent && mcEvent->GenEventHeader()) flowEvent->SetMCReactionPlaneAngle(mcEvent);

  //fListHistos->Print();
  //  fOutputFile->WriteObject(flowEvent,"myFlowEventSimple");
  PostData(1,flowEvent);
  if (fQA)
  {
    PostData(2,fQAInt);
    PostData(3,fQADiff);
  }
}

//________________________________________________________________________
void AliAnalysisTaskFlowEvent::Terminate(Option_t *)
{
  // Called once at the end of the query -- do not call in case of CAF
}

<|endoftext|>