<commit_before>/**
   *  \file   parametercontainer.hh
   *
   *  \brief  containing class ParameterContainer
   **/

#ifndef DUNE_STUFF_PARAMETERCONTAINER_HH_INCLUDED
#define DUNE_STUFF_PARAMETERCONTAINER_HH_INCLUDED

#ifdef HAVE_CMAKE_CONFIG
 #include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
 #include <config.h>
#endif // ifdef HAVE_CMAKE_CONFIG

#if HAVE_DUNE_FEM

#include <dune/common/deprecated.hh>
#include <dune/fem/io/parameter.hh>

#include <dune/stuff/common/logging.hh>
#include <dune/stuff/common/filesystem.hh>
#include <dune/stuff/common/misc.hh>
#include <dune/stuff/common/parameter/validation.hh>
#include <dune/stuff/common/string.hh>
#include <dune/stuff/common/parameter/configcontainer.hh>

#include <vector>
#include <algorithm>
#include <fstream>

#include <boost/format.hpp>

namespace Dune {
namespace Stuff {
namespace Common {

/**
   *  \brief  class containing global parameters
   *  \deprecated
   *  ParameterContainer contains all the needed global parameters getting them via Dune::Parameter
   *
   **/
class ParameterContainer
{
public:
  /**
     *  \brief  destuctor
     *
     *  doing nothing
     **/
  ~ParameterContainer()
  {}

  /**
     *  \brief  prints all parameters
     *
     *  \todo   implement me
     *
     *  \param  out stream to print to
     **/
  void Print(std::ostream& out) const {
    out << "\nthis is the ParameterContainer.Print() function" << std::endl;
  }

  /**
     *  \brief  checks command line parameters
     *
     *  \return true, if comman line arguments are valid
     **/
  bool ReadCommandLine(int argc, char** argv) {
    if (argc == 2)
    {
      parameter_filename_ = argv[1];
      Dune::Parameter::append(parameter_filename_);
    } else {
      Dune::Parameter::append(argc, argv);
    }
    const std::string datadir = Dune::Parameter::getValidValue(std::string("fem.io.datadir"),
                                                               std::string("data"),
                                                               ValidateAny< std::string >()
                                                               );
    Dune::Parameter::append("fem.prefix", datadir);
    if ( !Dune::Parameter::exists("fem.io.logdir") )
      Dune::Parameter::append("fem.io.logdir", "log");
    warning_output_ = Dune::Parameter::getValue("disableParameterWarnings", warning_output_);
    return CheckSetup();
  } // ReadCommandLine

  /** \brief checks for mandatory params
     *
     *  \return true, if all needed parameters exist
     **/
  bool CheckSetup() {
    typedef std::vector< std::string >::iterator
        Iterator;
    Iterator it = mandatory_params_.begin();
    Iterator new_end = std::remove_if(it, mandatory_params_.end(), Dune::Parameter::exists);
    all_set_up_ = (new_end == it);
    for ( ; new_end != it; ++it)
    {
      std::cerr << "\nError: " << parameter_filename_
                << " is missing parameter: "
                << *it << std::endl;
    }
    return all_set_up_;
  } // CheckSetup

  /**
     *  \brief  prints, how a parameterfile schould look like
     *
     *  \param out stream to print
     **/
  void PrintParameterSpecs(std::ostream& out) {
    out << "\na valid parameterfile should at least specify the following parameters:\n"
        << "Remark: the correspondig files have to exist!\n"
        << "(copy this into your parameterfile)\n";
    std::vector< std::string >::const_iterator it = mandatory_params_.begin();
    for ( ; it != mandatory_params_.end(); ++it)
      std::cerr << *it << ": VALUE\n";
    std::cerr << std::endl;
  } // PrintParameterSpecs

  std::string DgfFilename(unsigned int dim) const {
    assert(dim > 0 && dim < 4);
    assert(all_set_up_);
    std::string retval = Dune::Parameter::getValue< std::string >( (boost::format("dgf_file_%dd") % dim).str() );
    Dune::Parameter::append( (boost::format("fem.io.macroGridFile_%dd") % dim).str(), retval );
    return retval;
  } // DgfFilename

  /** \brief  passthrough to underlying Dune::Parameter
     *  \param  useDbgStream
     *          needs to be set to false when using this function in Logging::Create,
     *              otherwise an assertion will will cause streams aren't available yet
     **/
  template< typename T >
  T getParam(std::string name, T def, bool useDbgStream = true) {
    return getParam(name, def, ValidateAny< T >(), useDbgStream);
  }

  template< typename T, class Validator >
  T getParam(std::string name, T def, const Validator& validator, bool UNUSED_UNLESS_DEBUG(useDbgStream) = true) {
    assert(all_set_up_);
    assert( validator(def) );
    #ifndef NDEBUG
    if ( warning_output_ && !Dune::Parameter::exists(name) )
    {
      if (useDbgStream)
        Dune::Stuff::Common::Logger().debug() << "WARNING: using default value for parameter \"" << name << "\"" << std::endl;
      else
        std::cerr << "WARNING: using default value for parameter \"" << name << "\"" << std::endl;
    }
    #endif // ifndef NDEBUG
    try {
      return Dune::Parameter::getValidValue(name, def, validator);
    } catch (Dune::ParameterInvalid& p) {
      std::cerr << boost::format("Dune::Fem::Parameter reports inconsistent parameter: %s\n") % p.what();
    }
    return def;
  } // getParam

  std::map< char, std::string > getFunction(const std::string& name, const std::string def = "0") {
    std::map< char, std::string > ret;
    ret['x'] = getParam(name + "_x", def);
    ret['y'] = getParam(name + "_y", def);
    ret['z'] = getParam(name + "_z", def);
    return ret;
  } // getFunction

  //! passthrough to underlying Dune::Parameter
  template< typename T >
  void setParam(std::string name, T val) {
    assert(all_set_up_);
    return Dune::Parameter::append( name, Dune::Stuff::Common::toString(val) );
  }

  //! extension to Fem::paramter that allows vector/list like paramteres from a single key
  template< class T >
  std::vector< T > getList(const std::string name, T def) {
    if ( !Dune::Parameter::exists(name) )
    {
      std::vector< T > ret;
      ret.push_back(def);
      return ret;
    }
    std::string tokenstring = getParam( name, std::string("dummy") );
    std::string delimiter = getParam(std::string("parameterlist_delimiter"), std::string(";"), false);
    return Dune::Stuff::Common::tokenize< T >(tokenstring, delimiter);
  } // getList

private:
  bool all_set_up_;
  bool warning_output_;
  std::string parameter_filename_;
  std::vector< std::string > mandatory_params_;

  /**
     *  \brief  constuctor
     *
     *  \attention  call ReadCommandLine() to set up parameterParameterContainer
     **/
  ParameterContainer()
    : all_set_up_(false)
      , warning_output_(true) {
    const std::string p[] = { "dgf_file_2d", "dgf_file_3d" };

    mandatory_params_ = std::vector< std::string >( p, p + ( sizeof(p) / sizeof(p[0]) ) );
  }

  friend ParameterContainer& Parameters();
};

//! global ParameterContainer instance
ParameterContainer& DUNE_DEPRECATED_MSG("use the Dune::ParameterTree based ConfigParameterContainer instead") Parameters() {
  static ParameterContainer parameters;
  return parameters;
}

//! get a path in datadir with existence guarantee (cannot be in filessytem.hh -- cyclic dep )
std::string getFileinDatadir(const std::string& fn) {
  boost::filesystem::path path( Config().get( "fem.io.datadir", std::string(".") ) );

  path /= fn;
  boost::filesystem::create_directories( path.parent_path() );
  return path.string();
} // getFileinDatadir

} // namespace Common
} // namespace Stuff
} // namespace Dune

#endif //HAVE_DUNE_FEM

#endif // end of DUNE_STUFF_PARAMETERHANDLER.HH

/** Copyright (c) 2012, Rene Milk
   * All rights reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions are met:
   *
   * 1. Redistributions of source code must retain the above copyright notice, this
   *    list of conditions and the following disclaimer.
   * 2. Redistributions in binary form must reproduce the above copyright notice,
   *    this list of conditions and the following disclaimer in the documentation
   *    and/or other materials provided with the distribution.
   *
   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
   * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   *
   * The views and conclusions contained in the software and documentation are those
   * of the authors and should not be interpreted as representing official policies,
   * either expressed or implied, of the FreeBSD Project.
   **/
<commit_msg>[param] delete deprecated parameter container<commit_after><|endoftext|>


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

#include "webrtc/modules/desktop_capture/win/dxgi_texture_staging.h"

#include <comdef.h>
#include <unknwn.h>
#include <DXGI.h>
#include <DXGI1_2.h>

#include "webrtc/rtc_base/checks.h"
#include "webrtc/rtc_base/logging.h"

using Microsoft::WRL::ComPtr;

namespace webrtc {

DxgiTextureStaging::DxgiTextureStaging(const D3dDevice& device)
    : device_(device) {}

DxgiTextureStaging::~DxgiTextureStaging() = default;

bool DxgiTextureStaging::InitializeStage(ID3D11Texture2D* texture) {
  RTC_DCHECK(texture);
  D3D11_TEXTURE2D_DESC desc = {0};
  texture->GetDesc(&desc);

  desc.ArraySize = 1;
  desc.BindFlags = 0;
  desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
  desc.MipLevels = 1;
  desc.MiscFlags = 0;
  desc.SampleDesc.Count = 1;
  desc.SampleDesc.Quality = 0;
  desc.Usage = D3D11_USAGE_STAGING;
  if (stage_) {
    AssertStageAndSurfaceAreSameObject();
    D3D11_TEXTURE2D_DESC current_desc;
    stage_->GetDesc(&current_desc);
    if (memcmp(&desc, &current_desc, sizeof(D3D11_TEXTURE2D_DESC)) == 0) {
      return true;
    }

    // The descriptions are not consistent, we need to create a new
    // ID3D11Texture2D instance.
    stage_.Reset();
    surface_.Reset();
  } else {
    RTC_DCHECK(!surface_);
  }

  _com_error error = device_.d3d_device()->CreateTexture2D(
      &desc, nullptr, stage_.GetAddressOf());
  if (error.Error() != S_OK || !stage_) {
    LOG(LS_ERROR) << "Failed to create a new ID3D11Texture2D as stage, error "
                  << error.ErrorMessage() << ", code " << error.Error();
    return false;
  }

  error = stage_.As(&surface_);
  if (error.Error() != S_OK || !surface_) {
    LOG(LS_ERROR) << "Failed to convert ID3D11Texture2D to IDXGISurface, error "
                  << error.ErrorMessage() << ", code " << error.Error();
    return false;
  }

  return true;
}

void DxgiTextureStaging::AssertStageAndSurfaceAreSameObject() {
  ComPtr<IUnknown> left;
  ComPtr<IUnknown> right;
  bool left_result = SUCCEEDED(stage_.As(&left));
  bool right_result = SUCCEEDED(surface_.As(&right));
  RTC_DCHECK(left_result);
  RTC_DCHECK(right_result);
  RTC_DCHECK(left.Get() == right.Get());
}

bool DxgiTextureStaging::CopyFromTexture(
    const DXGI_OUTDUPL_FRAME_INFO& frame_info,
    ID3D11Texture2D* texture) {
  RTC_DCHECK(texture && frame_info.AccumulatedFrames > 0);

  // AcquireNextFrame returns a CPU inaccessible IDXGIResource, so we need to
  // copy it to a CPU accessible staging ID3D11Texture2D.
  if (!InitializeStage(texture)) {
    return false;
  }

  device_.context()->CopyResource(static_cast<ID3D11Resource*>(stage_.Get()),
                                  static_cast<ID3D11Resource*>(texture));

  *rect() = {0};
  _com_error error = surface_->Map(rect(), DXGI_MAP_READ);
  if (error.Error() != S_OK) {
    *rect() = {0};
    LOG(LS_ERROR) << "Failed to map the IDXGISurface to a bitmap, error "
                  << error.ErrorMessage() << ", code " << error.Error();
    return false;
  }

  return true;
}

bool DxgiTextureStaging::DoRelease() {
  _com_error error = surface_->Unmap();
  if (error.Error() != S_OK) {
    stage_.Reset();
    surface_.Reset();
  }
  // If using staging mode, we only need to recreate ID3D11Texture2D instance.
  // This will happen during next CopyFrom call. So this function always returns
  // true.
  return true;
}

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

#include "webrtc/modules/desktop_capture/win/dxgi_texture_staging.h"

#include <comdef.h>
#include <unknwn.h>
#include <DXGI.h>
#include <DXGI1_2.h>

#include "webrtc/rtc_base/checks.h"
#include "webrtc/rtc_base/logging.h"
#include "webrtc/system_wrappers/include/metrics.h"

using Microsoft::WRL::ComPtr;

namespace webrtc {

DxgiTextureStaging::DxgiTextureStaging(const D3dDevice& device)
    : device_(device) {}

DxgiTextureStaging::~DxgiTextureStaging() = default;

bool DxgiTextureStaging::InitializeStage(ID3D11Texture2D* texture) {
  RTC_DCHECK(texture);
  D3D11_TEXTURE2D_DESC desc = {0};
  texture->GetDesc(&desc);

  desc.ArraySize = 1;
  desc.BindFlags = 0;
  desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
  desc.MipLevels = 1;
  desc.MiscFlags = 0;
  desc.SampleDesc.Count = 1;
  desc.SampleDesc.Quality = 0;
  desc.Usage = D3D11_USAGE_STAGING;
  if (stage_) {
    AssertStageAndSurfaceAreSameObject();
    D3D11_TEXTURE2D_DESC current_desc;
    stage_->GetDesc(&current_desc);
    const bool recreate_needed = (
        memcmp(&desc, &current_desc, sizeof(D3D11_TEXTURE2D_DESC)) != 0);
    RTC_HISTOGRAM_BOOLEAN("WebRTC.DesktopCapture.StagingTextureRecreate",
                          recreate_needed);
    if (!recreate_needed) {
      return true;
    }

    // The descriptions are not consistent, we need to create a new
    // ID3D11Texture2D instance.
    stage_.Reset();
    surface_.Reset();
  } else {
    RTC_DCHECK(!surface_);
  }

  _com_error error = device_.d3d_device()->CreateTexture2D(
      &desc, nullptr, stage_.GetAddressOf());
  if (error.Error() != S_OK || !stage_) {
    LOG(LS_ERROR) << "Failed to create a new ID3D11Texture2D as stage, error "
                  << error.ErrorMessage() << ", code " << error.Error();
    return false;
  }

  error = stage_.As(&surface_);
  if (error.Error() != S_OK || !surface_) {
    LOG(LS_ERROR) << "Failed to convert ID3D11Texture2D to IDXGISurface, error "
                  << error.ErrorMessage() << ", code " << error.Error();
    return false;
  }

  return true;
}

void DxgiTextureStaging::AssertStageAndSurfaceAreSameObject() {
  ComPtr<IUnknown> left;
  ComPtr<IUnknown> right;
  bool left_result = SUCCEEDED(stage_.As(&left));
  bool right_result = SUCCEEDED(surface_.As(&right));
  RTC_DCHECK(left_result);
  RTC_DCHECK(right_result);
  RTC_DCHECK(left.Get() == right.Get());
}

bool DxgiTextureStaging::CopyFromTexture(
    const DXGI_OUTDUPL_FRAME_INFO& frame_info,
    ID3D11Texture2D* texture) {
  RTC_DCHECK(texture && frame_info.AccumulatedFrames > 0);

  // AcquireNextFrame returns a CPU inaccessible IDXGIResource, so we need to
  // copy it to a CPU accessible staging ID3D11Texture2D.
  if (!InitializeStage(texture)) {
    return false;
  }

  device_.context()->CopyResource(static_cast<ID3D11Resource*>(stage_.Get()),
                                  static_cast<ID3D11Resource*>(texture));

  *rect() = {0};
  _com_error error = surface_->Map(rect(), DXGI_MAP_READ);
  if (error.Error() != S_OK) {
    *rect() = {0};
    LOG(LS_ERROR) << "Failed to map the IDXGISurface to a bitmap, error "
                  << error.ErrorMessage() << ", code " << error.Error();
    return false;
  }

  return true;
}

bool DxgiTextureStaging::DoRelease() {
  _com_error error = surface_->Unmap();
  if (error.Error() != S_OK) {
    stage_.Reset();
    surface_.Reset();
  }
  // If using staging mode, we only need to recreate ID3D11Texture2D instance.
  // This will happen during next CopyFrom call. So this function always returns
  // true.
  return true;
}

}  // namespace webrtc
<|endoftext|>


<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
 * Copyright (C) 2003-2005 3Dlabs Inc. Ltd.
 * Copyright (C) 2004-2005 Nathan Cournia
 * Copyright (C) 2008 Zebra Imaging
 *
 * This application is open source and may be redistributed and/or modified
 * freely and without restriction, both in commericial and non commericial
 * applications, as long as this copyright notice is maintained.
 *
 * This application 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.
 *
*/

/* file:        src/osg/GLStaticLibrary.cpp
 * author:      Alok Priyadarshi 2010-04-27
*/

#include "GLStaticLibrary.h"
#include <osg/GL>
#include <osg/Notify>

#include <map>
#include <string>

// This file is intended for GL static linking only.
#if defined(OSG_GL_LIBRARY_STATIC)

using namespace osg;

namespace {
typedef void (*GLProc)(void);
typedef std::map<std::string, GLProc> GLProcAddressMap;
static bool sProcAddressInitialized = false;
static GLProcAddressMap sProcAddressMap;

#define ADD_FUNCTION(FunctionName) sProcAddressMap[#FunctionName] = reinterpret_cast<GLProc>(&FunctionName);

void initGLES2ProcAddress()
{
    ADD_FUNCTION(glActiveTexture)
    ADD_FUNCTION(glAttachShader)
    ADD_FUNCTION(glBindAttribLocation)
    ADD_FUNCTION(glBindBuffer)
    ADD_FUNCTION(glBindFramebuffer)
    ADD_FUNCTION(glBindRenderbuffer)
    ADD_FUNCTION(glBindTexture)
    ADD_FUNCTION(glBlendColor)
    ADD_FUNCTION(glBlendEquation)
    ADD_FUNCTION(glBlendEquationSeparate)
    ADD_FUNCTION(glBlendFunc)
    ADD_FUNCTION(glBlendFuncSeparate)
    ADD_FUNCTION(glBufferData)
    ADD_FUNCTION(glBufferSubData)
    ADD_FUNCTION(glCheckFramebufferStatus)
    ADD_FUNCTION(glClear)
    ADD_FUNCTION(glClearColor)
    ADD_FUNCTION(glClearDepthf)
    ADD_FUNCTION(glClearStencil)
    ADD_FUNCTION(glColorMask)
    ADD_FUNCTION(glCompileShader)
    ADD_FUNCTION(glCompressedTexImage2D)
    ADD_FUNCTION(glCompressedTexSubImage2D)
    ADD_FUNCTION(glCopyTexImage2D)
    ADD_FUNCTION(glCopyTexSubImage2D)
    ADD_FUNCTION(glCreateProgram)
    ADD_FUNCTION(glCreateShader)
    ADD_FUNCTION(glCullFace)
    ADD_FUNCTION(glDeleteBuffers)
    ADD_FUNCTION(glDeleteFramebuffers)
    ADD_FUNCTION(glDeleteProgram)
    ADD_FUNCTION(glDeleteRenderbuffers)
    ADD_FUNCTION(glDeleteShader)
    ADD_FUNCTION(glDeleteTextures)
    ADD_FUNCTION(glDepthFunc)
    ADD_FUNCTION(glDepthMask)

    ADD_FUNCTION(glDepthRangef)
    ADD_FUNCTION(glDetachShader)
    ADD_FUNCTION(glDisable)
    ADD_FUNCTION(glDisableVertexAttribArray)
    ADD_FUNCTION(glDrawArrays)
    ADD_FUNCTION(glDrawElements)
    ADD_FUNCTION(glEnable)
    ADD_FUNCTION(glEnableVertexAttribArray)
    ADD_FUNCTION(glFinish)
    ADD_FUNCTION(glFlush)
    ADD_FUNCTION(glFramebufferRenderbuffer)
    ADD_FUNCTION(glFramebufferTexture2D)
    ADD_FUNCTION(glFrontFace)
    ADD_FUNCTION(glGenBuffers)
    ADD_FUNCTION(glGenerateMipmap)
    ADD_FUNCTION(glGenFramebuffers)
    ADD_FUNCTION(glGenRenderbuffers)
    ADD_FUNCTION(glGenTextures)
    ADD_FUNCTION(glGetActiveAttrib)
    ADD_FUNCTION(glGetActiveUniform)
    ADD_FUNCTION(glGetAttachedShaders)
    ADD_FUNCTION(glGetAttribLocation)
    ADD_FUNCTION(glGetBooleanv)
    ADD_FUNCTION(glGetBufferParameteriv)
    ADD_FUNCTION(glGetError)
    ADD_FUNCTION(glGetFloatv)
    ADD_FUNCTION(glGetFramebufferAttachmentParameteriv)
    ADD_FUNCTION(glGetIntegerv)
    ADD_FUNCTION(glGetProgramiv)
    ADD_FUNCTION(glGetProgramInfoLog)
    ADD_FUNCTION(glGetRenderbufferParameteriv)
    ADD_FUNCTION(glGetShaderiv)
    ADD_FUNCTION(glGetShaderInfoLog)
    ADD_FUNCTION(glGetShaderPrecisionFormat)
    ADD_FUNCTION(glGetShaderSource)
    ADD_FUNCTION(glGetString)
    ADD_FUNCTION(glGetTexParameterfv)
    ADD_FUNCTION(glGetTexParameteriv)
    ADD_FUNCTION(glGetUniformfv)
    ADD_FUNCTION(glGetUniformiv)
    ADD_FUNCTION(glGetUniformLocation)
    ADD_FUNCTION(glGetVertexAttribfv)
    ADD_FUNCTION(glGetVertexAttribiv)
    ADD_FUNCTION(glGetVertexAttribPointerv)
    ADD_FUNCTION(glHint)
    ADD_FUNCTION(glIsBuffer)
    ADD_FUNCTION(glIsEnabled)
    ADD_FUNCTION(glIsFramebuffer)
    ADD_FUNCTION(glIsProgram)
    ADD_FUNCTION(glIsRenderbuffer)
    ADD_FUNCTION(glIsShader)
    ADD_FUNCTION(glIsTexture)
    ADD_FUNCTION(glLineWidth)
    ADD_FUNCTION(glLinkProgram)
    ADD_FUNCTION(glPixelStorei)
    ADD_FUNCTION(glPolygonOffset)
    ADD_FUNCTION(glReadPixels)
    ADD_FUNCTION(glReleaseShaderCompiler)
    ADD_FUNCTION(glRenderbufferStorage)
    ADD_FUNCTION(glSampleCoverage)
    ADD_FUNCTION(glScissor)
    ADD_FUNCTION(glShaderBinary)
    ADD_FUNCTION(glShaderSource)
    ADD_FUNCTION(glStencilFunc)
    ADD_FUNCTION(glStencilFuncSeparate)
    ADD_FUNCTION(glStencilMask)
    ADD_FUNCTION(glStencilMaskSeparate)
    ADD_FUNCTION(glStencilOp)
    ADD_FUNCTION(glStencilOpSeparate)
    ADD_FUNCTION(glTexImage2D)
    ADD_FUNCTION(glTexParameterf)
    ADD_FUNCTION(glTexParameterfv)
    ADD_FUNCTION(glTexParameteri)
    ADD_FUNCTION(glTexParameteriv)
    ADD_FUNCTION(glTexSubImage2D)
    ADD_FUNCTION(glUniform1f)
    ADD_FUNCTION(glUniform1fv)
    ADD_FUNCTION(glUniform1i)
    ADD_FUNCTION(glUniform1iv)
    ADD_FUNCTION(glUniform2f)
    ADD_FUNCTION(glUniform2fv)
    ADD_FUNCTION(glUniform2i)
    ADD_FUNCTION(glUniform2iv)
    ADD_FUNCTION(glUniform3f)
    ADD_FUNCTION(glUniform3fv)
    ADD_FUNCTION(glUniform3i)
    ADD_FUNCTION(glUniform3iv)
    ADD_FUNCTION(glUniform4f)
    ADD_FUNCTION(glUniform4fv)
    ADD_FUNCTION(glUniform4i)
    ADD_FUNCTION(glUniform4iv)
    ADD_FUNCTION(glUniformMatrix2fv)
    ADD_FUNCTION(glUniformMatrix3fv)
    ADD_FUNCTION(glUniformMatrix4fv)
    ADD_FUNCTION(glUseProgram)
    ADD_FUNCTION(glValidateProgram)
    ADD_FUNCTION(glVertexAttrib1f)
    ADD_FUNCTION(glVertexAttrib1fv)
    ADD_FUNCTION(glVertexAttrib2f)
    ADD_FUNCTION(glVertexAttrib2fv)
    ADD_FUNCTION(glVertexAttrib3f)
    ADD_FUNCTION(glVertexAttrib3fv)
    ADD_FUNCTION(glVertexAttrib4f)
    ADD_FUNCTION(glVertexAttrib4fv)
    ADD_FUNCTION(glVertexAttribPointer)
    ADD_FUNCTION(glViewport)
}

void initProcAddress()
{
#if defined(OSG_GLES2_AVAILABLE)
    initGLES2ProcAddress();
#else
    OSG_NOTICE << "initProcAddress() not implemented for static GL lib yet." << std::endl;
#endif
}

}  // namespace

void* GLStaticLibrary::getProcAddress(const char* procName)
{
    // TODO(alokp): Add a mutex around sProcAddressInitialized.
    if (!sProcAddressInitialized)
    {
        initProcAddress();
        sProcAddressInitialized = true;
    }

    GLProcAddressMap::const_iterator iter = sProcAddressMap.find(procName);
    return iter != sProcAddressMap.end() ? iter->second : 0;
}

#endif  // OSG_GLES2_LIBRARY_STATIC

<commit_msg>From Alok Priyadarshi, build fix for gcc.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
 * Copyright (C) 2003-2005 3Dlabs Inc. Ltd.
 * Copyright (C) 2004-2005 Nathan Cournia
 * Copyright (C) 2008 Zebra Imaging
 *
 * This application is open source and may be redistributed and/or modified
 * freely and without restriction, both in commericial and non commericial
 * applications, as long as this copyright notice is maintained.
 *
 * This application 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.
 *
*/

/* file:        src/osg/GLStaticLibrary.cpp
 * author:      Alok Priyadarshi 2010-04-27
*/

#include "GLStaticLibrary.h"
#include <osg/GL>
#include <osg/Notify>

#include <map>
#include <string>

// This file is intended for GL static linking only.
#if defined(OSG_GL_LIBRARY_STATIC)

using namespace osg;

namespace {
typedef void (*GLProc)(void);
typedef std::map<std::string, GLProc> GLProcAddressMap;
static bool sProcAddressInitialized = false;
static GLProcAddressMap sProcAddressMap;

#define ADD_FUNCTION(FunctionName) sProcAddressMap[#FunctionName] = reinterpret_cast<GLProc>(&FunctionName);

void initGLES2ProcAddress()
{
    ADD_FUNCTION(glActiveTexture)
    ADD_FUNCTION(glAttachShader)
    ADD_FUNCTION(glBindAttribLocation)
    ADD_FUNCTION(glBindBuffer)
    ADD_FUNCTION(glBindFramebuffer)
    ADD_FUNCTION(glBindRenderbuffer)
    ADD_FUNCTION(glBindTexture)
    ADD_FUNCTION(glBlendColor)
    ADD_FUNCTION(glBlendEquation)
    ADD_FUNCTION(glBlendEquationSeparate)
    ADD_FUNCTION(glBlendFunc)
    ADD_FUNCTION(glBlendFuncSeparate)
    ADD_FUNCTION(glBufferData)
    ADD_FUNCTION(glBufferSubData)
    ADD_FUNCTION(glCheckFramebufferStatus)
    ADD_FUNCTION(glClear)
    ADD_FUNCTION(glClearColor)
    ADD_FUNCTION(glClearDepthf)
    ADD_FUNCTION(glClearStencil)
    ADD_FUNCTION(glColorMask)
    ADD_FUNCTION(glCompileShader)
    ADD_FUNCTION(glCompressedTexImage2D)
    ADD_FUNCTION(glCompressedTexSubImage2D)
    ADD_FUNCTION(glCopyTexImage2D)
    ADD_FUNCTION(glCopyTexSubImage2D)
    ADD_FUNCTION(glCreateProgram)
    ADD_FUNCTION(glCreateShader)
    ADD_FUNCTION(glCullFace)
    ADD_FUNCTION(glDeleteBuffers)
    ADD_FUNCTION(glDeleteFramebuffers)
    ADD_FUNCTION(glDeleteProgram)
    ADD_FUNCTION(glDeleteRenderbuffers)
    ADD_FUNCTION(glDeleteShader)
    ADD_FUNCTION(glDeleteTextures)
    ADD_FUNCTION(glDepthFunc)
    ADD_FUNCTION(glDepthMask)
    ADD_FUNCTION(glDepthRangef)
    ADD_FUNCTION(glDetachShader)
    ADD_FUNCTION(glDisable)
    ADD_FUNCTION(glDisableVertexAttribArray)
    ADD_FUNCTION(glDrawArrays)
    ADD_FUNCTION(glDrawElements)
    ADD_FUNCTION(glEnable)
    ADD_FUNCTION(glEnableVertexAttribArray)
    ADD_FUNCTION(glFinish)
    ADD_FUNCTION(glFlush)
    ADD_FUNCTION(glFramebufferRenderbuffer)
    ADD_FUNCTION(glFramebufferTexture2D)
    ADD_FUNCTION(glFrontFace)
    ADD_FUNCTION(glGenBuffers)
    ADD_FUNCTION(glGenerateMipmap)
    ADD_FUNCTION(glGenFramebuffers)
    ADD_FUNCTION(glGenRenderbuffers)
    ADD_FUNCTION(glGenTextures)
    ADD_FUNCTION(glGetActiveAttrib)
    ADD_FUNCTION(glGetActiveUniform)
    ADD_FUNCTION(glGetAttachedShaders)
    ADD_FUNCTION(glGetAttribLocation)
    ADD_FUNCTION(glGetBooleanv)
    ADD_FUNCTION(glGetBufferParameteriv)
    ADD_FUNCTION(glGetError)
    ADD_FUNCTION(glGetFloatv)
    ADD_FUNCTION(glGetFramebufferAttachmentParameteriv)
    ADD_FUNCTION(glGetIntegerv)
    ADD_FUNCTION(glGetProgramiv)
    ADD_FUNCTION(glGetProgramInfoLog)
    ADD_FUNCTION(glGetRenderbufferParameteriv)
    ADD_FUNCTION(glGetShaderiv)
    ADD_FUNCTION(glGetShaderInfoLog)
    ADD_FUNCTION(glGetShaderPrecisionFormat)
    ADD_FUNCTION(glGetShaderSource)
    ADD_FUNCTION(glGetString)
    ADD_FUNCTION(glGetTexParameterfv)
    ADD_FUNCTION(glGetTexParameteriv)
    ADD_FUNCTION(glGetUniformfv)
    ADD_FUNCTION(glGetUniformiv)
    ADD_FUNCTION(glGetUniformLocation)
    ADD_FUNCTION(glGetVertexAttribfv)
    ADD_FUNCTION(glGetVertexAttribiv)
    ADD_FUNCTION(glGetVertexAttribPointerv)
    ADD_FUNCTION(glHint)
    ADD_FUNCTION(glIsBuffer)
    ADD_FUNCTION(glIsEnabled)
    ADD_FUNCTION(glIsFramebuffer)
    ADD_FUNCTION(glIsProgram)
    ADD_FUNCTION(glIsRenderbuffer)
    ADD_FUNCTION(glIsShader)
    ADD_FUNCTION(glIsTexture)
    ADD_FUNCTION(glLineWidth)
    ADD_FUNCTION(glLinkProgram)
    ADD_FUNCTION(glPixelStorei)
    ADD_FUNCTION(glPolygonOffset)
    ADD_FUNCTION(glReadPixels)
    ADD_FUNCTION(glReleaseShaderCompiler)
    ADD_FUNCTION(glRenderbufferStorage)
    ADD_FUNCTION(glSampleCoverage)
    ADD_FUNCTION(glScissor)
    ADD_FUNCTION(glShaderBinary)
    ADD_FUNCTION(glShaderSource)
    ADD_FUNCTION(glStencilFunc)
    ADD_FUNCTION(glStencilFuncSeparate)
    ADD_FUNCTION(glStencilMask)
    ADD_FUNCTION(glStencilMaskSeparate)
    ADD_FUNCTION(glStencilOp)
    ADD_FUNCTION(glStencilOpSeparate)
    ADD_FUNCTION(glTexImage2D)
    ADD_FUNCTION(glTexParameterf)
    ADD_FUNCTION(glTexParameterfv)
    ADD_FUNCTION(glTexParameteri)
    ADD_FUNCTION(glTexParameteriv)
    ADD_FUNCTION(glTexSubImage2D)
    ADD_FUNCTION(glUniform1f)
    ADD_FUNCTION(glUniform1fv)
    ADD_FUNCTION(glUniform1i)
    ADD_FUNCTION(glUniform1iv)
    ADD_FUNCTION(glUniform2f)
    ADD_FUNCTION(glUniform2fv)
    ADD_FUNCTION(glUniform2i)
    ADD_FUNCTION(glUniform2iv)
    ADD_FUNCTION(glUniform3f)
    ADD_FUNCTION(glUniform3fv)
    ADD_FUNCTION(glUniform3i)
    ADD_FUNCTION(glUniform3iv)
    ADD_FUNCTION(glUniform4f)
    ADD_FUNCTION(glUniform4fv)
    ADD_FUNCTION(glUniform4i)
    ADD_FUNCTION(glUniform4iv)
    ADD_FUNCTION(glUniformMatrix2fv)
    ADD_FUNCTION(glUniformMatrix3fv)
    ADD_FUNCTION(glUniformMatrix4fv)
    ADD_FUNCTION(glUseProgram)
    ADD_FUNCTION(glValidateProgram)
    ADD_FUNCTION(glVertexAttrib1f)
    ADD_FUNCTION(glVertexAttrib1fv)
    ADD_FUNCTION(glVertexAttrib2f)
    ADD_FUNCTION(glVertexAttrib2fv)
    ADD_FUNCTION(glVertexAttrib3f)
    ADD_FUNCTION(glVertexAttrib3fv)
    ADD_FUNCTION(glVertexAttrib4f)
    ADD_FUNCTION(glVertexAttrib4fv)
    ADD_FUNCTION(glVertexAttribPointer)
    ADD_FUNCTION(glViewport)
}

void initProcAddress()
{
#if defined(OSG_GLES2_AVAILABLE)
    initGLES2ProcAddress();
#else
    OSG_NOTICE << "initProcAddress() not implemented for static GL lib yet." << std::endl;
#endif
}

}  // namespace

void* GLStaticLibrary::getProcAddress(const char* procName)
{
    // TODO(alokp): Add a mutex around sProcAddressInitialized.
    if (!sProcAddressInitialized)
    {
        initProcAddress();
        sProcAddressInitialized = true;
    }

    GLProcAddressMap::const_iterator iter = sProcAddressMap.find(procName);
    return iter != sProcAddressMap.end() ? reinterpret_cast<void*>(iter->second) : 0;
}

#endif  // OSG_GLES2_LIBRARY_STATIC
<|endoftext|>


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

//-----------------------------------------------------------------------------
/// \class AliAnalysisTaskSingleMu
/// Analysis task for single muons in the spectrometer.
/// The output is a list of histograms.
/// The macro class can run on AOD or ESDs.
/// If Monte Carlo information is present, some basics checks are performed.
///
/// \author Diego Stocco
//-----------------------------------------------------------------------------

//----------------------------------------------------------------------------
//    Implementation of the class for trigger chamber efficiency determinaltion
//----------------------------------------------------------------------------

#define AliAnalysisTaskTrigChEff_cxx

// ROOT includes
#include "TH1.h"
#include "TCanvas.h"
#include "TROOT.h"
#include "TString.h"
#include "TList.h"

// STEER includes
#include "AliLog.h"
#include "AliESDEvent.h"
#include "AliESDMuonTrack.h"

// ANALYSIS includes
#include "AliAnalysisTaskSE.h"

#include "AliAnalysisTaskTrigChEff.h"

ClassImp(AliAnalysisTaskTrigChEff)

//________________________________________________________________________
AliAnalysisTaskTrigChEff::AliAnalysisTaskTrigChEff(const char *name) :
  AliAnalysisTaskSE(name),
  fUseGhosts(kFALSE),
  fList(0)
{
  //
  /// Constructor.
  //
  // Output slot #1 writes into a TObjArray container
  DefineOutput(1,  TList::Class());
  if (fUseGhosts) AliInfo("Use also trigger tracks not matching tracker tracks");
}

//________________________________________________________________________
AliAnalysisTaskTrigChEff::~AliAnalysisTaskTrigChEff()
{
  delete fList;
}

//___________________________________________________________________________
void AliAnalysisTaskTrigChEff::UserCreateOutputObjects() {
  //
  /// Create histograms
  /// Called once
  //

  TString cathCode[2] = {"bendPlane", "nonBendPlane"};
  TString countTypeName[2] = {"CountInCh", "NonCountInCh"};

  const Char_t* yAxisTitle = "counts";

  const Int_t kNboards = 234; //AliMpConstants::NofLocalBoards();
  const Int_t kFirstTrigCh = 11;//AliMpConstants::NofTrackingChambers()+1;

  Int_t chamberBins = kNchambers;
  Float_t chamberLow = kFirstTrigCh-0.5, chamberHigh = kFirstTrigCh+kNchambers-0.5;
  const Char_t* chamberName = "chamber";

  Int_t slatBins = kNslats;
  Float_t slatLow = 0-0.5, slatHigh = kNslats-0.5;
  const Char_t* slatName = "slat";

  Int_t boardBins = kNboards;
  Float_t boardLow = 1-0.5, boardHigh = kNboards+1.-0.5;
  const Char_t* boardName = "board";

  Int_t angleBins = 280;
  Float_t angleLow = -70., angleHigh = 70.;
  const Char_t* angleNameX = "#theta_{x} (deg)";
  const Char_t* angleNameY = "#theta_{y} (deg)";

  TString baseName, histoName;
  fList = new TList();

  TH1F* histo;

  histo = new TH1F("nTracksInSlat", "Num. of tracks used for efficiency calculation",
		   slatBins, slatLow, slatHigh);
  histo->GetXaxis()->SetTitle(slatName);
  histo->GetYaxis()->SetTitle("num of used tracks");

  fList->AddAt(histo, kHtracksInSlat);

  histo = new TH1F("nTracksInBoard", "Num. of tracks used for efficiency calculation",
		   boardBins, boardLow, boardHigh);
  histo->GetXaxis()->SetTitle(boardName);
  histo->GetYaxis()->SetTitle("num of used tracks");

  fList->AddAt(histo, kHtracksInBoard);

  for(Int_t hType=0; hType<kNcounts; hType++){
    Int_t hindex = (hType==0) ? kHchamberEff : kHchamberNonEff;
    for(Int_t cath=0; cath<kNcathodes; cath++){
      histoName = Form("%sChamber%s", cathCode[cath].Data(), countTypeName[hType].Data());
      histo = new TH1F(histoName, histoName,
		       chamberBins, chamberLow, chamberHigh);
      histo->GetXaxis()->SetTitle(chamberName);
      histo->GetYaxis()->SetTitle(yAxisTitle);

      fList->AddAt(histo, hindex + cath);
    } // loop on cath
  } // loop on counts

  for(Int_t hType=0; hType<kNcounts; hType++){
    Int_t hindex = (hType==0) ? kHslatEff : kHslatNonEff;
    for(Int_t cath=0; cath<kNcathodes; cath++){
      for(Int_t ch=0; ch<kNchambers; ch++){
	Int_t chCath = GetPlane(cath, ch);
	histoName = Form("%sSlat%s%i", cathCode[cath].Data(), countTypeName[hType].Data(), kFirstTrigCh+ch);
	histo = new TH1F(histoName, histoName,
			 slatBins, slatLow, slatHigh);
	histo->GetXaxis()->SetTitle(slatName);
	histo->GetYaxis()->SetTitle(yAxisTitle);

	fList->AddAt(histo, hindex + chCath);
      } // loop on chamber
    } // loop on cath
  } // loop on counts

  for(Int_t hType=0; hType<kNcounts; hType++){
    Int_t hindex = (hType==0) ? kHboardEff : kHboardNonEff;
    for(Int_t cath=0; cath<kNcathodes; cath++){
      for(Int_t ch=0; ch<kNchambers; ch++){
	Int_t chCath = GetPlane(cath, ch);
	histoName = Form("%sBoard%s%i", cathCode[cath].Data(), countTypeName[hType].Data(), kFirstTrigCh+ch);
	histo = new TH1F(histoName, histoName,
			 boardBins, boardLow, boardHigh);
	histo->GetXaxis()->SetTitle(boardName);
	histo->GetYaxis()->SetTitle(yAxisTitle);

	fList->AddAt(histo, hindex + chCath);
      } // loop on chamber
    } // loop on cath
  } // loop on counts

  histo = new TH1F("thetaX", "Angular distribution",
		   angleBins, angleLow, angleHigh);
  histo->GetXaxis()->SetTitle(angleNameX);
  histo->GetYaxis()->SetTitle("entries");
  fList->AddAt(histo, kHthetaX);

  histo = new TH1F("thetaY", "Angular distribution",
		   angleBins, angleLow, angleHigh);
  histo->GetXaxis()->SetTitle(angleNameY);
  histo->GetYaxis()->SetTitle("entries");
  fList->AddAt(histo, kHthetaY);

}

//________________________________________________________________________
void AliAnalysisTaskTrigChEff::UserExec(Option_t *) {
  //
  /// Main loop
  /// Called for each event
  //
  AliESDEvent* esdEvent = dynamic_cast<AliESDEvent*> (InputEvent());

  if (!esdEvent) {
    Printf("ERROR: esdEvent not available\n");
    return;
  }

  Int_t slat = 0, board = 0;
  UShort_t pattern = 0;
  AliESDMuonTrack *esdTrack = 0x0;

  const Float_t kRadToDeg = 180./TMath::Pi();
  Int_t nTracks = esdEvent->GetNumberOfMuonTracks();

  const Int_t kFirstTrigCh = 11; //AliMpConstants::NofTrackingChambers()+1;

  TArrayI othersEfficient(kNchambers);

  for (Int_t itrack = 0; itrack < nTracks; itrack++) {
    esdTrack = esdEvent->GetMuonTrack(itrack);

    if ( ! esdTrack->ContainTrackerData() && ! fUseGhosts ) continue;

    pattern =  esdTrack->GetHitsPatternInTrigCh();
    Int_t effFlag = AliESDMuonTrack::GetEffFlag(pattern);

    if(effFlag < AliESDMuonTrack::kChEff) continue; // Track not good for efficiency calculation

    ((TH1F*)fList->At(kHthetaX))->Fill(esdTrack->GetThetaX() * kRadToDeg);
    ((TH1F*)fList->At(kHthetaY))->Fill(esdTrack->GetThetaY() * kRadToDeg);

    othersEfficient.Reset(1);
    for(Int_t cath=0; cath<kNcathodes; cath++){
      for(Int_t ich=0; ich<kNchambers; ich++){
	if( ! AliESDMuonTrack::IsChamberHit(pattern, cath, ich)){
	  for(Int_t jch=0; jch<kNchambers; jch++){
	    if ( jch != ich) {
	      othersEfficient[jch] = 0;
	      //AliInfo(Form("%s ch %i by New", baseOutString.Data(), jch));
	    }
	  } // loop on other chambers
	  break;
	} // if chamber not efficient
      } // loop on chambers
    } // loop on cathodes

    Bool_t rejectTrack = kTRUE;
    for (Int_t ich=0; ich<kNchambers; ich++){
      if ( othersEfficient[ich] > 0 ){
	rejectTrack = kFALSE;
	break;
      }
    }

    if ( rejectTrack ) continue;

    slat = AliESDMuonTrack::GetSlatOrInfo(pattern);
    board = esdTrack->LoCircuit();

    if(effFlag >= AliESDMuonTrack::kSlatEff) ((TH1F*)fList->At(kHtracksInSlat))->Fill(slat);
    if(effFlag >= AliESDMuonTrack::kBoardEff) ((TH1F*)fList->At(kHtracksInBoard))->Fill(board);

    for(Int_t cath=0; cath<kNcathodes; cath++){
      for(Int_t ch=0; ch<kNchambers; ch++){
	if ( ! othersEfficient[ch] )
	  continue; // Reject track if the info of the chamber under study
	            // is necessary to create the track itself

	Int_t whichType = AliESDMuonTrack::IsChamberHit(pattern, cath, ch) ? kChHit : kChNonHit;

	Int_t iChamber = kFirstTrigCh + ch;
	Int_t hindex = ( whichType == kChHit ) ? kHchamberEff : kHchamberNonEff;
	((TH1F*)fList->At(hindex + cath))->Fill(iChamber);

	if(effFlag < AliESDMuonTrack::kSlatEff) continue; // Track crossed different slats
	Int_t chCath = GetPlane(cath, ch);
	hindex = ( whichType == kChHit ) ? kHslatEff : kHslatNonEff;
	((TH1F*)fList->At(hindex + chCath))->Fill(slat);

	if(effFlag < AliESDMuonTrack::kBoardEff) continue; // Track crossed different boards
	hindex = ( whichType == kChHit ) ? kHboardEff : kHboardNonEff;
	((TH1F*)fList->At(hindex + chCath))->Fill(board);
      } // loop on chambers
    } // loop on cathodes
  } // loop on tracks

  // Post final data. It will be written to a file with option "RECREATE"
  PostData(1, fList);
}

//________________________________________________________________________
void AliAnalysisTaskTrigChEff::Terminate(Option_t *) {
  //
  /// Draw result to the screen
  /// Called once at the end of the query.
  //
  if (!gROOT->IsBatch()) {
    fList = dynamic_cast<TList*> (GetOutputData(1));

    TCanvas *can[kNcathodes];
    TH1F *num = 0x0;
    TH1F *den = 0x0;
    for(Int_t cath=0; cath<kNcathodes; cath++){
      TString canName = Form("can%i",cath);
      can[cath] = new TCanvas(canName.Data(),canName.Data(),10*(1+cath),10*(1+cath),310,310);
      can[cath]->SetFillColor(10); can[cath]->SetHighLightColor(10);
      can[cath]->SetLeftMargin(0.15); can[cath]->SetBottomMargin(0.15);
      can[cath]->Divide(2,2);
      for(Int_t ch=0; ch<kNchambers; ch++){
	Int_t chCath = GetPlane(cath, ch);
	num = (TH1F*)(fList->At(kHboardEff + chCath)->Clone());
	den = (TH1F*)(fList->At(kHboardNonEff + chCath)->Clone());
	den->Add(num);
	num->Divide(den);
	can[cath]->cd(ch+1);
	num->DrawCopy("E");
      }
    }
  }
}
<commit_msg>1. Correctly fill the theta values for ghosts. 2. Improve the efficiency plots in the terminate function  (Diego)<commit_after>/**************************************************************************
 * Copyright(c) 1998-2007, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

//-----------------------------------------------------------------------------
/// \class AliAnalysisTaskSingleMu
/// Analysis task for single muons in the spectrometer.
/// The output is a list of histograms.
/// The macro class can run on AOD or ESDs.
/// If Monte Carlo information is present, some basics checks are performed.
///
/// \author Diego Stocco
//-----------------------------------------------------------------------------

//----------------------------------------------------------------------------
//    Implementation of the class for trigger chamber efficiency determinaltion
//----------------------------------------------------------------------------

#define AliAnalysisTaskTrigChEff_cxx

// ROOT includes
#include "TH1.h"
#include "TCanvas.h"
#include "TROOT.h"
#include "TString.h"
#include "TList.h"
#include "TGraphAsymmErrors.h"

// STEER includes
#include "AliLog.h"
#include "AliESDEvent.h"
#include "AliESDMuonTrack.h"

// ANALYSIS includes
#include "AliAnalysisTaskSE.h"

#include "AliAnalysisTaskTrigChEff.h"

ClassImp(AliAnalysisTaskTrigChEff)

//________________________________________________________________________
AliAnalysisTaskTrigChEff::AliAnalysisTaskTrigChEff(const char *name) :
  AliAnalysisTaskSE(name),
  fUseGhosts(kFALSE),
  fList(0)
{
  //
  /// Constructor.
  //
  // Output slot #1 writes into a TObjArray container
  DefineOutput(1,  TList::Class());
}

//________________________________________________________________________
AliAnalysisTaskTrigChEff::~AliAnalysisTaskTrigChEff()
{
  delete fList;
}

//___________________________________________________________________________
void AliAnalysisTaskTrigChEff::UserCreateOutputObjects() {
  //
  /// Create histograms
  /// Called once
  //

  TString cathCode[2] = {"bendPlane", "nonBendPlane"};
  TString countTypeName[2] = {"CountInCh", "NonCountInCh"};

  const Char_t* yAxisTitle = "counts";

  const Int_t kNboards = 234; //AliMpConstants::NofLocalBoards();
  const Int_t kFirstTrigCh = 11;//AliMpConstants::NofTrackingChambers()+1;

  Int_t chamberBins = kNchambers;
  Float_t chamberLow = kFirstTrigCh-0.5, chamberHigh = kFirstTrigCh+kNchambers-0.5;
  const Char_t* chamberName = "chamber";

  Int_t slatBins = kNslats;
  Float_t slatLow = 0-0.5, slatHigh = kNslats-0.5;
  const Char_t* slatName = "slat";

  Int_t boardBins = kNboards;
  Float_t boardLow = 1-0.5, boardHigh = kNboards+1.-0.5;
  const Char_t* boardName = "board";

  Int_t angleBins = 280;
  Float_t angleLow = -70., angleHigh = 70.;
  const Char_t* angleNameX = "#theta_{x} (deg)";
  const Char_t* angleNameY = "#theta_{y} (deg)";

  TString baseName, histoName;
  fList = new TList();

  TH1F* histo;

  histo = new TH1F("nTracksInSlat", "Num. of tracks used for efficiency calculation",
		   slatBins, slatLow, slatHigh);
  histo->GetXaxis()->SetTitle(slatName);
  histo->GetYaxis()->SetTitle("num of used tracks");

  fList->AddAt(histo, kHtracksInSlat);

  histo = new TH1F("nTracksInBoard", "Num. of tracks used for efficiency calculation",
		   boardBins, boardLow, boardHigh);
  histo->GetXaxis()->SetTitle(boardName);
  histo->GetYaxis()->SetTitle("num of used tracks");

  fList->AddAt(histo, kHtracksInBoard);

  for(Int_t hType=0; hType<kNcounts; hType++){
    Int_t hindex = (hType==0) ? kHchamberEff : kHchamberNonEff;
    for(Int_t cath=0; cath<kNcathodes; cath++){
      histoName = Form("%sChamber%s", cathCode[cath].Data(), countTypeName[hType].Data());
      histo = new TH1F(histoName, histoName,
		       chamberBins, chamberLow, chamberHigh);
      histo->GetXaxis()->SetTitle(chamberName);
      histo->GetYaxis()->SetTitle(yAxisTitle);

      fList->AddAt(histo, hindex + cath);
    } // loop on cath
  } // loop on counts

  for(Int_t hType=0; hType<kNcounts; hType++){
    Int_t hindex = (hType==0) ? kHslatEff : kHslatNonEff;
    for(Int_t cath=0; cath<kNcathodes; cath++){
      for(Int_t ch=0; ch<kNchambers; ch++){
	Int_t chCath = GetPlane(cath, ch);
	histoName = Form("%sSlat%s%i", cathCode[cath].Data(), countTypeName[hType].Data(), kFirstTrigCh+ch);
	histo = new TH1F(histoName, histoName,
			 slatBins, slatLow, slatHigh);
	histo->GetXaxis()->SetTitle(slatName);
	histo->GetYaxis()->SetTitle(yAxisTitle);

	fList->AddAt(histo, hindex + chCath);
      } // loop on chamber
    } // loop on cath
  } // loop on counts

  for(Int_t hType=0; hType<kNcounts; hType++){
    Int_t hindex = (hType==0) ? kHboardEff : kHboardNonEff;
    for(Int_t cath=0; cath<kNcathodes; cath++){
      for(Int_t ch=0; ch<kNchambers; ch++){
	Int_t chCath = GetPlane(cath, ch);
	histoName = Form("%sBoard%s%i", cathCode[cath].Data(), countTypeName[hType].Data(), kFirstTrigCh+ch);
	histo = new TH1F(histoName, histoName,
			 boardBins, boardLow, boardHigh);
	histo->GetXaxis()->SetTitle(boardName);
	histo->GetYaxis()->SetTitle(yAxisTitle);

	fList->AddAt(histo, hindex + chCath);
      } // loop on chamber
    } // loop on cath
  } // loop on counts

  histo = new TH1F("thetaX", "Angular distribution",
		   angleBins, angleLow, angleHigh);
  histo->GetXaxis()->SetTitle(angleNameX);
  histo->GetYaxis()->SetTitle("entries");
  fList->AddAt(histo, kHthetaX);

  histo = new TH1F("thetaY", "Angular distribution",
		   angleBins, angleLow, angleHigh);
  histo->GetXaxis()->SetTitle(angleNameY);
  histo->GetYaxis()->SetTitle("entries");
  fList->AddAt(histo, kHthetaY);

}

//________________________________________________________________________
void AliAnalysisTaskTrigChEff::UserExec(Option_t *) {
  //
  /// Main loop
  /// Called for each event
  //
  AliESDEvent* esdEvent = dynamic_cast<AliESDEvent*> (InputEvent());

  if (!esdEvent) {
    Printf("ERROR: esdEvent not available\n");
    return;
  }

  Int_t slat = 0, board = 0;
  UShort_t pattern = 0;
  AliESDMuonTrack *esdTrack = 0x0;

  Int_t nTracks = esdEvent->GetNumberOfMuonTracks();

  const Int_t kFirstTrigCh = 11; //AliMpConstants::NofTrackingChambers()+1;

  TArrayI othersEfficient(kNchambers);

  for (Int_t itrack = 0; itrack < nTracks; itrack++) {
    esdTrack = esdEvent->GetMuonTrack(itrack);

    if ( ! esdTrack->ContainTrackerData() && ! fUseGhosts ) continue;

    pattern =  esdTrack->GetHitsPatternInTrigCh();
    Int_t effFlag = AliESDMuonTrack::GetEffFlag(pattern);

    if(effFlag < AliESDMuonTrack::kChEff) continue; // Track not good for efficiency calculation

    ((TH1F*)fList->At(kHthetaX))->Fill(esdTrack->GetThetaXUncorrected() * TMath::RadToDeg());
    ((TH1F*)fList->At(kHthetaY))->Fill(esdTrack->GetThetaYUncorrected() * TMath::RadToDeg());

    othersEfficient.Reset(1);
    for(Int_t cath=0; cath<kNcathodes; cath++){
      for(Int_t ich=0; ich<kNchambers; ich++){
	if( ! AliESDMuonTrack::IsChamberHit(pattern, cath, ich)){
	  for(Int_t jch=0; jch<kNchambers; jch++){
	    if ( jch != ich) {
	      othersEfficient[jch] = 0;
	      //AliInfo(Form("%s ch %i by New", baseOutString.Data(), jch));
	    }
	  } // loop on other chambers
	  break;
	} // if chamber not efficient
      } // loop on chambers
    } // loop on cathodes

    Bool_t rejectTrack = kTRUE;
    for (Int_t ich=0; ich<kNchambers; ich++){
      if ( othersEfficient[ich] > 0 ){
	rejectTrack = kFALSE;
	break;
      }
    }

    if ( rejectTrack ) continue;

    slat = AliESDMuonTrack::GetSlatOrInfo(pattern);
    board = esdTrack->LoCircuit();

    if(effFlag >= AliESDMuonTrack::kSlatEff) ((TH1F*)fList->At(kHtracksInSlat))->Fill(slat);
    if(effFlag >= AliESDMuonTrack::kBoardEff) ((TH1F*)fList->At(kHtracksInBoard))->Fill(board);

    for(Int_t cath=0; cath<kNcathodes; cath++){
      for(Int_t ch=0; ch<kNchambers; ch++){
	if ( ! othersEfficient[ch] )
	  continue; // Reject track if the info of the chamber under study
	            // is necessary to create the track itself

	Int_t whichType = AliESDMuonTrack::IsChamberHit(pattern, cath, ch) ? kChHit : kChNonHit;

	Int_t iChamber = kFirstTrigCh + ch;
	Int_t hindex = ( whichType == kChHit ) ? kHchamberEff : kHchamberNonEff;
	((TH1F*)fList->At(hindex + cath))->Fill(iChamber);

	if(effFlag < AliESDMuonTrack::kSlatEff) continue; // Track crossed different slats
	Int_t chCath = GetPlane(cath, ch);
	hindex = ( whichType == kChHit ) ? kHslatEff : kHslatNonEff;
	((TH1F*)fList->At(hindex + chCath))->Fill(slat);

	if(effFlag < AliESDMuonTrack::kBoardEff) continue; // Track crossed different boards
	hindex = ( whichType == kChHit ) ? kHboardEff : kHboardNonEff;
	((TH1F*)fList->At(hindex + chCath))->Fill(board);
      } // loop on chambers
    } // loop on cathodes
  } // loop on tracks

  // Post final data. It will be written to a file with option "RECREATE"
  PostData(1, fList);
}

//________________________________________________________________________
void AliAnalysisTaskTrigChEff::Terminate(Option_t *) {
  //
  /// Draw result to the screen
  /// Called once at the end of the query.
  //
  if ( gROOT->IsBatch() ) return;
  fList = dynamic_cast<TList*> (GetOutputData(1));

  TCanvas *can;
  TH1F *num = 0x0;
  TH1F *den = 0x0;
  TGraphAsymmErrors* effGraph = 0x0;
  TString baseName[3] = {"Chamber", "RPC", "Board"};
  Int_t baseIndex1[3] = {kHchamberEff, kHslatEff, kHboardEff};
  Int_t baseIndex2[3] = {kHchamberNonEff, kHslatNonEff, kHboardNonEff};
  TString cathName[2] = {"BendPlane", "NonBendPlane"};
  for (Int_t itype=0; itype<3; itype++) {
    for(Int_t cath=0; cath<kNcathodes; cath++){
      TString canName = Form("efficiencyPer%s_%s",baseName[itype].Data(),cathName[cath].Data());
      can = new TCanvas(canName.Data(),canName.Data(),10*(1+2*itype+cath),10*(1+2*itype+cath),310,310);
      can->SetFillColor(10); can->SetHighLightColor(10);
      can->SetLeftMargin(0.15); can->SetBottomMargin(0.15);
      if ( itype > 0 )
	can->Divide(2,2);

      for(Int_t ch=0; ch<kNchambers; ch++){
	Int_t chCath = ( itype == 0 ) ? cath : GetPlane(cath, ch);
	num = (TH1F*)(fList->At(baseIndex1[itype] + chCath)->Clone());
	den = (TH1F*)(fList->At(baseIndex2[itype] + chCath)->Clone());
	den->Add(num);
	effGraph = new TGraphAsymmErrors(num, den);
	effGraph->GetYaxis()->SetRangeUser(0., 1.1);
	effGraph->GetYaxis()->SetTitle("Efficiency");
	effGraph->GetXaxis()->SetTitle(baseName[itype].Data());
	can->cd(ch+1);
	effGraph->Draw("AP");
	if ( itype == 0 ) break;
      } // loop on chamber
    } // loop on cathode
  } // loop on histo
}
<|endoftext|>


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

#include "webrtc/modules/desktop_capture/window_capturer.h"

#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/base/scoped_ptr.h"
#include "webrtc/modules/desktop_capture/desktop_capture_options.h"
#include "webrtc/modules/desktop_capture/desktop_frame.h"
#include "webrtc/modules/desktop_capture/desktop_region.h"
#include "webrtc/system_wrappers/interface/logging.h"

namespace webrtc {

class WindowCapturerTest : public testing::Test,
                           public DesktopCapturer::Callback {
 public:
  void SetUp() override {
    capturer_.reset(
        WindowCapturer::Create(DesktopCaptureOptions::CreateDefault()));
  }

  void TearDown() override {}

  // DesktopCapturer::Callback interface
  SharedMemory* CreateSharedMemory(size_t size) override { return NULL; }

  void OnCaptureCompleted(DesktopFrame* frame) override { frame_.reset(frame); }

 protected:
  rtc::scoped_ptr<WindowCapturer> capturer_;
  rtc::scoped_ptr<DesktopFrame> frame_;
};

// Verify that we can enumerate windows.
TEST_F(WindowCapturerTest, Enumerate) {
  WindowCapturer::WindowList windows;
  EXPECT_TRUE(capturer_->GetWindowList(&windows));

  // Verify that window titles are set.
  for (WindowCapturer::WindowList::iterator it = windows.begin();
       it != windows.end(); ++it) {
    EXPECT_FALSE(it->title.empty());
  }
}

// Verify we can capture a window.
//
// TODO(sergeyu): Currently this test just looks at the windows that already
// exist. Ideally it should create a test window and capture from it, but there
// is no easy cross-platform way to create new windows (potentially we could
// have a python script showing Tk dialog, but launching code will differ
// between platforms).
TEST_F(WindowCapturerTest, Capture) {
  WindowCapturer::WindowList windows;
  capturer_->Start(this);
  EXPECT_TRUE(capturer_->GetWindowList(&windows));

  // Verify that we can select and capture each window.
  for (WindowCapturer::WindowList::iterator it = windows.begin();
       it != windows.end(); ++it) {
    frame_.reset();
    if (capturer_->SelectWindow(it->id)) {
      capturer_->Capture(DesktopRegion());
    }

    // If we failed to capture a window make sure it no longer exists.
    if (!frame_.get()) {
      WindowCapturer::WindowList new_list;
      EXPECT_TRUE(capturer_->GetWindowList(&new_list));
      for (WindowCapturer::WindowList::iterator new_list_it = windows.begin();
           new_list_it != windows.end(); ++new_list_it) {
        EXPECT_FALSE(it->id == new_list_it->id);
      }
      continue;
    }

    EXPECT_GT(frame_->size().width(), 0);
    EXPECT_GT(frame_->size().height(), 0);
  }
}

}  // namespace webrtc
<commit_msg>Fix an apparent typo in a unittest that caused it to not actually check the new window list it fetched.<commit_after>/*
 *  Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/modules/desktop_capture/window_capturer.h"

#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/base/scoped_ptr.h"
#include "webrtc/modules/desktop_capture/desktop_capture_options.h"
#include "webrtc/modules/desktop_capture/desktop_frame.h"
#include "webrtc/modules/desktop_capture/desktop_region.h"
#include "webrtc/system_wrappers/interface/logging.h"

namespace webrtc {

class WindowCapturerTest : public testing::Test,
                           public DesktopCapturer::Callback {
 public:
  void SetUp() override {
    capturer_.reset(
        WindowCapturer::Create(DesktopCaptureOptions::CreateDefault()));
  }

  void TearDown() override {}

  // DesktopCapturer::Callback interface
  SharedMemory* CreateSharedMemory(size_t size) override { return NULL; }

  void OnCaptureCompleted(DesktopFrame* frame) override { frame_.reset(frame); }

 protected:
  rtc::scoped_ptr<WindowCapturer> capturer_;
  rtc::scoped_ptr<DesktopFrame> frame_;
};

// Verify that we can enumerate windows.
TEST_F(WindowCapturerTest, Enumerate) {
  WindowCapturer::WindowList windows;
  EXPECT_TRUE(capturer_->GetWindowList(&windows));

  // Verify that window titles are set.
  for (WindowCapturer::WindowList::iterator it = windows.begin();
       it != windows.end(); ++it) {
    EXPECT_FALSE(it->title.empty());
  }
}

// Verify we can capture a window.
//
// TODO(sergeyu): Currently this test just looks at the windows that already
// exist. Ideally it should create a test window and capture from it, but there
// is no easy cross-platform way to create new windows (potentially we could
// have a python script showing Tk dialog, but launching code will differ
// between platforms).
TEST_F(WindowCapturerTest, Capture) {
  WindowCapturer::WindowList windows;
  capturer_->Start(this);
  EXPECT_TRUE(capturer_->GetWindowList(&windows));

  // Verify that we can select and capture each window.
  for (WindowCapturer::WindowList::iterator it = windows.begin();
       it != windows.end(); ++it) {
    frame_.reset();
    if (capturer_->SelectWindow(it->id)) {
      capturer_->Capture(DesktopRegion());
    }

    // If we failed to capture a window make sure it no longer exists.
    if (!frame_.get()) {
      WindowCapturer::WindowList new_list;
      EXPECT_TRUE(capturer_->GetWindowList(&new_list));
      for (WindowCapturer::WindowList::iterator new_list_it = new_list.begin();
           new_list_it != new_list.end(); ++new_list_it) {
        EXPECT_FALSE(it->id == new_list_it->id);
      }
      continue;
    }

    EXPECT_GT(frame_->size().width(), 0);
    EXPECT_GT(frame_->size().height(), 0);
  }
}

}  // namespace webrtc
<|endoftext|>


<commit_before>/// @brief provides CORDIC for cos function
/// @ref see H. Dawid, H. Meyr, "CORDIC Algorithms and Architectures"

#include "./../../fixed_point_lib/src/CORDIC/lut/lut.hpp"

namespace std {
    template<typename T, size_t n, size_t f, class op, class up>
    utils::number<T, n, f, op, up> cos(utils::number<T, n, f, op, up> const& val)
    {
        #define pi fixed_point(3.141592653589793)
        #define pi2 fixed_point(6.283185307179586)
        #define pi_half fixed_point(1.5707963267948965)

        typedef utils::number<T, n, f, op, up> fixed_point;
        using utils::cordic::lut;
        BOOST_STATIC_ASSERT(std::numeric_limits<fixed_point>::is_signed);

        // convergence interval for CORDIC rotations is [-pi/2, pi/2].
        // So one has to map input angle to that interval
        fixed_point arg(0);
        int sign(-1);
        {
            // put argument to [-pi, pi] interval (with change of sign for
            // cos)
            fixed_point const x = pi - std::fmod(val, pi2);
            if (x < -pi_half) {     // convert to interval [-pi/2, pi/2]
                arg = x + pi;

                sign = 1;
            }
            else if (x > pi_half) {
                arg = x - pi;

                sign = 1;
            }
            else {
                arg = x;
            }
        }

        typedef lut<f, fixed_point> lut_type;
        static lut_type const angles = lut_type::build_arctan_lut();

        // normalization factor: see page 10, table 24.1 and pages 4-5, equations
        // (5)-(6)
        // factor converges to the limit 1.64676 very fast: it tooks 8 iterations
        // only. 8 iterations correpsonds to precision of size 0.007812 for
        // angle approximation
        static fixed_point norm_factor(1.0 / lut_type::compute_circular_scale(f));

        // rotation mode: see page 6
        // shift sequence is just 0, 1, ... (circular coordinate system)
        fixed_point x(norm_factor), y(0.0), z(arg);
        fixed_point x1, y1, z1;
        BOOST_FOREACH(size_t i, boost::irange<size_t>(0, f, 1))
        {
            int const sign = (z > fixed_point(0)) ? 1 : -1;
            fixed_point const x_scaled = fixed_point::wrap(sign * (x.value() >> i));
            fixed_point const y_scaled = fixed_point::wrap(sign * (y.value() >> i));

            x1 = fixed_point(x - y_scaled);
            y1 = fixed_point(y + x_scaled);
            z1 = fixed_point(z - fixed_point((sign > 0) ? angles[i] : -angles[i]));

            x = x1; y = y1; z = z1;
        }

        return (sign > 0) ? x : - x;

        #undef pi
        #undef pi2
        #undef pi_half
    }
}
<commit_msg>cos.inl: core namespace + 'number' -> 'fixed_point' + using of math constants from fixed-point class<commit_after>/// @brief provides CORDIC for cos function
/// @ref see H. Dawid, H. Meyr, "CORDIC Algorithms and Architectures"

#include "./../../fixed_point_lib/src/CORDIC/lut/lut.hpp"

namespace std {
    template<typename T, size_t n, size_t f, class op, class up>
    core::fixed_point<T, n, f, op, up> cos(core::fixed_point<T, n, f, op, up> const& val)
    {
        typedef core::fixed_point<T, n, f, op, up> fp;
        using core::cordic::lut;
        BOOST_STATIC_ASSERT(std::numeric_limits<fixed_point>::is_signed);

        // convergence interval for CORDIC rotations is [-pi/2, pi/2].
        // So one has to map input angle to that interval
        fp arg(0);
        int sign(-1);
        {
            // put argument to [-pi, pi] interval (with change of sign for
            // cos)
            fp const x = fp::CONST_PI - std::fmod(val, fp::CONST_2PI);
            if (x < -fp::CONST_PI_2) {     // convert to interval [-pi/2, pi/2]
                arg = x + fp::CONST_PI;

                sign = 1;
            }
            else if (x > fp::CONST_PI_2) {
                arg = x - fp::CONST_PI;

                sign = 1;
            }
            else {
                arg = x;
            }
        }

        typedef lut<f, fp> lut_type;
        static lut_type const angles = lut_type::build_arctan_lut();

        // normalization factor: see page 10, table 24.1 and pages 4-5, equations
        // (5)-(6)
        // factor converges to the limit 1.64676 very fast: it tooks 8 iterations
        // only. 8 iterations correpsonds to precision of size 0.007812 for
        // angle approximation
        static fp norm_factor(1.0 / lut_type::compute_circular_scale(f));

        // rotation mode: see page 6
        // shift sequence is just 0, 1, ... (circular coordinate system)
        fp x(norm_factor), y(0.0), z(arg);
        fp x1, y1, z1;
        BOOST_FOREACH(size_t i, boost::irange<size_t>(0, f, 1))
        {
            int const sign = (z > fp(0)) ? 1 : -1;
            fp const x_scaled = fp::wrap(sign * (x.value() >> i));
            fp const y_scaled = fp::wrap(sign * (y.value() >> i));

            x1 = fp(x - y_scaled);
            y1 = fp(y + x_scaled);
            z1 = fp(z - fp((sign > 0) ? angles[i] : -angles[i]));

            x = x1; y = y1; z = z1;
        }

        return (sign > 0) ? x : - x;
    }
}
<|endoftext|>


<commit_before>#include "PropertySetting.h"
#include "Sprite.h"
#include "Symbol.h"

#include <sprite2/UpdateParams.h>

#include <ee/panel_msg.h>

namespace libanim
{

PropertySetting::PropertySetting(ee::EditPanelImpl* edit_impl, Sprite* spr)
	: ee::SpritePropertySetting(edit_impl, spr)
{
	m_type = "Animation";
}

void PropertySetting::OnPropertyGridChange(const std::string& name, const wxAny& value)
{
	ee::SpritePropertySetting::OnPropertyGridChange(name, value);

	Sprite* spr = static_cast<Sprite*>(GetSprite());
	if (name == "Loop") {
		spr->SetLoop(wxANY_AS(value, bool));
	} else if (name == "Interval") {
		spr->SetInterval(wxANY_AS(value, float));
	} else if (name == "FPS") {
		spr->SetFPS(wxANY_AS(value, int));
	} else if (name == "Start Random") {
		spr->SetStartRandom(s2::UpdateParams(), wxANY_AS(value, bool));
	} else if (name == "Static") {
		spr->SetStaticTime(wxANY_AS(value, int));
		spr->SetActive(false, NULL);
		ee::SetCanvasDirtySJ::Instance()->SetDirty();
	} else if (name == "Active") {
		spr->SetActive(wxANY_AS(value, bool), NULL);
	}
}

void PropertySetting::UpdateProperties(wxPropertyGrid* pg)
{
	ee::SpritePropertySetting::UpdateProperties(pg);

	Sprite* spr = static_cast<Sprite*>(GetSprite());
	pg->GetProperty("Loop")->SetValue(spr->IsLoop());
	pg->GetProperty("Interval")->SetValue(spr->GetInterval());
	pg->GetProperty("FPS")->SetValue(spr->GetFPS());
	pg->GetProperty("Start Random")->SetValue(spr->IsStartRandom());
	pg->GetProperty("Static")->SetValue(spr->GetStaticTime());
	pg->GetProperty("Active")->SetValue(spr->IsActive());
}

void PropertySetting::InitProperties(wxPropertyGrid* pg)
{
	ee::SpritePropertySetting::InitProperties(pg);

	pg->Append(new wxPropertyCategory("ANIMATION", wxPG_LABEL));

	Sprite* spr = static_cast<Sprite*>(GetSprite());

	pg->Append(new wxBoolProperty("Loop", wxPG_LABEL, spr->IsLoop()));
	pg->SetPropertyAttribute("Loop", wxPG_BOOL_USE_CHECKBOX, spr->IsLoop(), wxPG_RECURSE);

	pg->Append(new wxFloatProperty("Interval", wxPG_LABEL, spr->GetInterval()));

	pg->Append(new wxIntProperty("FPS", wxPG_LABEL, spr->GetFPS()));

	pg->Append(new wxBoolProperty("Start Random", wxPG_LABEL, spr->IsStartRandom()));
	pg->SetPropertyAttribute("Start Random", wxPG_BOOL_USE_CHECKBOX, spr->IsStartRandom(), wxPG_RECURSE);

	wxIntProperty* static_prop = new wxIntProperty("Static", wxPG_LABEL, spr->GetStaticTime());
	static_prop->SetValue(spr->GetStaticTime());
	pg->Append(static_prop);

	pg->Append(new wxBoolProperty("Active", wxPG_LABEL, spr->IsActive()));
	pg->SetPropertyAttribute("Active", wxPG_BOOL_USE_CHECKBOX, spr->IsLoop(), wxPG_RECURSE);
}

}<commit_msg>[FIXED] anim property's wxPG_BOOL_USE_CHECKBOX<commit_after>#include "PropertySetting.h"
#include "Sprite.h"
#include "Symbol.h"

#include <sprite2/UpdateParams.h>

#include <ee/panel_msg.h>

namespace libanim
{

PropertySetting::PropertySetting(ee::EditPanelImpl* edit_impl, Sprite* spr)
	: ee::SpritePropertySetting(edit_impl, spr)
{
	m_type = "Animation";
}

void PropertySetting::OnPropertyGridChange(const std::string& name, const wxAny& value)
{
	ee::SpritePropertySetting::OnPropertyGridChange(name, value);

	Sprite* spr = static_cast<Sprite*>(GetSprite());
	if (name == "Loop") {
		spr->SetLoop(wxANY_AS(value, bool));
	} else if (name == "Interval") {
		spr->SetInterval(wxANY_AS(value, float));
	} else if (name == "FPS") {
		spr->SetFPS(wxANY_AS(value, int));
	} else if (name == "Start Random") {
		spr->SetStartRandom(s2::UpdateParams(), wxANY_AS(value, bool));
	} else if (name == "Static") {
		spr->SetStaticTime(wxANY_AS(value, int));
		spr->SetActive(false, NULL);
		ee::SetCanvasDirtySJ::Instance()->SetDirty();
	} else if (name == "Active") {
		spr->SetActive(wxANY_AS(value, bool), NULL);
	}
}

void PropertySetting::UpdateProperties(wxPropertyGrid* pg)
{
	ee::SpritePropertySetting::UpdateProperties(pg);

	Sprite* spr = static_cast<Sprite*>(GetSprite());
	pg->GetProperty("Loop")->SetValue(spr->IsLoop());
	pg->GetProperty("Interval")->SetValue(spr->GetInterval());
	pg->GetProperty("FPS")->SetValue(spr->GetFPS());
	pg->GetProperty("Start Random")->SetValue(spr->IsStartRandom());
	pg->GetProperty("Static")->SetValue(spr->GetStaticTime());
	pg->GetProperty("Active")->SetValue(spr->IsActive());
}

void PropertySetting::InitProperties(wxPropertyGrid* pg)
{
	ee::SpritePropertySetting::InitProperties(pg);

	pg->Append(new wxPropertyCategory("ANIMATION", wxPG_LABEL));

	Sprite* spr = static_cast<Sprite*>(GetSprite());

	pg->Append(new wxBoolProperty("Loop", wxPG_LABEL, spr->IsLoop()));
	pg->SetPropertyAttribute("Loop", wxPG_BOOL_USE_CHECKBOX, true, wxPG_RECURSE);

	pg->Append(new wxFloatProperty("Interval", wxPG_LABEL, spr->GetInterval()));

	pg->Append(new wxIntProperty("FPS", wxPG_LABEL, spr->GetFPS()));

	pg->Append(new wxBoolProperty("Start Random", wxPG_LABEL, spr->IsStartRandom()));
	pg->SetPropertyAttribute("Start Random", wxPG_BOOL_USE_CHECKBOX, true, wxPG_RECURSE);

	wxIntProperty* static_prop = new wxIntProperty("Static", wxPG_LABEL, spr->GetStaticTime());
	static_prop->SetValue(spr->GetStaticTime());
	pg->Append(static_prop);

	pg->Append(new wxBoolProperty("Active", wxPG_LABEL, spr->IsActive()));
	pg->SetPropertyAttribute("Active", wxPG_BOOL_USE_CHECKBOX, true, wxPG_RECURSE);
}

}<|endoftext|>


<commit_before>#include "locomotion_control.h"

Locomotion_Control::Locomotion_Control(ros::NodeHandle* nh,
                                       AL::ALMotionProxy* mProxy) {
  nh_ = nh;
  mProxy_ = mProxy;
  INFO("Setting up Nao locomotion publishers" << std::endl);
  moving_pub_ = nh_->advertise<std_msgs::Bool>("isMoving", 10);
  INFO("Setting up Nao motion publishers" << std::endl);
  srv_move_ = nh_->advertiseService("move", &Locomotion_Control::move, this);
  srv_move_to_ = nh_->advertiseService("moveTo",
                                       &Locomotion_Control::moveTo, this);
  srv_move_toward_ = nh_->advertiseService("moveToward",
                     &Locomotion_Control::moveToward, this);
  srv_move_init_ = nh_->advertiseService("moveInit",
                                         &Locomotion_Control::moveInit, this);
  srv_wait_move_finished_ = nh_->advertiseService("waitMoveFinish",
                            &Locomotion_Control::waitUntilMoveIsFinished, this);
  srv_stop_move_ = nh_->advertiseService("stopMove",
                                         &Locomotion_Control::stopMove, this);
  srv_get_move_config_ = nh_->advertiseService("getMoveConfig",
                         &Locomotion_Control::getMoveConfig, this);
  srv_get_robot_position_ = nh_->advertiseService("getRobotPosition",
                            &Locomotion_Control::getRobotPosition, this);
  srv_get_next_robot_position_ = nh_->advertiseService("getNextRobotPosition",
                                 &Locomotion_Control::getNextRobotPosition, this);
  srv_get_robot_velocity_ = nh_->advertiseService("getRobotVelocity",
                            &Locomotion_Control::getRobotVelocity, this);
  srv_get_walk_arms_enabled_ = nh_->advertiseService("getWalkArmsEnabled",
                               &Locomotion_Control::getWalkArmsEnabled, this);
  srv_set_walk_arms_enabled_ = nh_->advertiseService("setWalkArmsEnabled",
                               &Locomotion_Control::setWalkArmsEnabled, this);
}

Locomotion_Control::~Locomotion_Control() {
  ros::shutdown();
}

bool Locomotion_Control::move(motion::move::Request &req,
                              motion::move::Response &res) {
  // Check for size of moveConfiguration
  int configSize = req.moveConfiguration.names.size();
  AL::ALValue moveConfiguration;
  if (configSize > 0) {
    moveConfiguration.arraySetSize(configSize);
    for (int i = 0; i < configSize; ++i) {
      moveConfiguration[i] = AL::ALValue::array(
                               req.moveConfiguration.names[i],
                               req.moveConfiguration.values[i]);
    }
  }

  res.res = true;
  if (configSize == 0) {
    mProxy_->move(req.targetVelocity.x,
                  req.targetVelocity.y,
                  req.targetVelocity.theta);
  } else if (configSize > 0) {
    mProxy_->move(req.targetVelocity.x,
                  req.targetVelocity.y,
                  req.targetVelocity.theta,
                  moveConfiguration);
  } else {
    res.res = false;
  }
  return true;
}

bool Locomotion_Control::moveTo(motion::moveTo::Request &req,
                                motion::moveTo::Response &res) {
  //  Check for multiple positions
  int posNum = req.controlPoints.size();
  AL::ALValue controlPoints;
  if (posNum > 1) {
    controlPoints.arraySetSize(posNum);
    for (int i = 0; i < posNum; ++i) {
      controlPoints[i] = AL::ALValue::array(req.controlPoints[i].x,
                                            req.controlPoints[i].y,
                                            req.controlPoints[i].theta);
    }
  }

  // Check for size of moveConfiguration
  int configSize = req.moveConfiguration.names.size();
  AL::ALValue moveConfiguration;
  if (configSize > 0) {
    moveConfiguration.arraySetSize(configSize);
    for (int i = 0; i < configSize; ++i) {
      moveConfiguration[i] = AL::ALValue::array(
                               req.moveConfiguration.names[i],
                               req.moveConfiguration.values[i]);
    }
  }

  res.res = true;
  if (posNum == 1 && configSize == 0) {
    mProxy_->post.moveTo(req.controlPoints[0].x,
                         req.controlPoints[0].y,
                         req.controlPoints[0].theta);
  } else if (posNum > 1 && configSize == 0) {
    mProxy_->post.moveTo(controlPoints);
  } else if (posNum == 1 && configSize > 0) {
    mProxy_->post.moveTo(req.controlPoints[0].x,
                         req.controlPoints[0].y,
                         req.controlPoints[0].theta,
                         moveConfiguration);
  } else if (posNum > 1 && configSize > 0) {
    mProxy_->post.moveTo(controlPoints, moveConfiguration);
  } else {
    res.res = false;
  }
  return true;
}

bool Locomotion_Control::moveToward(motion::moveToward::Request &req,
                                    motion::moveToward::Response &res) {
  // Check for size of moveConfiguration
  int configSize = req.moveConfiguration.names.size();
  AL::ALValue moveConfiguration;
  if (configSize > 0) {
    moveConfiguration.arraySetSize(configSize);
    for (int i = 0; i < configSize; ++i) {
      moveConfiguration[i] = AL::ALValue::array(
                               req.moveConfiguration.names[i],
                               req.moveConfiguration.values[i]);
    }
  }

  res.res = true;
  if (configSize == 0) {
    mProxy_->moveToward(req.normVelocity.x,
                        req.normVelocity.y,
                        req.normVelocity.theta);
  } else if (configSize > 0) {
    mProxy_->moveToward(req.normVelocity.x,
                        req.normVelocity.y,
                        req.normVelocity.theta,
                        moveConfiguration);
  } else {
    res.res = false;
  }
  return true;
}

bool Locomotion_Control::moveInit(std_srvs::Empty::Request &req,
                                  std_srvs::Empty::Response &res) {
  mProxy_->moveInit();
  return true;
}

bool Locomotion_Control::waitUntilMoveIsFinished(
  std_srvs::Empty::Request &req,
  std_srvs::Empty::Response &res) {
  mProxy_->waitUntilMoveIsFinished();
  return true;
}

bool Locomotion_Control::moveIsActive() {
  mProxy_->moveIsActive();
  return true;
}

bool Locomotion_Control::stopMove(std_srvs::Empty::Request &req,
                                  std_srvs::Empty::Response &res) {
  mProxy_->stopMove();
  return true;
}

bool Locomotion_Control::getMoveConfig(motion::getMoveConfig::Request &req,
                                       motion::getMoveConfig::Response &res) {
  AL::ALValue moveConfiguration;
  moveConfiguration = mProxy_->getMoveConfig(req.config);
  std::size_t CSize = moveConfiguration.getSize();
  res.moveConfiguration.names.resize(CSize);
  res.moveConfiguration.values.resize(CSize);
  for (int i = 0; i < CSize; ++i) {
    res.moveConfiguration.names[i] = moveConfiguration[i][0].toString();
    res.moveConfiguration.values[i] = moveConfiguration[i][1];
  }
  return true;
}

bool Locomotion_Control::getRobotPosition(
  motion::getRobotPosition::Request &req,
  motion::getRobotPosition::Response &res) {
  bool useSensors = req.useSensors;
  res.positions = mProxy_->getRobotPosition(useSensors);
  return true;
}

bool Locomotion_Control::getNextRobotPosition(
  motion::getNextRobotPosition::Request &req,
  motion::getNextRobotPosition::Response &res) {
  res.positions = mProxy_->getNextRobotPosition();
  return true;
}

bool Locomotion_Control::getRobotVelocity(
  motion::getRobotVelocity::Request &req,
  motion::getRobotVelocity::Response &res) {
  res.velocity = mProxy_->getRobotVelocity();
  return true;
}

bool Locomotion_Control::getWalkArmsEnabled(
  motion::getWalkArmsEnabled::Request &req,
  motion::getWalkArmsEnabled::Response &res) {
  AL::ALValue result = mProxy_->getWalkArmsEnabled();
  res.armMotions.resize(2);
  res.armMotions[0] = static_cast<bool>(result[0]);
  res.armMotions[1] = static_cast<bool>(result[1]);
  return true;
}

bool Locomotion_Control::setWalkArmsEnabled(
  motion::setWalkArmsEnabled::Request &req,
  motion::setWalkArmsEnabled::Response &res) {
  bool left = req.leftArmEnable;
  bool right = req.rightArmEnable;
  mProxy_->setWalkArmsEnabled(left, right);
  return true;
}

void Locomotion_Control::spinTopics() {
  std_msgs::Bool msg;
  msg.data = moveIsActive();
  moving_pub_.publish(msg);
}
<commit_msg>Fix isMoveActive function, so that real result is actually published<commit_after>#include "locomotion_control.h"

Locomotion_Control::Locomotion_Control(ros::NodeHandle* nh,
                                       AL::ALMotionProxy* mProxy) {
  nh_ = nh;
  mProxy_ = mProxy;
  INFO("Setting up Nao locomotion publishers" << std::endl);
  moving_pub_ = nh_->advertise<std_msgs::Bool>("isMoving", 10);
  INFO("Setting up Nao motion publishers" << std::endl);
  srv_move_ = nh_->advertiseService("move", &Locomotion_Control::move, this);
  srv_move_to_ = nh_->advertiseService("moveTo",
                                       &Locomotion_Control::moveTo, this);
  srv_move_toward_ = nh_->advertiseService("moveToward",
                     &Locomotion_Control::moveToward, this);
  srv_move_init_ = nh_->advertiseService("moveInit",
                                         &Locomotion_Control::moveInit, this);
  srv_wait_move_finished_ = nh_->advertiseService("waitMoveFinish",
                            &Locomotion_Control::waitUntilMoveIsFinished, this);
  srv_stop_move_ = nh_->advertiseService("stopMove",
                                         &Locomotion_Control::stopMove, this);
  srv_get_move_config_ = nh_->advertiseService("getMoveConfig",
                         &Locomotion_Control::getMoveConfig, this);
  srv_get_robot_position_ = nh_->advertiseService("getRobotPosition",
                            &Locomotion_Control::getRobotPosition, this);
  srv_get_next_robot_position_ = nh_->advertiseService("getNextRobotPosition",
                                 &Locomotion_Control::getNextRobotPosition, this);
  srv_get_robot_velocity_ = nh_->advertiseService("getRobotVelocity",
                            &Locomotion_Control::getRobotVelocity, this);
  srv_get_walk_arms_enabled_ = nh_->advertiseService("getWalkArmsEnabled",
                               &Locomotion_Control::getWalkArmsEnabled, this);
  srv_set_walk_arms_enabled_ = nh_->advertiseService("setWalkArmsEnabled",
                               &Locomotion_Control::setWalkArmsEnabled, this);
}

Locomotion_Control::~Locomotion_Control() {
  ros::shutdown();
}

bool Locomotion_Control::move(motion::move::Request &req,
                              motion::move::Response &res) {
  // Check for size of moveConfiguration
  int configSize = req.moveConfiguration.names.size();
  AL::ALValue moveConfiguration;
  if (configSize > 0) {
    moveConfiguration.arraySetSize(configSize);
    for (int i = 0; i < configSize; ++i) {
      moveConfiguration[i] = AL::ALValue::array(
                               req.moveConfiguration.names[i],
                               req.moveConfiguration.values[i]);
    }
  }

  res.res = true;
  if (configSize == 0) {
    mProxy_->move(req.targetVelocity.x,
                  req.targetVelocity.y,
                  req.targetVelocity.theta);
  } else if (configSize > 0) {
    mProxy_->move(req.targetVelocity.x,
                  req.targetVelocity.y,
                  req.targetVelocity.theta,
                  moveConfiguration);
  } else {
    res.res = false;
  }
  return true;
}

bool Locomotion_Control::moveTo(motion::moveTo::Request &req,
                                motion::moveTo::Response &res) {
  //  Check for multiple positions
  int posNum = req.controlPoints.size();
  AL::ALValue controlPoints;
  if (posNum > 1) {
    controlPoints.arraySetSize(posNum);
    for (int i = 0; i < posNum; ++i) {
      controlPoints[i] = AL::ALValue::array(req.controlPoints[i].x,
                                            req.controlPoints[i].y,
                                            req.controlPoints[i].theta);
    }
  }

  // Check for size of moveConfiguration
  int configSize = req.moveConfiguration.names.size();
  AL::ALValue moveConfiguration;
  if (configSize > 0) {
    moveConfiguration.arraySetSize(configSize);
    for (int i = 0; i < configSize; ++i) {
      moveConfiguration[i] = AL::ALValue::array(
                               req.moveConfiguration.names[i],
                               req.moveConfiguration.values[i]);
    }
  }

  res.res = true;
  if (posNum == 1 && configSize == 0) {
    mProxy_->post.moveTo(req.controlPoints[0].x,
                         req.controlPoints[0].y,
                         req.controlPoints[0].theta);
  } else if (posNum > 1 && configSize == 0) {
    mProxy_->post.moveTo(controlPoints);
  } else if (posNum == 1 && configSize > 0) {
    mProxy_->post.moveTo(req.controlPoints[0].x,
                         req.controlPoints[0].y,
                         req.controlPoints[0].theta,
                         moveConfiguration);
  } else if (posNum > 1 && configSize > 0) {
    mProxy_->post.moveTo(controlPoints, moveConfiguration);
  } else {
    res.res = false;
  }
  return true;
}

bool Locomotion_Control::moveToward(motion::moveToward::Request &req,
                                    motion::moveToward::Response &res) {
  // Check for size of moveConfiguration
  int configSize = req.moveConfiguration.names.size();
  AL::ALValue moveConfiguration;
  if (configSize > 0) {
    moveConfiguration.arraySetSize(configSize);
    for (int i = 0; i < configSize; ++i) {
      moveConfiguration[i] = AL::ALValue::array(
                               req.moveConfiguration.names[i],
                               req.moveConfiguration.values[i]);
    }
  }

  res.res = true;
  if (configSize == 0) {
    mProxy_->moveToward(req.normVelocity.x,
                        req.normVelocity.y,
                        req.normVelocity.theta);
  } else if (configSize > 0) {
    mProxy_->moveToward(req.normVelocity.x,
                        req.normVelocity.y,
                        req.normVelocity.theta,
                        moveConfiguration);
  } else {
    res.res = false;
  }
  return true;
}

bool Locomotion_Control::moveInit(std_srvs::Empty::Request &req,
                                  std_srvs::Empty::Response &res) {
  mProxy_->moveInit();
  return true;
}

bool Locomotion_Control::waitUntilMoveIsFinished(
  std_srvs::Empty::Request &req,
  std_srvs::Empty::Response &res) {
  mProxy_->waitUntilMoveIsFinished();
  return true;
}

bool Locomotion_Control::moveIsActive() {
  return mProxy_->moveIsActive();
}

bool Locomotion_Control::stopMove(std_srvs::Empty::Request &req,
                                  std_srvs::Empty::Response &res) {
  mProxy_->stopMove();
  return true;
}

bool Locomotion_Control::getMoveConfig(motion::getMoveConfig::Request &req,
                                       motion::getMoveConfig::Response &res) {
  AL::ALValue moveConfiguration;
  moveConfiguration = mProxy_->getMoveConfig(req.config);
  std::size_t CSize = moveConfiguration.getSize();
  res.moveConfiguration.names.resize(CSize);
  res.moveConfiguration.values.resize(CSize);
  for (int i = 0; i < CSize; ++i) {
    res.moveConfiguration.names[i] = moveConfiguration[i][0].toString();
    res.moveConfiguration.values[i] = moveConfiguration[i][1];
  }
  return true;
}

bool Locomotion_Control::getRobotPosition(
  motion::getRobotPosition::Request &req,
  motion::getRobotPosition::Response &res) {
  bool useSensors = req.useSensors;
  res.positions = mProxy_->getRobotPosition(useSensors);
  return true;
}

bool Locomotion_Control::getNextRobotPosition(
  motion::getNextRobotPosition::Request &req,
  motion::getNextRobotPosition::Response &res) {
  res.positions = mProxy_->getNextRobotPosition();
  return true;
}

bool Locomotion_Control::getRobotVelocity(
  motion::getRobotVelocity::Request &req,
  motion::getRobotVelocity::Response &res) {
  res.velocity = mProxy_->getRobotVelocity();
  return true;
}

bool Locomotion_Control::getWalkArmsEnabled(
  motion::getWalkArmsEnabled::Request &req,
  motion::getWalkArmsEnabled::Response &res) {
  AL::ALValue result = mProxy_->getWalkArmsEnabled();
  res.armMotions.resize(2);
  res.armMotions[0] = static_cast<bool>(result[0]);
  res.armMotions[1] = static_cast<bool>(result[1]);
  return true;
}

bool Locomotion_Control::setWalkArmsEnabled(
  motion::setWalkArmsEnabled::Request &req,
  motion::setWalkArmsEnabled::Response &res) {
  bool left = req.leftArmEnable;
  bool right = req.rightArmEnable;
  mProxy_->setWalkArmsEnabled(left, right);
  return true;
}

void Locomotion_Control::spinTopics() {
  std_msgs::Bool msg;
  msg.data = moveIsActive();
  moving_pub_.publish(msg);
}
<|endoftext|>


<commit_before>#include <cstddef>
#include <cstdlib>
#include <hls_video.h>

#include "Accel.h"
#include "AccelSchedule.h"
#include "AccelTest.h"
#include "Dense.h"
#include "ZipIO.h"
#include "ParamIO.h"
#include "DataIO.h"
#include "Timer.h"

int main(int argc, char** argv) {
  if (argc < 2) {
    printf ("Give number of character to produce as 1st arg\n");
    printf ("Give the initial srting as 2nd arg optional\n");
    return 0;
  }
  const unsigned n_char = std::stoi(argv[1]);
  bool Init = false;
  char* str_init = NULL;

  if (argc == 3) {
    Init = true;
    printf("* Initial string is %s\n", str_init);
    str_init = argv[2];   // *ML: cant loas text with ' '
  }
  // print some config numbers
  printf ("* WT_WORDS   = %u\n", WT_WORDS);
  printf ("* BIAS_WORDS = %u\n", BIAS_WORDS);

  // Load input data
  //printf ("## Loading input data ##\n");
  // ML: hidden state can be initialized by a given string

  // Load parameters
  printf ("## Loading parameters ##\n");
  Params params(get_root_dir() + "/params/rnn_parameters.zip");

  // ---------------------------------------------------------------------
  // allocate and binarize all weights
  // ---------------------------------------------------------------------
  Word* wt[N_LAYERS];
  Word* b[N_LAYERS];

  for (unsigned l = 0; l < N_LAYERS; ++l) {
    const unsigned M = M_tab[l];
    const unsigned N = N_tab[l];

    if (layer_is_rnn(l+1)) {
      wt[l] = new Word[(M+N)*4*N / WORD_SIZE];
      b[l] = new Word[4*N / WORD_SIZE];
    }
    else {
      wt[l] = new Word[M*N / WORD_SIZE];    // ML: RNN layers
      b[l] = new Word[N / WORD_SIZE];
    }
    if (layer_is_rnn(l+1)) {
      for (unsigned w_l = 0; w_l < N_W_LAYERS; ++w_l) {
        // ML: set in_to weight and hid_to weight
        const float* weights_in = params.float_data(widx_tab[l*N_W_LAYERS*2 + 2*w_l]);
        const float* weights_hid = params.float_data(widx_tab[l*N_W_LAYERS*2 + 2*w_l +1]);
        set_rnn_weight_array(wt[l], weights_in, weights_hid, l+1, w_l);
        // ML: set bias
        const float* bias = params.float_data(bidx_tab[l*N_W_LAYERS + w_l]);
        set_rnn_bias_array(b[l], bias, l+1, w_l);
      }
    } else {

      const float* weights = params.float_data(widx_tab[16]);
      set_dense_weight_array(wt[l], weights, l+1);
      const float* bias = params.float_data(bidx_tab[8]);
      set_dense_bias_array(b[l], bias, l+1);
    }

  }

  // ---------------------------------------------------------------------
  // // compute accelerator schedule (divides up weights)
  // ---------------------------------------------------------------------
  AccelSchedule layer_sched[N_LAYERS];
  for (unsigned l = 0; l < N_LAYERS; ++l) {
    compute_accel_schedule(
        wt[l], b[l],
        M_tab[l], N_tab[l], T_tab[l],
        layer_sched[l], l
    );
  }

  // allocate memories for data i/o for the accelerator
  Word* data_i  = (Word*) MEM_ALLOC( DMEM_WORDS * sizeof(Word) );   // ML: need to be modified!
  Word* data_o  = (Word*) MEM_ALLOC( DMEM_O_WORDS * sizeof(Word) );
  if (!data_i || !data_o) {
    fprintf (stderr, "**** ERROR: Alloc failed in %s\n", __FILE__);
    return (-2);
  }

  unsigned n_errors = 0;

  printf("## Initialing the RNN\n");

  if (Init) {
    unsigned i = 0;
    while (str_init[i] != '\0') {
      set_char_to_word(data_i, str_init[i]);

      for (unsigned l = 1; l <= 3; ++l) {
        const unsigned M = M_tab[l-1];
        const unsigned N = N_tab[l-1];

        dense_layer(
          data_i, data_o,
          l-1,
          (l==1) ? (64/DATA_PER_WORD) : 0,    // input_words
          0,    // output_words = 0
          layer_sched[l-1]
        );
      }
      i++;
    }
  }

  printf ("## Running RNN for %d characters\n", n_char);

  //--------------------------------------------------------------
  // Run RNN
  //--------------------------------------------------------------

  // ML: load an arbitrary input character [1, 0. 0, ..., 0]
  for (unsigned i = 0; i < VOCAB_SIZE/DATA_PER_WORD; ++i) {
    if (i == 0) {
      data_i[i] = 0;
      DATA start_seed = 1;
      data_i[i](15,0) = start_seed(15,0);
    } else {
      data_i[i] = 0;
    }
  }

  for (unsigned n = 0; n < n_char; ++n) {

    //------------------------------------------------------------
    // Execute RNN layers
    //------------------------------------------------------------
    for (unsigned l = 1; l <= 3; ++l) {
      const unsigned M = M_tab[l-1];
      const unsigned N = N_tab[l-1];

      dense_layer(
        data_i, data_o,
        l-1,
        (n==0 && l==1 && (~Init)) ? (64/DATA_PER_WORD) : 0,    // input_words
        (l==3) ? (64/DATA_PER_WORD) : 0,
        layer_sched[l-1]
      );
    }

    //------------------------------------------------------------
    // Execute the prediciton
    //------------------------------------------------------------
    int prediction = 0;
    int max = -512; // ML: may shoulb be less

    for (unsigned i = 0; i < VOCAB_SIZE; i++) {
      DATA temp;
      int add = i / DATA_PER_WORD;
      int off = i % DATA_PER_WORD;
      temp(15,0) = data_o[add]((off+1)*16-1,off*16);
      if (temp.to_int() > max) {
        max = temp;
        prediction = i;
      }
    }

    assert(prediction >= 0 && prediction <= 63);

    std::cout<<vocab[prediction];

  }

  printf("\n");
  /*printf ("\n");
  printf ("Errors: %u (%4.2f%%)\n", n_errors, float(n_errors)*100/n_imgs);
  printf ("\n");
  printf ("Total accel runtime = %10.4f seconds\n", total_time());
  printf ("\n");*/

  MEM_FREE( data_o );
  MEM_FREE( data_i );
  for (unsigned n = 0; n < N_LAYERS; ++n) {
    delete[] wt[n];
    delete[] b[n];
  }
  return 0;
}
<commit_msg>fixed a bug<commit_after>#include <cstddef>
#include <cstdlib>
#include <hls_video.h>

#include "Accel.h"
#include "AccelSchedule.h"
#include "AccelTest.h"
#include "Dense.h"
#include "ZipIO.h"
#include "ParamIO.h"
#include "DataIO.h"
#include "Timer.h"

int main(int argc, char** argv) {
  if (argc < 2) {
    printf ("Give number of character to produce as 1st arg\n");
    printf ("Give the initial srting as 2nd arg optional\n");
    return 0;
  }
  const unsigned n_char = std::stoi(argv[1]);
  bool Init = false;
  char* str_init = NULL;

  if (argc == 3) {
    Init = true;
    str_init = argv[2];   // *ML: cant loas text with ' '
    printf("* Initial string is %s\n", str_init);
  }
  // print some config numbers
  printf ("* WT_WORDS   = %u\n", WT_WORDS);
  printf ("* BIAS_WORDS = %u\n", BIAS_WORDS);

  // Load input data
  //printf ("## Loading input data ##\n");
  // ML: hidden state can be initialized by a given string

  // Load parameters
  printf ("## Loading parameters ##\n");
  Params params(get_root_dir() + "/params/rnn_parameters.zip");

  // ---------------------------------------------------------------------
  // allocate and binarize all weights
  // ---------------------------------------------------------------------
  Word* wt[N_LAYERS];
  Word* b[N_LAYERS];

  for (unsigned l = 0; l < N_LAYERS; ++l) {
    const unsigned M = M_tab[l];
    const unsigned N = N_tab[l];

    if (layer_is_rnn(l+1)) {
      wt[l] = new Word[(M+N)*4*N / WORD_SIZE];
      b[l] = new Word[4*N / WORD_SIZE];
    }
    else {
      wt[l] = new Word[M*N / WORD_SIZE];    // ML: RNN layers
      b[l] = new Word[N / WORD_SIZE];
    }
    if (layer_is_rnn(l+1)) {
      for (unsigned w_l = 0; w_l < N_W_LAYERS; ++w_l) {
        // ML: set in_to weight and hid_to weight
        const float* weights_in = params.float_data(widx_tab[l*N_W_LAYERS*2 + 2*w_l]);
        const float* weights_hid = params.float_data(widx_tab[l*N_W_LAYERS*2 + 2*w_l +1]);
        set_rnn_weight_array(wt[l], weights_in, weights_hid, l+1, w_l);
        // ML: set bias
        const float* bias = params.float_data(bidx_tab[l*N_W_LAYERS + w_l]);
        set_rnn_bias_array(b[l], bias, l+1, w_l);
      }
    } else {

      const float* weights = params.float_data(widx_tab[16]);
      set_dense_weight_array(wt[l], weights, l+1);
      const float* bias = params.float_data(bidx_tab[8]);
      set_dense_bias_array(b[l], bias, l+1);
    }

  }

  // ---------------------------------------------------------------------
  // // compute accelerator schedule (divides up weights)
  // ---------------------------------------------------------------------
  AccelSchedule layer_sched[N_LAYERS];
  for (unsigned l = 0; l < N_LAYERS; ++l) {
    compute_accel_schedule(
        wt[l], b[l],
        M_tab[l], N_tab[l], T_tab[l],
        layer_sched[l], l
    );
  }

  // allocate memories for data i/o for the accelerator
  Word* data_i  = (Word*) MEM_ALLOC( DMEM_WORDS * sizeof(Word) );   // ML: need to be modified!
  Word* data_o  = (Word*) MEM_ALLOC( DMEM_O_WORDS * sizeof(Word) );
  if (!data_i || !data_o) {
    fprintf (stderr, "**** ERROR: Alloc failed in %s\n", __FILE__);
    return (-2);
  }

  unsigned n_errors = 0;

  printf("## Initialing the RNN\n");

  if (Init) {
    unsigned i = 0;
    while (str_init[i] != '\0') {
      set_char_to_word(data_i, str_init[i]);

      for (unsigned l = 1; l <= 3; ++l) {
        const unsigned M = M_tab[l-1];
        const unsigned N = N_tab[l-1];

        dense_layer(
          data_i, data_o,
          l-1,
          (l==1) ? (64/DATA_PER_WORD) : 0,    // input_words
          0,    // output_words = 0
          layer_sched[l-1]
        );
      }
      i++;
    }
  }

  printf ("## Running RNN for %d characters\n", n_char);

  //--------------------------------------------------------------
  // Run RNN
  //--------------------------------------------------------------

  // ML: load an arbitrary input character [1, 0. 0, ..., 0]
  for (unsigned i = 0; i < VOCAB_SIZE/DATA_PER_WORD; ++i) {
    if (i == 0) {
      data_i[i] = 0;
      DATA start_seed = 1;
      data_i[i](15,0) = start_seed(15,0);
    } else {
      data_i[i] = 0;
    }
  }

  for (unsigned n = 0; n < n_char; ++n) {

    //------------------------------------------------------------
    // Execute RNN layers
    //------------------------------------------------------------
    for (unsigned l = 1; l <= 3; ++l) {
      const unsigned M = M_tab[l-1];
      const unsigned N = N_tab[l-1];

      dense_layer(
        data_i, data_o,
        l-1,
        (n==0 && l==1 && (~Init)) ? (64/DATA_PER_WORD) : 0,    // input_words
        (l==3) ? (64/DATA_PER_WORD) : 0,
        layer_sched[l-1]
      );
    }

    //------------------------------------------------------------
    // Execute the prediciton
    //------------------------------------------------------------
    int prediction = 0;
    int max = -512; // ML: may shoulb be less

    for (unsigned i = 0; i < VOCAB_SIZE; i++) {
      DATA temp;
      int add = i / DATA_PER_WORD;
      int off = i % DATA_PER_WORD;
      temp(15,0) = data_o[add]((off+1)*16-1,off*16);
      if (temp.to_int() > max) {
        max = temp;
        prediction = i;
      }
    }

    assert(prediction >= 0 && prediction <= 63);

    std::cout<<vocab[prediction];

  }

  printf("\n");
  /*printf ("\n");
  printf ("Errors: %u (%4.2f%%)\n", n_errors, float(n_errors)*100/n_imgs);
  printf ("\n");
  printf ("Total accel runtime = %10.4f seconds\n", total_time());
  printf ("\n");*/

  MEM_FREE( data_o );
  MEM_FREE( data_i );
  for (unsigned n = 0; n < N_LAYERS; ++n) {
    delete[] wt[n];
    delete[] b[n];
  }
  return 0;
}
<|endoftext|>