<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

//$Id: color.hpp 39 2005-04-10 20:39:53Z pavlenko $

#ifndef COLOR_HPP
#define COLOR_HPP

#include <boost/format.hpp>
#include "config.hpp"
#include <sstream>

namespace mapnik {

    class MAPNIK_DECL Color
    {
    private:
        unsigned int rgba_;
    public:
        Color()
            :rgba_(0xffffffff) {}

        Color(int red,int green,int blue,int alpha=0xff)
            : rgba_((alpha&0xff) << 24 | (blue&0xff) << 16 | (green&0xff) << 8 | red&0xff) {}

        explicit Color(int rgba)
            : rgba_(rgba) {}

        Color(const Color& rhs)
            : rgba_(rhs.rgba_) {}

        Color& operator=(const Color& rhs)
        {
            if (this==&rhs) return *this;
            rgba_=rhs.rgba_;
            return *this;
        }
        inline unsigned int blue() const
        {
            return (rgba_>>16)&0xff;
        }
        inline unsigned int green() const
        {
            return (rgba_>>8)&0xff;
        }
        inline unsigned int red() const
        {
            return rgba_&0xff;
        }

        inline void set_red(unsigned int r)
        {
            rgba_ = (rgba_ & 0xffffff00) | (r&0xff);
        }

        inline void set_green(unsigned int g)
        {
            rgba_ = (rgba_ & 0xffff00ff) | ((g&0xff) << 8);
        }

        inline void set_blue(unsigned int b)
        {
            rgba_ = (rgba_ & 0xff00ffff) | ((b&0xff) << 16);
        }

        inline unsigned int alpha() const
        {
            return (rgba_>>24)&0xff;
        }

        inline unsigned int rgba() const
        {
            return rgba_;
        }
        inline void set_bgr(unsigned bgr)
        {
            rgba_ = (rgba_ & 0xff000000) | (bgr & 0xffffff);
        }
        inline bool operator==(Color const& other) const
        {
            return rgba_ == other.rgba_;
        }

        inline std::string to_string() const
        {
            std::stringstream ss;
            ss << "rgb (" << red() << ","  << green() << ","  << blue() <<")";
            return ss.str();
        }
        inline std::string to_hex_string() const
        {
            std::stringstream ss;
            ss << boost::format("#%1$02x%2$02x%3$02x") % red() % green() % blue();
            return ss.str();
        }
    };
}

#endif //COLOR_HPP
<commit_msg>This patch: * Adds set_alpha() * Reorders the get/set color functions to be red() green() blue() alpha() (code tidyness) * Changes the internal color variable to be named abgr_ instead of rgba_ since that is the order the colors are stored in it.<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

//$Id: color.hpp 39 2005-04-10 20:39:53Z pavlenko $

#ifndef COLOR_HPP
#define COLOR_HPP

#include <boost/format.hpp>
#include "config.hpp"
#include <sstream>

namespace mapnik {

    class MAPNIK_DECL Color
    {
    private:
        unsigned int abgr_;
    public:
        Color()
            :abgr_(0xffffffff) {}

        Color(int red,int green,int blue,int alpha=0xff)
            : abgr_((alpha&0xff) << 24 | (blue&0xff) << 16 | (green&0xff) << 8 | red&0xff) {}

        explicit Color(int rgba)
            : abgr_(rgba) {}

        Color(const Color& rhs)
            : abgr_(rhs.abgr_) {}

        Color& operator=(const Color& rhs)
        {
            if (this==&rhs) return *this;
            abgr_=rhs.abgr_;
            return *this;
        }
        inline unsigned int red() const
        {
            return abgr_&0xff;
        }
        inline unsigned int green() const
        {
            return (abgr_>>8)&0xff;
        }
        inline unsigned int blue() const
        {
            return (abgr_>>16)&0xff;
        }
        inline unsigned int alpha() const
        {
            return (abgr_>>24)&0xff;
        }

        inline void set_red(unsigned int r)
        {
            abgr_ = (abgr_ & 0xffffff00) | (r&0xff);
        }
        inline void set_green(unsigned int g)
        {
            abgr_ = (abgr_ & 0xffff00ff) | ((g&0xff) << 8);
        }
        inline void set_blue(unsigned int b)
        {
            abgr_ = (abgr_ & 0xff00ffff) | ((b&0xff) << 16);
        }
        inline void set_alpha(unsigned int a)
        {
            abgr_ = (abgr_ & 0x00ffffff | (a&0xff) << 24);
        }

        inline unsigned int rgba() const
        {
            return abgr_;
        }
        inline void set_bgr(unsigned bgr)
        {
            abgr_ = (abgr_ & 0xff000000) | (bgr & 0xffffff);
        }
        inline bool operator==(Color const& other) const
        {
            return abgr_ == other.abgr_;
        }

        inline std::string to_string() const
        {
            std::stringstream ss;
            ss << "rgb (" << red() << ","  << green() << ","  << blue() <<")";
            return ss.str();
        }
        inline std::string to_hex_string() const
        {
            std::stringstream ss;
            ss << boost::format("#%1$02x%2$02x%3$02x") % red() % green() % blue();
            return ss.str();
        }
    };
}

#endif //COLOR_HPP
<|endoftext|>


<commit_before>/* created by Ghabriel Nunes <ghabriel.nunes@gmail.com> [2017] */
#ifndef UTILS_DEBUG_HPP
#define UTILS_DEBUG_HPP

#include <csignal>
#include <iostream>
#include <unordered_map>

namespace {
    #define ALLOW_DEBUG_USAGE 1
    constexpr bool DEBUG_ENABLED = true;
    // constexpr bool ALLOW_DEBUG_USAGE = true;

    std::pair<size_t, std::string> debugBuffer;
    const std::unordered_map<int, std::string> debugLabels = {
        {SIGABRT, "Aborted"},
        {SIGFPE, "Division by zero"},
        {SIGILL, "SIGILL"},
        {SIGINT, "Interruption"},
        {SIGSEGV, "Segmentation fault"},
        {SIGTERM, "SIGTERM"}
    };

    inline void printer() {}
    inline void printer(int type) {
        auto line = std::to_string(debugBuffer.first);
        auto& filename = debugBuffer.second;
        std::cout << debugLabels.at(type) << " in " << filename
                  << ":" << line << std::endl;
        std::signal(type, SIG_DFL);
        std::raise(type);
    }

    template<bool = DEBUG_ENABLED>
    struct DebugContainer;

    template<>
    struct DebugContainer<true> {
        static void echo() {}

        template<typename T, typename... Args>
        static void echo(const T& value, Args&&... args) {
            std::cout << value << std::endl;
            echo(args...);
        }

        template<typename T>
        static void echoIndented(const T& value, size_t numTabs) {
            for (size_t i = 0; i < numTabs; i++) {
                std::cout << "\t";
            }
            echo(value);
        }

        template<typename T>
        static void trace(const std::string& name, const T& value) {
            std::cout << name << " = ";
            echo(value);
        }

        template<typename T>
        static void traceIterable(const std::string& name, const T& value) {
            unsigned long long counter = 0;
            for (auto& elem : value) {
                std::cout << name << "[" << std::to_string(counter++) << "] = ";
                echo(elem);
            }
        }

        static void debug(size_t line, const std::string& filename) {
            debugBuffer = {line, filename};
            static bool ready = false;
            if (!ready) {
                std::atexit(printer);
                for (auto& pair : debugLabels) {
                    std::signal(pair.first, printer);
                }
                ready = true;
            }
        }
    };

    template<>
    struct DebugContainer<false> {
        template<typename... Args>
        static void echo(Args&&...) {}

        template<typename T>
        static void echoIndented(const T&, size_t) {}

        template<typename T>
        static void trace(const std::string&, const T&) {}

        template<typename T>
        static void traceIterable(const std::string&, const T&) {}

        static void debug(size_t, const std::string&) {}
    };

    inline void echo() {}

    template<typename... Args>
    inline void echo(Args&&... args) {
        DebugContainer<>::echo(args...);
    }

    template<typename T>
    inline void echoIndented(const T& value, size_t numTabs) {
        DebugContainer<>::echoIndented(value, numTabs);
    }

    template<typename T>
    inline void trace(const std::string& name, const T& value) {
        DebugContainer<>::trace(name, value);
    }

    template<typename T>
    inline void traceIterable(const std::string& name, const T& value) {
        DebugContainer<>::traceIterable(name, value);
    }

    inline void debug(size_t line, const std::string& filename) {
        DebugContainer<>::debug(line, filename);
    }
}

#if ALLOW_DEBUG_USAGE == 1

#define ECHO(...) echo(__VA_ARGS__)
#define ECHOI(x,numTabs) echoIndented((x),(numTabs))
#define TRACE(x) trace((#x), (x));
#define TRACE_L(x,y) trace((x), (y))
#define TRACE_IT(x) traceIterable((#x), (x))
#define TRACE_ITL(x) traceIterable((l), (x))
#define BLANK ECHO("");
#define DEBUG debug(__LINE__, __FILE__);

#else

#define TRACE(x) {int debug_usage;}
#define TRACE_L(x,y) {int debug_usage;}
#define TRACE_IT(x) {int debug_usage;}
#define ECHO(...) {int debug_usage;}
#define ECHOI(x,n) {int debug_usage;}
#define BLANK {int debug_usage;}
#define DEBUG {int debug_usage;}

#endif

#endif
<commit_msg>Removed the empty version of printer<commit_after>/* created by Ghabriel Nunes <ghabriel.nunes@gmail.com> [2017] */
#ifndef UTILS_DEBUG_HPP
#define UTILS_DEBUG_HPP

#include <csignal>
#include <iostream>
#include <unordered_map>

namespace {
    #define ALLOW_DEBUG_USAGE 1
    constexpr bool DEBUG_ENABLED = true;
    // constexpr bool ALLOW_DEBUG_USAGE = true;

    std::pair<size_t, std::string> debugBuffer;
    const std::unordered_map<int, std::string> debugLabels = {
        {SIGABRT, "Aborted"},
        {SIGFPE, "Division by zero"},
        {SIGILL, "SIGILL"},
        {SIGINT, "Interruption"},
        {SIGSEGV, "Segmentation fault"},
        {SIGTERM, "SIGTERM"}
    };

    inline void printer(int type) {
        auto line = std::to_string(debugBuffer.first);
        auto& filename = debugBuffer.second;
        std::cout << debugLabels.at(type) << " in " << filename
                  << ":" << line << std::endl;
        std::signal(type, SIG_DFL);
        std::raise(type);
    }

    template<bool = DEBUG_ENABLED>
    struct DebugContainer;

    template<>
    struct DebugContainer<true> {
        static void echo() {}

        template<typename T, typename... Args>
        static void echo(const T& value, Args&&... args) {
            std::cout << value << std::endl;
            echo(args...);
        }

        template<typename T>
        static void echoIndented(const T& value, size_t numTabs) {
            for (size_t i = 0; i < numTabs; i++) {
                std::cout << "\t";
            }
            echo(value);
        }

        template<typename T>
        static void trace(const std::string& name, const T& value) {
            std::cout << name << " = ";
            echo(value);
        }

        template<typename T>
        static void traceIterable(const std::string& name, const T& value) {
            unsigned long long counter = 0;
            for (auto& elem : value) {
                std::cout << name << "[" << std::to_string(counter++) << "] = ";
                echo(elem);
            }
        }

        static void debug(size_t line, const std::string& filename) {
            debugBuffer = {line, filename};
            static bool ready = false;
            if (!ready) {
                for (auto& pair : debugLabels) {
                    std::signal(pair.first, printer);
                }
                ready = true;
            }
        }
    };

    template<>
    struct DebugContainer<false> {
        template<typename... Args>
        static void echo(Args&&...) {}

        template<typename T>
        static void echoIndented(const T&, size_t) {}

        template<typename T>
        static void trace(const std::string&, const T&) {}

        template<typename T>
        static void traceIterable(const std::string&, const T&) {}

        static void debug(size_t, const std::string&) {}
    };

    inline void echo() {}

    template<typename... Args>
    inline void echo(Args&&... args) {
        DebugContainer<>::echo(args...);
    }

    template<typename T>
    inline void echoIndented(const T& value, size_t numTabs) {
        DebugContainer<>::echoIndented(value, numTabs);
    }

    template<typename T>
    inline void trace(const std::string& name, const T& value) {
        DebugContainer<>::trace(name, value);
    }

    template<typename T>
    inline void traceIterable(const std::string& name, const T& value) {
        DebugContainer<>::traceIterable(name, value);
    }

    inline void debug(size_t line, const std::string& filename) {
        DebugContainer<>::debug(line, filename);
    }
}

#if ALLOW_DEBUG_USAGE == 1

#define ECHO(...) echo(__VA_ARGS__)
#define ECHOI(x,numTabs) echoIndented((x),(numTabs))
#define TRACE(x) trace((#x), (x));
#define TRACE_L(x,y) trace((x), (y))
#define TRACE_IT(x) traceIterable((#x), (x))
#define TRACE_ITL(x) traceIterable((l), (x))
#define BLANK ECHO("");
#define DEBUG debug(__LINE__, __FILE__);

#else

#define TRACE(x) {int debug_usage;}
#define TRACE_L(x,y) {int debug_usage;}
#define TRACE_IT(x) {int debug_usage;}
#define ECHO(...) {int debug_usage;}
#define ECHOI(x,n) {int debug_usage;}
#define BLANK {int debug_usage;}
#define DEBUG {int debug_usage;}

#endif

#endif
<|endoftext|>


<commit_before>///
/// @file  imath.hpp
/// @brief Integer math functions used in primesum.
///
/// Copyright (C) 2018 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#ifndef IMATH_HPP
#define IMATH_HPP

#include <isqrt.hpp>

#include <stdint.h>
#include <algorithm>
#include <cassert>
#include <climits>
#include <cmath>
#include <vector>

namespace primesum {

inline int64_t isquare(int64_t x)
{
  return x * x;
}

template <typename A, typename B>
inline A ceil_div(A a, B b)
{
  assert(b > 0);
  return (A) ((a + b - 1) / b);
}

template <typename T>
inline T number_of_bits(T)
{
  static_assert(sizeof(uint64_t) * CHAR_BIT == 64, "number_of_bits() is broken");
  return (T) (sizeof(T) * CHAR_BIT);
}

template <typename T>
inline T next_power_of_2(T x)
{
  if (x == 0)
    return 1;

  x--;
  for (T i = 1; i < number_of_bits(x); i += i)
    x |= (x >> i);

  return ++x;
}

template <typename T>
inline T prev_power_of_2(T x)
{
  for (T i = 1; i < number_of_bits(x); i += i)
    x |= (x >> i);

  return x - (x >> 1);
}

template <typename T>
inline int ilog(T x)
{
  return (int) std::log((double) x);
}

/// Raise to power
template <typename T>
inline T ipow(T x, int n)
{
  T r = 1;
  for (int i = 0; i < n; i++)
    r *= x;

  return r;
}

/// Integer nth root
template <int N, typename T>
inline T iroot(T x)
{
  if (N == 0)
    return 0;

  T r = (T) std::pow((double) x, 1.0 / N);

  // fix root too large
  for (; r > 0 && ipow(r, N - 1) > x / r; r--);

  // fix root too small
  for (; ipow(r + 1, N - 1) <= x / (r + 1); r++);

  return r;
}

/// Count the number of primes <= x using binary search.
/// @pre primes[1] = 2, primes[3] = 3, ...
/// @pre x <= primes.back()
///
template <typename T1, typename T2>
inline T2 pi_bsearch(const std::vector<T1>& primes, T2 x)
{
  assert(primes[0] == 0);
  return (T2) (std::upper_bound(primes.begin() + 1, primes.end(), x) - (primes.begin() + 1));
}

template <typename T1, typename T2, typename T3>
inline T2 in_between(T1 min, T2 x, T3 max)
{
  if (x < min)
    return (T2) min;
  if (x > max)
    return (T2) max;

  return x;
}

} // namespace

#endif
<commit_msg>Improve number_of_bits()<commit_after>///
/// @file  imath.hpp
/// @brief Integer math functions used in primesum.
///
/// Copyright (C) 2018 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#ifndef IMATH_HPP
#define IMATH_HPP

#include <isqrt.hpp>

#include <stdint.h>
#include <algorithm>
#include <cassert>
#include <cmath>
#include <limits>
#include <vector>

namespace primesum {

inline int64_t isquare(int64_t x)
{
  return x * x;
}

template <typename A, typename B>
inline A ceil_div(A a, B b)
{
  assert(b > 0);
  return (A) ((a + b - 1) / b);
}

template <typename T>
inline T number_of_bits(T)
{
  return (T) std::numeric_limits<T>::digits;
}

template <typename T>
inline T next_power_of_2(T x)
{
  if (x == 0)
    return 1;

  x--;
  for (T i = 1; i < number_of_bits(x); i += i)
    x |= (x >> i);

  return ++x;
}

template <typename T>
inline T prev_power_of_2(T x)
{
  for (T i = 1; i < number_of_bits(x); i += i)
    x |= (x >> i);

  return x - (x >> 1);
}

template <typename T>
inline int ilog(T x)
{
  return (int) std::log((double) x);
}

/// Raise to power
template <typename T>
inline T ipow(T x, int n)
{
  T r = 1;
  for (int i = 0; i < n; i++)
    r *= x;

  return r;
}

/// Integer nth root
template <int N, typename T>
inline T iroot(T x)
{
  if (N == 0)
    return 0;

  T r = (T) std::pow((double) x, 1.0 / N);

  // fix root too large
  for (; r > 0 && ipow(r, N - 1) > x / r; r--);

  // fix root too small
  for (; ipow(r + 1, N - 1) <= x / (r + 1); r++);

  return r;
}

/// Count the number of primes <= x using binary search.
/// @pre primes[1] = 2, primes[3] = 3, ...
/// @pre x <= primes.back()
///
template <typename T1, typename T2>
inline T2 pi_bsearch(const std::vector<T1>& primes, T2 x)
{
  assert(primes[0] == 0);
  return (T2) (std::upper_bound(primes.begin() + 1, primes.end(), x) - (primes.begin() + 1));
}

template <typename T1, typename T2, typename T3>
inline T2 in_between(T1 min, T2 x, T3 max)
{
  if (x < min)
    return (T2) min;
  if (x > max)
    return (T2) max;

  return x;
}

} // namespace

#endif
<|endoftext|>


<commit_before>// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "EC_WaterPlane.h"
#include "EC_Placeable.h"
#include "IAttribute.h"

#include "Renderer.h"
#include "SceneManager.h"
#include "SceneEvents.h"
#include "EventManager.h"
#include <OgreMaterialUtils.h>
#include "LoggingFunctions.h"
DEFINE_POCO_LOGGING_FUNCTIONS("EC_WaterPlane")

#include <Ogre.h>
#include <OgreQuaternion.h>
#include <OgreColourValue.h>
#include <OgreMath.h>
// NaN - check
#include <RexNetworkUtils.h>

#include "MemoryLeakCheck.h"

namespace Environment
{

    EC_WaterPlane::EC_WaterPlane(IModule *module)
        : IComponent(module->GetFramework()),
        xSizeAttr(this, "x-size", 5000),
        ySizeAttr(this, "y-size", 5000),
        depthAttr(this, "Depth", 20),
        positionAttr(this, "Position", Vector3df()),
        rotationAttr(this, "Rotation", Quaternion()),
        scaleUfactorAttr(this, "U factor", 0.0002f),
        scaleVfactorAttr(this, "V factor", 0.0002f),
        xSegmentsAttr(this, "Segments in x", 10),
        ySegmentsAttr(this, "Segments in y", 10),
        materialNameAttr(this, "Material", QString("Ocean")),
       //textureNameAttr(this, "Texture", QString("DefaultOceanSkyCube.dds")),
        fogColorAttr(this, "Fog color", Color(0.2f,0.4f,0.35f,1.0f)),
        fogStartAttr(this, "Fog start dist.", 100.f),
        fogEndAttr(this, "Fog end dist.", 2000.f),
        fogModeAttr(this, "Fog mode", 3),
        entity_(0),
        node_(0),
        attached_(false),
        attachedToRoot_(false)
    {
        static AttributeMetadata metadata;
        static bool metadataInitialized = false;

        if(!metadataInitialized)
        {
            metadata.enums[Ogre::FOG_NONE] = "NoFog";
            metadata.enums[Ogre::FOG_EXP] = "Exponential";
            metadata.enums[Ogre::FOG_EXP2] = "ExponentiallySquare";
            metadata.enums[Ogre::FOG_LINEAR] = "Linear";

            metadataInitialized = true;
        }

        fogModeAttr.SetMetadata(&metadata);

        renderer_ = framework_->GetServiceManager()->GetService<OgreRenderer::Renderer>();
        if(!renderer_.expired())
        {
            Ogre::SceneManager* scene_mgr = renderer_.lock()->GetSceneManager();
            node_ = scene_mgr->createSceneNode();
        }

        QObject::connect(this, SIGNAL(OnAttributeChanged(IAttribute*, AttributeChange::Type)),
            SLOT(AttributeUpdated(IAttribute*, AttributeChange::Type)));

        lastXsize_ = xSizeAttr.Get();
        lastYsize_ = ySizeAttr.Get();

        CreateWaterPlane();
        QObject::connect(this, SIGNAL(ParentEntitySet()), this, SLOT(SetParent()));

        // If there exist placeable copy its position for default position and rotation.

        /*
        EC_Placeable* placeable = dynamic_cast<EC_Placeable*>(FindPlaceable().get());
        if ( placeable != 0)
        {
            Vector3df vec = placeable->GetPosition();
            positionAttr.Set(vec,AttributeChange::Default);

            Quaternion rot =placeable->GetOrientation();
            rotationAttr.Set(rot, AttributeChange::Default);
            ComponentChanged(AttributeChange::Default);
        }
        */
    }

    EC_WaterPlane::~EC_WaterPlane()
    {
       if (renderer_.expired())
        return;

       OgreRenderer::RendererPtr renderer = renderer_.lock();
       RemoveWaterPlane();

        if (node_ != 0)
        {
            Ogre::SceneManager* scene_mgr = renderer->GetSceneManager();
            scene_mgr->destroySceneNode(node_);
            node_ = 0;
        }
    }

    void EC_WaterPlane::SetParent()
    {
        // Parent entity has set.

        // Has parent a placeable?

        EC_Placeable* placeable = dynamic_cast<EC_Placeable*>(FindPlaceable().get());

        if ( placeable != 0)
        {
            // Are we currently attached?
            if ( attached_ )
            {
                // Now there might be that we are attached to OgreRoot not to placeable node.
                DetachEntity();
                AttachEntity();
            }

        }

        QObject::connect(parent_entity_,SIGNAL(ComponentAdded(IComponent*, AttributeChange::Type)), this, SLOT(ComponentAdded(IComponent*, AttributeChange::Type)));
        QObject::connect(parent_entity_,SIGNAL(ComponentRemoved(IComponent*, AttributeChange::Type)), this, SLOT(ComponentRemoved(IComponent*, AttributeChange::Type)));

    }

    void EC_WaterPlane::ComponentAdded(IComponent* component, AttributeChange::Type type)
    {
        if ( component->TypeName() == EC_Placeable::TypeNameStatic() )
        {
            DetachEntity();

            EC_Placeable* placeable = static_cast<EC_Placeable* >(component);
            if ( placeable == 0)
                return;

            if ( entity_ == 0)
                return;

            Ogre::SceneNode* node = placeable->GetSceneNode();

            node->addChild(node_);
            node_->attachObject(entity_);
            node_->setVisible(true);

            attached_ = true;

        }
    }

    void EC_WaterPlane::ComponentRemoved(IComponent* component, AttributeChange::Type type)
    {
        if ( component->TypeName() == EC_Placeable::TypeNameStatic() )
        {
            DetachEntity();

            // Attacht entity directly to Ogre root.

            Ogre::SceneManager* scene_mgr = renderer_.lock()->GetSceneManager();
            if ( scene_mgr == 0)
                return;

            node_->attachObject(entity_);
            scene_mgr->getRootSceneNode()->addChild(node_);
            node_->setVisible(true);
            attachedToRoot_ = true;
            attached_ = true;

        }
    }

    bool EC_WaterPlane::IsUnderWater()
    {
      // Check that is camera inside of defined waterplane.
      ///todo this cannot be done this way, mesh orientation etc. must take care. Now we just assume that plane does not have orientation.

      if ( entity_ == 0)
        return false;

      Ogre::Camera *camera = renderer_.lock()->GetCurrentCamera();
      Ogre::Vector3 posCamera = camera->getDerivedPosition();

      Ogre::Vector3 pos;

      if (node_ != 0)
          pos = node_->_getDerivedPosition();
      else
          return false;

      int xSize = xSizeAttr.Get(), ySize = ySizeAttr.Get(), depth = depthAttr.Get();
      int x = posCamera.x, y = posCamera.y, z = posCamera.z;

      // HACK this is strange, i thought that it should be 0.5 but some reason, visually it looks like that you can travel really "outside" from water.
      int tmpMax = pos.x + 0.25*xSize;
      int tmpMin = pos.x - 0.25*xSize;

      if ( x >= tmpMin && x <= tmpMax )
        {
            tmpMax = pos.y + 0.25*ySize;
            tmpMin = pos.y - 0.25*ySize;

            if ( y >= tmpMin && y <= tmpMax)
            {
                tmpMax = pos.z;
                tmpMin = pos.z - depth;

                if ( z >= tmpMin && z <= tmpMax)
                {
                    return true;
                }
                else
                    return false;
            }
            else
                return false;
         }

         return false;
    }

    void EC_WaterPlane::CreateWaterPlane()
    {
        // Create waterplane

        if (renderer_.lock() != 0)
        {
            Ogre::SceneManager *sceneMgr = renderer_.lock()->GetSceneManager();
            assert(sceneMgr);

            if (node_ != 0)
            {

                int xSize = xSizeAttr.Get();
                int ySize = ySizeAttr.Get();
                float uTile =  scaleUfactorAttr.Get() * xSize; /// Default x-size 5000 --> uTile 1.0
                float vTile =  scaleVfactorAttr.Get() * ySize;

                Ogre::MeshPtr mesh = Ogre::MeshManager::getSingleton().createPlane(name_.toStdString().c_str(), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
                    Ogre::Plane(Ogre::Vector3::UNIT_Z, 0),xSize, ySize, xSegmentsAttr.Get(), ySegmentsAttr.Get(), true, 1, uTile, vTile, Ogre::Vector3::UNIT_X);

                entity_ = sceneMgr->createEntity(renderer_.lock()->GetUniqueObjectName(), name_.toStdString().c_str());
                entity_->setMaterialName(materialNameAttr.Get().toStdString().c_str());
                entity_->setCastShadows(false);
                // Tries to attach entity, if there is not EC_Placeable availible, it will not attach object
                AttachEntity();

            }
        }

    }

    void EC_WaterPlane::RemoveWaterPlane()
    {
        // Remove waterplane

        if (renderer_.expired() || !entity_)
            return;

        OgreRenderer::RendererPtr renderer = renderer_.lock();

        DetachEntity();

        Ogre::SceneManager* scene_mgr = renderer->GetSceneManager();
        scene_mgr->destroyEntity(entity_);
        entity_ = 0;

        Ogre::MeshManager::getSingleton().remove(name_.toStdString().c_str());

    }

    Ogre::ColourValue EC_WaterPlane::GetFogColorAsOgreValue() const
    {
        Color col = fogColorAttr.Get();
        return Ogre::ColourValue(col.r, col.g, col.b, col.a);

    }

    void EC_WaterPlane::AttributeUpdated(IAttribute* attribute, AttributeChange::Type change)
    {
        ChangeWaterPlane(attribute);
    }

    void EC_WaterPlane::SetPosition()
    {

        Vector3df vec = positionAttr.Get();

        //node_->setPosition(vec.x, vec.y, vec.z);

#if OGRE_VERSION_MINOR <= 6 && OGRE_VERSION_MAJOR <= 1
        //Ogre::Vector3 current_pos = node_->_getDerivedPosition();
        Ogre::Vector3 tmp(vec.x,vec.y,vec.z);

        if ( !RexTypes::IsValidPositionVector(tmp) )
            return;

        node_->setPosition(tmp);
#else
        Ogre::Vector3 pos(vec.x, vec.y, vec.z);
        if ( !RexTypes::IsValidPositionVector(vec) )
            return;

        //node_->_setDerivedPosition(pos);
        node_->setPosition(pos);
#endif

    }

    void EC_WaterPlane::SetOrientation()
    {

         // Set orientation
        Quaternion rot = rotationAttr.Get();

#if OGRE_VERSION_MINOR <= 6 && OGRE_VERSION_MAJOR <= 1
        Ogre::Quaternion current_rot = node_->_getDerivedOrientation();
        Ogre::Quaternion tmp(rot.w, rot.x, rot.y, rot.z);
        Ogre::Quaternion rota = current_rot +  tmp;
        node_->setOrientation(rota);

#else
        node_->_setDerivedOrientation(Ogre::Quaternion(rot.w, rot.x, rot.y, rot.z));
#endif
    }

    void EC_WaterPlane::ChangeWaterPlane(IAttribute* attribute)
    {
        std::string name = attribute->GetNameString();
        if ( ( name == xSizeAttr.GetNameString()
          || name == ySizeAttr.GetNameString()
          || name == scaleUfactorAttr.GetNameString()
          || name == scaleVfactorAttr.GetNameString() ) &&
          ( lastXsize_ != xSizeAttr.Get() || lastYsize_ != ySizeAttr.Get() ) )
        {
            RemoveWaterPlane();
            CreateWaterPlane();

            lastXsize_ = xSizeAttr.Get();
            lastYsize_ = ySizeAttr.Get();

        }
        else if ( name == xSegmentsAttr.GetNameString() || name == ySegmentsAttr.GetNameString() )
        {
            RemoveWaterPlane();
            CreateWaterPlane();
        }
        else if ( name == positionAttr.GetNameString() )
        {
            // Change position
            SetPosition();

        }
        else if ( name == rotationAttr.GetNameString() )
        {
            // Change rotation

            // Is there placeable component? If not use given rotation
            //if ( dynamic_cast<EC_Placeable*>(FindPlaceable().get()) == 0 )
            //{
               SetOrientation();
            //}

        }
        else if ( name == depthAttr.GetNameString() )
        {
            // Change depth
            // Currently do nothing..

        }
        else if ( name ==  materialNameAttr.GetNameString())
        {
            //Change material
            if ( entity_ != 0)
            {
                entity_->setMaterialName(materialNameAttr.Get().toStdString().c_str());
            }
        }
        /*
        // Currently commented out, working feature but not enabled yet.
        else if (name == textureNameAttr.GetNameString() )
        {

            QString currentMaterial = materialNameAttr.Get();

            // Check that has texture really changed.

            StringVector names;
            Ogre::MaterialPtr materialPtr = Ogre::MaterialManager::getSingleton().getByName(currentMaterial.toStdString().c_str());

            if ( materialPtr.get() == 0)
                return;

            OgreRenderer::GetTextureNamesFromMaterial(materialPtr, names);

            QString textureName = textureNameAttr.Get();

            for (StringVector::iterator iter = names.begin(); iter != names.end(); ++iter)
            {
                QString currentTextureName(iter->c_str());
                if ( currentTextureName == textureName)
                    return;
            }

            // So texture has really changed, let's change it.
            OgreRenderer::SetTextureUnitOnMaterial(materialPtr, textureName.toStdString(), 0);

        }
        */

    }

    ComponentPtr EC_WaterPlane::FindPlaceable() const
    {
        assert(framework_);
        ComponentPtr comp;
        if(!GetParentEntity())
            return comp;
        comp = GetParentEntity()->GetComponent<EC_Placeable>();
        return comp;

    }

    void EC_WaterPlane::AttachEntity()
    {
        if ( attached_ || entity_ == 0)
            return;

        EC_Placeable* placeable = dynamic_cast<EC_Placeable* >(FindPlaceable().get());

        // If there exist placeable attach node and entity to it
        if ( placeable != 0 )
        {
            Ogre::SceneNode* node = placeable->GetSceneNode();
            node->addChild(node_);
            node_->attachObject(entity_);
            node_->setVisible(true);
        }
        else
        {
            // There is no placeable attacht entity to OgreSceneRoot
            Ogre::SceneManager* scene_mgr = renderer_.lock()->GetSceneManager();
            node_->attachObject(entity_);
            scene_mgr->getRootSceneNode()->addChild(node_);
            node_->setVisible(true);
            attachedToRoot_ = true;

        }

        attached_ = true;

    }

    void EC_WaterPlane::DetachEntity()
    {

        if ( !attached_ || entity_ == 0 )
            return;

        EC_Placeable* placeable = dynamic_cast<EC_Placeable*>(FindPlaceable().get());

        if ( placeable != 0 && !attachedToRoot_)
        {
            Ogre::SceneNode* node = placeable->GetSceneNode();
            node_->detachObject(entity_);
            node->removeChild(node_);
        }
        else
        {
            // Attached to root.
            // Sanity check..
            if ( entity_->isAttached() )
            {
                Ogre::SceneManager* scene_mgr = renderer_.lock()->GetSceneManager();
                node_->detachObject(entity_);
                scene_mgr->getRootSceneNode()->removeChild(node_);
                attachedToRoot_ = false;
            }
        }

        attached_ = false;

    }

}<commit_msg>Linux build fix.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "EC_WaterPlane.h"
#include "EC_Placeable.h"
#include "IAttribute.h"

#include "Renderer.h"
#include "SceneManager.h"
#include "SceneEvents.h"
#include "EventManager.h"
#include <OgreMaterialUtils.h>
#include "LoggingFunctions.h"
DEFINE_POCO_LOGGING_FUNCTIONS("EC_WaterPlane")

#include <Ogre.h>
#include <OgreQuaternion.h>
#include <OgreColourValue.h>
#include <OgreMath.h>
// NaN - check
#include <RexNetworkUtils.h>

#include "MemoryLeakCheck.h"

namespace Environment
{

    EC_WaterPlane::EC_WaterPlane(IModule *module)
        : IComponent(module->GetFramework()),
        xSizeAttr(this, "x-size", 5000),
        ySizeAttr(this, "y-size", 5000),
        depthAttr(this, "Depth", 20),
        positionAttr(this, "Position", Vector3df()),
        rotationAttr(this, "Rotation", Quaternion()),
        scaleUfactorAttr(this, "U factor", 0.0002f),
        scaleVfactorAttr(this, "V factor", 0.0002f),
        xSegmentsAttr(this, "Segments in x", 10),
        ySegmentsAttr(this, "Segments in y", 10),
        materialNameAttr(this, "Material", QString("Ocean")),
       //textureNameAttr(this, "Texture", QString("DefaultOceanSkyCube.dds")),
        fogColorAttr(this, "Fog color", Color(0.2f,0.4f,0.35f,1.0f)),
        fogStartAttr(this, "Fog start dist.", 100.f),
        fogEndAttr(this, "Fog end dist.", 2000.f),
        fogModeAttr(this, "Fog mode", 3),
        entity_(0),
        node_(0),
        attached_(false),
        attachedToRoot_(false)
    {
        static AttributeMetadata metadata;
        static bool metadataInitialized = false;

        if(!metadataInitialized)
        {
            metadata.enums[Ogre::FOG_NONE] = "NoFog";
            metadata.enums[Ogre::FOG_EXP] = "Exponential";
            metadata.enums[Ogre::FOG_EXP2] = "ExponentiallySquare";
            metadata.enums[Ogre::FOG_LINEAR] = "Linear";

            metadataInitialized = true;
        }

        fogModeAttr.SetMetadata(&metadata);

        renderer_ = framework_->GetServiceManager()->GetService<OgreRenderer::Renderer>();
        if(!renderer_.expired())
        {
            Ogre::SceneManager* scene_mgr = renderer_.lock()->GetSceneManager();
            node_ = scene_mgr->createSceneNode();
        }

        QObject::connect(this, SIGNAL(OnAttributeChanged(IAttribute*, AttributeChange::Type)),
            SLOT(AttributeUpdated(IAttribute*, AttributeChange::Type)));

        lastXsize_ = xSizeAttr.Get();
        lastYsize_ = ySizeAttr.Get();

        CreateWaterPlane();
        QObject::connect(this, SIGNAL(ParentEntitySet()), this, SLOT(SetParent()));

        // If there exist placeable copy its position for default position and rotation.

        /*
        EC_Placeable* placeable = dynamic_cast<EC_Placeable*>(FindPlaceable().get());
        if ( placeable != 0)
        {
            Vector3df vec = placeable->GetPosition();
            positionAttr.Set(vec,AttributeChange::Default);

            Quaternion rot =placeable->GetOrientation();
            rotationAttr.Set(rot, AttributeChange::Default);
            ComponentChanged(AttributeChange::Default);
        }
        */
    }

    EC_WaterPlane::~EC_WaterPlane()
    {
       if (renderer_.expired())
        return;

       OgreRenderer::RendererPtr renderer = renderer_.lock();
       RemoveWaterPlane();

        if (node_ != 0)
        {
            Ogre::SceneManager* scene_mgr = renderer->GetSceneManager();
            scene_mgr->destroySceneNode(node_);
            node_ = 0;
        }
    }

    void EC_WaterPlane::SetParent()
    {
        // Parent entity has set.

        // Has parent a placeable?

        EC_Placeable* placeable = dynamic_cast<EC_Placeable*>(FindPlaceable().get());

        if ( placeable != 0)
        {
            // Are we currently attached?
            if ( attached_ )
            {
                // Now there might be that we are attached to OgreRoot not to placeable node.
                DetachEntity();
                AttachEntity();
            }

        }

        QObject::connect(parent_entity_,SIGNAL(ComponentAdded(IComponent*, AttributeChange::Type)), this, SLOT(ComponentAdded(IComponent*, AttributeChange::Type)));
        QObject::connect(parent_entity_,SIGNAL(ComponentRemoved(IComponent*, AttributeChange::Type)), this, SLOT(ComponentRemoved(IComponent*, AttributeChange::Type)));

    }

    void EC_WaterPlane::ComponentAdded(IComponent* component, AttributeChange::Type type)
    {
        if ( component->TypeName() == EC_Placeable::TypeNameStatic() )
        {
            DetachEntity();

            EC_Placeable* placeable = static_cast<EC_Placeable* >(component);
            if ( placeable == 0)
                return;

            if ( entity_ == 0)
                return;

            Ogre::SceneNode* node = placeable->GetSceneNode();

            node->addChild(node_);
            node_->attachObject(entity_);
            node_->setVisible(true);

            attached_ = true;

        }
    }

    void EC_WaterPlane::ComponentRemoved(IComponent* component, AttributeChange::Type type)
    {
        if ( component->TypeName() == EC_Placeable::TypeNameStatic() )
        {
            DetachEntity();

            // Attacht entity directly to Ogre root.

            Ogre::SceneManager* scene_mgr = renderer_.lock()->GetSceneManager();
            if ( scene_mgr == 0)
                return;

            node_->attachObject(entity_);
            scene_mgr->getRootSceneNode()->addChild(node_);
            node_->setVisible(true);
            attachedToRoot_ = true;
            attached_ = true;

        }
    }

    bool EC_WaterPlane::IsUnderWater()
    {
      // Check that is camera inside of defined waterplane.
      ///todo this cannot be done this way, mesh orientation etc. must take care. Now we just assume that plane does not have orientation.

      if ( entity_ == 0)
        return false;

      Ogre::Camera *camera = renderer_.lock()->GetCurrentCamera();
      Ogre::Vector3 posCamera = camera->getDerivedPosition();

      Ogre::Vector3 pos;

      if (node_ != 0)
          pos = node_->_getDerivedPosition();
      else
          return false;

      int xSize = xSizeAttr.Get(), ySize = ySizeAttr.Get(), depth = depthAttr.Get();
      int x = posCamera.x, y = posCamera.y, z = posCamera.z;

      // HACK this is strange, i thought that it should be 0.5 but some reason, visually it looks like that you can travel really "outside" from water.
      int tmpMax = pos.x + 0.25*xSize;
      int tmpMin = pos.x - 0.25*xSize;

      if ( x >= tmpMin && x <= tmpMax )
        {
            tmpMax = pos.y + 0.25*ySize;
            tmpMin = pos.y - 0.25*ySize;

            if ( y >= tmpMin && y <= tmpMax)
            {
                tmpMax = pos.z;
                tmpMin = pos.z - depth;

                if ( z >= tmpMin && z <= tmpMax)
                {
                    return true;
                }
                else
                    return false;
            }
            else
                return false;
         }

         return false;
    }

    void EC_WaterPlane::CreateWaterPlane()
    {
        // Create waterplane

        if (renderer_.lock() != 0)
        {
            Ogre::SceneManager *sceneMgr = renderer_.lock()->GetSceneManager();
            assert(sceneMgr);

            if (node_ != 0)
            {

                int xSize = xSizeAttr.Get();
                int ySize = ySizeAttr.Get();
                float uTile =  scaleUfactorAttr.Get() * xSize; /// Default x-size 5000 --> uTile 1.0
                float vTile =  scaleVfactorAttr.Get() * ySize;

                Ogre::MeshPtr mesh = Ogre::MeshManager::getSingleton().createPlane(name_.toStdString().c_str(), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
                    Ogre::Plane(Ogre::Vector3::UNIT_Z, 0),xSize, ySize, xSegmentsAttr.Get(), ySegmentsAttr.Get(), true, 1, uTile, vTile, Ogre::Vector3::UNIT_X);

                entity_ = sceneMgr->createEntity(renderer_.lock()->GetUniqueObjectName(), name_.toStdString().c_str());
                entity_->setMaterialName(materialNameAttr.Get().toStdString().c_str());
                entity_->setCastShadows(false);
                // Tries to attach entity, if there is not EC_Placeable availible, it will not attach object
                AttachEntity();

            }
        }

    }

    void EC_WaterPlane::RemoveWaterPlane()
    {
        // Remove waterplane

        if (renderer_.expired() || !entity_)
            return;

        OgreRenderer::RendererPtr renderer = renderer_.lock();

        DetachEntity();

        Ogre::SceneManager* scene_mgr = renderer->GetSceneManager();
        scene_mgr->destroyEntity(entity_);
        entity_ = 0;

        Ogre::MeshManager::getSingleton().remove(name_.toStdString().c_str());

    }

    Ogre::ColourValue EC_WaterPlane::GetFogColorAsOgreValue() const
    {
        Color col = fogColorAttr.Get();
        return Ogre::ColourValue(col.r, col.g, col.b, col.a);

    }

    void EC_WaterPlane::AttributeUpdated(IAttribute* attribute, AttributeChange::Type change)
    {
        ChangeWaterPlane(attribute);
    }

    void EC_WaterPlane::SetPosition()
    {

        Vector3df vec = positionAttr.Get();

        //node_->setPosition(vec.x, vec.y, vec.z);

#if OGRE_VERSION_MINOR <= 6 && OGRE_VERSION_MAJOR <= 1
        //Ogre::Vector3 current_pos = node_->_getDerivedPosition();
        Ogre::Vector3 tmp(vec.x,vec.y,vec.z);

        if ( !RexTypes::IsValidPositionVector(vec) )
            return;

        node_->setPosition(tmp);
#else
        Ogre::Vector3 pos(vec.x, vec.y, vec.z);
        if ( !RexTypes::IsValidPositionVector(vec) )
            return;

        //node_->_setDerivedPosition(pos);
        node_->setPosition(pos);
#endif

    }

    void EC_WaterPlane::SetOrientation()
    {

         // Set orientation
        Quaternion rot = rotationAttr.Get();

#if OGRE_VERSION_MINOR <= 6 && OGRE_VERSION_MAJOR <= 1
        Ogre::Quaternion current_rot = node_->_getDerivedOrientation();
        Ogre::Quaternion tmp(rot.w, rot.x, rot.y, rot.z);
        Ogre::Quaternion rota = current_rot +  tmp;
        node_->setOrientation(rota);

#else
        node_->_setDerivedOrientation(Ogre::Quaternion(rot.w, rot.x, rot.y, rot.z));
#endif
    }

    void EC_WaterPlane::ChangeWaterPlane(IAttribute* attribute)
    {
        std::string name = attribute->GetNameString();
        if ( ( name == xSizeAttr.GetNameString()
          || name == ySizeAttr.GetNameString()
          || name == scaleUfactorAttr.GetNameString()
          || name == scaleVfactorAttr.GetNameString() ) &&
          ( lastXsize_ != xSizeAttr.Get() || lastYsize_ != ySizeAttr.Get() ) )
        {
            RemoveWaterPlane();
            CreateWaterPlane();

            lastXsize_ = xSizeAttr.Get();
            lastYsize_ = ySizeAttr.Get();

        }
        else if ( name == xSegmentsAttr.GetNameString() || name == ySegmentsAttr.GetNameString() )
        {
            RemoveWaterPlane();
            CreateWaterPlane();
        }
        else if ( name == positionAttr.GetNameString() )
        {
            // Change position
            SetPosition();

        }
        else if ( name == rotationAttr.GetNameString() )
        {
            // Change rotation

            // Is there placeable component? If not use given rotation
            //if ( dynamic_cast<EC_Placeable*>(FindPlaceable().get()) == 0 )
            //{
               SetOrientation();
            //}

        }
        else if ( name == depthAttr.GetNameString() )
        {
            // Change depth
            // Currently do nothing..

        }
        else if ( name ==  materialNameAttr.GetNameString())
        {
            //Change material
            if ( entity_ != 0)
            {
                entity_->setMaterialName(materialNameAttr.Get().toStdString().c_str());
            }
        }
        /*
        // Currently commented out, working feature but not enabled yet.
        else if (name == textureNameAttr.GetNameString() )
        {

            QString currentMaterial = materialNameAttr.Get();

            // Check that has texture really changed.

            StringVector names;
            Ogre::MaterialPtr materialPtr = Ogre::MaterialManager::getSingleton().getByName(currentMaterial.toStdString().c_str());

            if ( materialPtr.get() == 0)
                return;

            OgreRenderer::GetTextureNamesFromMaterial(materialPtr, names);

            QString textureName = textureNameAttr.Get();

            for (StringVector::iterator iter = names.begin(); iter != names.end(); ++iter)
            {
                QString currentTextureName(iter->c_str());
                if ( currentTextureName == textureName)
                    return;
            }

            // So texture has really changed, let's change it.
            OgreRenderer::SetTextureUnitOnMaterial(materialPtr, textureName.toStdString(), 0);

        }
        */

    }

    ComponentPtr EC_WaterPlane::FindPlaceable() const
    {
        assert(framework_);
        ComponentPtr comp;
        if(!GetParentEntity())
            return comp;
        comp = GetParentEntity()->GetComponent<EC_Placeable>();
        return comp;

    }

    void EC_WaterPlane::AttachEntity()
    {
        if ( attached_ || entity_ == 0)
            return;

        EC_Placeable* placeable = dynamic_cast<EC_Placeable* >(FindPlaceable().get());

        // If there exist placeable attach node and entity to it
        if ( placeable != 0 )
        {
            Ogre::SceneNode* node = placeable->GetSceneNode();
            node->addChild(node_);
            node_->attachObject(entity_);
            node_->setVisible(true);
        }
        else
        {
            // There is no placeable attacht entity to OgreSceneRoot
            Ogre::SceneManager* scene_mgr = renderer_.lock()->GetSceneManager();
            node_->attachObject(entity_);
            scene_mgr->getRootSceneNode()->addChild(node_);
            node_->setVisible(true);
            attachedToRoot_ = true;

        }

        attached_ = true;

    }

    void EC_WaterPlane::DetachEntity()
    {

        if ( !attached_ || entity_ == 0 )
            return;

        EC_Placeable* placeable = dynamic_cast<EC_Placeable*>(FindPlaceable().get());

        if ( placeable != 0 && !attachedToRoot_)
        {
            Ogre::SceneNode* node = placeable->GetSceneNode();
            node_->detachObject(entity_);
            node->removeChild(node_);
        }
        else
        {
            // Attached to root.
            // Sanity check..
            if ( entity_->isAttached() )
            {
                Ogre::SceneManager* scene_mgr = renderer_.lock()->GetSceneManager();
                node_->detachObject(entity_);
                scene_mgr->getRootSceneNode()->removeChild(node_);
                attachedToRoot_ = false;
            }
        }

        attached_ = false;

    }

}<|endoftext|>


<commit_before>#include <iostream>
#include <Eigen/Dense>
#include "gtest/gtest.h"
#include "lsq.h"

TEST(LSQ, TestRunnable){
    Eigen::Matrix2f A;
    A << 1, 2, 2, 1;
    Eigen::Vector2f b;
    b << 5, 4;
    Eigen::Vector2f expected;
    expected << 1, 2;
    LSQ* lsq = new LSQ(A, b);
    Eigen::Vector2f x = lsq->solve();
    EXPECT_TRUE(expected.isApprox(x));
}

<commit_msg>Minor<commit_after>#include <Eigen/Dense>
#include "gtest/gtest.h"
#include "lsq.h"

TEST(LSQ, TestRunnable){
    Eigen::Matrix2f A;
    A << 1, 2, 2, 1;
    Eigen::Vector2f b;
    b << 5, 4;
    Eigen::Vector2f expected;
    expected << 1, 2;
    LSQ* lsq = new LSQ(A, b);
    Eigen::Vector2f x = lsq->solve();
    EXPECT_TRUE(expected.isApprox(x));
}

<|endoftext|>


<commit_before>#include "Engine\Engine.h"
#include "Game\Game.h"
#include <stdlib.h>
#include <crtdbg.h>

// TESTING PUSH FOR SAM 10-DEC 21:45

#define UPDATESPERSECOND 60
#define SKIPTICKS (1000 / UPDATESPERSECOND)

int main(int argc, char* args[])
{
	Engine engine;
	engine.init();

	Game game(engine);
	game.newGame();

	int gameState = 0;

	float nextUpdate = SDL_GetTicks();
	unsigned int currentTime;

	while (gameState != -1)
	{
		currentTime = SDL_GetTicks();

		gameState = game.getInput();

		while (nextUpdate < currentTime)
		{
			game.update();
			nextUpdate += SKIPTICKS;
		}

		float interpolation = (currentTime + SKIPTICKS - nextUpdate) / SKIPTICKS;
		game.draw(interpolation);
	}

	engine.close();
	return 0;
}<commit_msg>comment 21:48<commit_after>#include "Engine\Engine.h"
#include "Game\Game.h"
#include <stdlib.h>
#include <crtdbg.h>

// TESTING PUSH FOR SAM 10-DEC 21:45
// COLLABORATION A-GO-GO!!

#define UPDATESPERSECOND 60
#define SKIPTICKS (1000 / UPDATESPERSECOND)

int main(int argc, char* args[])
{
	Engine engine;
	engine.init();

	Game game(engine);
	game.newGame();

	int gameState = 0;

	float nextUpdate = SDL_GetTicks();
	unsigned int currentTime;

	while (gameState != -1)
	{
		currentTime = SDL_GetTicks();

		gameState = game.getInput();

		while (nextUpdate < currentTime)
		{
			game.update();
			nextUpdate += SKIPTICKS;
		}

		float interpolation = (currentTime + SKIPTICKS - nextUpdate) / SKIPTICKS;
		game.draw(interpolation);
	}

	engine.close();
	return 0;
}<|endoftext|>


<commit_before>/*
 * ProjectMain.cpp
 *
 * Created: 5/26/2015 2:22:43 PM
 *  Author: barna.peto
 */

/*Include Header files*/
#include <ProjectMain.h>
#include <schedulerConfig.h>

/*FOR PWM*/
#include <avr/io.h>
#include <avr/interrupt.h>

/*Include C Files*/
#include "TaskFunctions.c"

/*
* Main code called on reset is in  Arduino.h
*/

static TaskType_stType tasks_st[] = {
	{ T_INTERVAL_20MS,	task20ms },
	{ T_INTERVAL_40MS,	task40ms },
	{ T_INTERVAL_60MS,	task60ms },
	{ T_INTERVAL_100MS,	task100ms },
	{ T_INTERVAL_1000MS,task1000ms },
};

/**
 * Function Implementation
 * Return a pointer to tasks configuration table
 */
TaskType_stType *taskGetConfigPtr(void) {
	return tasks_st;
}

/**
 * Function Implementation
 * Return the number of current tasks scheduled to run
 */
uint8_t getNrTasks(void) {
	return sizeof(tasks_st) / sizeof(*tasks_st);
}

/**
 * Function Implementation
 * Initialize the timer
 */
void timer1_init() {
	// set the timer with a prescaler = 256;
	TCCR1B |= (1<<CS12);

	// initialize counter
	TCNT1 = T_TIMER_START;

	// enable overflow interrupt
	TIMSK1 |= (1<<TOIE1);

	//enable global intterupts
	sei();
}

uint16_t stui_tick;

uint8_t stui_TaskIndex;
volatile uint8_t taskTimeCounterFlag_u8;
volatile uint8_t taskTimeCounter_u8;
const uint8_t cui_numberOfTasks = getNrTasks();

static TaskType_stType *taskPtr;

ISR(TIMER1_OVF_vect) {
	TCNT1 = T_TIMER_START;
	taskTimeCounterFlag_u8 = 1;
	taskTimeCounter_u8++;
}

void setup()
{
	taskTimeCounterFlag_u8 = 0;
	taskTimeCounter_u8 = 0;

	/*This is the setup function. It will be called once
	pinMode(13,OUTPUT);
	Serial.begin(9600);
	Serial.print("Hello World!");

	//PWM setup
	DDRD |= (1 << DDD6);
	// PD6 is now an output

	OCR2A = 128;
	// set PWM for 50% duty cycle

	TCCR2A |= (1 << COM2A1);
	// set none-inverting mode

	TCCR2A |= (1 << WGM21) | (1 << WGM20);
	// set fast PWM Mode

	TCCR2B |= (1 << CS21);
	// set prescaler to 8 and starts PWM*/

	timer1_init();

	stui_tick = 0;						// System tick
	stui_TaskIndex = 0;

	taskPtr = taskGetConfigPtr();

}

void loop()
{
	// if 20ms have passed
	if(taskTimeCounterFlag_u8==1) {
		for(stui_TaskIndex=0; stui_TaskIndex < cui_numberOfTasks; stui_TaskIndex++) {
			if((taskTimeCounter_u8 % taskPtr[stui_TaskIndex].interval_u16) == 0 ) {

				if((taskPtr[stui_TaskIndex].ptrFunc) != NULL) {
					(*taskPtr[stui_TaskIndex].ptrFunc)();
				} else {
					// do nothing
				}

			}

		}
		taskTimeCounterFlag_u8 = 0;
	}

}

<commit_msg>Acelasi ProjectMain.cpp dar cu functiile pentru citire Input digitale si setare pwm pe pinii 3 si 11  adaugate<commit_after>/*
 * ProjectMain.cpp
 *
 * Created: 5/26/2015 2:22:43 PM
 *  Author: barna.peto
 */

/*Include Header files*/
#include <ProjectMain.h>
#include <schedulerConfig.h>

/*FOR PWM*/
#include <avr/io.h>
#include <avr/interrupt.h>

/*Include C Files*/
#include "TaskFunctions.c"

/*
* Main code called on reset is in  Arduino.h
*/

static TaskType_stType tasks_st[] = {
	{ T_INTERVAL_20MS,	task20ms },
	{ T_INTERVAL_40MS,	task40ms },
	{ T_INTERVAL_60MS,	task60ms },
	{ T_INTERVAL_100MS,	task100ms },
	{ T_INTERVAL_1000MS,task1000ms },
};

/**
 * Function Implementation
 * Return a pointer to tasks configuration table
 */
TaskType_stType *taskGetConfigPtr(void) {
	return tasks_st;
}

/**
 * Function Implementation
 * Return the number of current tasks scheduled to run
 */
uint8_t getNrTasks(void) {
	return sizeof(tasks_st) / sizeof(*tasks_st);
}

/**
 * Function Implementation
 * Initialize the timer
 */
void timer1_init() {
	// set the timer with a prescaler = 256;
	TCCR1B |= (1<<CS12);

	// initialize counter
	TCNT1 = T_TIMER_START;

	// enable overflow interrupt
	TIMSK1 |= (1<<TOIE1);

	//enable global intterupts
	sei();
}

uint16_t stui_tick;

uint8_t stui_TaskIndex;
volatile uint8_t taskTimeCounterFlag_u8;
volatile uint8_t taskTimeCounter_u8;
const uint8_t cui_numberOfTasks = getNrTasks();

static TaskType_stType *taskPtr;

ISR(TIMER1_OVF_vect) {
	TCNT1 = T_TIMER_START;
	taskTimeCounterFlag_u8 = 1;
	taskTimeCounter_u8++;
}

void setup()
{
	taskTimeCounterFlag_u8 = 0;
	taskTimeCounter_u8 = 0;

	InitPWM(pin); /*Functia de initializare pwm*/

	timer1_init();

	stui_tick = 0;						// System tick
	stui_TaskIndex = 0;

	taskPtr = taskGetConfigPtr();

}

void loop()
{
	// if 20ms have passed
	if(taskTimeCounterFlag_u8==1) {
		for(stui_TaskIndex=0; stui_TaskIndex < cui_numberOfTasks; stui_TaskIndex++) {
			if((taskTimeCounter_u8 % taskPtr[stui_TaskIndex].interval_u16) == 0 ) {

				if((taskPtr[stui_TaskIndex].ptrFunc) != NULL) {
					(*taskPtr[stui_TaskIndex].ptrFunc)();
				} else {
					// do nothing
				}

			}

		}
		taskTimeCounterFlag_u8 = 0;
	}

}

						//------------------------Cod pentru Citire IMPUTS---------------
#define CHECK_BIT(var,pos) ((var) & (1<<(pos))) //macro care verifica o pozitie din registru daca e pe 1 logic
//functia pentru citirea unui pin
int getValue(uint8_t pin){

uint8_t Register; // variabila in care stocam valoarea registrului din care citim

	//cautam registrul aferent piniului selectat, PINx de unde citim starea pinului
	if ((0 <=pin)||(pin <=7))
	{
		Register = PIND; //Registrii PINx sunt Read Only
	}
	else if((8 >=pin)||(pin <=13))
	{
		Register = PINB;
		//pin= pin-7; resetam pinul astfel incat sa putem citi din registrul pinB daca acesta nu e setat in memorie in continuare la PIND
	}
	else if((14 >=pin)||(pin <=19))
	{
		Register = PINC;
		//pin= pin-13;
	}

	else
	Register=NOT_A_PIN;

	//cautam pinul din registrul aferent,de aici putem afla starea pinilor daca sunt Input (1), sau Output (0);
	if(CHECK_BIT(Register,pin)==1)
	{ return true;}
	else
	{return false;}

}

//-------------Cod pentru Setare Output PWM-----------------
int DOPWM_setValue(char pin, int duty)
{
		//setam pinii ca si output
	if (pin == 3)
	{
		//setam pinul 3 ca output
		DDRD |= (1 << DDD3);
		// PD3 is now an output, pin Digital 3
	}
	else if (pin == 11)
	{
		DDRB |= (1 <<DDB3); // DDRB l-am gasit in fisierul iom328p.h ???
		// PB3 is now an output, pin Digital 11
	}

	char value;

	//formula pentru duty cycle in procente
	value = (duty*256)/100;

	//Setam duty cycle pentru fiecare pin cu registrii OCR2A, OCR2B
	OCR2A = value;

}
//functie de initializare pwm
InitPWM(char pin)
{
	//setam pinii ca si output
	if (pin == 3)
	{
		//setam pinul 3 ca output
		DDRD |= (1 << DDD3);
		// PD3 is now an output, pin Digital 3
	}
	else if (pin == 11)
	{
		DDRB |= (1 <<DDB3); // DDRB l-am gasit in fisierul iom328p.h ???
		// PB3 is now an output, pin Digital 11
	}
	/* SETAM TIMERUL 2 PENTRU Modul PHASE CORRECTED PWM*/
	//setam Timer Counter Control Register A pe None-inverting mode si PWM Phase Corrected Mode
	TCCR2A |= (1 << COM2A1) | (0 << COM2A0) | (1 << COM2B1)| (0 << COM2B0);
	// set none-inverting mode on bytes (7,6,5,4) for timer 2

	TCCR2A |= (0 << WGM21) | (1 << WGM20);
	// set  PWM Phase Corrected Mode using OCR2A TOP value on bytes (1,0)

	// setam Timer Counter Control Register B pe PWM Phase Corrected Mode si cu un prescaler de 64
	TCCR2B |= (1 << CS22) | (1 << WGM22);
	// set prescaler to 64 and starts PWM and sets  PWM Phase Corrected Mode

}
<|endoftext|>


<commit_before>#include <cmath>
#include <iostream>
#include "gtest/gtest.h"
#include "numgrind.h"
#include "Utils/utils.h"

#include "testhelpers.h"

using namespace NumGrind;

TEST(NumGrindProperCheckGrad, testLinear01) {
    //std::cout << "WARNING: testLinear01 not fully implemented";
    using namespace NumGrind::SymbolicGraph;
    NumGrind::GraphManager gm;

    Eigen::MatrixXf data(4, 2);
    Eigen::VectorXf targets(4);
    data << 0, 0,
            0, 1,
            1, 0,
            1, 1;
    targets << 0, 1, 1, 0;

    std::default_random_engine generator;
    generator.seed(42);

    auto X = gm.constant(data);
    auto y = gm.constant(targets);

    auto W1 = gm.variable(NumGrind::Utils::gaussf(2, 1, 0.0, 0.5, generator));
    auto b1 = gm.variable(NumGrind::Utils::gaussf(0.0, 0.5, generator));
    auto f = matmult(X, W1) + b1;
    auto err = sumOfSquares(f - y);

    auto vars = gm.initializeVariables();
    auto func = gm.funcFromNode(&err);
    //auto grad1 = gm.initializeGradient(vars);
    auto grad = gm.initializeGradient(vars);

    vars.fill(0);
    err.node()->forwardPass(vars);
    err.node()->backwardPass(1, grad);
    //std::cout << grad;
    ASSERT_FLOAT_EQ(grad[0], -4);
    ASSERT_FLOAT_EQ(grad[1], -2);
    ASSERT_FLOAT_EQ(grad[2], -2);
    //ASSERT_TRUE((grad1 - grad2).norm() < 0.01);
}

TEST(NumGrindProperCheckGrad, testLinear02) {
    using namespace NumGrind::SymbolicGraph;
    NumGrind::GraphManager gm;

    Eigen::MatrixXf data(4, 2);
    Eigen::VectorXf targets(4);
    data << 0, 0,
            0, 1,
            1, 0,
            1, 1;
    targets << 0, 1, 1, 0;

    std::default_random_engine generator;
    generator.seed(42);

    auto X = gm.constant(data);
    auto y = gm.constant(targets);

    auto W1 = gm.variable(NumGrind::Utils::gaussf(2, 1, 0.0, 0.5, generator));
    auto b1 = gm.variable(NumGrind::Utils::gaussf(0.0, 0.5, generator));
    auto f = matmult(X, W1) + b1;
    auto err = sumOfSquares(f - y);

    auto vars = gm.initializeVariables();
    auto func = gm.funcFromNode(&err);
    auto grad = gm.initializeGradient(vars);
    auto grad2 = gm.initializeGradient(vars);

    vars << 5, 0, 0;
    err.node()->forwardPass(vars);
    err.node()->backwardPass(1, grad);
    //std::cout << grad;
    ASSERT_FLOAT_EQ(grad[0], 36);
    ASSERT_FLOAT_EQ(grad[1], 8 + 10);
    ASSERT_FLOAT_EQ(grad[2], 18);
    //ASSERT_TRUE((grad1 - grad2).norm() < 0.01);
}

<commit_msg>add 3 linear gradient tests<commit_after>#include <cmath>
#include <iostream>
#include "gtest/gtest.h"
#include "numgrind.h"
#include "Utils/utils.h"

#include "testhelpers.h"

using namespace NumGrind;

TEST(NumGrindProperCheckGrad, testLinear01) {
    //std::cout << "WARNING: testLinear01 not fully implemented";
    using namespace NumGrind::SymbolicGraph;
    NumGrind::GraphManager gm;

    Eigen::MatrixXf data(4, 2);
    Eigen::VectorXf targets(4);
    data << 0, 0,
            0, 1,
            1, 0,
            1, 1;
    targets << 0, 1, 1, 0;

    std::default_random_engine generator;
    generator.seed(42);

    auto X = gm.constant(data);
    auto y = gm.constant(targets);

    auto W1 = gm.variable(NumGrind::Utils::gaussf(2, 1, 0.0, 0.5, generator));
    auto b1 = gm.variable(NumGrind::Utils::gaussf(0.0, 0.5, generator));
    auto f = matmult(X, W1) + b1;
    auto err = sumOfSquares(f - y);

    auto vars = gm.initializeVariables();
    auto func = gm.funcFromNode(&err);
    //auto grad1 = gm.initializeGradient(vars);
    auto grad = gm.initializeGradient(vars);

    vars.fill(0);
    err.node()->forwardPass(vars);
    err.node()->backwardPass(1, grad);
    //std::cout << grad;
    ASSERT_FLOAT_EQ(grad[0], -4);
    ASSERT_FLOAT_EQ(grad[1], -2);
    ASSERT_FLOAT_EQ(grad[2], -2);
    //ASSERT_TRUE((grad1 - grad2).norm() < 0.01);
}

TEST(NumGrindProperCheckGrad, testLinear02) {
    using namespace NumGrind::SymbolicGraph;
    NumGrind::GraphManager gm;

    Eigen::MatrixXf data(4, 2);
    Eigen::VectorXf targets(4);
    data << 0, 0,
            0, 1,
            1, 0,
            1, 1;
    targets << 0, 1, 1, 0;

    std::default_random_engine generator;
    generator.seed(42);

    auto X = gm.constant(data);
    auto y = gm.constant(targets);

    auto W1 = gm.variable(NumGrind::Utils::gaussf(2, 1, 0.0, 0.5, generator));
    auto b1 = gm.variable(NumGrind::Utils::gaussf(0.0, 0.5, generator));
    auto f = matmult(X, W1) + b1;
    auto err = sumOfSquares(f - y);

    auto vars = gm.initializeVariables();
    auto func = gm.funcFromNode(&err);
    auto grad = gm.initializeGradient(vars);
    auto grad2 = gm.initializeGradient(vars);

    vars << 5, 0, 0;
    err.node()->forwardPass(vars);
    err.node()->backwardPass(1, grad);
    ASSERT_FLOAT_EQ(grad[0], 36);
    ASSERT_FLOAT_EQ(grad[1], 8 + 10);
    ASSERT_FLOAT_EQ(grad[2], 18);
}

TEST(NumGrindProperCheckGrad, testLinear03) {
    using namespace NumGrind::SymbolicGraph;
    NumGrind::GraphManager gm;

    Eigen::MatrixXf data(4, 2);
    Eigen::VectorXf targets(4);
    data << 0, 0,
            0, 1,
            1, 0,
            1, 1;
    targets << 0, 1, 1, 0;

    std::default_random_engine generator;
    generator.seed(42);

    auto X = gm.constant(data);
    auto y = gm.constant(targets);

    auto W1 = gm.variable(NumGrind::Utils::vec2EVecf({1, 0}));
    auto b1 = gm.variable(5);
    auto f = matmult(X, W1) + b1;
    auto err = sumOfSquares(f - y);

    auto vars = gm.initializeVariables();
    auto func = gm.funcFromNode(&err);
    auto grad = gm.initializeGradient(vars);
    auto grad2 = gm.initializeGradient(vars);

    err.node()->forwardPass(vars);
    err.node()->backwardPass(1, grad);
    ASSERT_FLOAT_EQ(grad[0], 40);
    ASSERT_FLOAT_EQ(grad[1], 22);
    ASSERT_FLOAT_EQ(grad[2], 8 + 12);
}

TEST(NumGrindProperCheckGrad, testLinear04) {
    using namespace NumGrind::SymbolicGraph;
    NumGrind::GraphManager gm;

    Eigen::MatrixXf data(4, 2);
    Eigen::VectorXf targets(4);
    data << 0, 0,
            0, 1,
            1, 0,
            1, 1;
    targets << 0, 1, 1, 0;

    std::default_random_engine generator;
    generator.seed(42);

    auto X = gm.constant(data);
    auto y = gm.constant(targets);

    auto W1 = gm.variable(NumGrind::Utils::vec2EVecf({1, -3}));
    auto b1 = gm.variable(5);
    auto f = matmult(X, W1) + b1;
    auto err = sumOfSquares(f - y);

    auto vars = gm.initializeVariables();
    auto func = gm.funcFromNode(&err);
    auto grad = gm.initializeGradient(vars);
    auto grad2 = gm.initializeGradient(vars);

    err.node()->forwardPass(vars);
    err.node()->backwardPass(1, grad);
    ASSERT_FLOAT_EQ(grad[0], 28);
    ASSERT_FLOAT_EQ(grad[1], 10 + 6);
    ASSERT_FLOAT_EQ(grad[2], 2 + 6);
}

TEST(NumGrindProperCheckGrad, testLinear05) {
    using namespace NumGrind::SymbolicGraph;
    NumGrind::GraphManager gm;

    Eigen::MatrixXf data(4, 2);
    Eigen::VectorXf targets(4);
    data << 0, 0,
            0, 2,
            1, 0,
            1, 1;
    targets << 0, 6, 1, 0;

    std::default_random_engine generator;
    generator.seed(42);

    auto X = gm.constant(data);
    auto y = gm.constant(targets);

    auto W1 = gm.variable(NumGrind::Utils::vec2EVecf({1, -3}));
    auto b1 = gm.variable(5);
    auto f = matmult(X, W1) + b1;
    auto err = sumOfSquares(f - y);

    auto vars = gm.initializeVariables();
    auto func = gm.funcFromNode(&err);
    auto grad = gm.initializeGradient(vars);
    auto grad2 = gm.initializeGradient(vars);

    err.node()->forwardPass(vars);
    err.node()->backwardPass(1, grad);
    ASSERT_FLOAT_EQ(grad[0], 12);
    ASSERT_FLOAT_EQ(grad[1], 10 + 6);
    ASSERT_FLOAT_EQ(grad[2], -28 + 6);
}
<|endoftext|>


<commit_before>/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2015 BMW Car IT GmbH
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */
#include "joynr/Variant.h"
#include "joynr/SerializerRegistry.h"
#include "joynr/JsonTokenizer.h"
#include "ExampleTypes.h"
#include "joynr/Request.h"
#include "jsonserializer/RequestSerializer.h"
#include "joynr/joynrlogging.h"

#include "gtest/gtest.h"
#include "gmock/gmock.h"

#include <vector>
#include <utility>
#include <iostream>
#include <string>
#include <cassert>
#include <initializer_list>

#include "joynr/infrastructure/DacTypes/MasterAccessControlEntry.h"
#include "joynr/types/TestTypes/TEverythingStruct.h"
#include "joynr/JsonSerializer.h"

#include <QString>

using namespace ::testing;
using namespace joynr;

//---- Example usage -----------------------------------------------------------
class JoynrJsonSerializerTest : public ::testing::Test {

public:
    JoynrJsonSerializerTest(){}
    void SetUp() {
    }
protected:
    static joynr::joynr_logging::Logger* logger;
};

joynr::joynr_logging::Logger* JoynrJsonSerializerTest::logger(
        joynr::joynr_logging::Logging::getInstance()->getLogger("TST", "JoynrJsonSerializerTest")
);

TEST_F(JoynrJsonSerializerTest, exampleVariant)
{
    // Create a datastructure
    std::vector<Variant> variants;

    variants.push_back(Variant::make<SomeType>());
    variants.push_back(Variant::make<SomeOtherType>(2));
    variants.push_back(Variant::make<int>(3));
    variants.push_back(Variant::make<std::string>("Hello World"));

    variants.push_back(Variant::make<std::vector<SomeOtherType>>
                       (std::initializer_list<SomeOtherType>{
                            SomeOtherType(1),
                            SomeOtherType(2),
                            SomeOtherType(3),
                            SomeOtherType(4),
                            SomeOtherType(5)}));

    // Use the datastructure
    for (auto& v : variants) {
        if (v.is<SomeType>()) {
            std::cout << "Variant is SomeType" << std::endl;
        } else if (v.is<SomeOtherType>()) {
            std::cout << "Variant is SomeOtherType value "
                      << v.get<SomeOtherType>().getA() << std::endl;
        } else if (v.is<int>()) {
            std::cout << "Variant is int value "
                      << v.get<int>() << std::endl;
        } else if (v.is<std::string>()) {
            std::cout << "Variant is std::string value "
                      << v.get<std::string>() << std::endl;
        } else if (v.is<std::vector<SomeOtherType>>()) {
            std::cout << "Variant is a data structure ";
            auto& vec = v.get<std::vector<SomeOtherType>>();
            for (auto& i : vec) {
                std::cout << i.getA() << " ";
            }
            std::cout << std::endl;
        }
    }

}

TEST_F(JoynrJsonSerializerTest, exampleDeserializerKnownType)
{
    std::string json(R"({"a": 5, "b": 6})"); // raw string literal
    JsonTokenizer tokenizer(json);

    if (tokenizer.hasNextObject()) {
        SomeOtherType t;
        ClassDeserializer<SomeOtherType>::deserialize(t, tokenizer.nextObject());
        LOG_TRACE(logger, QString("Deserialized value is %1").arg(t.getA()));
    }
}

TEST_F(JoynrJsonSerializerTest, exampleDeserializerUnknownType)
{
    std::string json(R"({"_typeName": "joynr.SomeOtherType","a": 123})");
    JsonTokenizer tokenizer(json);

    if (tokenizer.hasNextObject()) {
        auto variant = deserialize(tokenizer.nextObject());
        assert(variant.is<SomeOtherType>());
        LOG_TRACE(logger, QString("Unknown type deserialized value is %1").arg(variant.get<SomeOtherType>().getA()));
    }
}

TEST_F(JoynrJsonSerializerTest, exampleDeserializerValue)
{
    std::string json(R"([{"_typeName": "joynr.SomeOtherType","a": 123},{"_typeName": "joynr.SomeOtherType","a": 456}])"); // raw string literal
    LOG_TRACE(logger, QString("json: %1").arg(QString::fromStdString(json)));
    std::vector<SomeOtherType*> vector = JsonSerializer::deserializeVector<SomeOtherType>(json);
    EXPECT_EQ(vector.size(), 2);
    EXPECT_EQ(vector.at(0)->getA(), 123);
    EXPECT_EQ(vector.at(1)->getA(), 456);

    std::vector<Variant> variantVector;
    variantVector.push_back(Variant::make<SomeOtherType>(*vector.at(0)));
    variantVector.push_back(Variant::make<SomeOtherType>(*vector.at(1)));
    std::string variantVectorStr = JsonSerializer::serializeVector(variantVector);
    LOG_TRACE(logger, QString("variantVector: %1").arg(QString::fromStdString(variantVectorStr)));
    EXPECT_EQ(json, variantVectorStr);

    // Clean up
    for (SomeOtherType* p : vector) {
        delete p;
    }
}

std::string convertPermission(ExamplePermission::Enum e)
{
    switch (e) {
    case ExamplePermission::YES:
        return "YES";
    case ExamplePermission::ASK:
        return "ASK";
    case ExamplePermission::NO:
        return "NO";
    default:
        return "UNKNOWN";
    }
}

TEST_F(JoynrJsonSerializerTest, exampleDeserializerJoynrType)
{
    std::string json(R"({"_typeName":"joynr.infrastructure.ExampleMasterAccessControlEntry","defaultConsumerPermission":"YES","operation":"*","possibleConsumerPermissions":["YES","NO"]})");
    JsonTokenizer tokenizer(json);

    if (tokenizer.hasNextObject()) {
        auto variant = deserialize(tokenizer.nextObject());
        assert(variant.is<ExampleMasterAccessControlEntry>());
        ExampleMasterAccessControlEntry& entry = variant.get<ExampleMasterAccessControlEntry>();
        LOG_TRACE(logger, QString("ExampleMasterAccessControlEntry JSON: %1").arg(QString::fromStdString(json)));
        LOG_TRACE(logger, QString("ExampleMasterAccessControlEntry operation: %1").arg(QString::fromStdString(entry.getOperation())));
        LOG_TRACE(logger, QString("ExampleMasterAccessControlEntry defaultConsumerPermission: %1").arg(QString::fromStdString(convertPermission(entry.getDefaultConsumerPermission()))));
        std::stringstream strStream;
        for (auto& i : entry.getPossibleConsumerPermissions()) {
            strStream << convertPermission(i) << " ";
        }
        LOG_TRACE(logger, QString("ExampleMasterAccessControlEntry possibleConsumerPermissions: %1").arg(QString::fromStdString(strStream.str())));
    }
}

TEST_F(JoynrJsonSerializerTest, exampleDeserializerJoynrRequest)
{
    // Create a Request
    Request expectedRequest;
    expectedRequest.setMethodName("realMethod");
    expectedRequest.setRequestReplyId("000-10000-01011");

    // Create a vector of variants to use as parameters
    std::string someString{"Hello World"};
    Variant param1 = Variant::make<std::string>(someString);
    expectedRequest.addParam(param1, "String");
    const int32_t expectedInt = 101;
    Variant param2 = Variant::make<int>(expectedInt);
    expectedRequest.addParam(param2, "Integer");
    SomeOtherType expectedSomeOtherType(2);
    Variant param3 = Variant::make<SomeOtherType>(expectedSomeOtherType);
    expectedRequest.addParam(param3, "SomeOtherType");
    const float expectedFloat = 9.99f;
    Variant param4 = Variant::make<float>(expectedFloat);
    expectedRequest.addParam(param4, "Float");
    bool expectedBool = true;
    Variant param5 = Variant::make<bool>(expectedBool);
    expectedRequest.addParam(param5, "Bool");

    // Serialize into JSON
    std::stringstream stream;
    auto serializer = ClassSerializer<Request>();
    serializer.serialize(expectedRequest, stream);
    std::string json{ stream.str() };
    LOG_TRACE(logger, QString("Request JSON: %1").arg(QString::fromStdString(json)));

    // Deserialize from JSON
    JsonTokenizer tokenizer(json);

    if (tokenizer.hasNextObject()) {
        Request request;
        ClassDeserializer<Request>::deserialize(request, tokenizer.nextObject());
        std::vector<Variant> params = request.getParams();
        EXPECT_EQ(expectedRequest.getParams().size(), params.size());
        Variant intParam = params[1];
        EXPECT_TRUE(intParam.is<uint64_t>());
        EXPECT_FALSE(intParam.is<int32_t>());
        EXPECT_EQ(expectedInt, static_cast<int32_t>(intParam.get<uint64_t>()));
        Variant someOtherTypeParam = params[2];
        EXPECT_TRUE(someOtherTypeParam.is<SomeOtherType>());
        EXPECT_EQ(expectedSomeOtherType.getA(), someOtherTypeParam.get<SomeOtherType>().getA());
        std::cout << "Deserialized value is " << someOtherTypeParam.get<SomeOtherType>().getA() << std::endl;
        Variant floatParam = params[3];
        EXPECT_TRUE(floatParam.is<double>());
        EXPECT_FALSE(floatParam.is<float>());
        EXPECT_EQ(expectedFloat, static_cast<float>(floatParam.get<double>()));
        Variant boolParam = params[4];
        EXPECT_TRUE(boolParam.is<bool>());
        EXPECT_EQ(expectedBool, boolParam.get<bool>());
    }
}

// test with real MasterAccessControlEntry
TEST_F(JoynrJsonSerializerTest, serializeDeserializeMasterAccessControlEntry)
{
    using namespace joynr::infrastructure::DacTypes;

    std::vector<TrustLevel::Enum> possibleTrustLevels(
                std::initializer_list<TrustLevel::Enum>{
                    TrustLevel::LOW,
                    TrustLevel::MID,
                    TrustLevel::HIGH
                });

    std::vector<Permission::Enum> possiblePermissions(
                std::initializer_list<Permission::Enum>{
                    Permission::NO,
                    Permission::ASK,
                    Permission::YES
                });

    MasterAccessControlEntry expectedMac(R"(*)",
                                                         R"(unittest)",
                                                         R"(vehicle/radio)",
                                                         TrustLevel::LOW,
                                                         possibleTrustLevels,
                                                         TrustLevel::HIGH,
                                                         possibleTrustLevels,
                                                         R"(*)",
                                                         Permission::YES,
                                                         possiblePermissions);

    // Serialize
    std::stringstream stream;
    auto serializer = ClassSerializer<MasterAccessControlEntry>{};
    serializer.serialize(expectedMac, stream);
    std::string json{ stream.str() };

    LOG_TRACE(logger, QString("MAC JSON: %1").arg(QString::fromStdString(json)));

    // Deserialize
    MasterAccessControlEntry mac;
    JsonTokenizer tokenizer(json);
    if (tokenizer.hasNextObject()) {
        ClassDeserializer<MasterAccessControlEntry>::deserialize(mac, tokenizer.nextObject());
    }

    // Check that the object serialized/deserialized correctly
    EXPECT_EQ(expectedMac.getDefaultConsumerPermission(), mac.getDefaultConsumerPermission());
    EXPECT_EQ(expectedMac.getDefaultRequiredControlEntryChangeTrustLevel(), mac.getDefaultRequiredControlEntryChangeTrustLevel());
    EXPECT_EQ(expectedMac.getDefaultRequiredTrustLevel(), mac.getDefaultRequiredTrustLevel());
    EXPECT_EQ(expectedMac.getDomain(), mac.getDomain());
    EXPECT_EQ(expectedMac.getInterfaceName(), mac.getInterfaceName());
    EXPECT_EQ(expectedMac.getOperation(), mac.getOperation());
    EXPECT_EQ(expectedMac.getPossibleConsumerPermissions(), mac.getPossibleConsumerPermissions());
    EXPECT_EQ(expectedMac.getPossibleRequiredControlEntryChangeTrustLevels(), mac.getPossibleRequiredControlEntryChangeTrustLevels());
    EXPECT_EQ(expectedMac.getPossibleRequiredTrustLevels(), mac.getPossibleRequiredTrustLevels());
    EXPECT_EQ(expectedMac.getUid(), mac.getUid());
    EXPECT_EQ(expectedMac, mac);
}

// test with TEverythingStruct
TEST_F(JoynrJsonSerializerTest, serializeDeserializeTEverythingStruct)
{
    using namespace joynr::types::TestTypes;

    std::vector<uint8_t> byteBuffer(
                std::initializer_list<uint8_t>{
                    1,2,3
                });
    std::vector<uint8_t> uInt8Array(
                std::initializer_list<uint8_t>{
                    3,2,1
                });
    std::vector<TEnum::Enum> enumArray(
                std::initializer_list<TEnum::Enum>{
                    TEnum::TLITERALB
                });
    std::vector<std::string> stringArray(
                std::initializer_list<std::string>{
                    "one", "four"
                });
    std::vector<Vowel::Enum> vowelinies(
                std::initializer_list<Vowel::Enum>{
                    Vowel::A,
                    Vowel::E
                });
    Word wordWithVowelinies{vowelinies};
    Word wordEmpty{};
    std::vector<Word> words(
                std::initializer_list<Word>{
                    wordWithVowelinies,
                    wordEmpty
                });

    TEverythingStruct expectedEverythingStruct{
        1,
        2,
        3,
        4,
        5,
        6,
        7,
        8,
        9.012,
        10.101f,
        "const std::string &tString",
        true,
        byteBuffer,
        uInt8Array,
        TEnum::TLITERALA,
        enumArray,
        stringArray,
        wordWithVowelinies,
        words
    };

    // Serialize
    std::stringstream stream;
    auto serializer = ClassSerializer<TEverythingStruct>{};
    serializer.serialize(expectedEverythingStruct, stream);
    std::string json{ stream.str() };

    // TODO: replace with logging
    LOG_TRACE(logger, QString("TEverythingStruct JSON: %1").arg(QString::fromStdString(json)));

    // Deserialize
    TEverythingStruct* everythingStruct = JsonSerializer::deserialize<TEverythingStruct>(json);

    // Check that the object serialized/deserialized correctly
    EXPECT_EQ(expectedEverythingStruct, *everythingStruct);
    delete everythingStruct;
}
<commit_msg>[C++] ReplySerializer serializes response field of reply object<commit_after>/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2015 BMW Car IT GmbH
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */
#include "joynr/Variant.h"
#include "joynr/SerializerRegistry.h"
#include "joynr/JsonTokenizer.h"
#include "ExampleTypes.h"
#include "joynr/Request.h"
#include "joynr/Reply.h"
#include "jsonserializer/RequestSerializer.h"
#include "jsonserializer/ReplySerializer.h"
#include "joynr/joynrlogging.h"

#include "gtest/gtest.h"
#include "gmock/gmock.h"

#include <vector>
#include <utility>
#include <iostream>
#include <string>
#include <cassert>
#include <initializer_list>

#include "joynr/infrastructure/DacTypes/MasterAccessControlEntry.h"
#include "joynr/types/TestTypes/TEverythingStruct.h"
#include "joynr/JsonSerializer.h"

#include <QString>

using namespace ::testing;
using namespace joynr;

//---- Example usage -----------------------------------------------------------
class JoynrJsonSerializerTest : public ::testing::Test {

public:
    JoynrJsonSerializerTest(){}
    void SetUp() {
    }
protected:
    static joynr::joynr_logging::Logger* logger;
};

joynr::joynr_logging::Logger* JoynrJsonSerializerTest::logger(
        joynr::joynr_logging::Logging::getInstance()->getLogger("TST", "JoynrJsonSerializerTest")
);

TEST_F(JoynrJsonSerializerTest, exampleVariant)
{
    // Create a datastructure
    std::vector<Variant> variants;

    variants.push_back(Variant::make<SomeType>());
    variants.push_back(Variant::make<SomeOtherType>(2));
    variants.push_back(Variant::make<int>(3));
    variants.push_back(Variant::make<std::string>("Hello World"));

    variants.push_back(Variant::make<std::vector<SomeOtherType>>
                       (std::initializer_list<SomeOtherType>{
                            SomeOtherType(1),
                            SomeOtherType(2),
                            SomeOtherType(3),
                            SomeOtherType(4),
                            SomeOtherType(5)}));

    // Use the datastructure
    for (auto& v : variants) {
        if (v.is<SomeType>()) {
            std::cout << "Variant is SomeType" << std::endl;
        } else if (v.is<SomeOtherType>()) {
            std::cout << "Variant is SomeOtherType value "
                      << v.get<SomeOtherType>().getA() << std::endl;
        } else if (v.is<int>()) {
            std::cout << "Variant is int value "
                      << v.get<int>() << std::endl;
        } else if (v.is<std::string>()) {
            std::cout << "Variant is std::string value "
                      << v.get<std::string>() << std::endl;
        } else if (v.is<std::vector<SomeOtherType>>()) {
            std::cout << "Variant is a data structure ";
            auto& vec = v.get<std::vector<SomeOtherType>>();
            for (auto& i : vec) {
                std::cout << i.getA() << " ";
            }
            std::cout << std::endl;
        }
    }

}

TEST_F(JoynrJsonSerializerTest, exampleDeserializerKnownType)
{
    std::string json(R"({"a": 5, "b": 6})"); // raw string literal
    JsonTokenizer tokenizer(json);

    if (tokenizer.hasNextObject()) {
        SomeOtherType t;
        ClassDeserializer<SomeOtherType>::deserialize(t, tokenizer.nextObject());
        LOG_TRACE(logger, QString("Deserialized value is %1").arg(t.getA()));
    }
}

TEST_F(JoynrJsonSerializerTest, exampleDeserializerUnknownType)
{
    std::string json(R"({"_typeName": "joynr.SomeOtherType","a": 123})");
    JsonTokenizer tokenizer(json);

    if (tokenizer.hasNextObject()) {
        auto variant = deserialize(tokenizer.nextObject());
        assert(variant.is<SomeOtherType>());
        LOG_TRACE(logger, QString("Unknown type deserialized value is %1").arg(variant.get<SomeOtherType>().getA()));
    }
}

TEST_F(JoynrJsonSerializerTest, exampleDeserializerValue)
{
    std::string json(R"([{"_typeName": "joynr.SomeOtherType","a": 123},{"_typeName": "joynr.SomeOtherType","a": 456}])"); // raw string literal
    LOG_TRACE(logger, QString("json: %1").arg(QString::fromStdString(json)));
    std::vector<SomeOtherType*> vector = JsonSerializer::deserializeVector<SomeOtherType>(json);
    EXPECT_EQ(vector.size(), 2);
    EXPECT_EQ(vector.at(0)->getA(), 123);
    EXPECT_EQ(vector.at(1)->getA(), 456);

    std::vector<Variant> variantVector;
    variantVector.push_back(Variant::make<SomeOtherType>(*vector.at(0)));
    variantVector.push_back(Variant::make<SomeOtherType>(*vector.at(1)));
    std::string variantVectorStr = JsonSerializer::serializeVector(variantVector);
    LOG_TRACE(logger, QString("variantVector: %1").arg(QString::fromStdString(variantVectorStr)));
    EXPECT_EQ(json, variantVectorStr);

    // Clean up
    for (SomeOtherType* p : vector) {
        delete p;
    }
}

std::string convertPermission(ExamplePermission::Enum e)
{
    switch (e) {
    case ExamplePermission::YES:
        return "YES";
    case ExamplePermission::ASK:
        return "ASK";
    case ExamplePermission::NO:
        return "NO";
    default:
        return "UNKNOWN";
    }
}

TEST_F(JoynrJsonSerializerTest, exampleDeserializerJoynrType)
{
    std::string json(R"({"_typeName":"joynr.infrastructure.ExampleMasterAccessControlEntry","defaultConsumerPermission":"YES","operation":"*","possibleConsumerPermissions":["YES","NO"]})");
    JsonTokenizer tokenizer(json);

    if (tokenizer.hasNextObject()) {
        auto variant = deserialize(tokenizer.nextObject());
        assert(variant.is<ExampleMasterAccessControlEntry>());
        ExampleMasterAccessControlEntry& entry = variant.get<ExampleMasterAccessControlEntry>();
        LOG_TRACE(logger, QString("ExampleMasterAccessControlEntry JSON: %1").arg(QString::fromStdString(json)));
        LOG_TRACE(logger, QString("ExampleMasterAccessControlEntry operation: %1").arg(QString::fromStdString(entry.getOperation())));
        LOG_TRACE(logger, QString("ExampleMasterAccessControlEntry defaultConsumerPermission: %1").arg(QString::fromStdString(convertPermission(entry.getDefaultConsumerPermission()))));
        std::stringstream strStream;
        for (auto& i : entry.getPossibleConsumerPermissions()) {
            strStream << convertPermission(i) << " ";
        }
        LOG_TRACE(logger, QString("ExampleMasterAccessControlEntry possibleConsumerPermissions: %1").arg(QString::fromStdString(strStream.str())));
    }
}

TEST_F(JoynrJsonSerializerTest, exampleDeserializerJoynrRequest)
{
    // Create a Request
    Request expectedRequest;
    expectedRequest.setMethodName("realMethod");
    expectedRequest.setRequestReplyId("000-10000-01011");

    // Create a vector of variants to use as parameters
    std::string someString{"Hello World"};
    Variant param1 = Variant::make<std::string>(someString);
    expectedRequest.addParam(param1, "String");
    const int32_t expectedInt = 101;
    Variant param2 = Variant::make<int>(expectedInt);
    expectedRequest.addParam(param2, "Integer");
    SomeOtherType expectedSomeOtherType(2);
    Variant param3 = Variant::make<SomeOtherType>(expectedSomeOtherType);
    expectedRequest.addParam(param3, "SomeOtherType");
    const float expectedFloat = 9.99f;
    Variant param4 = Variant::make<float>(expectedFloat);
    expectedRequest.addParam(param4, "Float");
    bool expectedBool = true;
    Variant param5 = Variant::make<bool>(expectedBool);
    expectedRequest.addParam(param5, "Bool");

    // Serialize into JSON
    std::stringstream stream;
    auto serializer = ClassSerializer<Request>();
    serializer.serialize(expectedRequest, stream);
    std::string json{ stream.str() };
    LOG_TRACE(logger, QString("Request JSON: %1").arg(QString::fromStdString(json)));

    // Deserialize from JSON
    JsonTokenizer tokenizer(json);

    if (tokenizer.hasNextObject()) {
        Request request;
        ClassDeserializer<Request>::deserialize(request, tokenizer.nextObject());
        std::vector<Variant> params = request.getParams();
        EXPECT_EQ(expectedRequest.getParams().size(), params.size());
        Variant intParam = params[1];
        EXPECT_TRUE(intParam.is<uint64_t>());
        EXPECT_FALSE(intParam.is<int32_t>());
        EXPECT_EQ(expectedInt, static_cast<int32_t>(intParam.get<uint64_t>()));
        Variant someOtherTypeParam = params[2];
        EXPECT_TRUE(someOtherTypeParam.is<SomeOtherType>());
        EXPECT_EQ(expectedSomeOtherType.getA(), someOtherTypeParam.get<SomeOtherType>().getA());
        std::cout << "Deserialized value is " << someOtherTypeParam.get<SomeOtherType>().getA() << std::endl;
        Variant floatParam = params[3];
        EXPECT_TRUE(floatParam.is<double>());
        EXPECT_FALSE(floatParam.is<float>());
        EXPECT_EQ(expectedFloat, static_cast<float>(floatParam.get<double>()));
        Variant boolParam = params[4];
        EXPECT_TRUE(boolParam.is<bool>());
        EXPECT_EQ(expectedBool, boolParam.get<bool>());
    }
}

TEST_F(JoynrJsonSerializerTest, exampleDeserializerJoynrReply)
{
    // Create a Reply
    Reply expectedReply;
    std::string someString{"Hello World"};
    std::vector<Variant> expectedResponse;
    expectedResponse.push_back(Variant::make<std::string>(someString));
    const int32_t expectedInt = 101;
    expectedResponse.push_back(Variant::make<int>(expectedInt));
    SomeOtherType expectedSomeOtherType(2);
    expectedResponse.push_back(Variant::make<SomeOtherType>(expectedSomeOtherType));
    const float expectedFloat = 9.99f;
    expectedResponse.push_back(Variant::make<float>(expectedFloat));
    bool expectedBool = true;
    expectedResponse.push_back(Variant::make<bool>(expectedBool));

    expectedReply.setResponse(expectedResponse);
    expectedReply.setRequestReplyId("000-10000-01100");

    // Serialize into JSON
    std::stringstream stream;
    auto serializer = ClassSerializer<Reply>{};
    serializer.serialize(expectedReply, stream);
    std::string json{ stream.str() };
    LOG_TRACE(logger, QString("Reply JSON: %1").arg(QString::fromStdString(json)));

    // Deserialize from JSON
    JsonTokenizer tokenizer(json);

    if (tokenizer.hasNextObject()) {
        Reply reply;
        ClassDeserializer<Reply>::deserialize(reply, tokenizer.nextObject());
        std::vector<Variant> response = reply.getResponse();
        EXPECT_EQ(expectedReply.getResponse().size(), response.size());
        Variant first = response[0];
        EXPECT_TRUE(first.is<std::string>());
        EXPECT_EQ(someString, first.get<std::string>());
        Variant intParam = response[1];
        EXPECT_TRUE(intParam.is<uint64_t>());
        EXPECT_FALSE(intParam.is<int32_t>());
        EXPECT_EQ(expectedInt, static_cast<int32_t>(intParam.get<uint64_t>()));
        Variant someOtherTypeParam = response[2];
        EXPECT_TRUE(someOtherTypeParam.is<SomeOtherType>());
        EXPECT_EQ(expectedSomeOtherType.getA(), someOtherTypeParam.get<SomeOtherType>().getA());
        std::cout << "Deserialized value is " << someOtherTypeParam.get<SomeOtherType>().getA() << std::endl;
        Variant floatParam = response[3];
        EXPECT_TRUE(floatParam.is<double>());
        EXPECT_FALSE(floatParam.is<float>());
        EXPECT_EQ(expectedFloat, static_cast<float>(floatParam.get<double>()));
        Variant boolParam = response[4];
        EXPECT_TRUE(boolParam.is<bool>());
        EXPECT_EQ(expectedBool, boolParam.get<bool>());
        EXPECT_EQ(expectedReply.getRequestReplyId(), reply.getRequestReplyId());
    }
}

// test with real MasterAccessControlEntry
TEST_F(JoynrJsonSerializerTest, serializeDeserializeMasterAccessControlEntry)
{
    using namespace joynr::infrastructure::DacTypes;

    std::vector<TrustLevel::Enum> possibleTrustLevels(
                std::initializer_list<TrustLevel::Enum>{
                    TrustLevel::LOW,
                    TrustLevel::MID,
                    TrustLevel::HIGH
                });

    std::vector<Permission::Enum> possiblePermissions(
                std::initializer_list<Permission::Enum>{
                    Permission::NO,
                    Permission::ASK,
                    Permission::YES
                });

    MasterAccessControlEntry expectedMac(R"(*)",
                                                         R"(unittest)",
                                                         R"(vehicle/radio)",
                                                         TrustLevel::LOW,
                                                         possibleTrustLevels,
                                                         TrustLevel::HIGH,
                                                         possibleTrustLevels,
                                                         R"(*)",
                                                         Permission::YES,
                                                         possiblePermissions);

    // Serialize
    std::stringstream stream;
    auto serializer = ClassSerializer<MasterAccessControlEntry>{};
    serializer.serialize(expectedMac, stream);
    std::string json{ stream.str() };

    LOG_TRACE(logger, QString("MAC JSON: %1").arg(QString::fromStdString(json)));

    // Deserialize
    MasterAccessControlEntry mac;
    JsonTokenizer tokenizer(json);
    if (tokenizer.hasNextObject()) {
        ClassDeserializer<MasterAccessControlEntry>::deserialize(mac, tokenizer.nextObject());
    }

    // Check that the object serialized/deserialized correctly
    EXPECT_EQ(expectedMac.getDefaultConsumerPermission(), mac.getDefaultConsumerPermission());
    EXPECT_EQ(expectedMac.getDefaultRequiredControlEntryChangeTrustLevel(), mac.getDefaultRequiredControlEntryChangeTrustLevel());
    EXPECT_EQ(expectedMac.getDefaultRequiredTrustLevel(), mac.getDefaultRequiredTrustLevel());
    EXPECT_EQ(expectedMac.getDomain(), mac.getDomain());
    EXPECT_EQ(expectedMac.getInterfaceName(), mac.getInterfaceName());
    EXPECT_EQ(expectedMac.getOperation(), mac.getOperation());
    EXPECT_EQ(expectedMac.getPossibleConsumerPermissions(), mac.getPossibleConsumerPermissions());
    EXPECT_EQ(expectedMac.getPossibleRequiredControlEntryChangeTrustLevels(), mac.getPossibleRequiredControlEntryChangeTrustLevels());
    EXPECT_EQ(expectedMac.getPossibleRequiredTrustLevels(), mac.getPossibleRequiredTrustLevels());
    EXPECT_EQ(expectedMac.getUid(), mac.getUid());
    EXPECT_EQ(expectedMac, mac);
}

// test with TEverythingStruct
TEST_F(JoynrJsonSerializerTest, serializeDeserializeTEverythingStruct)
{
    using namespace joynr::types::TestTypes;

    std::vector<uint8_t> byteBuffer(
                std::initializer_list<uint8_t>{
                    1,2,3
                });
    std::vector<uint8_t> uInt8Array(
                std::initializer_list<uint8_t>{
                    3,2,1
                });
    std::vector<TEnum::Enum> enumArray(
                std::initializer_list<TEnum::Enum>{
                    TEnum::TLITERALB
                });
    std::vector<std::string> stringArray(
                std::initializer_list<std::string>{
                    "one", "four"
                });
    std::vector<Vowel::Enum> vowelinies(
                std::initializer_list<Vowel::Enum>{
                    Vowel::A,
                    Vowel::E
                });
    Word wordWithVowelinies{vowelinies};
    Word wordEmpty{};
    std::vector<Word> words(
                std::initializer_list<Word>{
                    wordWithVowelinies,
                    wordEmpty
                });

    TEverythingStruct expectedEverythingStruct{
        1,
        2,
        3,
        4,
        5,
        6,
        7,
        8,
        9.012,
        10.101f,
        "const std::string &tString",
        true,
        byteBuffer,
        uInt8Array,
        TEnum::TLITERALA,
        enumArray,
        stringArray,
        wordWithVowelinies,
        words
    };

    // Serialize
    std::stringstream stream;
    auto serializer = ClassSerializer<TEverythingStruct>{};
    serializer.serialize(expectedEverythingStruct, stream);
    std::string json{ stream.str() };

    // TODO: replace with logging
    LOG_TRACE(logger, QString("TEverythingStruct JSON: %1").arg(QString::fromStdString(json)));

    // Deserialize
    TEverythingStruct* everythingStruct = JsonSerializer::deserialize<TEverythingStruct>(json);

    // Check that the object serialized/deserialized correctly
    EXPECT_EQ(expectedEverythingStruct, *everythingStruct);
    delete everythingStruct;
}
<|endoftext|>