<commit_before>#include "console.h"
#include "sofa/helper/Utils.h"

#ifndef WIN32
#  include <unistd.h>           // for isatty()
#endif

namespace sofa {
namespace helper {

    Console::ColorsStatus Console::s_colorsStatus = Console::ColorsAuto;

#ifdef WIN32

    static HANDLE s_console = NULL;

    static Console::ColorType initConsoleAndGetDefaultColor()
    {
        s_console = GetStdHandle(STD_OUTPUT_HANDLE);

        if(s_console == INVALID_HANDLE_VALUE)
        {
            std::cerr << "Console::init(): " << Utils::GetLastError() << std::endl;
            return Console::ColorType(7);
        }
        if(s_console == NULL)
        {
            std::cerr << "Console::init(): no stdout handle!" << std::endl;
            return Console::ColorType(7);
        }
        else
        {
            CONSOLE_SCREEN_BUFFER_INFO currentInfo;
            GetConsoleScreenBufferInfo(s_console, &currentInfo);
            return currentInfo.wAttributes;
        }
    }

    const Console::ColorType Console::BLACK         = Console::ColorType(0);
    const Console::ColorType Console::BLUE          = Console::ColorType(1);
    const Console::ColorType Console::GREEN         = Console::ColorType(2);
    const Console::ColorType Console::CYAN          = Console::ColorType(3);
    const Console::ColorType Console::RED           = Console::ColorType(4);
    const Console::ColorType Console::PURPLE        = Console::ColorType(5);
    const Console::ColorType Console::YELLOW        = Console::ColorType(6);
    const Console::ColorType Console::WHITE         = Console::ColorType(7);
    const Console::ColorType Console::BRIGHT_BLACK  = Console::ColorType(8);
    const Console::ColorType Console::BRIGHT_BLUE   = Console::ColorType(9);
    const Console::ColorType Console::BRIGHT_GREEN  = Console::ColorType(10);
    const Console::ColorType Console::BRIGHT_CYAN   = Console::ColorType(11);
    const Console::ColorType Console::BRIGHT_RED    = Console::ColorType(12);
    const Console::ColorType Console::BRIGHT_PURPLE = Console::ColorType(13);
    const Console::ColorType Console::BRIGHT_YELLOW = Console::ColorType(14);
    const Console::ColorType Console::BRIGHT_WHITE  = Console::ColorType(15);
    const Console::ColorType Console::DEFAULT_COLOR = initConsoleAndGetDefaultColor();

    void Console::setColorsStatus(ColorsStatus status)
    {
        s_colorsStatus = status;
    }

    bool Console::shouldUseColors(std::ostream& stream)
    {
        // On Windows, colors are not handled with control characters, so we can
        // probably always use them unless explicitely disabled.
        return getColorsStatus() != ColorsDisabled;
    }

    SOFA_HELPER_API std::ostream& operator<<( std::ostream& stream, Console::ColorType color )
    {
        if (Console::shouldUseColors(stream))
            SetConsoleTextAttribute(s_console, color.value);
        return stream;
    }

#else

    const Console::ColorType Console::BLACK         = Console::ColorType("\033[0;30m");
    const Console::ColorType Console::RED           = Console::ColorType("\033[0;31m");
    const Console::ColorType Console::GREEN         = Console::ColorType("\033[0;32m");
    const Console::ColorType Console::YELLOW        = Console::ColorType("\033[0;33m");
    const Console::ColorType Console::BLUE          = Console::ColorType("\033[0;34m");
    const Console::ColorType Console::PURPLE        = Console::ColorType("\033[0;35m");
    const Console::ColorType Console::CYAN          = Console::ColorType("\033[0;36m");
    const Console::ColorType Console::WHITE         = Console::ColorType("\033[0;37m");
    const Console::ColorType Console::BRIGHT_BLACK  = Console::ColorType("\033[1;30m");
    const Console::ColorType Console::BRIGHT_RED    = Console::ColorType("\033[1;31m");
    const Console::ColorType Console::BRIGHT_GREEN  = Console::ColorType("\033[1;32m");
    const Console::ColorType Console::BRIGHT_YELLOW = Console::ColorType("\033[1;33m");
    const Console::ColorType Console::BRIGHT_BLUE   = Console::ColorType("\033[1;34m");
    const Console::ColorType Console::BRIGHT_PURPLE = Console::ColorType("\033[1;35m");
    const Console::ColorType Console::BRIGHT_CYAN   = Console::ColorType("\033[1;36m");
    const Console::ColorType Console::BRIGHT_WHITE  = Console::ColorType("\033[1;37m");
    const Console::ColorType Console::DEFAULT_COLOR = Console::ColorType("\033[0m");

    static bool s_stdoutIsRedirected = false;
    static bool s_stderrIsRedirected = false;

    void Console::setColorsStatus(ColorsStatus status)
    {
        s_colorsStatus = status;
        // Check for redirections and save the result.  (This assumes that
        // stdout and stderr won't be redirected in the middle of the execution
        // of the program, which seems reasonable to me.)
        s_stdoutIsRedirected = isatty(STDOUT_FILENO) == 0;
        s_stderrIsRedirected = isatty(STDERR_FILENO) == 0;
    }

    bool Console::shouldUseColors(std::ostream& stream)
    {
        if (s_colorsStatus == Console::ColorsAuto)
            return (&stream == &std::cout && !s_stdoutIsRedirected)
                || (&stream == &std::cerr && !s_stderrIsRedirected);
        else
            return s_colorsStatus == Console::ColorsEnabled;
    }

    std::ostream& operator<<( std::ostream& stream, Console::ColorType color )
    {
        if (Console::shouldUseColors(stream))
            return stream << color.value;
        else
            return stream;
    }

#endif

    Console::ColorsStatus Console::getColorsStatus()
    {
        return s_colorsStatus;
    }

}
}
<commit_msg>helper: Minor refactoring in console.cpp<commit_after>#include "console.h"
#include "sofa/helper/Utils.h"

#ifndef WIN32
#  include <unistd.h>           // for isatty()
#endif

namespace sofa {
namespace helper {

    Console::ColorsStatus Console::s_colorsStatus = Console::ColorsAuto;

#ifdef WIN32

    static HANDLE getOutputHandle()
    {
        static bool first = true;
        static s_console = NULL;
        if (first)
        {
            s_console = GetStdHandle(STD_OUTPUT_HANDLE);
            if (s_console == INVALID_HANDLE_VALUE)
            {
                std::cerr << "Console::getOutputHandle(): " << Utils::GetLastError() << std::endl;
            }
            if (s_console == NULL)
            {
                std::cerr << "Console::getOutputHandle(): no stdout handle!" << std::endl;
            }
            first = false;
        }
        return s_console;
    }

    static Console::ColorType getDefaultColor()
    {
        CONSOLE_SCREEN_BUFFER_INFO currentInfo;
        GetConsoleScreenBufferInfo(getOutputHandle(), &currentInfo);
        return currentInfo.wAttributes;
    }

    const Console::ColorType Console::BLACK         = Console::ColorType(0);
    const Console::ColorType Console::BLUE          = Console::ColorType(1);
    const Console::ColorType Console::GREEN         = Console::ColorType(2);
    const Console::ColorType Console::CYAN          = Console::ColorType(3);
    const Console::ColorType Console::RED           = Console::ColorType(4);
    const Console::ColorType Console::PURPLE        = Console::ColorType(5);
    const Console::ColorType Console::YELLOW        = Console::ColorType(6);
    const Console::ColorType Console::WHITE         = Console::ColorType(7);
    const Console::ColorType Console::BRIGHT_BLACK  = Console::ColorType(8);
    const Console::ColorType Console::BRIGHT_BLUE   = Console::ColorType(9);
    const Console::ColorType Console::BRIGHT_GREEN  = Console::ColorType(10);
    const Console::ColorType Console::BRIGHT_CYAN   = Console::ColorType(11);
    const Console::ColorType Console::BRIGHT_RED    = Console::ColorType(12);
    const Console::ColorType Console::BRIGHT_PURPLE = Console::ColorType(13);
    const Console::ColorType Console::BRIGHT_YELLOW = Console::ColorType(14);
    const Console::ColorType Console::BRIGHT_WHITE  = Console::ColorType(15);
    const Console::ColorType Console::DEFAULT_COLOR = getDefaultColor();

    void Console::setColorsStatus(ColorsStatus status)
    {
        s_colorsStatus = status;
    }

    bool Console::shouldUseColors(std::ostream& stream)
    {
        // On Windows, colors are not handled with control characters, so we can
        // probably always use them unless explicitely disabled.
        return getColorsStatus() != ColorsDisabled;
    }

    SOFA_HELPER_API std::ostream& operator<<( std::ostream& stream, Console::ColorType color )
    {
        if (Console::shouldUseColors(stream))
            SetConsoleTextAttribute(getOutputHandle(), color.value);
        return stream;
    }

#else

    const Console::ColorType Console::BLACK         = Console::ColorType("\033[0;30m");
    const Console::ColorType Console::RED           = Console::ColorType("\033[0;31m");
    const Console::ColorType Console::GREEN         = Console::ColorType("\033[0;32m");
    const Console::ColorType Console::YELLOW        = Console::ColorType("\033[0;33m");
    const Console::ColorType Console::BLUE          = Console::ColorType("\033[0;34m");
    const Console::ColorType Console::PURPLE        = Console::ColorType("\033[0;35m");
    const Console::ColorType Console::CYAN          = Console::ColorType("\033[0;36m");
    const Console::ColorType Console::WHITE         = Console::ColorType("\033[0;37m");
    const Console::ColorType Console::BRIGHT_BLACK  = Console::ColorType("\033[1;30m");
    const Console::ColorType Console::BRIGHT_RED    = Console::ColorType("\033[1;31m");
    const Console::ColorType Console::BRIGHT_GREEN  = Console::ColorType("\033[1;32m");
    const Console::ColorType Console::BRIGHT_YELLOW = Console::ColorType("\033[1;33m");
    const Console::ColorType Console::BRIGHT_BLUE   = Console::ColorType("\033[1;34m");
    const Console::ColorType Console::BRIGHT_PURPLE = Console::ColorType("\033[1;35m");
    const Console::ColorType Console::BRIGHT_CYAN   = Console::ColorType("\033[1;36m");
    const Console::ColorType Console::BRIGHT_WHITE  = Console::ColorType("\033[1;37m");
    const Console::ColorType Console::DEFAULT_COLOR = Console::ColorType("\033[0m");

    static bool s_stdoutIsRedirected = false;
    static bool s_stderrIsRedirected = false;

    void Console::setColorsStatus(ColorsStatus status)
    {
        s_colorsStatus = status;
        // Check for redirections and save the result.  (This assumes that
        // stdout and stderr won't be redirected in the middle of the execution
        // of the program, which seems reasonable to me.)
        s_stdoutIsRedirected = isatty(STDOUT_FILENO) == 0;
        s_stderrIsRedirected = isatty(STDERR_FILENO) == 0;
    }

    bool Console::shouldUseColors(std::ostream& stream)
    {
        if (s_colorsStatus == Console::ColorsAuto)
            return (&stream == &std::cout && !s_stdoutIsRedirected)
                || (&stream == &std::cerr && !s_stderrIsRedirected);
        else
            return s_colorsStatus == Console::ColorsEnabled;
    }

    std::ostream& operator<<( std::ostream& stream, Console::ColorType color )
    {
        if (Console::shouldUseColors(stream))
            return stream << color.value;
        else
            return stream;
    }

#endif

    Console::ColorsStatus Console::getColorsStatus()
    {
        return s_colorsStatus;
    }

}
}
<|endoftext|>


<commit_before>#include "PointCloudView.hpp"

#include <pcl/io/io.h>
#include <pcl/common/transforms.h>
#include <pcl/filters/voxel_grid.h>

using namespace maps;

PointCloudView::
PointCloudView() {
  mCloud.reset(new maps::PointCloud());
  mResolution = 0;
}

PointCloudView::
~PointCloudView() {
}

void PointCloudView::
setResolution(const float iResolution) {
  mResolution = iResolution;
}

maps::PointCloud::Ptr PointCloudView::
getPointCloud() const {
  return mCloud;
}

const ViewBase::Type PointCloudView::
getType() const {
  return TypePointCloud;
}

ViewBase::Ptr PointCloudView::
clone() const {
  PointCloudView* view = new PointCloudView(*this);
  pcl::copyPointCloud(*mCloud, *view->mCloud);
  return ViewBase::Ptr(view);
}

void PointCloudView::
set(const maps::PointCloud::Ptr& iCloud) {
  if (mResolution > 0) {
    pcl::VoxelGrid<maps::PointCloud::PointType> grid;
    grid.setInputCloud(iCloud);
    grid.setLeafSize(mResolution,mResolution,mResolution);
    grid.filter(*mCloud);
  }
  else {
    pcl::copyPointCloud(*iCloud, *mCloud);
  }
}

maps::PointCloud::Ptr PointCloudView::
getAsPointCloud(const bool iTransform) const {
  maps::PointCloud::Ptr cloud(new maps::PointCloud(*mCloud));
  if (iTransform) {
    pcl::transformPointCloud(*cloud, *cloud,
                             Eigen::Affine3f(mTransform.matrix()));
  }
  /* NOTE: for projective transformation
  for (int i = 0; i < cloud->size(); ++i) {
    maps::PointCloud::PointType& pt = (*cloud)[i];
    Eigen::Vector4f projPt = mTransform*Eigen::Vector4f(pt.x,pt.y,pt.z,1);
    pt.getVector3fMap() = projPt.head<3>()/projPt[3];
  }
  */
  return cloud;
}
<commit_msg>PointCloudView::getAsPointCloud() should be using the transform inverse<commit_after>#include "PointCloudView.hpp"

#include <pcl/io/io.h>
#include <pcl/common/transforms.h>
#include <pcl/filters/voxel_grid.h>

using namespace maps;

PointCloudView::
PointCloudView() {
  mCloud.reset(new maps::PointCloud());
  mResolution = 0;
}

PointCloudView::
~PointCloudView() {
}

void PointCloudView::
setResolution(const float iResolution) {
  mResolution = iResolution;
}

maps::PointCloud::Ptr PointCloudView::
getPointCloud() const {
  return mCloud;
}

const ViewBase::Type PointCloudView::
getType() const {
  return TypePointCloud;
}

ViewBase::Ptr PointCloudView::
clone() const {
  PointCloudView* view = new PointCloudView(*this);
  pcl::copyPointCloud(*mCloud, *view->mCloud);
  return ViewBase::Ptr(view);
}

void PointCloudView::
set(const maps::PointCloud::Ptr& iCloud) {
  if (mResolution > 0) {
    pcl::VoxelGrid<maps::PointCloud::PointType> grid;
    grid.setInputCloud(iCloud);
    grid.setLeafSize(mResolution,mResolution,mResolution);
    grid.filter(*mCloud);
  }
  else {
    pcl::copyPointCloud(*iCloud, *mCloud);
  }
}

maps::PointCloud::Ptr PointCloudView::
getAsPointCloud(const bool iTransform) const {
  maps::PointCloud::Ptr cloud(new maps::PointCloud(*mCloud));
  if (iTransform) {
    pcl::transformPointCloud(*cloud, *cloud,
                             Eigen::Affine3f(mTransform.matrix()).inverse());
  }
  /* NOTE: for projective transformation
  for (int i = 0; i < cloud->size(); ++i) {
    maps::PointCloud::PointType& pt = (*cloud)[i];
    Eigen::Vector4f projPt = mTransform*Eigen::Vector4f(pt.x,pt.y,pt.z,1);
    pt.getVector3fMap() = projPt.head<3>()/projPt[3];
  }
  */
  return cloud;
}
<|endoftext|>


<commit_before>/*
  Copyright (c) 2014, J.D. Koftinoff Software, Ltd.
  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.

   3. Neither the name of J.D. Koftinoff Software, Ltd. nor the names of its
      contributors may be used to endorse or promote products derived from
      this software without specific prior written permission.

  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.
*/
#pragma once

#include "JDKSAvdeccMCU_World.hpp"
#include "JDKSAvdeccMCU_RawSocket.hpp"
#include "JDKSAvdeccMCU_Frame.hpp"
#include "JDKSAvdeccMCU_FixedBuffer.hpp"
#include "JDKSAvdeccMCU_Handler.hpp"

namespace JDKSAvdeccMCU
{

class ControlValueHolder : private FixedBuffer
{
  public:
    ControlValueHolder( uint8_t *buf,
                        uint16_t value_length,
                        uint8_t num_items = 1 )
        : FixedBuffer( buf, value_length * num_items )
        , m_value_length( value_length )
        , m_num_items( num_items )
        , m_dirty( true )
    {
        bzero( buf, m_value_length * m_num_items );
        setLength( m_value_length * m_num_items );
    }

    bool isDirty() const { return m_dirty; }
    void clearDirty() { m_dirty = false; }

    uint8_t getValueLength() const { return m_value_length; }

    uint8_t getNumItems() const { return m_num_items; }

    uint8_t getValueOctet( uint8_t item = 0 ) const
    {
        return getOctet( item * sizeof( uint8_t ) );
    }

    uint16_t getValueDoublet( uint8_t item = 0 ) const
    {
        return getOctet( item * sizeof( uint16_t ) );
    }

    uint32_t getValueQuadlet( uint8_t item = 0 ) const
    {
        return getOctet( item * sizeof( uint32_t ) );
    }

    template <typename T>
    T getValueAs( uint8_t item = 0 ) const
    {
        T r = 0;
        switch ( m_value_length )
        {
        case 1:
            r = reinterpret_cast<T>( getValueOctet( item ) );
            break;
        case 2:
            r = reinterpret_cast<T>( getValueDoublet( item ) );
            break;
        case 4:
            r = reinterpret_cast<T>( getValueQuadlet( item ) );
            break;
        }
        return r;
    }

    void setValueOctet( uint8_t v, uint8_t item = 0 )
    {
        setOctet( v, item * sizeof( uint8_t ) );
    }

    void setValueDoublet( uint16_t v, uint8_t item = 0 )
    {
        setDoublet( v, item * sizeof( uint16_t ) );
    }

    void setValueQuadlet( uint32_t v, uint8_t item = 0 )
    {
        setQuadlet( v, item * sizeof( uint32_t ) );
    }

    template <typename T>
    void setValueAs( T v, uint8_t item = 0 )
    {
        m_dirty = true;
        switch ( m_value_length )
        {
        case 1:
        {
            uint8_t octet_value = reinterpret_cast<uint8_t>( v );
            setValueOctet( octet_value, item );
            break;
        }
        case 2:
        {
            uint16_t doublet_value = reinterpret_cast<uint16_t>( v );
            setValueDoublet( doublet_value, item );
            break;
        }
        case 4:
        {
            uint32_t quadlet_value = reinterpret_cast<uint32_t>( v );
            setValueQuadlet( quadlet_value, item );
            break;
        }
        }
    }

    void setValue( uint8_t const *v )
    {
        memcpy( m_buf, v, m_value_length * m_num_items );
        m_dirty = true;
    }

  protected:
    uint16_t m_value_length;
    uint8_t m_num_items;
    bool m_dirty;
};

template <typename BaseValueType, uint8_t NumItems>
class ControlValueHolderWithStorage : public ControlValueHolder
{
  public:
    typedef BaseValueType value_type;
    static const uint8_t num_items = NumItems;

    ControlValueHolderWithStorage()
        : ControlValueHolder(
              m_value_storage, sizeof( BaseValueType ), NumItems )
    {
    }

  protected:
    uint8_t m_value_storage[sizeof( BaseValueType ) * NumItems];
};
}
<commit_msg>general setValue method takes a const void * instead of ptr to uint8_t<commit_after>/*
  Copyright (c) 2014, J.D. Koftinoff Software, Ltd.
  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.

   3. Neither the name of J.D. Koftinoff Software, Ltd. nor the names of its
      contributors may be used to endorse or promote products derived from
      this software without specific prior written permission.

  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.
*/
#pragma once

#include "JDKSAvdeccMCU_World.hpp"
#include "JDKSAvdeccMCU_RawSocket.hpp"
#include "JDKSAvdeccMCU_Frame.hpp"
#include "JDKSAvdeccMCU_FixedBuffer.hpp"
#include "JDKSAvdeccMCU_Handler.hpp"

namespace JDKSAvdeccMCU
{

class ControlValueHolder : private FixedBuffer
{
  public:
    ControlValueHolder( uint8_t *buf,
                        uint16_t value_length,
                        uint8_t num_items = 1 )
        : FixedBuffer( buf, value_length * num_items )
        , m_value_length( value_length )
        , m_num_items( num_items )
        , m_dirty( true )
    {
        bzero( buf, m_value_length * m_num_items );
        setLength( m_value_length * m_num_items );
    }

    bool isDirty() const { return m_dirty; }
    void clearDirty() { m_dirty = false; }

    uint8_t getValueLength() const { return m_value_length; }

    uint8_t getNumItems() const { return m_num_items; }

    uint8_t getValueOctet( uint8_t item = 0 ) const
    {
        return getOctet( item * sizeof( uint8_t ) );
    }

    uint16_t getValueDoublet( uint8_t item = 0 ) const
    {
        return getOctet( item * sizeof( uint16_t ) );
    }

    uint32_t getValueQuadlet( uint8_t item = 0 ) const
    {
        return getOctet( item * sizeof( uint32_t ) );
    }

    template <typename T>
    T getValueAs( uint8_t item = 0 ) const
    {
        T r = 0;
        switch ( m_value_length )
        {
        case 1:
            r = reinterpret_cast<T>( getValueOctet( item ) );
            break;
        case 2:
            r = reinterpret_cast<T>( getValueDoublet( item ) );
            break;
        case 4:
            r = reinterpret_cast<T>( getValueQuadlet( item ) );
            break;
        }
        return r;
    }

    void setValueOctet( uint8_t v, uint8_t item = 0 )
    {
        setOctet( v, item * sizeof( uint8_t ) );
    }

    void setValueDoublet( uint16_t v, uint8_t item = 0 )
    {
        setDoublet( v, item * sizeof( uint16_t ) );
    }

    void setValueQuadlet( uint32_t v, uint8_t item = 0 )
    {
        setQuadlet( v, item * sizeof( uint32_t ) );
    }

    template <typename T>
    void setValueAs( T v, uint8_t item = 0 )
    {
        m_dirty = true;
        switch ( m_value_length )
        {
        case 1:
        {
            uint8_t octet_value = reinterpret_cast<uint8_t>( v );
            setValueOctet( octet_value, item );
            break;
        }
        case 2:
        {
            uint16_t doublet_value = reinterpret_cast<uint16_t>( v );
            setValueDoublet( doublet_value, item );
            break;
        }
        case 4:
        {
            uint32_t quadlet_value = reinterpret_cast<uint32_t>( v );
            setValueQuadlet( quadlet_value, item );
            break;
        }
        }
    }

    void setValue( void const *v )
    {
        memcpy( m_buf, v, m_value_length * m_num_items );
        m_dirty = true;
    }

  protected:
    uint16_t m_value_length;
    uint8_t m_num_items;
    bool m_dirty;
};

template <typename BaseValueType, uint8_t NumItems>
class ControlValueHolderWithStorage : public ControlValueHolder
{
  public:
    typedef BaseValueType value_type;
    static const uint8_t num_items = NumItems;

    ControlValueHolderWithStorage()
        : ControlValueHolder(
              m_value_storage, sizeof( BaseValueType ), NumItems )
    {
    }

  protected:
    uint8_t m_value_storage[sizeof( BaseValueType ) * NumItems];
};
}
<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// File CLFtester.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Description: CFL tester solve routines
//
///////////////////////////////////////////////////////////////////////////////

#include <IncNavierStokesSolver/EquationSystems/IncNavierStokes.h>

namespace Nektar
{
	/*
    NekDouble IncNavierStokes::v_GetTimeStep(const Array<OneD,int> ExpOrder, const Array<OneD,NekDouble> CFL, NekDouble timeCFL)
    {

        int nvariables      = m_fields.num_elements();
        int nTotQuadPoints  = GetTotPoints();
        int n_element       = m_fields[0]->GetExpSize();

        const NekDouble minLengthStdTri  = 1.414213;
        const NekDouble minLengthStdQuad = 2.0;
        const NekDouble cLambda          = 0.2; // Spencer book pag. 317

        Array<OneD, NekDouble> tstep      (n_element, 0.0);
        Array<OneD, NekDouble> stdVelocity(n_element, 0.0);
        Array<OneD, Array<OneD, NekDouble> > velfields(
                                                m_velocity.num_elements());

        for(int i = 0; i < m_velocity.num_elements(); ++i)
        {
            velfields[i] = m_fields[m_velocity[i]]->UpdatePhys();
        }
        stdVelocity = GetStdVelocity(velfields);

        for(int el = 0; el < n_element; ++el)
        {
            int npoints = m_fields[0]->GetExp(el)->GetTotPoints();

            tstep[el] =  CFL[el]/(stdVelocity[el]*cLambda*(ExpOrder[el]-1)*(ExpOrder[el]-1));
        }

        NekDouble TimeStep = Vmath::Vmin(n_element,tstep,1);

        return TimeStep;
    }

    NekDouble IncNavierStokes::v_GetTimeStep(int ExpOrder, NekDouble CFL, NekDouble TimeStability)
    {
        Array<OneD, int> ExpOrderList(m_fields[0]->GetExpSize(),ExpOrder);
        Array<OneD, NekDouble> CFLList(m_fields[0]->GetExpSize(),CFL);

        return v_GetTimeStep(ExpOrderList,CFLList,TimeStability);
    }

    Array<OneD,NekDouble> IncNavierStokes::GetStdVelocity(const Array<OneD, Array<OneD,NekDouble> > inarray)
	{
        // Checking if the problem is 2D
        ASSERTL0(m_expdim>=2,"Method not implemented for 1D");

        int nTotQuadPoints  = GetTotPoints();
        int n_element  = m_fields[0]->GetExpSize();       // number of element in the mesh
        int nvel = inarray.num_elements();
        int npts = 0;

        NekDouble pntVelocity;

        // Getting the standard velocity vector on the 2D normal space
        Array<OneD, Array<OneD, NekDouble> > stdVelocity(nvel);

        Array<OneD, NekDouble> stdV(n_element,0.0);
        for (int i = 0; i < nvel; ++i)
        {
            stdVelocity[i] = Array<OneD, NekDouble>(nTotQuadPoints);
        }

        if(nvel == 2)
        {
            for(int el = 0; el < n_element; ++el)
            {

                int n_points = m_fields[0]->GetExp(el)->GetTotPoints();

                Array<OneD, const NekDouble> jac  = m_fields[0]->GetExp(el)->GetGeom2D()->GetJac();
                Array<TwoD, const NekDouble> gmat = m_fields[0]->GetExp(el)->GetGeom2D()->GetGmat();

                if(m_fields[0]->GetExp(el)->GetGeom2D()->GetGtype() == SpatialDomains::eDeformed)
                {
                    for(int i=0; i<n_points; i++)
                    {
                        stdVelocity[0][i] = gmat[0][i]*inarray[0][i] + gmat[2][i]*inarray[1][i];
                        stdVelocity[1][i] = gmat[1][i]*inarray[0][i] + gmat[3][i]*inarray[1][i];
                    }
                }
                else
                {
                    for(int i=0; i<n_points; i++)
                    {
                        stdVelocity[0][i] = gmat[0][0]*inarray[0][i] + gmat[2][0]*inarray[1][i];
                        stdVelocity[1][i] = gmat[1][0]*inarray[0][i] + gmat[3][0]*inarray[1][i];
                    }
                }

                for(int i=0; i<n_points; i++)
                {
                    pntVelocity = sqrt(stdVelocity[0][i]*stdVelocity[0][i] + stdVelocity[1][i]*stdVelocity[1][i]);
                    if(pntVelocity>stdV[el])
                    {
                        stdV[el] = pntVelocity;
                    }

                }
            }
        }
        else
        {
            for(int el = 0; el < n_element; ++el)
            {

                int n_points = m_fields[0]->GetExp(el)->GetTotPoints();

                Array<OneD, const NekDouble> jac  = m_fields[0]->GetExp(el)->GetGeom3D()->GetJac();
                Array<TwoD, const NekDouble> gmat = m_fields[0]->GetExp(el)->GetGeom3D()->GetGmat();

                if(m_fields[0]->GetExp(el)->GetGeom3D()->GetGtype() == SpatialDomains::eDeformed)
                {
                    for(int i=0; i<n_points; i++)
                    {
                        stdVelocity[0][i] = gmat[0][i]*inarray[0][i] + gmat[3][i]*inarray[1][i] + gmat[6][i]*inarray[2][i];
                        stdVelocity[1][i] = gmat[1][i]*inarray[0][i] + gmat[4][i]*inarray[1][i] + gmat[7][i]*inarray[2][i];
                        stdVelocity[2][i] = gmat[2][i]*inarray[0][i] + gmat[5][i]*inarray[1][i] + gmat[8][i]*inarray[2][i];
                    }
                }
                else
                {
                    Array<OneD, const NekDouble> jac  = m_fields[0]->GetExp(el)->GetGeom3D()->GetJac();
                    Array<TwoD, const NekDouble> gmat = m_fields[0]->GetExp(el)->GetGeom3D()->GetGmat();

                    for(int i=0; i<n_points; i++)
                    {
                        stdVelocity[0][i] = gmat[0][0]*inarray[0][i] + gmat[3][0]*inarray[1][i] + gmat[6][0]*inarray[2][i];
                        stdVelocity[1][i] = gmat[1][0]*inarray[0][i] + gmat[4][0]*inarray[1][i] + gmat[7][0]*inarray[2][i];
                        stdVelocity[2][i] = gmat[2][0]*inarray[0][i] + gmat[5][0]*inarray[1][i] + gmat[8][0]*inarray[2][i];
                    }
                }

                for(int i=0; i<n_points; i++)
                {
                    pntVelocity = sqrt(stdVelocity[0][i]*stdVelocity[0][i] + stdVelocity[1][i]*stdVelocity[1][i] + stdVelocity[2][i]*stdVelocity[2][i]);
                    if(pntVelocity>stdV[el])
                    {
                        stdV[el] = pntVelocity;
                    }
                }
            }
        }

        return stdV;
	}
     */
}
<commit_msg>Removed CFLTester.cpp from IncNavierStokesSolver.<commit_after><|endoftext|>


<commit_before>#ifndef ALEPH_TOPOLOGY_IO_ADJACENCY_MATRIX_HH__
#define ALEPH_TOPOLOGY_IO_ADJACENCY_MATRIX_HH__

#include <aleph/utilities/String.hh>

#include <aleph/topology/filtrations/Data.hh>

#include <algorithm>
#include <fstream>
#include <istream>
#include <string>
#include <unordered_map>
#include <vector>

#include <cmath>

namespace aleph
{

namespace topology
{

namespace io
{

/**
  @class AdjacencyMatrixReader
  @brief Reads square adjacency matrices in text format

  This reader class is meant to load square adjacency matrices (square)
  in text format. Entry (i,j) in the matrix contains the edge weight of
  the (unique) edge connecting nodes i and j.

  Depending on the configuration of the class, cells with a pre-defined
  weight (usually zero) are taken to indicate missing edges.

  The number of rows and columns must not vary over the file. An *empty*
  line is permitted, though. Likewise, lines starting with `#` will just
  be ignored. An example of a 3-by-3 matrix follows:

  \code
  0 1 2
  3 4 5
  2 1 7
  \endcode

  All simplicial complexes created by this class will be reported
  in filtration order, following the detected weights.
*/

class AdjacencyMatrixReader
{
public:

  /**
    Reads a simplicial complex from a file.

    @param filename Input filename
    @param  K       Simplicial complex
  */

  template <class SimplicialComplex> void operator()( const std::string& filename, SimplicialComplex& K )
  {
    std::ifstream in( filename );
    if( !in )
      throw std::runtime_error( "Unable to read input file" );

    this->operator()( in, K );
  }

  /** @overload operator()( const std::string&, SimplicialComplex& ) */
  template <class SimplicialComplex> void operator()( std::istream& in, SimplicialComplex& K )
  {
    using Simplex    = typename SimplicialComplex::ValueType;
    using DataType   = typename Simplex::DataType;
    using VertexType = typename Simplex::VertexType;

    auto position    = in.tellg();
    std::size_t n    = 0;

    // An 'unrolled' version of all edge weights that can be read from
    // the file. They are supposed to correspond to a matrix with some
    // number of columns and some number of rows.
    std::vector<DataType> values;

    using namespace aleph::utilities;

    {
      std::string line;
      while( std::getline( in, line ) )
      {
        // Skip empty lines and comments as promised
        if( line.empty() || line.front() == '#' )
          continue;

        ++n;
      }

      in.clear();
      in.seekg( position );
    }

    // FIXME: this will not work in case comments are part of the file.
    // Drat---should probably rewrite it.
    std::copy( std::istream_iterator<DataType>( in ), std::istream_iterator<DataType>(),
               std::back_inserter( values ) );

    // We cannot fill an empty simplicial complex. It might be useful to
    // throw an error here, though.
    if( values.empty() )
      return;

    _height = height;
    _width  = values.size() / height;

    if( values.size() % height != 0 )
      throw std::runtime_error( "Format error: number of columns must not vary" );

    // This is required in order to assign the weight of nodes
    // correctly; we cannot trust the weights to be positive.
    auto minData = *std::min_element( values.begin(), values.end() );

    std::vector<Simplex> simplices;
    simplices.reserve( _width * _height + ( _width + _height ) );

    // Edges -----------------------------------------------------------
    //
    // Create the edges first and update information about their weights
    // along with them.

    // For determining the minimum weight, we first loop over all
    // possible edges, create a lookup table for the weights, and
    // finally create all the vertices using this lookup table. A
    // vertex will only information stored here if the right flag
    // has been set by the client.
    std::unordered_map<VertexType, DataType> minWeight;

    auto updateOrSetWeight
      = [&minWeight, this] ( const VertexType& v, const DataType& w )
        {
          if( minWeight.find( v ) == minWeight.end() )
            minWeight[v] = w;
          else
          {
            if( _assignMinimumAbsoluteVertexWeight )
            {
              if( std::abs( w ) < std::abs( minWeight[v] ) )
                minWeight[v] = w;
            }
            else
              minWeight[v] = std::min( minWeight[v], w );
          }
        };

    for( std::size_t y = 0; y < _height; y++ )
    {
      for( std::size_t x = 0; x < _width; x++ )
      {
        auto i = static_cast<VertexType>( _width * y + x   );
        auto w = values[i];

        // Map matrix indices to the corresponding vertex indices as
        // outline above.
        auto u = VertexType(y);
        auto v = VertexType(x + _height);

        updateOrSetWeight( u, w );
        updateOrSetWeight( v, w );

        simplices.push_back( Simplex( {u,v}, w ) );
      }
    }

    // Vertices --------------------------------------------------------
    //
    // Create a vertex for every node in the input data. An (n,m)-matrix
    // thus gives rise to n+m nodes.

    for( std::size_t i = 0; i < _height + _width; i++ )
    {
      // Notice that that `minWeight` map is guaranteed to contain the
      // weight (potentially signed) that corresponds to the vertex. A
      // different way of setting up the map depends on the flags that
      // are set by the client.
      simplices.push_back(
        Simplex( VertexType( i ),
          _assignMinimumVertexWeight || _assignMinimumAbsoluteVertexWeight
            ?  minWeight[ VertexType(i) ]
            :  minData )
      );
    }

    K = SimplicialComplex( simplices.begin(), simplices.end() );

    // Establish filtration order based on weights. There does not seem
    // to be much of a point to make this configurable; the edge weight
    // is a given property of the data.
    K.sort(
      filtrations::Data<Simplex>()
    );
  }

  /** @returns Dimension of matrix that was read last */
  std::size_t dimension() const noexcept { return _dimension; }

private:

  // Dimension of the matrix that was read last by this reader; this
  // will only be set if the matrix is actually square.
  std::size_t _dimension = 0;
};

} // namespace io

} // namespace topology

} // namespace aleph

#endif
<commit_msg>Extended adjacency matrix reader<commit_after>#ifndef ALEPH_TOPOLOGY_IO_ADJACENCY_MATRIX_HH__
#define ALEPH_TOPOLOGY_IO_ADJACENCY_MATRIX_HH__

#include <aleph/utilities/String.hh>

#include <aleph/topology/filtrations/Data.hh>

#include <algorithm>
#include <fstream>
#include <istream>
#include <string>
#include <unordered_map>
#include <vector>

#include <cmath>

namespace aleph
{

namespace topology
{

namespace io
{

/**
  @class AdjacencyMatrixReader
  @brief Reads square adjacency matrices in text format

  This reader class is meant to load square adjacency matrices (square)
  in text format. Entry (i,j) in the matrix contains the edge weight of
  the (unique) edge connecting nodes i and j.

  Depending on the configuration of the class, cells with a pre-defined
  weight (usually zero) are taken to indicate missing edges.

  The number of rows and columns must not vary over the file. An *empty*
  line is permitted, though. Likewise, lines starting with `#` will just
  be ignored. An example of a 3-by-3 matrix follows:

  \code
  0 1 2
  3 4 5
  2 1 7
  \endcode

  All simplicial complexes created by this class will be reported
  in filtration order, following the detected weights.
*/

class AdjacencyMatrixReader
{
public:

  /**
    Reads a simplicial complex from a file.

    @param filename Input filename
    @param  K       Simplicial complex
  */

  template <class SimplicialComplex> void operator()( const std::string& filename, SimplicialComplex& K )
  {
    std::ifstream in( filename );
    if( !in )
      throw std::runtime_error( "Unable to read input file" );

    this->operator()( in, K );
  }

  /** @overload operator()( const std::string&, SimplicialComplex& ) */
  template <class SimplicialComplex> void operator()( std::istream& in, SimplicialComplex& K )
  {
    using Simplex    = typename SimplicialComplex::ValueType;
    using DataType   = typename Simplex::DataType;
    using VertexType = typename Simplex::VertexType;

    auto position    = in.tellg();
    std::size_t n    = 0;

    // An 'unrolled' version of all edge weights that can be read from
    // the file. They are supposed to correspond to a matrix with some
    // number of columns and some number of rows.
    std::vector<DataType> values;

    using namespace aleph::utilities;

    {
      std::string line;
      while( std::getline( in, line ) )
      {
        // Skip empty lines and comments as promised
        if( line.empty() || line.front() == '#' )
          continue;

        ++n;
      }

      in.clear();
      in.seekg( position );
    }

    // FIXME: this will not work in case comments are part of the file.
    // Drat---should probably rewrite it.
    std::copy( std::istream_iterator<DataType>( in ), std::istream_iterator<DataType>(),
               std::back_inserter( values ) );

    // We cannot fill an empty simplicial complex. It might be useful to
    // throw an error here, though.
    if( values.empty() )
      return;

    _dimension = n;

    if( values.size() != _dimension * _dimension )
      throw std::runtime_error( "Format error: number of columns must not vary" );

    std::vector<Simplex> simplices;

    // First part of that equation reserves $n$ nodes, where $n$ is the
    // dimension of the matrix, followed by at most $n^2$ edges. Notice
    // that this assumes that *all* edges are defined.
    simplices.reserve( _dimension + ( _dimension * _dimension ) );

    // Edges -----------------------------------------------------------
    //
    // Create the edges first and update information about their weights
    // along with them.

    for( std::size_t y = 0; y < _dimension; y++ )
    {
      for( std::size_t x = 0; x < _dimension; x++ )
      {
        auto i = static_cast<VertexType>( _dimension * y + x   );
        auto w = values[i];

        // Map matrix indices to the corresponding vertex indices as
        // outlined above.
        auto u = VertexType(y);
        auto v = VertexType(x + _dimension);

        // TODO: skip edge if its weight is going to be ignored anyway
        // according to the client input.

        // We have no choice here but to store the corresponding simplex
        // with *exactly* the weight as it was specified in the file.
        simplices.push_back( Simplex( {u,v}, w ) );
      }
    }

    // Vertices --------------------------------------------------------
    //
    // Create a vertex for every node in the input data. This will use
    // the minimum weight detected in the file.
    auto minWeight = *std::min_element( values.begin(), values.end() );

    for( std::size_t i = 0; i < _dimension; i++ )
    {
      simplices.push_back(
        Simplex( VertexType( i ), minWeight )
      );
    }

    K = SimplicialComplex( simplices.begin(), simplices.end() );

    // Establish filtration order based on weights. There does not seem
    // to be much of a point to make this configurable; the edge weight
    // is a given property of the data.
    K.sort(
      filtrations::Data<Simplex>()
    );
  }

  /** @returns Dimension of matrix that was read last */
  std::size_t dimension() const noexcept { return _dimension; }

private:

  // Dimension of the matrix that was read last by this reader; this
  // will only be set if the matrix is actually square.
  std::size_t _dimension = 0;
};

} // namespace io

} // namespace topology

} // namespace aleph

#endif
<|endoftext|>


<commit_before>#pragma once
#include "depthai-shared/common/Extrinsics.hpp"

struct CameraInfo {
    std::vector<std::vector<float>> intrinsicMatrix;
    std::vector<float> distortionCoeff;
    Extrinsics extrinsics;
    double measuredFovRad; //fov in radians
    // TODO(sachin): Should I add type of distortion model here ?
    NLOHMANN_DEFINE_TYPE_INTRUSIVE(CameraInfo, intrinsicMatrix, distortionCoeff, extrinsics, measuredFovRad);
};
<commit_msg>added width and height and changed fov rad to deg<commit_after>#pragma once
#include "depthai-shared/common/Extrinsics.hpp"

struct CameraInfo {
    int width, height;
    std::vector<std::vector<float>> intrinsicMatrix;
    std::vector<float> distortionCoeff;
    Extrinsics extrinsics;
    double measuredFovDeg; //fov in deg
    // TODO(sachin): Should I add type of distortion model here ?
    NLOHMANN_DEFINE_TYPE_INTRUSIVE(CameraInfo, intrinsicMatrix, distortionCoeff, extrinsics, measuredFovDeg);
};
<|endoftext|>


<commit_before>/*
 * The MIT License
 *
 * Copyright 2017-2018 Norwegian University of Technology
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING  FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#ifndef FMICPP_MODELDESCRIPTION_HPP
#define FMICPP_MODELDESCRIPTION_HPP

#include <memory>
#include <string>
#include <optional>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>

#include "ModelStructure.hpp"
#include "ModelVariables.hpp"
#include "DefaultExperiment.hpp"
#include "FmuTypeAttributes.hpp"

using std::string;
using std::unique_ptr;
using std::shared_ptr;
using boost::property_tree::ptree;

namespace fmicpp::fmi2::xml {

    class CoSimulationModelDescription;

    class ModelExchangeModelDescription;

    class ModelDescription {

    private:
        string guid_;
        string fmiVersion_;
        string modelName_;
        string description_;
        string version_;
        string author_;
        string license_;
        string copyright_;
        string generationTool_;
        string generationDateAndTime_;

        unsigned int numberOfEventIndicators_;

        ModelVariables modelVariables_;
        ModelStructure modelStructure_;
        std::optional<DefaultExperiment> defaultExperiment_;

        shared_ptr<CoSimulationAttributes> coSimulation_ = nullptr;
        shared_ptr<ModelExchangeAttributes> modelExchange_ = nullptr;

    public:

        string guid() const;

        string fmiVersion() const;

        string modelName() const;

        string description() const;

        string version() const;

        string author() const;

        string license() const;

        string copyright() const;

        string generationTool() const;

        string generationDateAndTime() const;

        unsigned int numberOfEventIndicators() const;

        unsigned int numberOfContinuousStates() const;

        const ModelVariables &modelVariables() const;

        const ModelStructure &modelStructure() const;

        const std::optional<DefaultExperiment> defaultExperiment() const;

        bool supportsModelExchange() const;

        bool supportsCoSimulation() const;

        shared_ptr<CoSimulationModelDescription> asCoSimulationModelDescription() const;

        shared_ptr<ModelExchangeModelDescription> asModelExchangeModelDescription() const;

        ScalarVariable getVariableByName(const string &name) const;

        ScalarVariable getVariableByValueReference(const fmi2ValueReference vr) const;

        void load(const string &fileName);

    };

}

#endif //FMICPP_MODELDESCRIPTION_HPP
<commit_msg>rearrange code<commit_after>/*
 * The MIT License
 *
 * Copyright 2017-2018 Norwegian University of Technology
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING  FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#ifndef FMICPP_MODELDESCRIPTION_HPP
#define FMICPP_MODELDESCRIPTION_HPP

#include <memory>
#include <string>
#include <optional>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>

#include "ModelStructure.hpp"
#include "ModelVariables.hpp"
#include "DefaultExperiment.hpp"
#include "FmuTypeAttributes.hpp"

using std::string;
using std::unique_ptr;
using std::shared_ptr;
using boost::property_tree::ptree;

namespace fmicpp::fmi2::xml {

    class CoSimulationModelDescription;

    class ModelExchangeModelDescription;

    class ModelDescription {

    private:
        string guid_;
        string fmiVersion_;
        string modelName_;
        string description_;
        string version_;
        string author_;
        string license_;
        string copyright_;
        string generationTool_;
        string generationDateAndTime_;

        unsigned int numberOfEventIndicators_;

        ModelVariables modelVariables_;
        ModelStructure modelStructure_;
        std::optional<DefaultExperiment> defaultExperiment_;

        shared_ptr<CoSimulationAttributes> coSimulation_ = nullptr;
        shared_ptr<ModelExchangeAttributes> modelExchange_ = nullptr;

    public:

        string guid() const;

        string fmiVersion() const;

        string modelName() const;

        string description() const;

        string version() const;

        string author() const;

        string license() const;

        string copyright() const;

        string generationTool() const;

        string generationDateAndTime() const;

        unsigned int numberOfEventIndicators() const;

        unsigned int numberOfContinuousStates() const;

        const ModelVariables &modelVariables() const;

        const ModelStructure &modelStructure() const;

        const std::optional<DefaultExperiment> defaultExperiment() const;

        bool supportsModelExchange() const;

        bool supportsCoSimulation() const;

        ScalarVariable getVariableByName(const string &name) const;

        ScalarVariable getVariableByValueReference(const fmi2ValueReference vr) const;

        shared_ptr<CoSimulationModelDescription> asCoSimulationModelDescription() const;

        shared_ptr<ModelExchangeModelDescription> asModelExchangeModelDescription() const;

        void load(const string &fileName);

    };

}

#endif //FMICPP_MODELDESCRIPTION_HPP
<|endoftext|>


<commit_before>#ifndef __INTERPROC_BUFFER_READER_
#define __INTERPROC_BUFFER_READER_

#include <functional>
#include <asio/error_code.hpp>
#include <asio/ip/tcp.hpp>
#include <asio/read.hpp>
#include <asio/streambuf.hpp>
#include <asio/buffers_iterator.hpp>
#include "../interproc.hpp"

namespace interproc {
    namespace streamsocket {
        // TODO: timeouts
        template<typename socket_type, typename buffer_type = interproc::buffer>
        class reader {
            using handler_t = std::function<void(const asio::error_code &_error, const long unsigned int&)>;
        protected:
            buffer buffer_;
            asio::streambuf response_;
            bool streambuf_read_;
            std::shared_ptr<socket_type> socket_;
            handler_t default_handler_;
        public:

            explicit reader(std::shared_ptr<socket_type> _socket) : socket_(_socket) {
                default_handler_ = std::bind(&interproc::streamsocket::reader<socket_type>::handle_read, this, std::placeholders::_1);
            };

            void read(int _size = -1, handler_t _handler = nullptr) {
                if (_size >= 0) {
                    streambuf_read_ = false;
                    buffer_.resize(_size);
                    if (_size) {
                        char *bufstart = &buffer_[0];
                        asio::async_read(*socket_, asio::buffer(bufstart, _size), (_handler ? _handler : default_handler_));
                    } else {
                        handle_read(asio::error_code());
                    }
                } else {
                    streambuf_read_ = true;
                    asio::async_read(*socket_, response_,
                            asio::transfer_at_least(1),
                            (_handler ? _handler : default_handler_));
                }
            }

            void handle_read(const asio::error_code &_error) {
                if (!_error) {
                    if (on_success) {
                        buffer_type data;
                        if (streambuf_read_) {
                            buffer_.clear();
                            asio::streambuf::const_buffers_type bufs = response_.data();
                            data = buffer_type(asio::buffers_begin(bufs), asio::buffers_begin(bufs) + response_.size());
                        } else {
                            data = buffer_type(buffer_.data(), buffer_.size());
                        }
                        on_success(std::move(data));
                    }
                } else {
                    if (on_fail) on_fail(_error);
                }
            }

            std::function<void(const asio::error_code &)> on_fail;
            std::function<void(buffer_type &&_buffer)> on_success;
        };
    }
}

#endif<commit_msg>* clear stream buffer after receive<commit_after>#ifndef __INTERPROC_BUFFER_READER_
#define __INTERPROC_BUFFER_READER_

#include <functional>
#include <asio/error_code.hpp>
#include <asio/ip/tcp.hpp>
#include <asio/read.hpp>
#include <asio/streambuf.hpp>
#include <asio/buffers_iterator.hpp>
#include "../interproc.hpp"

namespace interproc {
    namespace streamsocket {
        // TODO: timeouts
        template<typename socket_type, typename buffer_type = interproc::buffer>
        class reader {
            using handler_t = std::function<void(const asio::error_code &_error, const long unsigned int&)>;
        protected:
            buffer buffer_;
            asio::streambuf response_;
            bool streambuf_read_;
            std::shared_ptr<socket_type> socket_;
            handler_t default_handler_;
        public:

            explicit reader(std::shared_ptr<socket_type> _socket) : socket_(_socket) {
                default_handler_ = std::bind(&interproc::streamsocket::reader<socket_type>::handle_read, this, std::placeholders::_1);
            };

            void read(int _size = -1, handler_t _handler = nullptr) {
                buffer_.clear();
                if (_size >= 0) {
                    streambuf_read_ = false;
                    buffer_.resize(_size);
                    if (_size) {
                        char *bufstart = &buffer_[0];
                        asio::async_read(*socket_, asio::buffer(bufstart, _size), (_handler ? _handler : default_handler_));
                    } else {
                        handle_read(asio::error_code());
                    }
                } else {
                    streambuf_read_ = true;
                    asio::async_read(*socket_, response_,
                            asio::transfer_at_least(1),
                            (_handler ? _handler : default_handler_));
                }
            }

            void handle_read(const asio::error_code &_error) {
                if (!_error) {
                    if (on_success) {
                        buffer_type data;
                        if (streambuf_read_) {
                            buffer_.clear();
                            asio::streambuf::const_buffers_type bufs = response_.data();
                            data = buffer_type(asio::buffers_begin(bufs), asio::buffers_begin(bufs) + response_.size());
                            response_.consume(response_.size());
                        } else {
                            data = buffer_type(buffer_.data(), buffer_.size());
                        }
                        on_success(std::move(data));
                    }
                } else {
                    if (on_fail) on_fail(_error);
                }
            }

            std::function<void(const asio::error_code &)> on_fail;
            std::function<void(buffer_type &&_buffer)> on_success;
        };
    }
}

#endif<|endoftext|>


<commit_before>#ifndef OSRM_UTIL_GUIDANCE_NAME_ANNOUNCEMENT_HPP_
#define OSRM_UTIL_GUIDANCE_NAME_ANNOUNCEMENT_HPP_

/* A set of tools required for guidance in both pre and post-processing */

#include "extractor/name_table.hpp"
#include "extractor/suffix_table.hpp"

#include "util/attributes.hpp"
#include "util/typedefs.hpp"

#include <algorithm>
#include <string>
#include <tuple>
#include <utility>
#include <vector>

#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/predicate.hpp>

namespace osrm
{
namespace util
{
namespace guidance
{
// Name Change Logic
// Used both during Extraction as well as during Post-Processing

inline std::string_view longest_common_substring(const std::string_view lhs,
                                                 const std::string_view rhs)
{
    if (lhs.empty() || rhs.empty())
        return "";

    // array for dynamic programming
    std::vector<std::uint32_t> dp_previous(rhs.size(), 0), dp_current(rhs.size(), 0);

    // to remember the best location
    std::uint32_t best = 0;
    std::uint32_t best_pos = 0;
    using std::swap;
    for (std::uint32_t i = 0; i < lhs.size(); ++i)
    {
        for (std::uint32_t j = 0; j < rhs.size(); ++j)
        {
            if (lhs[i] == rhs[j])
            {
                dp_current[j] = (j == 0) ? 1 : (dp_previous[j - 1] + 1);
                if (dp_current[j] > best)
                {
                    best = dp_current[j];
                    best_pos = i + 1;
                }
            }
        }
        swap(dp_previous, dp_current);
    }
    // the best position marks the end of the string
    return lhs.substr(best_pos - best, best);
}

// TODO US-ASCII support only, no UTF-8 support
// While UTF-8 might work in some cases, we do not guarantee full functionality
template <typename StringView> inline auto decompose(const StringView &lhs, const StringView &rhs)
{
    auto const lcs = longest_common_substring(lhs, rhs);

    // trim spaces, transform to lower
    const auto trim = [](StringView view) {
        // we compare suffixes based on this value, it might break UTF chars, but as long as we are
        // consistent in handling, we do not create bad results
        std::string str;
        str.reserve(view.size());
        std::transform(
            str.begin(), str.end(), str.begin(), [](unsigned char c) { return std::tolower(c); });
        auto front = str.find_first_not_of(' ');

        if (front == std::string::npos)
            return str;

        auto back = str.find_last_not_of(' ');
        return str.substr(front, back - front + 1);
    };

    if (lcs.empty())
    {
        return std::make_tuple(trim(lhs), trim(rhs), std::string(), std::string());
    }

    // find the common substring in both
    auto lhs_pos = lhs.find(lcs);
    auto rhs_pos = rhs.find(lcs);

    BOOST_ASSERT(lhs_pos + lcs.size() <= lhs.size());
    BOOST_ASSERT(rhs_pos + lcs.size() <= rhs.size());

    // prefixes
    auto lhs_prefix = (lhs_pos > 0) ? lhs.substr(0, lhs_pos) : StringView();
    auto rhs_prefix = (rhs_pos > 0) ? rhs.substr(0, rhs_pos) : StringView();

    // suffices
    auto lhs_suffix = lhs.substr(lhs_pos + lcs.size());
    auto rhs_suffix = rhs.substr(rhs_pos + lcs.size());

    return std::make_tuple(trim(lhs_prefix), trim(lhs_suffix), trim(rhs_prefix), trim(rhs_suffix));
}

// Note: there is an overload without suffix checking below.
// (that's the reason we template the suffix table here)
template <typename StringView, typename SuffixTable>
inline bool requiresNameAnnounced(const StringView &from_name,
                                  const StringView &from_ref,
                                  const StringView &from_pronunciation,
                                  const StringView &from_exits,
                                  const StringView &to_name,
                                  const StringView &to_ref,
                                  const StringView &to_pronunciation,
                                  const StringView &to_exits,
                                  const SuffixTable &suffix_table)
{
    // first is empty and the second is not
    if ((from_name.empty() && from_ref.empty()) && !(to_name.empty() && to_ref.empty()))
        return true;

    // FIXME, handle in profile to begin with?
    // Input for this function should be a struct separating streetname, suffix (e.g. road,
    // boulevard, North, West ...), and a list of references

    // check similarity of names
    const auto names_are_empty = from_name.empty() && to_name.empty();
    const auto name_is_contained =
        boost::starts_with(from_name, to_name) || boost::starts_with(to_name, from_name);

    const auto checkForPrefixOrSuffixChange = [](const std::string_view first,
                                                 const std::string_view second,
                                                 const SuffixTable &suffix_table) {
        std::string first_prefix, first_suffix, second_prefix, second_suffix;
        std::tie(first_prefix, first_suffix, second_prefix, second_suffix) =
            decompose(first, second);
        const auto checkTable = [&](const std::string &str) {
            return str.empty() || suffix_table.isSuffix(str);
        };

        return checkTable(first_prefix) && checkTable(first_suffix) && checkTable(second_prefix) &&
               checkTable(second_suffix);
    };

    const auto is_suffix_change = checkForPrefixOrSuffixChange(from_name, to_name, suffix_table);
    const auto names_are_equal = from_name == to_name || name_is_contained || is_suffix_change;
    const auto name_is_removed = !from_name.empty() && to_name.empty();
    // references are contained in one another
    const auto refs_are_empty = from_ref.empty() && to_ref.empty();
    const auto ref_is_contained =
        from_ref.empty() || to_ref.empty() ||
        (from_ref.find(to_ref) != std::string::npos || to_ref.find(from_ref) != std::string::npos);
    const auto ref_is_removed = !from_ref.empty() && to_ref.empty();

    const auto obvious_change =
        (names_are_empty && refs_are_empty) || (names_are_equal && ref_is_contained) ||
        (names_are_equal && refs_are_empty) || (ref_is_contained && name_is_removed) ||
        (names_are_equal && ref_is_removed) || is_suffix_change;

    const auto needs_announce =
        // " (Ref)" -> "Name " and reverse
        (from_name.empty() && !from_ref.empty() && !to_name.empty() && to_ref.empty()) ||
        (!from_name.empty() && from_ref.empty() && to_name.empty() && !to_ref.empty()) ||
        // ... or names are empty but reference changed
        (names_are_empty && !ref_is_contained);

    const auto pronunciation_changes = from_pronunciation != to_pronunciation;

    // when exiting onto ramps, we need to be careful about exit numbers. These can often be only
    // assigned to the first part of the ramp
    //
    //  a . . b . c . . d
    //         ` e . . f
    //
    // could assign the exit number to `be` when exiting `abcd` instead of the full ramp.
    //
    // Issuing a new-name instruction here would result in the turn assuming the short segment to be
    // irrelevant and remove the exit number in a collapse scenario. We don't want to issue any
    // instruction from be-ef, since we only loose the exit number. So we want to make sure that we
    // don't just loose an exit number, when exits change
    const auto exits_change = from_exits != to_exits;
    const auto looses_exit = (names_are_equal && !from_exits.empty() && to_exits.empty());

    return !obvious_change || needs_announce || pronunciation_changes ||
           (exits_change && !looses_exit);
}

// Overload without suffix checking
inline bool requiresNameAnnounced(const std::string &from_name,
                                  const std::string &from_ref,
                                  const std::string &from_pronunciation,
                                  const std::string &from_exits,
                                  const std::string &to_name,
                                  const std::string &to_ref,
                                  const std::string &to_pronunciation,
                                  const std::string &to_exits)
{
    // Dummy since we need to provide a SuffixTable but do not have the data for it.
    // (Guidance Post-Processing does not keep the suffix table around at the moment)
    struct NopSuffixTable final
    {
        NopSuffixTable() {}
        bool isSuffix(const std::string_view) const { return false; }
    } static const table;

    return requiresNameAnnounced(std::string_view(from_name),
                                 std::string_view(from_ref),
                                 std::string_view(from_pronunciation),
                                 std::string_view(from_exits),
                                 std::string_view(to_name),
                                 std::string_view(to_ref),
                                 std::string_view(to_pronunciation),
                                 std::string_view(to_exits),
                                 table);
}

inline bool requiresNameAnnounced(const NameID from_name_id,
                                  const NameID to_name_id,
                                  const extractor::NameTable &name_table,
                                  const extractor::SuffixTable &suffix_table)
{
    if (from_name_id == to_name_id)
        return false;
    else
        return requiresNameAnnounced(name_table.GetNameForID(from_name_id),
                                     name_table.GetRefForID(from_name_id),
                                     name_table.GetPronunciationForID(from_name_id),
                                     name_table.GetExitsForID(from_name_id),
                                     //
                                     name_table.GetNameForID(to_name_id),
                                     name_table.GetRefForID(to_name_id),
                                     name_table.GetPronunciationForID(to_name_id),
                                     name_table.GetExitsForID(to_name_id),
                                     //
                                     suffix_table);
}

} // namespace guidance
} // namespace util
} // namespace osrm

#endif /* OSRM_UTIL_GUIDANCE_NAME_ANNOUNCEMENT_HPP_ */
<commit_msg>Use std::back_inserter<commit_after>#ifndef OSRM_UTIL_GUIDANCE_NAME_ANNOUNCEMENT_HPP_
#define OSRM_UTIL_GUIDANCE_NAME_ANNOUNCEMENT_HPP_

/* A set of tools required for guidance in both pre and post-processing */

#include "extractor/name_table.hpp"
#include "extractor/suffix_table.hpp"

#include "util/attributes.hpp"
#include "util/typedefs.hpp"

#include <algorithm>
#include <string>
#include <tuple>
#include <utility>
#include <vector>

#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/predicate.hpp>

namespace osrm
{
namespace util
{
namespace guidance
{
// Name Change Logic
// Used both during Extraction as well as during Post-Processing

inline std::string_view longest_common_substring(const std::string_view lhs,
                                                 const std::string_view rhs)
{
    if (lhs.empty() || rhs.empty())
        return "";

    // array for dynamic programming
    std::vector<std::uint32_t> dp_previous(rhs.size(), 0), dp_current(rhs.size(), 0);

    // to remember the best location
    std::uint32_t best = 0;
    std::uint32_t best_pos = 0;
    using std::swap;
    for (std::uint32_t i = 0; i < lhs.size(); ++i)
    {
        for (std::uint32_t j = 0; j < rhs.size(); ++j)
        {
            if (lhs[i] == rhs[j])
            {
                dp_current[j] = (j == 0) ? 1 : (dp_previous[j - 1] + 1);
                if (dp_current[j] > best)
                {
                    best = dp_current[j];
                    best_pos = i + 1;
                }
            }
        }
        swap(dp_previous, dp_current);
    }
    // the best position marks the end of the string
    return lhs.substr(best_pos - best, best);
}

// TODO US-ASCII support only, no UTF-8 support
// While UTF-8 might work in some cases, we do not guarantee full functionality
template <typename StringView> inline auto decompose(const StringView &lhs, const StringView &rhs)
{
    auto const lcs = longest_common_substring(lhs, rhs);

    // trim spaces, transform to lower
    const auto trim = [](StringView view) {
        // we compare suffixes based on this value, it might break UTF chars, but as long as we are
        // consistent in handling, we do not create bad results
        std::string str;
        str.reserve(view.size());
        std::transform(
            view.begin(), view.end(), std::back_inserter(str), [](unsigned char c) { return std::tolower(c); });
        auto front = str.find_first_not_of(' ');

        if (front == std::string::npos)
            return str;

        auto back = str.find_last_not_of(' ');
        return str.substr(front, back - front + 1);
    };

    if (lcs.empty())
    {
        return std::make_tuple(trim(lhs), trim(rhs), std::string(), std::string());
    }

    // find the common substring in both
    auto lhs_pos = lhs.find(lcs);
    auto rhs_pos = rhs.find(lcs);

    BOOST_ASSERT(lhs_pos + lcs.size() <= lhs.size());
    BOOST_ASSERT(rhs_pos + lcs.size() <= rhs.size());

    // prefixes
    auto lhs_prefix = (lhs_pos > 0) ? lhs.substr(0, lhs_pos) : StringView();
    auto rhs_prefix = (rhs_pos > 0) ? rhs.substr(0, rhs_pos) : StringView();

    // suffices
    auto lhs_suffix = lhs.substr(lhs_pos + lcs.size());
    auto rhs_suffix = rhs.substr(rhs_pos + lcs.size());

    return std::make_tuple(trim(lhs_prefix), trim(lhs_suffix), trim(rhs_prefix), trim(rhs_suffix));
}

// Note: there is an overload without suffix checking below.
// (that's the reason we template the suffix table here)
template <typename StringView, typename SuffixTable>
inline bool requiresNameAnnounced(const StringView &from_name,
                                  const StringView &from_ref,
                                  const StringView &from_pronunciation,
                                  const StringView &from_exits,
                                  const StringView &to_name,
                                  const StringView &to_ref,
                                  const StringView &to_pronunciation,
                                  const StringView &to_exits,
                                  const SuffixTable &suffix_table)
{
    // first is empty and the second is not
    if ((from_name.empty() && from_ref.empty()) && !(to_name.empty() && to_ref.empty()))
        return true;

    // FIXME, handle in profile to begin with?
    // Input for this function should be a struct separating streetname, suffix (e.g. road,
    // boulevard, North, West ...), and a list of references

    // check similarity of names
    const auto names_are_empty = from_name.empty() && to_name.empty();
    const auto name_is_contained =
        boost::starts_with(from_name, to_name) || boost::starts_with(to_name, from_name);

    const auto checkForPrefixOrSuffixChange = [](const std::string_view first,
                                                 const std::string_view second,
                                                 const SuffixTable &suffix_table) {
        std::string first_prefix, first_suffix, second_prefix, second_suffix;
        std::tie(first_prefix, first_suffix, second_prefix, second_suffix) =
            decompose(first, second);
        const auto checkTable = [&](const std::string &str) {
            return str.empty() || suffix_table.isSuffix(str);
        };

        return checkTable(first_prefix) && checkTable(first_suffix) && checkTable(second_prefix) &&
               checkTable(second_suffix);
    };

    const auto is_suffix_change = checkForPrefixOrSuffixChange(from_name, to_name, suffix_table);
    const auto names_are_equal = from_name == to_name || name_is_contained || is_suffix_change;
    const auto name_is_removed = !from_name.empty() && to_name.empty();
    // references are contained in one another
    const auto refs_are_empty = from_ref.empty() && to_ref.empty();
    const auto ref_is_contained =
        from_ref.empty() || to_ref.empty() ||
        (from_ref.find(to_ref) != std::string::npos || to_ref.find(from_ref) != std::string::npos);
    const auto ref_is_removed = !from_ref.empty() && to_ref.empty();

    const auto obvious_change =
        (names_are_empty && refs_are_empty) || (names_are_equal && ref_is_contained) ||
        (names_are_equal && refs_are_empty) || (ref_is_contained && name_is_removed) ||
        (names_are_equal && ref_is_removed) || is_suffix_change;

    const auto needs_announce =
        // " (Ref)" -> "Name " and reverse
        (from_name.empty() && !from_ref.empty() && !to_name.empty() && to_ref.empty()) ||
        (!from_name.empty() && from_ref.empty() && to_name.empty() && !to_ref.empty()) ||
        // ... or names are empty but reference changed
        (names_are_empty && !ref_is_contained);

    const auto pronunciation_changes = from_pronunciation != to_pronunciation;

    // when exiting onto ramps, we need to be careful about exit numbers. These can often be only
    // assigned to the first part of the ramp
    //
    //  a . . b . c . . d
    //         ` e . . f
    //
    // could assign the exit number to `be` when exiting `abcd` instead of the full ramp.
    //
    // Issuing a new-name instruction here would result in the turn assuming the short segment to be
    // irrelevant and remove the exit number in a collapse scenario. We don't want to issue any
    // instruction from be-ef, since we only loose the exit number. So we want to make sure that we
    // don't just loose an exit number, when exits change
    const auto exits_change = from_exits != to_exits;
    const auto looses_exit = (names_are_equal && !from_exits.empty() && to_exits.empty());

    return !obvious_change || needs_announce || pronunciation_changes ||
           (exits_change && !looses_exit);
}

// Overload without suffix checking
inline bool requiresNameAnnounced(const std::string &from_name,
                                  const std::string &from_ref,
                                  const std::string &from_pronunciation,
                                  const std::string &from_exits,
                                  const std::string &to_name,
                                  const std::string &to_ref,
                                  const std::string &to_pronunciation,
                                  const std::string &to_exits)
{
    // Dummy since we need to provide a SuffixTable but do not have the data for it.
    // (Guidance Post-Processing does not keep the suffix table around at the moment)
    struct NopSuffixTable final
    {
        NopSuffixTable() {}
        bool isSuffix(const std::string_view) const { return false; }
    } static const table;

    return requiresNameAnnounced(std::string_view(from_name),
                                 std::string_view(from_ref),
                                 std::string_view(from_pronunciation),
                                 std::string_view(from_exits),
                                 std::string_view(to_name),
                                 std::string_view(to_ref),
                                 std::string_view(to_pronunciation),
                                 std::string_view(to_exits),
                                 table);
}

inline bool requiresNameAnnounced(const NameID from_name_id,
                                  const NameID to_name_id,
                                  const extractor::NameTable &name_table,
                                  const extractor::SuffixTable &suffix_table)
{
    if (from_name_id == to_name_id)
        return false;
    else
        return requiresNameAnnounced(name_table.GetNameForID(from_name_id),
                                     name_table.GetRefForID(from_name_id),
                                     name_table.GetPronunciationForID(from_name_id),
                                     name_table.GetExitsForID(from_name_id),
                                     //
                                     name_table.GetNameForID(to_name_id),
                                     name_table.GetRefForID(to_name_id),
                                     name_table.GetPronunciationForID(to_name_id),
                                     name_table.GetExitsForID(to_name_id),
                                     //
                                     suffix_table);
}

} // namespace guidance
} // namespace util
} // namespace osrm

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


<commit_before>//
// Created by yangyanjun on 2017/3/31.
//

#include "SceneParticles.h"

#include <cstdio>
#include <cstdlib>
#include <iostream>
using std::endl;
using std::cerr;

#include "bmpreader.h"

#include "glutils.h"

using glm::vec3;

#define GLM_ENABLE_EXPERIMENTAL
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp>

SceneParticles::SceneParticles() : width(800), height(600), time(0) {}

void SceneParticles::initScene()
{
    compileAndLinkShader();

    glClearColor(0.1f,0.1f,0.1f,1.0f);

//    glDisable(GL_DEPTH_TEST);

    // Enable blending
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    // Set the point size
    glPointSize(10.0f);

    plane = new VBOPlane(13.0f, 10.0f, 200, 2);
    projection = mat4(1.0f);

    angle = glm::half_pi<float>();

    // Generate our vertex buffers
    initBuffers();

    // The particle texture
    const char * texName = "media/texture/bluewater.bmp";
    glActiveTexture(GL_TEXTURE0);
    BMPReader::loadTex(texName);

    prog.setUniform("ParticleTex", 0);
    prog.setUniform("ParticleLifetime", 13.5f);
    prog.setUniform("Gravity", vec3(0.0f,-0.2f,0.0f));
}

void SceneParticles::initBuffers()
{
    nParticles = 8000;

    // Generate the buffers
    glGenBuffers(1, &initVel);   // Initial velocity buffer
    glGenBuffers(1, &startTime); // Start time buffer

    // Allocate space for all buffers
    int size = nParticles * 3 * sizeof(float);
    glBindBuffer(GL_ARRAY_BUFFER, initVel);
    glBufferData(GL_ARRAY_BUFFER, size, NULL, GL_STATIC_DRAW);
    glBindBuffer(GL_ARRAY_BUFFER, startTime);
    glBufferData(GL_ARRAY_BUFFER, nParticles * sizeof(float), NULL, GL_STATIC_DRAW);

    // Fill the first velocity buffer with random velocities
    vec3 v(0.0f);
    float velocity, theta, phi;
    GLfloat *data = new GLfloat[nParticles * 3];
    for (unsigned int i = 0; i < nParticles; i++ ) {

        theta = glm::mix(0.0f, glm::pi<float>() / 6.0f, randFloat());
        phi = glm::mix(0.0f, glm::two_pi<float>(), randFloat());

        v.x = sinf(theta) * cosf(phi);
        v.y = cosf(theta);
        v.z = sinf(theta) * sinf(phi);

        velocity = glm::mix(1.25f,1.5f,randFloat());
        v = glm::normalize(v) * velocity;

        data[3*i]   = v.x;
        data[3*i+1] = v.y;
        data[3*i+2] = v.z;
    }
    glBindBuffer(GL_ARRAY_BUFFER,initVel);
    glBufferSubData(GL_ARRAY_BUFFER, 0, size, data);

    // Fill the start time buffer
    delete [] data;
    data = new GLfloat[nParticles];
    float time = 0.0f;
    float rate = 0.00075f;
    for( unsigned int i = 0; i < nParticles; i++ ) {
        data[i] = time;
        time += rate;
    }
    glBindBuffer(GL_ARRAY_BUFFER,startTime);
    glBufferSubData(GL_ARRAY_BUFFER, 0, nParticles * sizeof(float), data);

    glBindBuffer(GL_ARRAY_BUFFER,0);
    delete [] data;

    // Attach these to the torus's vertex array
    glGenVertexArrays(1, &particles);
    glBindVertexArray(particles);
    glBindBuffer(GL_ARRAY_BUFFER, initVel);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL);
    glEnableVertexAttribArray(0);

    glBindBuffer(GL_ARRAY_BUFFER, startTime);
    glVertexAttribPointer(1, 1, GL_FLOAT, GL_FALSE, 0, NULL);
    glEnableVertexAttribArray(1);

    glBindVertexArray(0);

}

float SceneParticles::randFloat() {
    return ((float)rand() / RAND_MAX);
}

void SceneParticles::update( float t )
{
    time = t;
}

void SceneParticles::render()
{
    prog.setUniform("Time", time);
    glClear(GL_COLOR_BUFFER_BIT );
    view = glm::lookAt(vec3(3.0f * cos(angle),1.5f,3.0f * sin(angle)), vec3(0.0f,1.5f,0.0f), vec3(0.0f,1.0f,0.0f));
    model = mat4(1.0f);
    setMatrices();

    glBindVertexArray(particles);
    glDrawArrays(GL_POINTS,0,nParticles);
}

void SceneParticles::setMatrices()
{
    mat4 mv = view * model;
    prog.setUniform("MVP", projection * mv);
}

void SceneParticles::resize(int w, int h)
{
    glViewport(0,0,w,h);
    width = w;
    height = h;
    projection = glm::perspective(glm::radians(60.0f), (float)w/h, 0.3f, 100.0f);
}

void SceneParticles::compileAndLinkShader()
{
    try {
//        prog.compileShader("shader/particles.vert",GLSLShader::VERTEX);
//        prog.compileShader("shader/particles.frag",GLSLShader::FRAGMENT);
        prog.compileShader("shader/particles.vs",GLSLShader::VERTEX);
        prog.compileShader("shader/particles.fs",GLSLShader::FRAGMENT);

        prog.link();
        prog.use();
    } catch(GLSLProgramException &e ) {
        cerr << e.what() << endl;
        exit( EXIT_FAILURE );
    }
}

<commit_msg>chapter09 - bug  fix<commit_after>//
// Created by yangyanjun on 2017/3/31.
//

#include "SceneParticles.h"

#include <cstdio>
#include <cstdlib>
#include <iostream>
using std::endl;
using std::cerr;

#include "bmpreader.h"

#include "glutils.h"

using glm::vec3;

#define GLM_ENABLE_EXPERIMENTAL
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp>

SceneParticles::SceneParticles() : width(800), height(600), time(0) {}

void SceneParticles::initScene()
{
    compileAndLinkShader();

    glClearColor(0.1f,0.1f,0.1f,1.0f);

//    glDisable(GL_DEPTH_TEST);

    // Enable blending
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    // Set the point size
    glPointSize(10.0f);

    plane = new VBOPlane(13.0f, 10.0f, 200, 2);
    projection = mat4(1.0f);

    angle = glm::half_pi<float>();

    // Generate our vertex buffers
    initBuffers();

    // The particle texture
    const char * texName = "media/texture/bluewater.bmp";
    glActiveTexture(GL_TEXTURE0);
    BMPReader::loadTex(texName);

    prog.setUniform("ParticleTex", 0);
    prog.setUniform("ParticleLifetime", 13.5f);
    prog.setUniform("Gravity", vec3(0.0f,-0.2f,0.0f));
}

void SceneParticles::initBuffers()
{
    nParticles = 8000;

    // Generate the buffers
    glGenBuffers(1, &initVel);   // Initial velocity buffer
    glGenBuffers(1, &startTime); // Start time buffer

    // Allocate space for all buffers
    int size = nParticles * 3 * sizeof(float);
    glBindBuffer(GL_ARRAY_BUFFER, initVel);
    glBufferData(GL_ARRAY_BUFFER, size, NULL, GL_STATIC_DRAW);
    glBindBuffer(GL_ARRAY_BUFFER, startTime);
    glBufferData(GL_ARRAY_BUFFER, nParticles * sizeof(float), NULL, GL_STATIC_DRAW);

    // Fill the first velocity buffer with random velocities
    vec3 v(0.0f);
    float velocity, theta, phi;
    GLfloat *data = new GLfloat[nParticles * 3];
    for (unsigned int i = 0; i < nParticles; i++ ) {

        theta = glm::mix(0.0f, glm::pi<float>() / 6.0f, randFloat());
        phi = glm::mix(0.0f, glm::two_pi<float>(), randFloat());

        v.x = sinf(theta) * cosf(phi);
        v.y = cosf(theta);
        v.z = sinf(theta) * sinf(phi);

        velocity = glm::mix(1.25f,1.5f,randFloat());
        v = glm::normalize(v) * velocity;

        data[3*i]   = v.x;
        data[3*i+1] = v.y;
        data[3*i+2] = v.z;
    }
    glBindBuffer(GL_ARRAY_BUFFER,initVel);
    glBufferSubData(GL_ARRAY_BUFFER, 0, size, data);

    // Fill the start time buffer
    delete [] data;
    data = new GLfloat[nParticles];
    float time = 0.0f;
    float rate = 0.00075f;
    for( unsigned int i = 0; i < nParticles; i++ ) {
        data[i] = time;
        time += rate;
    }
    glBindBuffer(GL_ARRAY_BUFFER,startTime);
    glBufferSubData(GL_ARRAY_BUFFER, 0, nParticles * sizeof(float), data);

    glBindBuffer(GL_ARRAY_BUFFER,0);
    delete [] data;

    // Attach these to the torus's vertex array
    glGenVertexArrays(1, &particles);
    glBindVertexArray(particles);
    glBindBuffer(GL_ARRAY_BUFFER, initVel);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL);
    glEnableVertexAttribArray(0);

    glBindBuffer(GL_ARRAY_BUFFER, startTime);
    glVertexAttribPointer(1, 1, GL_FLOAT, GL_FALSE, 0, NULL);
    glEnableVertexAttribArray(1);

    glBindVertexArray(0);

}

float SceneParticles::randFloat() {
    return ((float)rand() / RAND_MAX);
}

void SceneParticles::update( float t )
{
    time = t;
}

void SceneParticles::render()
{
    prog.setUniform("Time", time);
    glClear(GL_COLOR_BUFFER_BIT );
    view = glm::lookAt(vec3(3.0f * cos(angle),1.5f,3.0f * sin(angle)), vec3(0.0f,1.5f,0.0f), vec3(0.0f,1.0f,0.0f));
    model = mat4(1.0f);
    setMatrices();

    glBindVertexArray(particles);
    glDrawArrays(GL_POINTS,0,nParticles);
}

void SceneParticles::setMatrices()
{
    mat4 mv = view * model;
    prog.setUniform("MVP", projection * mv);
}

void SceneParticles::resize(int w, int h)
{
    glViewport(0,0,w,h);
    width = w;
    height = h;
    projection = glm::perspective(glm::radians(60.0f), (float)w/h, 0.3f, 100.0f);
}

void SceneParticles::compileAndLinkShader()
{
    try {
        prog.compileShader("shader/particles.vert",GLSLShader::VERTEX);
        prog.compileShader("shader/particles.frag",GLSLShader::FRAGMENT);
//        prog.compileShader("shader/particles.vs",GLSLShader::VERTEX);
//        prog.compileShader("shader/particles.fs",GLSLShader::FRAGMENT);

        prog.link();
        prog.use();
    } catch(GLSLProgramException &e ) {
        cerr << e.what() << endl;
        exit( EXIT_FAILURE );
    }
}

<|endoftext|>