<commit_before>#pragma once

#include <string>

#include <functional>
#include <memory>
#include <mutex>
#include <set>
#include <tuple>

#include "balancer.hpp"
#include "connection.hpp"
#include "log.hpp"
#include "pool.hpp"
#include "resolver.hpp"
#include "result.hpp"
#include "request/info.hpp"
#include "settings.hpp"

namespace elasticsearch {

namespace aux {

void empty() {}

} // namespace aux

const std::string INET_ADDR_PREFIX = "inet[";
const std::string INET_ADDR_SUFFIX = "]";

class http_transport_t {
public:
    typedef blackhole::synchronized<blackhole::logger_base_t> logger_type;

    typedef boost::asio::io_service loop_type;
    typedef http_connection_t connection_type;
    typedef pool_t<connection_type> pool_type;
    typedef pool_type::endpoint_type endpoint_type;

private:
    settings_t settings;

    loop_type& loop;
    logger_type& log;

    pool_type pool;
    std::unique_ptr<balancing::strategy<pool_type>> balancer;
    urlfetcher_t urlfetcher;
public:
    http_transport_t(settings_t settings, loop_type& loop, logger_type& log) :
        settings(settings),
        loop(loop),
        log(log),
        balancer(new balancing::round_robin<pool_type>()),
        urlfetcher(loop)
    {}

    void add_nodes(const std::vector<endpoint_type>& endpoints) {
        for (auto it = endpoints.begin(); it != endpoints.end(); ++it) {
            add_node(*it);
        }
    }

    void add_node(const endpoint_type& endpoint) {
        boost::system::error_code ec;
        auto address = endpoint.address().to_string(ec);
        if (ec) {
            ES_LOG(log, "can't add node endpoint '%s': %s", endpoint, ec.message());
            return;
        }

        ES_LOG(log, "adding '%s:%d' to the pool ...", address, endpoint.port());
        bool inserted;
        std::tie(std::ignore, inserted) = pool.insert(
            endpoint,
            std::make_shared<connection_type>(
                endpoint,
                settings.connections,
                urlfetcher,
                log
            )
        );

        if (!inserted) {
            ES_LOG(log, "adding endpoint to the pool is rejected - already exists");
        }
    }

    void remove_node(const endpoint_type& endpoint) {
        ES_LOG(log, "removing '%s' from the pool ...", endpoint);
        pool.remove(endpoint);
    }

    void sniff() {
        sniff(&aux::empty);
    }

    void sniff(std::function<void()>&& then) {
        ES_LOG(log, "sniffing nodes info ...");
        auto callback = std::bind(
            &http_transport_t::on_sniff, this, std::placeholders::_1, then
        );
        perform(actions::nodes_info_t(), callback);
    }

    template<class Action>
    void perform(Action action,
                 typename callback<Action>::type callback,
                 int attempt = 1) {
        typedef typename Action::result_type result_type;

        BOOST_ASSERT(balancer);

        ES_LOG(log, "performing '%s' request [attempt %d/%d] ...",
            action.name(), attempt, settings.retries);
        if (attempt > settings.retries) {
            ES_LOG(log, "failed: too many attempts done");
            loop.post(
                std::bind(
                    callback,
                    result_type(error_t(generic_error_t("too many attempts")))
                )
            );
            return;
        }

        if (auto connection = balancer->next(pool)) {
            ES_LOG(log, "balancing at %s", connection->endpoint());
            auto watcher = std::bind(
                &http_transport_t::on_response<Action>,
                this, action, callback, attempt, std::placeholders::_1
            );
            connection->perform(std::move(action), watcher, settings.timeout);
        } else {
            if (attempt == 1) {
                ES_LOG(log, "no connections - adding default nodes ...");
                add_nodes(settings.endpoints);
                loop.post(
                    std::bind(
                        &http_transport_t::perform<Action>,
                        this, std::move(action), callback, attempt + 1
                    )
                );
            } else {
                ES_LOG(log, "failed: no connections left");
                loop.post(
                    std::bind(
                        callback,
                        result_type(error_t(generic_error_t("no connections left")))
                    )
                );
            }
        }
    }

private:
    template<class Action>
    void on_response(Action action,
                typename callback<Action>::type callback,
                int attempt,
                typename Action::result_type&& result) {
        if (error_t* error = boost::get<error_t>(&result)) {
            switch (error->which()) {
            case 0:
                on_connection_error<Action>(
                    std::move(action),
                    callback,
                    attempt,
                    boost::get<connection_error_t>(*error)
                );
                break;
            case 1:
                on_generic_error(boost::get<generic_error_t>(*error));
                break;
            default:
                BOOST_ASSERT(false);
            }
        }

        callback(std::move(result));
    }

    template<class Action>
    typename std::enable_if<
        !std::is_same<Action, actions::nodes_info_t>::value
    >::type
    on_connection_error(Action action,
                        typename callback<Action>::type callback,
                        int attempt,
                        const connection_error_t& err) {
        ES_LOG(log, "request failed with error: %s", err.reason);

        remove_node(err.endpoint);
        if (settings.sniffer.when.error) {
            ES_LOG(log, "sniff.on.error is true - preparing to update nodes list");
            sniff(
                std::bind(
                    &http_transport_t::perform<Action>,
                    this, std::move(action), callback, attempt + 1
                )
            );
            return;
        }
    }

    template<class Action>
    typename std::enable_if<
        std::is_same<Action, actions::nodes_info_t>::value
    >::type
    on_connection_error(Action,
                        typename callback<Action>::type,
                        int,
                        const connection_error_t& err) {
        ES_LOG(log, "request failed with error: %s", err.reason);

        remove_node(err.endpoint);
    }

    void on_generic_error(const generic_error_t& err) {
        ES_LOG(log, "request failed with error: %s", err.reason);
    }

    void on_sniff(result_t<response::nodes_info_t>::type&& result,
                  std::function<void()> next) {
        if (auto* info = boost::get<response::nodes_info_t>(&result)) {
            ES_LOG(log, "successfully sniffed %d node%s",
                info->nodes.size(),
                info->nodes.size() > 1 ? "s" : ""
            );

            std::set<std::string> addresses;
            const auto& nodes = info->nodes;
            for (auto it = nodes.begin(); it != nodes.end(); ++it) {
                const response::node_t& node = it->second;
                extract_addresses(addresses, node.addresses);
            }

            typedef boost::asio::ip::tcp protocol_type;
            std::vector<endpoint_type> endpoints;
            for (auto it = addresses.begin(); it != addresses.end(); ++it) {
                try {
                    endpoints.push_back(
                        resolver<protocol_type>::resolve(*it, loop)
                    );
                } catch (const std::exception& err) {
                    ES_LOG(log, "failed to resolve %s address: %s", *it, err.what());
                }
            }

            add_nodes(endpoints);
        }

        next();
    }

    void extract_addresses(std::set<std::string>& result,
                           const response::node_t::addresses_type& addresses) const {
        auto it = addresses.find("http");
        if (it == addresses.end()) {
            return;
        }

        const std::string& address = it->second;
        if (boost::algorithm::starts_with(address, INET_ADDR_PREFIX)) {
            const std::string& parsed = address.substr(
                INET_ADDR_PREFIX.size(),
                address.size() -
                    INET_ADDR_PREFIX.size() -
                    INET_ADDR_SUFFIX.size()
            );
            result.insert(parsed);
        } else {
            ES_LOG(log, "unknown address type: %s", address);
        }
    }
};

} // namespace elasticsearch

<commit_msg>[Elasticsearch] Unnecessary code.<commit_after>#pragma once

#include <string>

#include <functional>
#include <memory>
#include <mutex>
#include <set>
#include <tuple>

#include "balancer.hpp"
#include "connection.hpp"
#include "log.hpp"
#include "pool.hpp"
#include "resolver.hpp"
#include "result.hpp"
#include "request/info.hpp"
#include "settings.hpp"

namespace elasticsearch {

namespace aux {

void empty() {}

} // namespace aux

const std::string INET_ADDR_PREFIX = "inet[";
const std::string INET_ADDR_SUFFIX = "]";

class http_transport_t {
public:
    typedef blackhole::synchronized<blackhole::logger_base_t> logger_type;

    typedef boost::asio::io_service loop_type;
    typedef http_connection_t connection_type;
    typedef pool_t<connection_type> pool_type;
    typedef pool_type::endpoint_type endpoint_type;

private:
    settings_t settings;

    loop_type& loop;
    logger_type& log;

    pool_type pool;
    std::unique_ptr<balancing::strategy<pool_type>> balancer;
    urlfetcher_t urlfetcher;
public:
    http_transport_t(settings_t settings, loop_type& loop, logger_type& log) :
        settings(settings),
        loop(loop),
        log(log),
        balancer(new balancing::round_robin<pool_type>()),
        urlfetcher(loop)
    {}

    void add_nodes(const std::vector<endpoint_type>& endpoints) {
        for (auto it = endpoints.begin(); it != endpoints.end(); ++it) {
            add_node(*it);
        }
    }

    void add_node(const endpoint_type& endpoint) {
        boost::system::error_code ec;
        auto address = endpoint.address().to_string(ec);
        if (ec) {
            ES_LOG(log, "can't add node endpoint '%s': %s", endpoint, ec.message());
            return;
        }

        ES_LOG(log, "adding '%s:%d' to the pool ...", address, endpoint.port());
        bool inserted;
        std::tie(std::ignore, inserted) = pool.insert(
            endpoint,
            std::make_shared<connection_type>(
                endpoint,
                settings.connections,
                urlfetcher,
                log
            )
        );

        if (!inserted) {
            ES_LOG(log, "adding endpoint to the pool is rejected - already exists");
        }
    }

    void remove_node(const endpoint_type& endpoint) {
        ES_LOG(log, "removing '%s' from the pool ...", endpoint);
        pool.remove(endpoint);
    }

    void sniff() {
        sniff(&aux::empty);
    }

    void sniff(std::function<void()>&& then) {
        ES_LOG(log, "sniffing nodes info ...");
        auto callback = std::bind(
            &http_transport_t::on_sniff, this, std::placeholders::_1, then
        );
        perform(actions::nodes_info_t(), callback);
    }

    template<class Action>
    void perform(Action action,
                 typename callback<Action>::type callback,
                 int attempt = 1) {
        typedef typename Action::result_type result_type;

        BOOST_ASSERT(balancer);

        ES_LOG(log, "performing '%s' request [attempt %d/%d] ...",
            action.name(), attempt, settings.retries);
        if (attempt > settings.retries) {
            ES_LOG(log, "failed: too many attempts done");
            loop.post(
                std::bind(
                    callback,
                    result_type(error_t(generic_error_t("too many attempts")))
                )
            );
            return;
        }

        if (auto connection = balancer->next(pool)) {
            ES_LOG(log, "balancing at %s", connection->endpoint());
            auto watcher = std::bind(
                &http_transport_t::on_response<Action>,
                this, action, callback, attempt, std::placeholders::_1
            );
            connection->perform(std::move(action), watcher, settings.timeout);
        } else {
            if (attempt == 1) {
                ES_LOG(log, "no connections - adding default nodes ...");
                add_nodes(settings.endpoints);
                loop.post(
                    std::bind(
                        &http_transport_t::perform<Action>,
                        this, std::move(action), callback, attempt + 1
                    )
                );
            } else {
                ES_LOG(log, "failed: no connections left");
                loop.post(
                    std::bind(
                        callback,
                        result_type(error_t(generic_error_t("no connections left")))
                    )
                );
            }
        }
    }

private:
    template<class Action>
    void on_response(Action action,
                typename callback<Action>::type callback,
                int attempt,
                typename Action::result_type&& result) {
        if (error_t* error = boost::get<error_t>(&result)) {
            switch (error->which()) {
            case 0:
                on_connection_error<Action>(
                    std::move(action),
                    callback,
                    attempt,
                    boost::get<connection_error_t>(*error)
                );
                break;
            case 1:
                on_generic_error(boost::get<generic_error_t>(*error));
                break;
            default:
                BOOST_ASSERT(false);
            }
        }

        callback(std::move(result));
    }

    template<class Action>
    typename std::enable_if<
        !std::is_same<Action, actions::nodes_info_t>::value
    >::type
    on_connection_error(Action action,
                        typename callback<Action>::type callback,
                        int attempt,
                        const connection_error_t& err) {
        ES_LOG(log, "request failed with error: %s", err.reason);

        remove_node(err.endpoint);
        if (settings.sniffer.when.error) {
            ES_LOG(log, "sniff.on.error is true - preparing to update nodes list");
            sniff(
                std::bind(
                    &http_transport_t::perform<Action>,
                    this, std::move(action), callback, attempt + 1
                )
            );
        }
    }

    template<class Action>
    typename std::enable_if<
        std::is_same<Action, actions::nodes_info_t>::value
    >::type
    on_connection_error(Action,
                        typename callback<Action>::type,
                        int,
                        const connection_error_t& err) {
        ES_LOG(log, "request failed with error: %s", err.reason);

        remove_node(err.endpoint);
    }

    void on_generic_error(const generic_error_t& err) {
        ES_LOG(log, "request failed with error: %s", err.reason);
    }

    void on_sniff(result_t<response::nodes_info_t>::type&& result,
                  std::function<void()> next) {
        if (auto* info = boost::get<response::nodes_info_t>(&result)) {
            ES_LOG(log, "successfully sniffed %d node%s",
                info->nodes.size(),
                info->nodes.size() > 1 ? "s" : ""
            );

            std::set<std::string> addresses;
            const auto& nodes = info->nodes;
            for (auto it = nodes.begin(); it != nodes.end(); ++it) {
                const response::node_t& node = it->second;
                extract_addresses(addresses, node.addresses);
            }

            typedef boost::asio::ip::tcp protocol_type;
            std::vector<endpoint_type> endpoints;
            for (auto it = addresses.begin(); it != addresses.end(); ++it) {
                try {
                    endpoints.push_back(
                        resolver<protocol_type>::resolve(*it, loop)
                    );
                } catch (const std::exception& err) {
                    ES_LOG(log, "failed to resolve %s address: %s", *it, err.what());
                }
            }

            add_nodes(endpoints);
        }

        next();
    }

    void extract_addresses(std::set<std::string>& result,
                           const response::node_t::addresses_type& addresses) const {
        auto it = addresses.find("http");
        if (it == addresses.end()) {
            return;
        }

        const std::string& address = it->second;
        if (boost::algorithm::starts_with(address, INET_ADDR_PREFIX)) {
            const std::string& parsed = address.substr(
                INET_ADDR_PREFIX.size(),
                address.size() -
                    INET_ADDR_PREFIX.size() -
                    INET_ADDR_SUFFIX.size()
            );
            result.insert(parsed);
        } else {
            ES_LOG(log, "unknown address type: %s", address);
        }
    }
};

} // namespace elasticsearch

<|endoftext|>


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

// the class BlockMatrixArray had no local type value_type that is
// needed in some places. in particular, this is needed for
// PreconditionBlockSSOR

#include <base/logstream.h>
#include <lac/block_matrix_array.h>
#include <lac/sparse_matrix.h>
#include <lac/precondition_block.h>
#include <iostream>
#include <fstream>

int main ()
{
  std::ofstream logfile("block_matrix_array_01.output");
  deallog.attach(logfile);
  deallog.depth_console(0);

  BlockMatrixArray<SparseMatrix<double> >::value_type i = 1.0;
  deallog << i << std::endl;

				   // the following did not compile
				   // right away
  PreconditionBlockSSOR<BlockMatrixArray<SparseMatrix<double> > > p;

  return 0;
}
<commit_msg>.<commit_after>//----------------------------  block_matrix_array_01.cc  ---------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 2005 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//----------------------------  block_matrix_array_01.cc  ---------------------------

// the class BlockMatrixArray had no local type value_type that is
// needed in some places. in particular, this is needed for
// PreconditionBlockSSOR
//
// the test also didn't link before, due to some functions that were
// either missing or in the wrong place

#include <base/logstream.h>
#include <lac/block_matrix_array.h>
#include <lac/sparse_matrix.h>
#include <lac/precondition_block.h>
#include <iostream>
#include <fstream>

int main ()
{
  std::ofstream logfile("block_matrix_array_01.output");
  deallog.attach(logfile);
  deallog.depth_console(0);

  BlockMatrixArray<SparseMatrix<double> >::value_type i = 1.0;
  deallog << i << std::endl;

				   // the following did not compile
				   // right away
  PreconditionBlockSSOR<BlockMatrixArray<SparseMatrix<double> > > p;

  return 0;
}
<|endoftext|>


<commit_before>/*
    Copyright (C) 1998, 1999 by Nathaniel 'NooTe' Saint Martin
    Copyright (C) 1998, 1999 by Jorrit Tyberghein
    Written by Nathaniel 'NooTe' Saint Martin

    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; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "cssysdef.h"
#include "csutil/scf.h"
#include "ivaria/reporter.h"
#include "iutil/objreg.h"

#include "dsound.h"

#include "sndrdr.h"
#include "sndlstn.h"

SCF_IMPLEMENT_IBASE(csSoundListenerDS3D)
	SCF_IMPLEMENTS_INTERFACE(iSoundListener)
SCF_IMPLEMENT_IBASE_END;

csSoundListenerDS3D::csSoundListenerDS3D(iBase *piBase) {
  SCF_CONSTRUCT_IBASE(piBase);
  PrimaryBuffer = NULL;
  Listener = NULL;
  Renderer = NULL;
}

csSoundListenerDS3D::~csSoundListenerDS3D() {
  if (Renderer) Renderer->DecRef();
  if (Listener) Listener->Release();
  if (PrimaryBuffer) {
    PrimaryBuffer->Stop();
    PrimaryBuffer->Release();
  }
}

bool csSoundListenerDS3D::Initialize(csSoundRenderDS3D *srdr) {
  srdr->IncRef();
  Renderer = srdr;

  DSBUFFERDESC dsbd;
  dsbd.dwSize = sizeof(DSBUFFERDESC);
  dsbd.dwFlags = DSBCAPS_PRIMARYBUFFER | DSBCAPS_CTRL3D | DSBCAPS_CTRLVOLUME;
  dsbd.dwReserved = 0;
  dsbd.dwBufferBytes = 0;
  dsbd.lpwfxFormat = NULL;

  csRef<iReporter> reporter = CS_QUERY_REGISTRY (Renderer->object_reg,
  	iReporter);

  HRESULT r;
  r = Renderer->AudioRenderer->CreateSoundBuffer(&dsbd, &PrimaryBuffer, NULL);
  if (r != DS_OK) {
    if (reporter)
      reporter->Report (CS_REPORTER_SEVERITY_WARNING,
      	"crystalspace.sound.ds3d", "DS3D listener: "
        "Cannot create primary sound buffer (%s).", Renderer->GetError(r));
    if (reporter) reporter->DecRef ();
    return false;
  }

  r = PrimaryBuffer->QueryInterface(IID_IDirectSound3DListener, (void **) &Listener);
  if (r != DS_OK) {
    if (reporter)
      reporter->Report (CS_REPORTER_SEVERITY_WARNING,
      	"crystalspace.sound.ds3d",
        "DS3D listener: Cannot query listener"
        " interface from primary sound buffer (%s).", Renderer->GetError(r));
    if (reporter) reporter->DecRef ();
    return false;
  }

  Dirty = true;
  Prepare();
  if (reporter) reporter->DecRef ();
  return true;
}

void csSoundListenerDS3D::SetPosition(const csVector3 &v) {
  Dirty = true;
  csSoundListener::SetPosition(v);
  Listener->SetPosition( v.x, v.y, v.z, DS3D_DEFERRED);
}

void csSoundListenerDS3D::SetDirection(const csVector3 &f, const csVector3 &t) {
  Dirty = true;
  csSoundListener::SetDirection(f, t);
  Listener->SetOrientation(f.x, f.y, f.z,t.x, t.y, t.z,DS3D_DEFERRED);
}

void csSoundListenerDS3D::SetHeadSize(float size) {
//  Dirty = true;
  csSoundListener::SetHeadSize(size);
// @@@
}

void csSoundListenerDS3D::SetVelocity(const csVector3 &v) {
  Dirty = true;
  csSoundListener::SetVelocity(v);
  Listener->SetVelocity(v.x, v.y, v.z, DS3D_DEFERRED);
}

void csSoundListenerDS3D::SetDopplerFactor(float factor) {
  Dirty = true;
  csSoundListener::SetDopplerFactor(factor);
  Listener->SetDopplerFactor(factor, DS3D_DEFERRED);
}

void csSoundListenerDS3D::SetDistanceFactor(float factor) {
  Dirty = true;
  csSoundListener::SetDistanceFactor(factor);
  Listener->SetDistanceFactor(factor, DS3D_DEFERRED);
}

void csSoundListenerDS3D::SetRollOffFactor(float factor) {
  Dirty = true;
  csSoundListener::SetRollOffFactor(factor);
  Listener->SetRolloffFactor(factor, DS3D_DEFERRED);
}

void csSoundListenerDS3D::SetEnvironment(csSoundEnvironment env) {
//  Dirty = true;
  csSoundListener::SetEnvironment(env);
// @@@
}

void csSoundListenerDS3D::Prepare() {
  if (!Dirty) return;
  Listener->CommitDeferredSettings();
  Dirty = false;
}
<commit_msg>Found some other extra DecRef() calls that were invalid after changing to csRef.<commit_after>/*
    Copyright (C) 1998, 1999 by Nathaniel 'NooTe' Saint Martin
    Copyright (C) 1998, 1999 by Jorrit Tyberghein
    Written by Nathaniel 'NooTe' Saint Martin

    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; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "cssysdef.h"
#include "csutil/scf.h"
#include "ivaria/reporter.h"
#include "iutil/objreg.h"

#include "dsound.h"

#include "sndrdr.h"
#include "sndlstn.h"

SCF_IMPLEMENT_IBASE(csSoundListenerDS3D)
	SCF_IMPLEMENTS_INTERFACE(iSoundListener)
SCF_IMPLEMENT_IBASE_END;

csSoundListenerDS3D::csSoundListenerDS3D(iBase *piBase) {
  SCF_CONSTRUCT_IBASE(piBase);
  PrimaryBuffer = NULL;
  Listener = NULL;
  Renderer = NULL;
}

csSoundListenerDS3D::~csSoundListenerDS3D() {
  if (Renderer) Renderer->DecRef();
  if (Listener) Listener->Release();
  if (PrimaryBuffer) {
    PrimaryBuffer->Stop();
    PrimaryBuffer->Release();
  }
}

bool csSoundListenerDS3D::Initialize(csSoundRenderDS3D *srdr) {
  srdr->IncRef();
  Renderer = srdr;

  DSBUFFERDESC dsbd;
  dsbd.dwSize = sizeof(DSBUFFERDESC);
  dsbd.dwFlags = DSBCAPS_PRIMARYBUFFER | DSBCAPS_CTRL3D | DSBCAPS_CTRLVOLUME;
  dsbd.dwReserved = 0;
  dsbd.dwBufferBytes = 0;
  dsbd.lpwfxFormat = NULL;

  csRef<iReporter> reporter = CS_QUERY_REGISTRY (Renderer->object_reg,
  	iReporter);

  HRESULT r;
  r = Renderer->AudioRenderer->CreateSoundBuffer(&dsbd, &PrimaryBuffer, NULL);
  if (r != DS_OK) {
    if (reporter)
      reporter->Report (CS_REPORTER_SEVERITY_WARNING,
      	"crystalspace.sound.ds3d", "DS3D listener: "
        "Cannot create primary sound buffer (%s).", Renderer->GetError(r));
    return false;
  }

  r = PrimaryBuffer->QueryInterface(IID_IDirectSound3DListener, (void **) &Listener);
  if (r != DS_OK) {
    if (reporter)
      reporter->Report (CS_REPORTER_SEVERITY_WARNING,
      	"crystalspace.sound.ds3d",
        "DS3D listener: Cannot query listener"
        " interface from primary sound buffer (%s).", Renderer->GetError(r));
    return false;
  }

  Dirty = true;
  Prepare();
  return true;
}

void csSoundListenerDS3D::SetPosition(const csVector3 &v) {
  Dirty = true;
  csSoundListener::SetPosition(v);
  Listener->SetPosition( v.x, v.y, v.z, DS3D_DEFERRED);
}

void csSoundListenerDS3D::SetDirection(const csVector3 &f, const csVector3 &t) {
  Dirty = true;
  csSoundListener::SetDirection(f, t);
  Listener->SetOrientation(f.x, f.y, f.z,t.x, t.y, t.z,DS3D_DEFERRED);
}

void csSoundListenerDS3D::SetHeadSize(float size) {
//  Dirty = true;
  csSoundListener::SetHeadSize(size);
// @@@
}

void csSoundListenerDS3D::SetVelocity(const csVector3 &v) {
  Dirty = true;
  csSoundListener::SetVelocity(v);
  Listener->SetVelocity(v.x, v.y, v.z, DS3D_DEFERRED);
}

void csSoundListenerDS3D::SetDopplerFactor(float factor) {
  Dirty = true;
  csSoundListener::SetDopplerFactor(factor);
  Listener->SetDopplerFactor(factor, DS3D_DEFERRED);
}

void csSoundListenerDS3D::SetDistanceFactor(float factor) {
  Dirty = true;
  csSoundListener::SetDistanceFactor(factor);
  Listener->SetDistanceFactor(factor, DS3D_DEFERRED);
}

void csSoundListenerDS3D::SetRollOffFactor(float factor) {
  Dirty = true;
  csSoundListener::SetRollOffFactor(factor);
  Listener->SetRolloffFactor(factor, DS3D_DEFERRED);
}

void csSoundListenerDS3D::SetEnvironment(csSoundEnvironment env) {
//  Dirty = true;
  csSoundListener::SetEnvironment(env);
// @@@
}

void csSoundListenerDS3D::Prepare() {
  if (!Dirty) return;
  Listener->CommitDeferredSettings();
  Dirty = false;
}
<|endoftext|>


<commit_before>/*
    statisticsplugin.cpp

    Copyright (c) 2003-2004 by Marc Cramdal        <marc.cramdal@gmail.com>

   Copyright (c) 2007      by the Kopete Developers <kopete-devel@kde.org>

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

#include <math.h>

#include <qfile.h>
//Added by qt3to4:
#include <QList>
#include <qtimer.h>

#include <kgenericfactory.h>
#include <kaboutdata.h>
#include <kaction.h>
#include <kactioncollection.h>
#include <kmessagebox.h>
#include <kstandarddirs.h>
#include <kdeversion.h>

#include "kopetechatsessionmanager.h"
#include "kopetemetacontact.h"
#include "kopeteview.h"
#include "kopetecontactlist.h"
#include "kopeteuiglobal.h"
#include "kopetemessageevent.h"
#include "kopeteonlinestatus.h"
#include "kopeteaccountmanager.h"
#include "kopeteaccount.h"
#include "kopetecontact.h"

#include "statisticscontact.h"
#include "statisticsdialog.h"
#include "statisticsplugin.h"
#include "statisticsadaptor.h"
#include "statisticsdb.h"

K_PLUGIN_FACTORY(StatisticsPluginFactory, registerPlugin<StatisticsPlugin>();)
K_EXPORT_PLUGIN(StatisticsPluginFactory( "kopete_statistics" ))

StatisticsPlugin::StatisticsPlugin( QObject *parent, const QVariantList &/*args*/ )
	: Kopete::Plugin( StatisticsPluginFactory::componentData(), parent )
{

	KAction *viewMetaContactStatistics = new KAction( KIcon("view-statistics"), i18n("View &Statistics" ),
		this );
	actionCollection()->addAction ( "viewMetaContactStatistics", viewMetaContactStatistics );
	connect(viewMetaContactStatistics, SIGNAL(triggered(bool)), this, SLOT(slotViewStatistics()));
	viewMetaContactStatistics->setEnabled(Kopete::ContactList::self()->selectedMetaContacts().count() == 1);

	connect(Kopete::ChatSessionManager::self(),SIGNAL(chatSessionCreated(Kopete::ChatSession*)),
				this, SLOT(slotViewCreated(Kopete::ChatSession*)));
	connect(Kopete::ChatSessionManager::self(),SIGNAL(aboutToReceive(Kopete::Message&)),
				this, SLOT(slotAboutToReceive(Kopete::Message&)));

	connect(Kopete::ContactList::self(), SIGNAL(metaContactSelected(bool)),
		viewMetaContactStatistics, SLOT(setEnabled(bool)));
	connect(Kopete::ContactList::self(), SIGNAL(metaContactAdded(Kopete::MetaContact*)),
	        this, SLOT(slotMetaContactAdded(Kopete::MetaContact*)));
	connect(Kopete::ContactList::self(), SIGNAL(metaContactRemoved(Kopete::MetaContact*)),
	        this, SLOT(slotMetaContactRemoved(Kopete::MetaContact*)));

	setXMLFile("statisticsui.rc");

	/* Initialization reads the database, so it could be a bit time-consuming
	due to disk access. This should overcome the problem and makes it non-blocking. */
	QTimer::singleShot(0, this, SLOT(slotInitialize()));

	new StatisticsAdaptor(this);
	QDBusConnection dbus = QDBusConnection::sessionBus();
	dbus.registerObject("/Statistics", this);
}

void StatisticsPlugin::slotInitialize()
{
	// Initializes the database
	m_db = new StatisticsDB();

	QList<Kopete::MetaContact*> list = Kopete::ContactList::self()->metaContacts();
	foreach(Kopete::MetaContact *metaContact, list)
	{
		slotMetaContactAdded(metaContact);
	}
}

StatisticsPlugin::~StatisticsPlugin()
{
	qDeleteAll(statisticsContactMap);
	statisticsContactMap.clear();
}

void StatisticsPlugin::slotAboutToReceive(Kopete::Message& m)
{
	if (!m.from())
		return;

	StatisticsContact *sc = statisticsContactMap.value(m.from()->metaContact());
	if (sc)
		sc->newMessageReceived(m);
}

void StatisticsPlugin::slotViewCreated(Kopete::ChatSession* session)
{
	connect(session, SIGNAL(closing(Kopete::ChatSession*)), this, SLOT(slotViewClosed(Kopete::ChatSession*)));
}

void StatisticsPlugin::slotViewClosed(Kopete::ChatSession* session)
{
	QList<Kopete::Contact*> list = session->members();
	foreach(Kopete::Contact *contact, list)
	{
		// If this contact is not in other chat sessions
		if (!contact->manager())
		{
			StatisticsContact *sc = statisticsContactMap.value(contact->metaContact());
			if (sc)
				sc->setIsChatWindowOpen(false);
		}
	}
}

void StatisticsPlugin::slotViewStatistics()
{
	Kopete::MetaContact *mc = Kopete::ContactList::self()->selectedMetaContacts().first();

	kDebug(14315) << "statistics - dialog: " + mc->displayName();

	StatisticsContact *sc = statisticsContactMap.value(mc);
	if (sc)
	{
		StatisticsDialog* dialog = new StatisticsDialog(sc, db());
		dialog->setObjectName( QLatin1String( "StatisticsDialog" ) );
		dialog->show();
	}
}

void StatisticsPlugin::slotOnlineStatusChanged(Kopete::MetaContact *metaContact, Kopete::OnlineStatus::StatusType status)
{
	StatisticsContact *sc = statisticsContactMap.value(metaContact);
	if (sc)
		sc->onlineStatusChanged(status);
}

void StatisticsPlugin::slotMetaContactAdded(Kopete::MetaContact *mc)
{
	connect(mc, SIGNAL(onlineStatusChanged(Kopete::MetaContact *, Kopete::OnlineStatus::StatusType)), this,
	        SLOT(slotOnlineStatusChanged(Kopete::MetaContact*, Kopete::OnlineStatus::StatusType)));

	statisticsContactMap[mc] = new StatisticsContact(mc, db());
}

void StatisticsPlugin::slotMetaContactRemoved(Kopete::MetaContact *mc)
{
	disconnect(mc, 0, this, 0);
	StatisticsContact *sc = statisticsContactMap.value(mc);
	if (sc)
	{
		statisticsContactMap.remove(mc);
		delete sc;
	}
}

StatisticsContact* StatisticsPlugin::findStatisticsContact(QString id) const
{
	QMapIterator<Kopete::MetaContact*, StatisticsContact*> it(statisticsContactMap);
	while (it.hasNext())
	{
		it.next();
		if (it.key()->metaContactId() == id)
			return it.value();
	}

	return 0;
}

void StatisticsPlugin::dbusStatisticsDialog(QString id)
{
	kDebug(14315) << "statistics - DBus dialog :" << id;

	StatisticsContact *sc = findStatisticsContact(id);
	if (sc)
	{
		StatisticsDialog* dialog = new StatisticsDialog(sc, db());
		dialog->setObjectName( QLatin1String("StatisticsDialog") );
		dialog->show();
	}
}

bool StatisticsPlugin::dbusWasOnline(QString id, int timeStamp)
{
	QDateTime dt;
	dt.setTime_t(timeStamp);
	return dbusWasStatus(id, dt, Kopete::OnlineStatus::Online);
}

bool StatisticsPlugin::dbusWasOnline(QString id, QString dateTime)
{
	return dbusWasStatus(id, QDateTime::fromString(dateTime), Kopete::OnlineStatus::Online);
}

bool StatisticsPlugin::dbusWasAway(QString id, int timeStamp)
{
	QDateTime dt;
	dt.setTime_t(timeStamp);
	return dbusWasStatus(id, dt, Kopete::OnlineStatus::Away);
}

bool StatisticsPlugin::dbusWasAway(QString id, QString dateTime)
{
	return dbusWasStatus(id, QDateTime::fromString(dateTime), Kopete::OnlineStatus::Away);
}

bool StatisticsPlugin::dbusWasOffline(QString id, int timeStamp)
{
	QDateTime dt;
	dt.setTime_t(timeStamp);
	return dbusWasStatus(id, dt, Kopete::OnlineStatus::Offline);
}

bool StatisticsPlugin::dbusWasOffline(QString id, QString dateTime)
{
	return dbusWasStatus(id, QDateTime::fromString(dateTime), Kopete::OnlineStatus::Offline);
}

bool StatisticsPlugin::dbusWasStatus(QString id, QDateTime dateTime, Kopete::OnlineStatus::StatusType status)
{
	kDebug(14315) << "statistics - DBus wasOnline :" << id;

	if (dateTime.isValid())
	{
		StatisticsContact *sc = findStatisticsContact(id);
		if (sc)
			return sc->wasStatus(dateTime, status);
	}

	return false;
}

QString StatisticsPlugin::dbusStatus(QString id, int timeStamp)
{
	QDateTime dt;
	dt.setTime_t(timeStamp);
	return dbusStatus(id, dt.toString());

}

QString StatisticsPlugin::dbusStatus(QString id, QString dateTime)
{
	QDateTime dt = QDateTime::fromString(dateTime);
	if (dt.isValid())
	{
		StatisticsContact *sc = findStatisticsContact(id);
		if (sc)
			return sc->statusAt(dt);
	}

	return "";
}

QString StatisticsPlugin::dbusMainStatus(QString id, int timeStamp)
{
	QDateTime dt;
	dt.setTime_t(timeStamp);
	if (dt.isValid())
	{
		StatisticsContact *sc = findStatisticsContact(id);
		if (sc)
			return sc->mainStatusDate(dt.date());
	}

	return "";
}

void StatisticsPlugin::aboutToUnload()
{
	/* Upon exit kopete will set the online status of each metacontact to
	 * "unknown", causing a storm of synchronous writes to the DB.
	 * Disconnect the signal and batch a single transaction.
	 */
	m_db->transaction();

	QMap<Kopete::MetaContact *, StatisticsContact *>::iterator it;
	for (it = statisticsContactMap.begin(); it != statisticsContactMap.end(); ++it) {
		Kopete::MetaContact *mc = it.key();
		StatisticsContact *sc = it.value();

		disconnect(mc, 0, this, 0);
		sc->onlineStatusChanged(Kopete::OnlineStatus::Unknown);
	}

	m_db->commit();

	/* Report ready for unload */
	emit readyForUnload();
}

#include "statisticsplugin.moc"
<commit_msg>Use kapp->processEvents() to minimize statistics plugin blockage. This does not solve the problem, Kopete feels sluggish when loading statistics plugin even after this change (CPU still goes to 100% usage), but it is better than blocking Kopete altogether.<commit_after>/*
    statisticsplugin.cpp

    Copyright (c) 2003-2004 by Marc Cramdal        <marc.cramdal@gmail.com>

   Copyright (c) 2007      by the Kopete Developers <kopete-devel@kde.org>

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

#include <math.h>

#include <qfile.h>
//Added by qt3to4:
#include <QList>
#include <qtimer.h>

#include <kgenericfactory.h>
#include <kaboutdata.h>
#include <kaction.h>
#include <kactioncollection.h>
#include <kmessagebox.h>
#include <kstandarddirs.h>
#include <kdeversion.h>
#include <kapplication.h>

#include "kopetechatsessionmanager.h"
#include "kopetemetacontact.h"
#include "kopeteview.h"
#include "kopetecontactlist.h"
#include "kopeteuiglobal.h"
#include "kopetemessageevent.h"
#include "kopeteonlinestatus.h"
#include "kopeteaccountmanager.h"
#include "kopeteaccount.h"
#include "kopetecontact.h"

#include "statisticscontact.h"
#include "statisticsdialog.h"
#include "statisticsplugin.h"
#include "statisticsadaptor.h"
#include "statisticsdb.h"

K_PLUGIN_FACTORY(StatisticsPluginFactory, registerPlugin<StatisticsPlugin>();)
K_EXPORT_PLUGIN(StatisticsPluginFactory( "kopete_statistics" ))

StatisticsPlugin::StatisticsPlugin( QObject *parent, const QVariantList &/*args*/ )
	: Kopete::Plugin( StatisticsPluginFactory::componentData(), parent )
{

	KAction *viewMetaContactStatistics = new KAction( KIcon("view-statistics"), i18n("View &Statistics" ),
		this );
	actionCollection()->addAction ( "viewMetaContactStatistics", viewMetaContactStatistics );
	connect(viewMetaContactStatistics, SIGNAL(triggered(bool)), this, SLOT(slotViewStatistics()));
	viewMetaContactStatistics->setEnabled(Kopete::ContactList::self()->selectedMetaContacts().count() == 1);

	connect(Kopete::ChatSessionManager::self(),SIGNAL(chatSessionCreated(Kopete::ChatSession*)),
				this, SLOT(slotViewCreated(Kopete::ChatSession*)));
	connect(Kopete::ChatSessionManager::self(),SIGNAL(aboutToReceive(Kopete::Message&)),
				this, SLOT(slotAboutToReceive(Kopete::Message&)));

	connect(Kopete::ContactList::self(), SIGNAL(metaContactSelected(bool)),
		viewMetaContactStatistics, SLOT(setEnabled(bool)));
	connect(Kopete::ContactList::self(), SIGNAL(metaContactAdded(Kopete::MetaContact*)),
	        this, SLOT(slotMetaContactAdded(Kopete::MetaContact*)));
	connect(Kopete::ContactList::self(), SIGNAL(metaContactRemoved(Kopete::MetaContact*)),
	        this, SLOT(slotMetaContactRemoved(Kopete::MetaContact*)));

	setXMLFile("statisticsui.rc");

	/* Initialization reads the database, so it could be a bit time-consuming
	due to disk access. This should overcome the problem and makes it non-blocking. */
	QTimer::singleShot(0, this, SLOT(slotInitialize()));

	new StatisticsAdaptor(this);
	QDBusConnection dbus = QDBusConnection::sessionBus();
	dbus.registerObject("/Statistics", this);
}

void StatisticsPlugin::slotInitialize()
{
	// Initializes the database
	m_db = new StatisticsDB();

	QList<Kopete::MetaContact*> list = Kopete::ContactList::self()->metaContacts();
	foreach(Kopete::MetaContact *metaContact, list)
	{
		kapp->processEvents();
		slotMetaContactAdded(metaContact);
	}
}

StatisticsPlugin::~StatisticsPlugin()
{
	qDeleteAll(statisticsContactMap);
	statisticsContactMap.clear();
}

void StatisticsPlugin::slotAboutToReceive(Kopete::Message& m)
{
	if (!m.from())
		return;

	StatisticsContact *sc = statisticsContactMap.value(m.from()->metaContact());
	if (sc)
		sc->newMessageReceived(m);
}

void StatisticsPlugin::slotViewCreated(Kopete::ChatSession* session)
{
	connect(session, SIGNAL(closing(Kopete::ChatSession*)), this, SLOT(slotViewClosed(Kopete::ChatSession*)));
}

void StatisticsPlugin::slotViewClosed(Kopete::ChatSession* session)
{
	QList<Kopete::Contact*> list = session->members();
	foreach(Kopete::Contact *contact, list)
	{
		// If this contact is not in other chat sessions
		if (!contact->manager())
		{
			StatisticsContact *sc = statisticsContactMap.value(contact->metaContact());
			if (sc)
				sc->setIsChatWindowOpen(false);
		}
	}
}

void StatisticsPlugin::slotViewStatistics()
{
	Kopete::MetaContact *mc = Kopete::ContactList::self()->selectedMetaContacts().first();

	kDebug(14315) << "statistics - dialog: " + mc->displayName();

	StatisticsContact *sc = statisticsContactMap.value(mc);
	if (sc)
	{
		StatisticsDialog* dialog = new StatisticsDialog(sc, db());
		dialog->setObjectName( QLatin1String( "StatisticsDialog" ) );
		dialog->show();
	}
}

void StatisticsPlugin::slotOnlineStatusChanged(Kopete::MetaContact *metaContact, Kopete::OnlineStatus::StatusType status)
{
	StatisticsContact *sc = statisticsContactMap.value(metaContact);
	if (sc)
		sc->onlineStatusChanged(status);
}

void StatisticsPlugin::slotMetaContactAdded(Kopete::MetaContact *mc)
{
	connect(mc, SIGNAL(onlineStatusChanged(Kopete::MetaContact *, Kopete::OnlineStatus::StatusType)), this,
	        SLOT(slotOnlineStatusChanged(Kopete::MetaContact*, Kopete::OnlineStatus::StatusType)));

	statisticsContactMap[mc] = new StatisticsContact(mc, db());
}

void StatisticsPlugin::slotMetaContactRemoved(Kopete::MetaContact *mc)
{
	disconnect(mc, 0, this, 0);
	StatisticsContact *sc = statisticsContactMap.value(mc);
	if (sc)
	{
		statisticsContactMap.remove(mc);
		delete sc;
	}
}

StatisticsContact* StatisticsPlugin::findStatisticsContact(QString id) const
{
	QMapIterator<Kopete::MetaContact*, StatisticsContact*> it(statisticsContactMap);
	while (it.hasNext())
	{
		it.next();
		if (it.key()->metaContactId() == id)
			return it.value();
	}

	return 0;
}

void StatisticsPlugin::dbusStatisticsDialog(QString id)
{
	kDebug(14315) << "statistics - DBus dialog :" << id;

	StatisticsContact *sc = findStatisticsContact(id);
	if (sc)
	{
		StatisticsDialog* dialog = new StatisticsDialog(sc, db());
		dialog->setObjectName( QLatin1String("StatisticsDialog") );
		dialog->show();
	}
}

bool StatisticsPlugin::dbusWasOnline(QString id, int timeStamp)
{
	QDateTime dt;
	dt.setTime_t(timeStamp);
	return dbusWasStatus(id, dt, Kopete::OnlineStatus::Online);
}

bool StatisticsPlugin::dbusWasOnline(QString id, QString dateTime)
{
	return dbusWasStatus(id, QDateTime::fromString(dateTime), Kopete::OnlineStatus::Online);
}

bool StatisticsPlugin::dbusWasAway(QString id, int timeStamp)
{
	QDateTime dt;
	dt.setTime_t(timeStamp);
	return dbusWasStatus(id, dt, Kopete::OnlineStatus::Away);
}

bool StatisticsPlugin::dbusWasAway(QString id, QString dateTime)
{
	return dbusWasStatus(id, QDateTime::fromString(dateTime), Kopete::OnlineStatus::Away);
}

bool StatisticsPlugin::dbusWasOffline(QString id, int timeStamp)
{
	QDateTime dt;
	dt.setTime_t(timeStamp);
	return dbusWasStatus(id, dt, Kopete::OnlineStatus::Offline);
}

bool StatisticsPlugin::dbusWasOffline(QString id, QString dateTime)
{
	return dbusWasStatus(id, QDateTime::fromString(dateTime), Kopete::OnlineStatus::Offline);
}

bool StatisticsPlugin::dbusWasStatus(QString id, QDateTime dateTime, Kopete::OnlineStatus::StatusType status)
{
	kDebug(14315) << "statistics - DBus wasOnline :" << id;

	if (dateTime.isValid())
	{
		StatisticsContact *sc = findStatisticsContact(id);
		if (sc)
			return sc->wasStatus(dateTime, status);
	}

	return false;
}

QString StatisticsPlugin::dbusStatus(QString id, int timeStamp)
{
	QDateTime dt;
	dt.setTime_t(timeStamp);
	return dbusStatus(id, dt.toString());

}

QString StatisticsPlugin::dbusStatus(QString id, QString dateTime)
{
	QDateTime dt = QDateTime::fromString(dateTime);
	if (dt.isValid())
	{
		StatisticsContact *sc = findStatisticsContact(id);
		if (sc)
			return sc->statusAt(dt);
	}

	return "";
}

QString StatisticsPlugin::dbusMainStatus(QString id, int timeStamp)
{
	QDateTime dt;
	dt.setTime_t(timeStamp);
	if (dt.isValid())
	{
		StatisticsContact *sc = findStatisticsContact(id);
		if (sc)
			return sc->mainStatusDate(dt.date());
	}

	return "";
}

void StatisticsPlugin::aboutToUnload()
{
	/* Upon exit kopete will set the online status of each metacontact to
	 * "unknown", causing a storm of synchronous writes to the DB.
	 * Disconnect the signal and batch a single transaction.
	 */
	m_db->transaction();

	QMap<Kopete::MetaContact *, StatisticsContact *>::iterator it;
	for (it = statisticsContactMap.begin(); it != statisticsContactMap.end(); ++it) {
		kapp->processEvents();
		Kopete::MetaContact *mc = it.key();
		StatisticsContact *sc = it.value();

		disconnect(mc, 0, this, 0);
		sc->onlineStatusChanged(Kopete::OnlineStatus::Unknown);
	}

	m_db->commit();

	/* Report ready for unload */
	emit readyForUnload();
}

#include "statisticsplugin.moc"
<|endoftext|>


<commit_before>#include <cstring>
#include "Frontend.h"
#include "CudaUtil.h"
#include "CudaRt.h"

using namespace std;

extern cudaError_t cudaChooseDevice(int *device, const cudaDeviceProp *prop) {
    /* FIXME: implement */
    cerr << "*** Error: cudaChooseDevice() not yet implemented!" << endl;
    return cudaErrorUnknown;
}

extern cudaError_t cudaGetDevice(int *device) {
    /* FIXME: implement */
    cerr << "*** Error: cudaGetDevice() not yet implemented!" << endl;
    return cudaErrorUnknown;
}

extern cudaError_t cudaGetDeviceCount(int *count) {
    Frontend *f = Frontend::GetFrontend();
    f->AddHostPointerForArguments(count);
    f->Execute("cudaGetDeviceCount");
    if(f->Success())
        *count = *(f->GetOutputHostPointer<int>());
    return f->GetExitCode();
}

extern cudaError_t cudaGetDeviceProperties(cudaDeviceProp *prop, int device) {
    Frontend *f = Frontend::GetFrontend();
    f->AddHostPointerForArguments(prop);
    f->AddVariableForArguments(device);
    f->Execute("cudaGetDeviceProperties");
    if(f->Success())
        *prop = *(f->GetOutputHostPointer<struct cudaDeviceProp>());
    return f->GetExitCode();
}

extern cudaError_t cudaSetDevice(int device) {
    Frontend *f = Frontend::GetFrontend();
    f->AddVariableForArguments(device);
    f->Execute("cudaSetDevice");
    return f->GetExitCode();
}

extern cudaError_t cudaSetDeviceFlags(int flags) {
    /* FIXME: implement */
    cerr << "*** Error: cudaSetDeviceFlags() not yet implemented!" << endl;
    return cudaErrorUnknown;
}

extern cudaError_t cudaSetValidDevices(int *device_arr, int len) {
    /* FIXME: implement */
    cerr << "*** Error: cudaSetValidDevices() not yet implemented!" << endl;
    return cudaErrorUnknown;
}
<commit_msg>implemented device routine handler<commit_after>#include <cstring>
#include "Frontend.h"
#include "CudaUtil.h"
#include "CudaRt.h"

using namespace std;

extern cudaError_t cudaChooseDevice(int *device, const cudaDeviceProp *prop) {
    Frontend *f = Frontend::GetFrontend();
    f->AddHostPointerForArguments(device);
    f->AddHostPointerForArguments(prop);
    f->Execute("cudaChooseDevice");
    if(f->Success())
        *device = *(f->GetOutputHostPointer<int>());
    return f->GetExitCode();
}

extern cudaError_t cudaGetDevice(int *device) {
    Frontend *f = Frontend::GetFrontend();
    f->AddHostPointerForArguments(device);
    f->Execute("cudaGetDevice");
    if(f->Success())
        *device = *(f->GetOutputHostPointer<int>());
    return f->GetExitCode();
}

extern cudaError_t cudaGetDeviceCount(int *count) {
    Frontend *f = Frontend::GetFrontend();
    f->AddHostPointerForArguments(count);
    f->Execute("cudaGetDeviceCount");
    if(f->Success())
        *count = *(f->GetOutputHostPointer<int>());
    return f->GetExitCode();
}

extern cudaError_t cudaGetDeviceProperties(cudaDeviceProp *prop, int device) {
    Frontend *f = Frontend::GetFrontend();
    f->AddHostPointerForArguments(prop);
    f->AddVariableForArguments(device);
    f->Execute("cudaGetDeviceProperties");
    if(f->Success())
        *prop = *(f->GetOutputHostPointer<struct cudaDeviceProp>());
    return f->GetExitCode();
}

extern cudaError_t cudaSetDevice(int device) {
    Frontend *f = Frontend::GetFrontend();
    f->AddVariableForArguments(device);
    f->Execute("cudaSetDevice");
    return f->GetExitCode();
}

extern cudaError_t cudaSetDeviceFlags(int flags) {
    Frontend *f = Frontend::GetFrontend();
    f->AddVariableForArguments(flags);
    f->Execute("cudaSetDeviceFlags");
    return f->GetExitCode();
}

extern cudaError_t cudaSetValidDevices(int *device_arr, int len) {
    Frontend *f = Frontend::GetFrontend();
    f->AddHostPointerForArguments(device_arr, len);
    f->AddVariableForArguments(len);
    f->Execute("cudaSetValidDevices");
    if(f->Success()) {
        int *out_device_arr = f->GetOutputHostPointer<int>();
        memmove(device_arr, out_device_arr, sizeof(int) * len);
    }
    return f->GetExitCode();
}
<|endoftext|>


<commit_before>//..............................................................................
//
//  This file is part of the Jancy toolkit.
//
//  Jancy is distributed under the MIT license.
//  For details see accompanying license.txt file,
//  the public copy of which is also available at:
//  http://tibbo.com/downloads/archive/jancy/license.txt
//
//..............................................................................

#include "pch.h"
#include "jnc_sys_Registry.h"
#include "jnc_sys_SysLib.h"

namespace jnc {
namespace sys {

//..............................................................................

JNC_DEFINE_OPAQUE_CLASS_TYPE(
	RegKey,
	"sys.RegKey",
	g_sysLibGuid,
	SysLibCacheSlot_RegKey,
	RegKey,
	NULL
	)

JNC_BEGIN_TYPE_FUNCTION_MAP(RegKey)
	JNC_MAP_CONSTRUCTOR(&jnc::construct<RegKey>)
	JNC_MAP_DESTRUCTOR(&jnc::destruct<RegKey>)
	JNC_MAP_FUNCTION("close",       &RegKey::close)
	JNC_MAP_FUNCTION("create",      &RegKey::create0)
	JNC_MAP_OVERLOAD(&RegKey::create1)
	JNC_MAP_FUNCTION("open",        &RegKey::open0)
	JNC_MAP_OVERLOAD(&RegKey::open1)
	JNC_MAP_FUNCTION("read",        &RegKey::read)
	JNC_MAP_FUNCTION("readDword",   &RegKey::readDword)
	JNC_MAP_FUNCTION("readString",  &RegKey::readString)
	JNC_MAP_FUNCTION("write",       &RegKey::write)
	JNC_MAP_FUNCTION("writeString", &RegKey::writeString)
JNC_END_TYPE_FUNCTION_MAP()

//..............................................................................

void
JNC_CDECL
RegKey::close()
{
	if (!m_key)
		return;

	::RegCloseKey(m_key);
	m_key = NULL;
}

DataPtr
JNC_CDECL
RegKey::read(
	RegKey* self,
	DataPtr namePtr,
	DataPtr typePtr
	)
{
	char buffer[256];
	sl::Array<byte_t> value(ref::BufKind_Stack, buffer, sizeof(buffer));

	dword_t type;
	size_t size = self->readImpl(&value, (char*)namePtr.m_p, &type);
	if (size == -1)
		return g_nullDataPtr;

	return memDup(namePtr.m_p, size);
}

uint32_t
JNC_CDECL
RegKey::readDword(DataPtr namePtr)
{
	char buffer[256];
	sl::Array<byte_t> value(ref::BufKind_Stack, buffer, sizeof(buffer));

	dword_t type;
	size_t size = readImpl(&value, (char*)namePtr.m_p, &type);
	if (size == -1)
		return 0;

	sl::String string;

	switch (type)
	{
	case REG_DWORD:
	case REG_QWORD:
		return *(uint32_t*)value.cp();

	case REG_DWORD_BIG_ENDIAN:
		return sl::swapByteOrder32(*(uint32_t*)value.cp());

	case REG_SZ:
	case REG_EXPAND_SZ:
	case REG_MULTI_SZ:
		string.copy((wchar_t*)value.cp(), size / sizeof(wchar_t));
		return atoi(string);

	default:
		return size >= sizeof(uint32_t) ? *(uint32_t*)value.cp() : 0;
	}
}

DataPtr
JNC_CDECL
RegKey::readString(
	RegKey* self,
	DataPtr namePtr
	)
{
	char buffer[256];
	sl::Array<byte_t> value(ref::BufKind_Stack, buffer, sizeof(buffer));

	dword_t type;
	size_t size = self->readImpl(&value, (char*)namePtr.m_p, &type);
	if (size == -1)
		return g_nullDataPtr;

	uint32_t dword;
	sl::String string;

	switch (type)
	{
	case REG_DWORD:
	case REG_QWORD:
		dword = *(uint32_t*)value.cp();
		string.format("%u", dword);
		break;

	case REG_DWORD_BIG_ENDIAN:
		dword = sl::swapByteOrder32(*(uint32_t*)value.cp());
		string.format("%u", dword);
		break;

	case REG_SZ:
	case REG_EXPAND_SZ:
	case REG_MULTI_SZ:
		string.copy((wchar_t*)value.cp(), size / sizeof(wchar_t));
		break;

	default:
		value.append(0); // just in case
		return strDup((char*)value.cp());
	}

	return strDup(string);
}

bool
JNC_CDECL
RegKey::writeString(
	DataPtr namePtr,
	DataPtr valuePtr
	)
{
	sl::String_w string((char*)valuePtr.m_p);
	return writeImpl((char*)namePtr.m_p, REG_SZ, string.sz(), (string.getLength() + 1) * sizeof(wchar_t));
}

bool
RegKey::createImpl(
	HKEY parent,
	const char* path
	)
{
	close();

	long result = ::RegCreateKeyExW(
		parent,
		sl::String_w(path),
		0,
		NULL,
		0,
		KEY_ALL_ACCESS,
		NULL,
		&m_key,
		NULL
		);

	return err::complete(result == ERROR_SUCCESS);
}

bool
RegKey::openImpl(
	HKEY parent,
	const char* path,
	REGSAM access
	)
{
	close();

	long result = ::RegOpenKeyExW(
		parent,
		sl::String_w(path),
		0,
		access,
		&m_key
		);

	return err::complete(result == ERROR_SUCCESS);
}

size_t
RegKey::readImpl(
	sl::Array<byte_t>* buffer,
	const char* name,
	dword_t* type
	)
{
	dword_t size = 0;

	long result = ::RegQueryValueExW(
		m_key,
		sl::String_w(name),
		NULL,
		type,
		NULL,
		&size
		);

	if (result != ERROR_SUCCESS)
	{
		err::setError(result);
		return -1;
	}

	result = buffer->setCount(size);
	if (!result)
		return -1;

	result = ::RegQueryValueExW(
		m_key,
		sl::String_w(name),
		NULL,
		type,
		buffer->p(),
		&size
		);

	if (result != ERROR_SUCCESS)
	{
		err::setError(result);
		return -1;
	}

	return buffer->getCount();
}

bool
JNC_CDECL
RegKey::writeImpl(
	const char* name,
	dword_t type,
	const void* p,
	size_t size
	)
{
	long result = ::RegSetValueExW(
		m_key,
		sl::String_w(name),
		0,
		type,
		(const byte_t*)p,
		size
		);

	return err::complete(result == ERROR_SUCCESS);
}

//..............................................................................

} // namespace sys
} // namespace jnc
<commit_msg>[jnc_sys] typo fix: unnecessary JNC_CDECL in RegKey::writeImpl<commit_after>//..............................................................................
//
//  This file is part of the Jancy toolkit.
//
//  Jancy is distributed under the MIT license.
//  For details see accompanying license.txt file,
//  the public copy of which is also available at:
//  http://tibbo.com/downloads/archive/jancy/license.txt
//
//..............................................................................

#include "pch.h"
#include "jnc_sys_Registry.h"
#include "jnc_sys_SysLib.h"

namespace jnc {
namespace sys {

//..............................................................................

JNC_DEFINE_OPAQUE_CLASS_TYPE(
	RegKey,
	"sys.RegKey",
	g_sysLibGuid,
	SysLibCacheSlot_RegKey,
	RegKey,
	NULL
	)

JNC_BEGIN_TYPE_FUNCTION_MAP(RegKey)
	JNC_MAP_CONSTRUCTOR(&jnc::construct<RegKey>)
	JNC_MAP_DESTRUCTOR(&jnc::destruct<RegKey>)
	JNC_MAP_FUNCTION("close",       &RegKey::close)
	JNC_MAP_FUNCTION("create",      &RegKey::create0)
	JNC_MAP_OVERLOAD(&RegKey::create1)
	JNC_MAP_FUNCTION("open",        &RegKey::open0)
	JNC_MAP_OVERLOAD(&RegKey::open1)
	JNC_MAP_FUNCTION("read",        &RegKey::read)
	JNC_MAP_FUNCTION("readDword",   &RegKey::readDword)
	JNC_MAP_FUNCTION("readString",  &RegKey::readString)
	JNC_MAP_FUNCTION("write",       &RegKey::write)
	JNC_MAP_FUNCTION("writeString", &RegKey::writeString)
JNC_END_TYPE_FUNCTION_MAP()

//..............................................................................

void
JNC_CDECL
RegKey::close()
{
	if (!m_key)
		return;

	::RegCloseKey(m_key);
	m_key = NULL;
}

DataPtr
JNC_CDECL
RegKey::read(
	RegKey* self,
	DataPtr namePtr,
	DataPtr typePtr
	)
{
	char buffer[256];
	sl::Array<byte_t> value(ref::BufKind_Stack, buffer, sizeof(buffer));

	dword_t type;
	size_t size = self->readImpl(&value, (char*)namePtr.m_p, &type);
	if (size == -1)
		return g_nullDataPtr;

	return memDup(namePtr.m_p, size);
}

uint32_t
JNC_CDECL
RegKey::readDword(DataPtr namePtr)
{
	char buffer[256];
	sl::Array<byte_t> value(ref::BufKind_Stack, buffer, sizeof(buffer));

	dword_t type;
	size_t size = readImpl(&value, (char*)namePtr.m_p, &type);
	if (size == -1)
		return 0;

	sl::String string;

	switch (type)
	{
	case REG_DWORD:
	case REG_QWORD:
		return *(uint32_t*)value.cp();

	case REG_DWORD_BIG_ENDIAN:
		return sl::swapByteOrder32(*(uint32_t*)value.cp());

	case REG_SZ:
	case REG_EXPAND_SZ:
	case REG_MULTI_SZ:
		string.copy((wchar_t*)value.cp(), size / sizeof(wchar_t));
		return atoi(string);

	default:
		return size >= sizeof(uint32_t) ? *(uint32_t*)value.cp() : 0;
	}
}

DataPtr
JNC_CDECL
RegKey::readString(
	RegKey* self,
	DataPtr namePtr
	)
{
	char buffer[256];
	sl::Array<byte_t> value(ref::BufKind_Stack, buffer, sizeof(buffer));

	dword_t type;
	size_t size = self->readImpl(&value, (char*)namePtr.m_p, &type);
	if (size == -1)
		return g_nullDataPtr;

	uint32_t dword;
	sl::String string;

	switch (type)
	{
	case REG_DWORD:
	case REG_QWORD:
		dword = *(uint32_t*)value.cp();
		string.format("%u", dword);
		break;

	case REG_DWORD_BIG_ENDIAN:
		dword = sl::swapByteOrder32(*(uint32_t*)value.cp());
		string.format("%u", dword);
		break;

	case REG_SZ:
	case REG_EXPAND_SZ:
	case REG_MULTI_SZ:
		string.copy((wchar_t*)value.cp(), size / sizeof(wchar_t));
		break;

	default:
		value.append(0); // just in case
		return strDup((char*)value.cp());
	}

	return strDup(string);
}

bool
JNC_CDECL
RegKey::writeString(
	DataPtr namePtr,
	DataPtr valuePtr
	)
{
	sl::String_w string((char*)valuePtr.m_p);
	return writeImpl((char*)namePtr.m_p, REG_SZ, string.sz(), (string.getLength() + 1) * sizeof(wchar_t));
}

bool
RegKey::createImpl(
	HKEY parent,
	const char* path
	)
{
	close();

	long result = ::RegCreateKeyExW(
		parent,
		sl::String_w(path),
		0,
		NULL,
		0,
		KEY_ALL_ACCESS,
		NULL,
		&m_key,
		NULL
		);

	return err::complete(result == ERROR_SUCCESS);
}

bool
RegKey::openImpl(
	HKEY parent,
	const char* path,
	REGSAM access
	)
{
	close();

	long result = ::RegOpenKeyExW(
		parent,
		sl::String_w(path),
		0,
		access,
		&m_key
		);

	return err::complete(result == ERROR_SUCCESS);
}

size_t
RegKey::readImpl(
	sl::Array<byte_t>* buffer,
	const char* name,
	dword_t* type
	)
{
	dword_t size = 0;

	long result = ::RegQueryValueExW(
		m_key,
		sl::String_w(name),
		NULL,
		type,
		NULL,
		&size
		);

	if (result != ERROR_SUCCESS)
	{
		err::setError(result);
		return -1;
	}

	result = buffer->setCount(size);
	if (!result)
		return -1;

	result = ::RegQueryValueExW(
		m_key,
		sl::String_w(name),
		NULL,
		type,
		buffer->p(),
		&size
		);

	if (result != ERROR_SUCCESS)
	{
		err::setError(result);
		return -1;
	}

	return buffer->getCount();
}

bool
RegKey::writeImpl(
	const char* name,
	dword_t type,
	const void* p,
	size_t size
	)
{
	long result = ::RegSetValueExW(
		m_key,
		sl::String_w(name),
		0,
		type,
		(const byte_t*)p,
		size
		);

	return err::complete(result == ERROR_SUCCESS);
}

//..............................................................................

} // namespace sys
} // namespace jnc
<|endoftext|>


<commit_before>#include "huroco_right_arm/moveit_right_arm_controller.h"
#include "huroco_right_arm/right_arm_server.h"

#define SUCCESS 1
#define FAILURE 0

ArmManipulator::ArmManipulator(moveit::planning_interface::MoveGroupInterface &group)
						:move_group_(group)
{
	move_group_.setPlannerId("RRTConnectkConfigDefault");
	move_group_.setPlanningTime(5.0);
	move_group_.allowReplanning(true);
	move_group_.setMaxVelocityScalingFactor(0.5);
	move_group_.setMaxAccelerationScalingFactor(0.5);
}

ArmManipulator::~ArmManipulator()
{

}

void ArmManipulator::setServer(RightArmServer *server)
{
	server_ = server;
}

int ArmManipulator::tryComputingCartesian(moveit::planning_interface::MoveGroupInterface &group, moveit_msgs::RobotTrajectory &trajectory, const double step, const std::vector<geometry_msgs::Pose> waypoints)
{
	double fraction = 0;
	int computed_time = 0;

	while(computed_time < ATTEMPTS) {
		if(fraction < 1) {
			fraction = group.computeCartesianPath(waypoints, step, 0.0, trajectory);
			ROS_INFO("Waypoints that are computed successfully: %f", fraction * 100);
		}
		else if(fraction == 1) {
			ROS_INFO("Successfully compute complete cartesian path.");
			return SUCCESS;
		}

		computed_time += 1;
	}
	return FAILURE;

}

int ArmManipulator::tryPlanning(moveit::planning_interface::MoveGroupInterface &group, moveit::planning_interface::MoveGroupInterface::Plan &plan)
{
	int planning_times = 0;
	int planning_status;

	while(ros::ok() && planning_times < ATTEMPTS) {
		planning_times += 1;
		planning_status = group.plan(plan);
		if(planning_status) {
			ROS_INFO("Generate a plan successfully.");
			return planning_status;
		}
		else {
			ROS_ERROR("Fail to generate a plan, please check the pose, %d times try", planning_times);
			if(planning_times == ATTEMPTS) return planning_status;
		}
	}
}

int ArmManipulator::executeCartesianPath(std::vector<geometry_msgs::Pose> waypoints, const double step)
{
	moveit_msgs::RobotTrajectory trajectory;
	moveit::planning_interface::MoveGroupInterface::Plan plan;

	int cartesian_status;
	int execute_status;

	/* reflex gripper TF */

	tf::Quaternion reflex_q(0, 0, 0, 1);
	tf::Vector3 reflex_t(-0.036, 0.020, -0.14);

	tf::Transform tf(reflex_q, reflex_t);

	geometry_msgs::Pose point = waypoints[0];

	tf::Quaternion reflex_qt(point.orientation.x, point.orientation.y, point.orientation.z, point.orientation.w);
	tf::Vector3 reflex_tt(point.position.x, point.position.y, point.position.z);

	tf::Transform tf_t(reflex_qt, reflex_tt);

	tf::Vector3 right_eef = tf_t * reflex_t;

	waypoints[0].position.x = right_eef.getX();
	waypoints[0].position.y = right_eef.getY();
	waypoints[0].position.z = right_eef.getZ();

	cartesian_status = tryComputingCartesian(move_group_, trajectory, step, waypoints);
	if(cartesian_status) {
		plan.trajectory_ = trajectory;
		ROS_INFO("Computed cartesian path successfully, trying to execute.");
		execute_status = move_group_.execute(plan);
		return execute_status;
	}
	else {
		ROS_ERROR("Not able to compute complete cartesian path with given waypoints, check your waypoints.");
		return cartesian_status;
	}
}

int ArmManipulator::executeGoal(const geometry_msgs::PoseStamped goal)
{
	move_group_.setPoseTarget(goal.pose, "reflex_frame");
	moveit::planning_interface::MoveGroupInterface::Plan plan;
	if(tryPlanning(move_group_, plan)) {
		ROS_INFO("Now execute goal");
		move_group_.execute(plan);
		move_group_.clearPoseTarget();
	}
	else {
		ROS_INFO("No execution attempt");
		move_group_.clearPoseTarget();
	}
}

/*
void ArmManipulator::stop()
{
	move_group_.stop();
}
*/

int ArmManipulator::initPose()
{
	std::map<std::string, double> joint_values;
	joint_values["right_s0"] = -0.7643059275639074;
	joint_values["right_s1"] = -0.8877913809886832;
	joint_values["right_e0"] = 0.9131020639887926;
	joint_values["right_e1"] = 2.446699356677235;
	joint_values["right_w0"] = -1.2935292993843752;
	joint_values["right_w1"] = -0.9453156605343862;
	joint_values["right_w2"] = 0.04295146206079158;

	move_group_.setJointValueTarget(joint_values);
	moveit::planning_interface::MoveGroupInterface::Plan plan;

	int joint_space_status = tryPlanning(move_group_, plan);
	int execute_status;

	if(joint_space_status) {
		ROS_INFO("Rotating joints");
		execute_status = move_group_.execute(plan);
		return execute_status;
	}
	else {
		ROS_ERROR("Invalid rotation");
		return joint_space_status;
	}
}

<commit_msg>update right arm controller<commit_after>#include "huroco_right_arm/moveit_right_arm_controller.h"
#include "huroco_right_arm/right_arm_server.h"

#define SUCCESS 1
#define FAILURE 0

ArmManipulator::ArmManipulator(moveit::planning_interface::MoveGroupInterface &group)
						:move_group_(group)
{
	move_group_.setPlannerId("RRTConnectkConfigDefault");
	move_group_.setPlanningTime(5.0);
	move_group_.allowReplanning(true);
	move_group_.setMaxVelocityScalingFactor(0.5);
	move_group_.setMaxAccelerationScalingFactor(0.5);
}

ArmManipulator::~ArmManipulator()
{

}

void ArmManipulator::setServer(RightArmServer *server)
{
	server_ = server;
}

int ArmManipulator::tryComputingCartesian(moveit::planning_interface::MoveGroupInterface &group, moveit_msgs::RobotTrajectory &trajectory, const double step, const std::vector<geometry_msgs::Pose> waypoints)
{
	double fraction = 0;
	int computed_time = 0;

	while(computed_time < ATTEMPTS) {
		if(fraction < 1) {
			fraction = group.computeCartesianPath(waypoints, step, 0.0, trajectory);
			ROS_INFO("Waypoints that are computed successfully: %f", fraction * 100);
		}
		else if(fraction == 1) {
			ROS_INFO("Successfully compute complete cartesian path.");
			return SUCCESS;
		}

		computed_time += 1;
	}
	return FAILURE;

}

int ArmManipulator::tryPlanning(moveit::planning_interface::MoveGroupInterface &group, moveit::planning_interface::MoveGroupInterface::Plan &plan)
{
	int planning_times = 0;
	int planning_status;

	while(ros::ok() && planning_times < ATTEMPTS) {
		planning_times += 1;
		planning_status = group.plan(plan);
		if(planning_status) {
			ROS_INFO("Generate a plan successfully.");
			return planning_status;
		}
		else {
			ROS_ERROR("Fail to generate a plan, please check the pose, %d times try", planning_times);
			if(planning_times == ATTEMPTS) return planning_status;
		}
	}
}

int ArmManipulator::executeCartesianPath(std::vector<geometry_msgs::Pose> waypoints, const double step)
{
	moveit_msgs::RobotTrajectory trajectory;
	moveit::planning_interface::MoveGroupInterface::Plan plan;

	int cartesian_status;
	int execute_status;

	/* reflex gripper TF */

	tf::Quaternion reflex_q(0, 0, 0, 1);
	tf::Vector3 reflex_t(-0.036, 0.020, -0.14);

	tf::Transform tf(reflex_q, reflex_t);

	std::vector<geometry_msgs::Pose>::iterator iter;
	for(iter = waypoints.begin(); iter != waypoints.end(); iter++) {
		tf::Quaternion reflex_qt(iter->orientation.x, iter->orientation.y, iter->orientation.z, iter->orientation.w);
		tf::Vector3 reflex_tt(iter->position.x, iter->position.y, iter->position.z);

		tf::Transform tf_t(reflex_qt, reflex_tt);

		tf::Vector3 right_eef = tf_t * reflex_t;

		iter->position.x = right_eef.getX();
		iter->position.y = right_eef.getY();
		iter->position.z = right_eef.getZ();
	}

	cartesian_status = tryComputingCartesian(move_group_, trajectory, step, waypoints);
	if(cartesian_status) {
		plan.trajectory_ = trajectory;
		ROS_INFO("Computed cartesian path successfully, trying to execute.");
		execute_status = move_group_.execute(plan);
		return execute_status;
	}
	else {
		ROS_ERROR("Not able to compute complete cartesian path with given waypoints, check your waypoints.");
		return cartesian_status;
	}
}

int ArmManipulator::executeGoal(const geometry_msgs::PoseStamped goal)
{
	move_group_.setPoseTarget(goal.pose, "reflex_frame");
	moveit::planning_interface::MoveGroupInterface::Plan plan;
	if(tryPlanning(move_group_, plan)) {
		ROS_INFO("Now execute goal");
		move_group_.execute(plan);
		move_group_.clearPoseTarget();
	}
	else {
		ROS_INFO("No execution attempt");
		move_group_.clearPoseTarget();
	}
}

/*
void ArmManipulator::stop()
{
	move_group_.stop();
}
*/

int ArmManipulator::initPose()
{
	std::map<std::string, double> joint_values;
	joint_values["right_s0"] = -0.7643059275639074;
	joint_values["right_s1"] = -0.8877913809886832;
	joint_values["right_e0"] = 0.9131020639887926;
	joint_values["right_e1"] = 2.446699356677235;
	joint_values["right_w0"] = -1.2935292993843752;
	joint_values["right_w1"] = -0.9453156605343862;
	joint_values["right_w2"] = 0.04295146206079158;

	move_group_.setJointValueTarget(joint_values);
	moveit::planning_interface::MoveGroupInterface::Plan plan;

	int joint_space_status = tryPlanning(move_group_, plan);
	int execute_status;

	if(joint_space_status) {
		ROS_INFO("Rotating joints");
		execute_status = move_group_.execute(plan);
		return execute_status;
	}
	else {
		ROS_ERROR("Invalid rotation");
		return joint_space_status;
	}
}

<|endoftext|>


<commit_before>// @(#)root/proofplayer:$Name:  $:$Id: TEventIter.cxx,v 1.32 2007/04/19 09:33:40 rdm Exp $
// Author: Maarten Ballintijn   07/01/02

/*************************************************************************
 * Copyright (C) 1995-2001, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TEventIter                                                           //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TEventIter.h"
#include "TCollection.h"
#include "TDSet.h"
#include "TFile.h"
#include "TKey.h"
#include "TProofDebug.h"
#include "TSelector.h"
#include "TTimeStamp.h"
#include "TTree.h"
#include "TVirtualPerfStats.h"
#include "TEventList.h"
#include "TMap.h"
#include "TObjString.h"
#include "TRegexp.h"

#include "TError.h"

ClassImp(TEventIter)

//______________________________________________________________________________
TEventIter::TEventIter()
{
   // Default constructor

   fDSet  = 0;
   fElem  = 0;
   fFile  = 0;
   fDir   = 0;
   fSel   = 0;
   fFirst = 0;
   fCur   = -1;
   fNum   = 0;
   fStop  = kFALSE;
   fOldBytesRead = 0;
}

//______________________________________________________________________________
TEventIter::TEventIter(TDSet *dset, TSelector *sel, Long64_t first, Long64_t num)
   : fDSet(dset), fSel(sel)
{
   // Constructor

   fElem  = 0;
   fFile  = 0;
   fDir   = 0;
   fFirst = first;
   fCur   = -1;
   fNum   = num;
   fStop  = kFALSE;
   fEventList = 0;
   fEventListPos = 0;
   fOldBytesRead = 0;
}

//______________________________________________________________________________
TEventIter::~TEventIter()
{
   // Destructor

   delete fFile;
}

//______________________________________________________________________________
void TEventIter::StopProcess(Bool_t /*abort*/)
{
   // Set flag to stop the process

   fStop = kTRUE;
}

//______________________________________________________________________________
TEventIter *TEventIter::Create(TDSet *dset, TSelector *sel, Long64_t first, Long64_t num)
{
   // Create and instance of the appropriate iterator

   if ( dset->IsTree() ) {
      return new TEventIterTree(dset, sel, first, num);
   } else {
      return new TEventIterObj(dset, sel, first, num);
   }
}

//______________________________________________________________________________
Int_t TEventIter::LoadDir()
{
   // Load directory

   Int_t ret = 0;

   // Check Filename
   if ( fFile == 0 || fFilename != fElem->GetFileName() ) {
      fDir = 0;
      delete fFile; fFile = 0;

      fFilename = fElem->GetFileName();

      TDirectory *dirsave = gDirectory;

      Double_t start = 0;
      if (gPerfStats != 0) start = TTimeStamp();

      fFile = TFile::Open(fFilename);

      if (gPerfStats != 0) {
         gPerfStats->FileOpenEvent(fFile, fFilename, double(TTimeStamp())-start);
         fOldBytesRead = 0;
      }

      if (dirsave) dirsave->cd();

      if (!fFile || fFile->IsZombie() ) {
         if (fFile)
            Error("Process","Cannot open file: %s (%s)",
               fFilename.Data(), strerror(fFile->GetErrno()) );
         else
            Error("Process","Cannot open file: %s (errno unavailable)",
               fFilename.Data());
         // cleanup ?
         return -1;
      }
      PDB(kLoop,2) Info("LoadDir","Opening file: %s", fFilename.Data() );
      ret = 1;
   }

   // Check Directory
   if ( fDir == 0 || fPath != fElem->GetDirectory() ) {
      TDirectory *dirsave = gDirectory;

      fPath = fElem->GetDirectory();
      if ( !fFile->cd(fPath) ) {
         Error("Process","Cannot cd to: %s",
            fPath.Data() );
         return -1;
      }
      PDB(kLoop,2) Info("Process","Cd to: %s", fPath.Data() );
      fDir = gDirectory;
      if (dirsave) dirsave->cd();
      ret = 1;
   }

   return ret;
}

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

ClassImp(TEventIterObj)

//______________________________________________________________________________
TEventIterObj::TEventIterObj()
{
   // Default ctor.

   fKeys     = 0;
   fNextKey  = 0;
   fObj      = 0;
}

//______________________________________________________________________________
TEventIterObj::TEventIterObj(TDSet *dset, TSelector *sel, Long64_t first, Long64_t num)
   : TEventIter(dset,sel,first,num)
{
   // Constructor

   fClassName = dset->GetType();
   fKeys     = 0;
   fNextKey  = 0;
   fObj      = 0;
}

//______________________________________________________________________________
TEventIterObj::~TEventIterObj()
{
   // Destructor

   // delete fKeys ?
   delete fNextKey;
   delete fObj;
}

//______________________________________________________________________________
Long64_t TEventIterObj::GetNextEvent()
{
   // Get next event

   if (fStop || fNum == 0) return -1;

   while ( fElem == 0 || fElemNum == 0 || fCur < fFirst-1 ) {

      if (gPerfStats != 0 && fFile != 0) {
         Long64_t bytesRead = fFile->GetBytesRead();
         gPerfStats->SetBytesRead(bytesRead - fOldBytesRead);
         fOldBytesRead = bytesRead;
      }

      fElem = fDSet->Next(fKeys->GetSize());
      if (fElem->GetEventList()) {
         Error("GetNextEvent", "EventLists not implemented");
         return -1;
      }

      if ( fElem == 0 ) {
         fNum = 0;
         return -1;
      }

      Int_t r = LoadDir();

      if ( r == -1 ) {

         // Error has been reported
         fNum = 0;
         return -1;

      } else if ( r == 1 ) {

         // New file and/or directory
         fKeys = fDir->GetListOfKeys();
         fNextKey = new TIter(fKeys);
      }

      // Validate values for this element
      fElemFirst = fElem->GetFirst();
      fElemNum = fElem->GetNum();
      fEventList = fElem->GetEventList();
      fEventListPos = 0;
      if (fEventList) {
         fElemNum = fEventList->GetN();
      }

      Long64_t num = fKeys->GetSize();

      if ( fElemFirst > num ) {
         Error("GetNextEvent","First (%d) higher then number of keys (%d) in %d",
            fElemFirst, num, fElem->GetName() );
         fNum = 0;
         return -1;
      }

      if ( fElemNum == -1 ) {
         fElemNum = num - fElemFirst;
      } else if ( fElemFirst+fElemNum  > num ) {
         Error("GetNextEvent","Num (%d) + First (%d) larger then number of keys (%d) in %s",
            fElemNum, fElemFirst, num, fElem->GetDirectory() );
         fElemNum = num - fElemFirst;
      }

      // Skip this element completely?
      if ( fCur + fElemNum < fFirst ) {
         fCur += fElemNum;
         continue;
      }

      // Position within this element. TODO: more efficient?
      fNextKey->Reset();
      for(fElemCur = -1; fElemCur < fElemFirst-1 ; fElemCur++, fNextKey->Next());
   }

   --fElemNum;
   ++fElemCur;
   --fNum;
   ++fCur;
   TKey *key = (TKey*) fNextKey->Next();
   TDirectory *dirsave = gDirectory;
   fDir->cd();
   fObj = key->ReadObj();
   if (dirsave) dirsave->cd();
   fSel->SetObject( fObj );

   return fElemCur;
}

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

ClassImp(TEventIterTree)

//______________________________________________________________________________
TEventIterTree::TEventIterTree()
{
   // Default ctor.

   fTree = 0;
}

//______________________________________________________________________________
TEventIterTree::TEventIterTree(TDSet *dset, TSelector *sel, Long64_t first, Long64_t num)
   : TEventIter(dset,sel,first,num)
{
   // Constructor

   fTreeName = dset->GetObjName();
   fTree = 0;
   fAcquiredTrees = new TList;
}

//______________________________________________________________________________
TEventIterTree::~TEventIterTree()
{
   // Destructor

   ReleaseAllTrees();
   SafeDelete(fAcquiredTrees);
}

//______________________________________________________________________________
void TEventIterTree::ReleaseAllTrees()
{
   // Release all acquired trees.

   TIter nxt(fAcquiredTrees);
   fAcquiredTrees->SetOwner(kFALSE);
   fAcquiredTrees->Clear();
}

//______________________________________________________________________________
TTree* TEventIterTree::GetTrees(TDSetElement *elem)
{
   // Create a Tree for the main TDSetElement and for all the friends.
   // Returns the main tree or 0 in case of an error.

   TTree* main = Load(elem);
   if (!main)
      return 0;

   fAcquiredTrees->AddFirst(main);

   TList *friends = elem->GetListOfFriends();
   if (friends) {
      TIter nxf(friends);
      TPair *p = 0;
      while ((p = (TPair *) nxf())) {
         TDSetElement *dse = (TDSetElement *) p->Key();
         TObjString *str = (TObjString *) p->Value();
         TTree* friendTree = Load(dse);
         if (friendTree) {
            fAcquiredTrees->AddFirst(friendTree);
            main->AddFriend(friendTree, str->GetName());
         } else {
            return 0;
         }
      }
   }
   return main;
}

//______________________________________________________________________________
TTree* TEventIterTree::Load(TDSetElement *e)
{
   // Load a tree from s TDSetElement

   if (!e) {
      Error("Load","undefined element", e->GetFileName());
      return (TTree *)0;
   }

   const char *fn = e->GetFileName();
   const char *dn = e->GetDirectory();
   const char *tn = e->GetObjName();

   // Open the file
   TFile *f = TFile::Open(fn);
   if (!f) {
      Error("GetTrees","file '%s' could not be open", fn);
      return (TTree *)0;
   }
   // Change dir, if required
   if (dn && !f->cd(dn)) {
      Error("Load","Cannot cd to: %s", dn);
      return (TTree *)0;
   }
   PDB(kLoop,2)
      Info("Load","cd to: %s", dn);

   // If a wild card we will use the first object of the type
   // requested compatible with the reg expression we got
   TString on(tn);
   TString sreg(tn);
   if (sreg.Length() <= 0 || sreg == "" || sreg.Contains("*")) {
      if (sreg.Contains("*"))
         sreg.ReplaceAll("*", ".*");
      else
         sreg = ".*";
      TRegexp re(sreg);
      if (f->GetListOfKeys()) {
         TIter nxk(f->GetListOfKeys());
         TKey *k = 0;
         while ((k = (TKey *) nxk())) {
            if (!strcmp(k->GetClassName(), "TTree")) {
               TString kn(k->GetName());
               if (kn.Index(re) != kNPOS) {
                  on = kn;
                  break;
               }
            }
         }
      }
   }

   // Point to the key
   TKey *key = f->GetKey(on);
   if (key == 0) {
      Error("Load", "Cannot find tree \"%s\" in %s", tn, fn);
      return (TTree*)0;
   }

   PDB(kLoop,2)
      Info("Load", "Reading: %s", tn);
   TDirectory *dirsave = gDirectory;
   f->cd();
   TTree *tree = dynamic_cast<TTree*> (key->ReadObj());
   if (dirsave)
      dirsave->cd();
   if (tree == 0) {
      Error("Load", "Cannot <dynamic_cast> obj to tree \"%s\"", tn);
      return (TTree*)0;
   }

   // Done
   return tree;
}

//______________________________________________________________________________
Long64_t TEventIterTree::GetNextEvent()
{
   // Get next event

   if (fStop || fNum == 0) return -1;

   Bool_t attach = kFALSE;

   while ( fElem == 0 || fElemNum == 0 || fCur < fFirst-1 ) {

      if (gPerfStats != 0 && fTree != 0) {
         Long64_t totBytesRead = fTree->GetCurrentFile()->GetBytesRead();
         Long64_t bytesRead = totBytesRead - fOldBytesRead;
         gPerfStats->SetBytesRead(bytesRead);
         fOldBytesRead = totBytesRead;
      }

      if (fTree) {
         fElem = fDSet->Next(fTree->GetEntries());
      } else {
         fElem = fDSet->Next();
      }

      if ( fElem == 0 ) {
         fNum = 0;
         return -1;
      }
      ReleaseAllTrees();

      TTree *newTree = GetTrees(fElem);
      if (!newTree) {
         // Error has been reported
         fNum = 0;
         return -1;
      }
      if (newTree != fTree) {
         fTree = newTree;
         attach = kTRUE;
         fOldBytesRead = fTree->GetCurrentFile()->GetBytesRead();
      }

      // Validate values for this element
      fElemFirst = fElem->GetFirst();
      fElemNum = fElem->GetNum();
      fEventList = fElem->GetEventList();
      fEventListPos = 0;
      if (fEventList)
         fElemNum = fEventList->GetN();

      Long64_t num = (Long64_t) fTree->GetEntries();

      if (!fEventList) {
         if ( fElemFirst > num ) {
            Error("GetNextEvent","First (%d) higher then number of entries (%d) in %s",
               fElemFirst, num, fElem->GetObjName() );
            fNum = 0;
            return -1;
         }
         if ( fElemNum == -1 ) {
            fElemNum = num - fElemFirst;
         } else if ( fElemFirst+fElemNum  > num ) {
            Error("GetNextEvent","Num (%d) + First (%d) larger then number of entries (%d) in %s",
               fElemNum, fElemFirst, num, fElem->GetName() );
            fElemNum = num - fElemFirst;
         }

         // Skip this element completely?
         if ( fCur + fElemNum < fFirst ) {
            fCur += fElemNum;
            continue;
         }
         // Position within this element. TODO: more efficient?
         fElemCur = fElemFirst-1;
      }
   }

   if ( attach ) {
      PDB(kLoop,1) Info("GetNextEvent","Call Init(%p)",fTree);
      fSel->Init(fTree);
      fSel->Notify();
      if (fSel->GetAbort() == TSelector::kAbortProcess) {
         // the error has been reported
         return -1;
      }
      attach = kFALSE;
   }
   if (!fEventList) {
      --fElemNum;
      ++fElemCur;
      --fNum;
      ++fCur;
      return fElemCur;
   }
   else {
      --fElemNum;
      Long64_t rv = fEventList->GetEntry(fEventListPos);
      fEventListPos++;
      return rv;
   }
}
<commit_msg><commit_after>// @(#)root/proofplayer:$Name:  $:$Id: TEventIter.cxx,v 1.33 2007/05/08 14:56:19 rdm Exp $
// Author: Maarten Ballintijn   07/01/02

/*************************************************************************
 * Copyright (C) 1995-2001, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TEventIter                                                           //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TEventIter.h"
#include "TCollection.h"
#include "TDSet.h"
#include "TFile.h"
#include "TKey.h"
#include "TProofDebug.h"
#include "TSelector.h"
#include "TTimeStamp.h"
#include "TTree.h"
#include "TVirtualPerfStats.h"
#include "TEventList.h"
#include "TMap.h"
#include "TObjString.h"
#include "TRegexp.h"

#include "TError.h"

ClassImp(TEventIter)

//______________________________________________________________________________
TEventIter::TEventIter()
{
   // Default constructor

   fDSet  = 0;
   fElem  = 0;
   fFile  = 0;
   fDir   = 0;
   fSel   = 0;
   fFirst = 0;
   fCur   = -1;
   fNum   = 0;
   fStop  = kFALSE;
   fOldBytesRead = 0;
}

//______________________________________________________________________________
TEventIter::TEventIter(TDSet *dset, TSelector *sel, Long64_t first, Long64_t num)
   : fDSet(dset), fSel(sel)
{
   // Constructor

   fElem  = 0;
   fFile  = 0;
   fDir   = 0;
   fFirst = first;
   fCur   = -1;
   fNum   = num;
   fStop  = kFALSE;
   fEventList = 0;
   fEventListPos = 0;
   fOldBytesRead = 0;
}

//______________________________________________________________________________
TEventIter::~TEventIter()
{
   // Destructor

   delete fFile;
}

//______________________________________________________________________________
void TEventIter::StopProcess(Bool_t /*abort*/)
{
   // Set flag to stop the process

   fStop = kTRUE;
}

//______________________________________________________________________________
TEventIter *TEventIter::Create(TDSet *dset, TSelector *sel, Long64_t first, Long64_t num)
{
   // Create and instance of the appropriate iterator

   if ( dset->IsTree() ) {
      return new TEventIterTree(dset, sel, first, num);
   } else {
      return new TEventIterObj(dset, sel, first, num);
   }
}

//______________________________________________________________________________
Int_t TEventIter::LoadDir()
{
   // Load directory

   Int_t ret = 0;

   // Check Filename
   if ( fFile == 0 || fFilename != fElem->GetFileName() ) {
      fDir = 0;
      delete fFile; fFile = 0;

      fFilename = fElem->GetFileName();

      TDirectory *dirsave = gDirectory;

      Double_t start = 0;
      if (gPerfStats != 0) start = TTimeStamp();

      fFile = TFile::Open(fFilename);

      if (gPerfStats != 0) {
         gPerfStats->FileOpenEvent(fFile, fFilename, double(TTimeStamp())-start);
         fOldBytesRead = 0;
      }

      if (dirsave) dirsave->cd();

      if (!fFile || fFile->IsZombie() ) {
         if (fFile)
            Error("Process","Cannot open file: %s (%s)",
               fFilename.Data(), strerror(fFile->GetErrno()) );
         else
            Error("Process","Cannot open file: %s (errno unavailable)",
               fFilename.Data());
         // cleanup ?
         return -1;
      }
      PDB(kLoop,2) Info("LoadDir","Opening file: %s", fFilename.Data() );
      ret = 1;
   }

   // Check Directory
   if ( fDir == 0 || fPath != fElem->GetDirectory() ) {
      TDirectory *dirsave = gDirectory;

      fPath = fElem->GetDirectory();
      if ( !fFile->cd(fPath) ) {
         Error("Process","Cannot cd to: %s",
            fPath.Data() );
         return -1;
      }
      PDB(kLoop,2) Info("Process","Cd to: %s", fPath.Data() );
      fDir = gDirectory;
      if (dirsave) dirsave->cd();
      ret = 1;
   }

   return ret;
}

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

ClassImp(TEventIterObj)

//______________________________________________________________________________
TEventIterObj::TEventIterObj()
{
   // Default ctor.

   fKeys     = 0;
   fNextKey  = 0;
   fObj      = 0;
}

//______________________________________________________________________________
TEventIterObj::TEventIterObj(TDSet *dset, TSelector *sel, Long64_t first, Long64_t num)
   : TEventIter(dset,sel,first,num)
{
   // Constructor

   fClassName = dset->GetType();
   fKeys     = 0;
   fNextKey  = 0;
   fObj      = 0;
}

//______________________________________________________________________________
TEventIterObj::~TEventIterObj()
{
   // Destructor

   // delete fKeys ?
   delete fNextKey;
   delete fObj;
}

//______________________________________________________________________________
Long64_t TEventIterObj::GetNextEvent()
{
   // Get next event

   if (fStop || fNum == 0) return -1;

   while ( fElem == 0 || fElemNum == 0 || fCur < fFirst-1 ) {

      if (gPerfStats != 0 && fFile != 0) {
         Long64_t bytesRead = fFile->GetBytesRead();
         gPerfStats->SetBytesRead(bytesRead - fOldBytesRead);
         fOldBytesRead = bytesRead;
      }

      fElem = fDSet->Next(fKeys->GetSize());
      if (fElem->GetEventList()) {
         Error("GetNextEvent", "EventLists not implemented");
         return -1;
      }

      if ( fElem == 0 ) {
         fNum = 0;
         return -1;
      }

      Int_t r = LoadDir();

      if ( r == -1 ) {

         // Error has been reported
         fNum = 0;
         return -1;

      } else if ( r == 1 ) {

         // New file and/or directory
         fKeys = fDir->GetListOfKeys();
         fNextKey = new TIter(fKeys);
      }

      // Validate values for this element
      fElemFirst = fElem->GetFirst();
      fElemNum = fElem->GetNum();
      fEventList = fElem->GetEventList();
      fEventListPos = 0;
      if (fEventList) {
         fElemNum = fEventList->GetN();
      }

      Long64_t num = fKeys->GetSize();

      if ( fElemFirst > num ) {
         Error("GetNextEvent","First (%d) higher then number of keys (%d) in %d",
            fElemFirst, num, fElem->GetName() );
         fNum = 0;
         return -1;
      }

      if ( fElemNum == -1 ) {
         fElemNum = num - fElemFirst;
      } else if ( fElemFirst+fElemNum  > num ) {
         Error("GetNextEvent","Num (%d) + First (%d) larger then number of keys (%d) in %s",
            fElemNum, fElemFirst, num, fElem->GetDirectory() );
         fElemNum = num - fElemFirst;
      }

      // Skip this element completely?
      if ( fCur + fElemNum < fFirst ) {
         fCur += fElemNum;
         continue;
      }

      // Position within this element. TODO: more efficient?
      fNextKey->Reset();
      for(fElemCur = -1; fElemCur < fElemFirst-1 ; fElemCur++, fNextKey->Next());
   }

   --fElemNum;
   ++fElemCur;
   --fNum;
   ++fCur;
   TKey *key = (TKey*) fNextKey->Next();
   TDirectory *dirsave = gDirectory;
   fDir->cd();
   fObj = key->ReadObj();
   if (dirsave) dirsave->cd();
   fSel->SetObject( fObj );

   return fElemCur;
}

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

ClassImp(TEventIterTree)

//______________________________________________________________________________
TEventIterTree::TEventIterTree()
{
   // Default ctor.

   fTree = 0;
}

//______________________________________________________________________________
TEventIterTree::TEventIterTree(TDSet *dset, TSelector *sel, Long64_t first, Long64_t num)
   : TEventIter(dset,sel,first,num)
{
   // Constructor

   fTreeName = dset->GetObjName();
   fTree = 0;
   fAcquiredTrees = new TList;
}

//______________________________________________________________________________
TEventIterTree::~TEventIterTree()
{
   // Destructor

   ReleaseAllTrees();
   SafeDelete(fAcquiredTrees);
}

//______________________________________________________________________________
void TEventIterTree::ReleaseAllTrees()
{
   // Release all acquired trees.

   TIter nxt(fAcquiredTrees);
   fAcquiredTrees->SetOwner(kFALSE);
   fAcquiredTrees->Clear();
}

//______________________________________________________________________________
TTree* TEventIterTree::GetTrees(TDSetElement *elem)
{
   // Create a Tree for the main TDSetElement and for all the friends.
   // Returns the main tree or 0 in case of an error.

   TTree* main = Load(elem);
   if (!main)
      return 0;

   fAcquiredTrees->AddFirst(main);

   TList *friends = elem->GetListOfFriends();
   if (friends) {
      TIter nxf(friends);
      TPair *p = 0;
      while ((p = (TPair *) nxf())) {
         TDSetElement *dse = (TDSetElement *) p->Key();
         TObjString *str = (TObjString *) p->Value();
         TTree* friendTree = Load(dse);
         if (friendTree) {
            fAcquiredTrees->AddFirst(friendTree);
            main->AddFriend(friendTree, str->GetName());
         } else {
            return 0;
         }
      }
   }
   return main;
}

//______________________________________________________________________________
TTree* TEventIterTree::Load(TDSetElement *e)
{
   // Load a tree from s TDSetElement

   if (!e) {
      Error("Load","undefined element", e->GetFileName());
      return (TTree *)0;
   }

   const char *fn = e->GetFileName();
   const char *dn = e->GetDirectory();
   const char *tn = e->GetObjName();

   // Open the file
   TFile *f = TFile::Open(fn);
   if (!f) {
      Error("GetTrees","file '%s' could not be open", fn);
      return (TTree *)0;
   }
   // Change dir, if required
   if (dn && !f->cd(dn)) {
      Error("Load","Cannot cd to: %s", dn);
      return (TTree *)0;
   }
   PDB(kLoop,2)
      Info("Load","cd to: %s", dn);

   // If a wild card we will use the first object of the type
   // requested compatible with the reg expression we got
   TString on(tn);
   TString sreg(tn);
   if (sreg.Length() <= 0 || sreg == "" || sreg.Contains("*")) {
      if (sreg.Contains("*"))
         sreg.ReplaceAll("*", ".*");
      else
         sreg = ".*";
      TRegexp re(sreg);
      if (f->GetListOfKeys()) {
         TIter nxk(f->GetListOfKeys());
         TKey *k = 0;
         while ((k = (TKey *) nxk())) {
            if (!strcmp(k->GetClassName(), "TTree")) {
               TString kn(k->GetName());
               if (kn.Index(re) != kNPOS) {
                  on = kn;
                  break;
               }
            }
         }
      }
   }

   // Point to the key
   TKey *key = f->GetKey(on);
   if (key == 0) {
      Error("Load", "Cannot find tree \"%s\" in %s", tn, fn);
      return (TTree*)0;
   }

   PDB(kLoop,2)
      Info("Load", "Reading: %s", tn);
   TDirectory *dirsave = gDirectory;
   f->cd();
   TTree *tree = dynamic_cast<TTree*> (key->ReadObj());
   if (dirsave)
      dirsave->cd();
   if (tree == 0) {
      Error("Load", "Cannot <dynamic_cast> obj to tree \"%s\"", tn);
      return (TTree*)0;
   }

   // Done
   return tree;
}

//______________________________________________________________________________
Long64_t TEventIterTree::GetNextEvent()
{
   // Get next event

   if (fStop || fNum == 0) return -1;

   Bool_t attach = kFALSE;

   while ( fElem == 0 || fElemNum == 0 || fCur < fFirst-1 ) {

      if (gPerfStats != 0 && fTree != 0) {
         Long64_t totBytesRead = fTree->GetCurrentFile()->GetBytesRead();
         Long64_t bytesRead = totBytesRead - fOldBytesRead;
         gPerfStats->SetBytesRead(bytesRead);
         fOldBytesRead = totBytesRead;
      }

      SafeDelete(fElem);
      if (fTree) {
         fElem = fDSet->Next(fTree->GetEntries());
      } else {
         fElem = fDSet->Next();
      }

      if ( fElem == 0 ) {
         fNum = 0;
         return -1;
      }
      ReleaseAllTrees();

      TTree *newTree = GetTrees(fElem);
      if (!newTree) {
         // Error has been reported
         fNum = 0;
         return -1;
      }
      if (newTree != fTree) {
         fTree = newTree;
         attach = kTRUE;
         fOldBytesRead = fTree->GetCurrentFile()->GetBytesRead();
      }

      // Validate values for this element
      fElemFirst = fElem->GetFirst();
      fElemNum = fElem->GetNum();
      fEventList = fElem->GetEventList();
      fEventListPos = 0;
      if (fEventList)
         fElemNum = fEventList->GetN();

      Long64_t num = (Long64_t) fTree->GetEntries();

      if (!fEventList) {
         if ( fElemFirst > num ) {
            Error("GetNextEvent","First (%d) higher then number of entries (%d) in %s",
               fElemFirst, num, fElem->GetObjName() );
            fNum = 0;
            return -1;
         }
         if ( fElemNum == -1 ) {
            fElemNum = num - fElemFirst;
         } else if ( fElemFirst+fElemNum  > num ) {
            Error("GetNextEvent","Num (%d) + First (%d) larger then number of entries (%d) in %s",
               fElemNum, fElemFirst, num, fElem->GetName() );
            fElemNum = num - fElemFirst;
         }

         // Skip this element completely?
         if ( fCur + fElemNum < fFirst ) {
            fCur += fElemNum;
            continue;
         }
         // Position within this element. TODO: more efficient?
         fElemCur = fElemFirst-1;
      }
   }

   if ( attach ) {
      PDB(kLoop,1) Info("GetNextEvent","Call Init(%p)",fTree);
      fSel->Init(fTree);
      fSel->Notify();
      if (fSel->GetAbort() == TSelector::kAbortProcess) {
         // the error has been reported
         return -1;
      }
      attach = kFALSE;
   }
   if (!fEventList) {
      --fElemNum;
      ++fElemCur;
      --fNum;
      ++fCur;
      return fElemCur;
   }
   else {
      --fElemNum;
      Long64_t rv = fEventList->GetEntry(fEventListPos);
      fEventListPos++;
      return rv;
   }
}
<|endoftext|>


<commit_before>#ifndef QRW_FOLLOWROUTECOMPONENT_HPP
#define QRW_FOLLOWROUTECOMPONENT_HPP

#include <vector>

#include <SFML/System/Vector2.hpp>

#include "animation/animation.hpp"
#include "foundation/gamecomponent.hpp"

namespace qrw
{
class Renderable;

class FollowRouteAnimationComponent : public GameComponent, public Animation
{
public:
	explicit FollowRouteAnimationComponent(Renderable* renderable);

	void start() override;

	void stop() override;

	void animate(float deltaTime) override;

	void addCorner(const sf::Vector2f corner) { corners_.push_back(corner); }

private:
	Renderable* renderable_;

	std::vector<sf::Vector2f> corners_;
};

} // namespace qrw

#endif // QRW_FOLLOWROUTECOMPONENT_HPP
<commit_msg>Fix parameter name<commit_after>#ifndef QRW_FOLLOWROUTECOMPONENT_HPP
#define QRW_FOLLOWROUTECOMPONENT_HPP

#include <vector>

#include <SFML/System/Vector2.hpp>

#include "animation/animation.hpp"
#include "foundation/gamecomponent.hpp"

namespace qrw
{
class Renderable;

class FollowRouteAnimationComponent : public GameComponent, public Animation
{
public:
	explicit FollowRouteAnimationComponent(Renderable* renderable);

	void start() override;

	void stop() override;

	void animate(float deltaTime) override;

	void addCorner(const sf::Vector2f edge) { corners_.push_back(edge); }

private:
	Renderable* renderable_;

	std::vector<sf::Vector2f> corners_;
};

} // namespace qrw

#endif // QRW_FOLLOWROUTECOMPONENT_HPP
<|endoftext|>