<commit_before>// This file is part of the dune-stuff project:
//   https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#include <string>
#include <vector>
#include <map>
#include <random>
#include <fstream>

#include <dune/stuff/common/disable_warnings.hh>
# include <dune/common/float_cmp.hh>
# include <dune/common/fvector.hh>
# include <dune/common/fmatrix.hh>
# include <dune/common/parallel/mpihelper.hh>

# if HAVE_DUNE_FEM
#   include <dune/fem/misc/mpimanager.hh>
# endif
#include <dune/stuff/common/reenable_warnings.hh>

#include <dune/stuff/test/gtest/gtest.h>
#include <dune/stuff/aliases.hh>
#include <dune/stuff/common/configuration.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/common/convergence-study.hh>

#include "main_header.hh"

class
  DUNE_DEPRECATED_MSG("Use the expectation macros of the gtest test suite (20.08.2014)!")
      errors_are_not_as_expected
  : public Dune::Exception
{};

std::vector< double >
  DUNE_DEPRECATED_MSG("Use the expectation macros of the gtest test suite (20.08.2014)!")
                      truncate_vector(const std::vector< double >& in, const size_t size)
{
  assert(size <= in.size());
  if (size == in.size())
    return in;
  else {
    std::vector< double > ret(size);
    for (size_t ii = 0; ii < size; ++ii)
      ret[ii] = in[ii];
    return ret;
  }
} // ... truncate_vector(...)

int main(int argc, char** argv)
{
#ifdef DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS
  try {
#endif

    testing::InitGoogleTest(&argc, argv);
    DSC_CONFIG.read_options(argc, argv);
#if HAVE_DUNE_FEM
    Dune::Fem::MPIManager::initialize(argc, argv);
#else
    Dune::MPIHelper::instance(argc, argv);
#endif

    DSC::Logger().create(
#ifdef DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING
                         DSC::LOG_CONSOLE | DSC::LOG_INFO | DSC::LOG_ERROR
#else
                         DSC::LOG_CONSOLE | DSC::LOG_ERROR
#endif
                                                                          , "", "", "");

    return RUN_ALL_TESTS();

#ifdef DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS
  } catch (Dune::Exception& e) {
    std::cerr << "\nDune reported error: " << e.what() << std::endl;
    std::abort();
  } catch (std::exception& e) {
    std::cerr << "\n" << e.what() << std::endl;
    std::abort();
  } catch (...) {
    std::cerr << "Unknown exception thrown!" << std::endl;
    std::abort();
  } // try
#endif // DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS
} // ... main(...)

<commit_msg>[test.main] fixed includes<commit_after>// This file is part of the dune-stuff project:
//   https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#include "config.h"

#include <string>
#include <vector>
#include <map>
#include <random>
#include <fstream>

#include <dune/stuff/common/disable_warnings.hh>
# include <dune/common/float_cmp.hh>
# include <dune/common/fvector.hh>
# include <dune/common/fmatrix.hh>
# include <dune/common/parallel/mpihelper.hh>

# if HAVE_DUNE_FEM
#   include <dune/fem/misc/mpimanager.hh>
# endif
#include <dune/stuff/common/reenable_warnings.hh>

#include <dune/stuff/test/gtest/gtest.h>
#include <dune/stuff/aliases.hh>
#include <dune/stuff/common/configuration.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/common/convergence-study.hh>

#include "common.hh"

class
  DUNE_DEPRECATED_MSG("Use the expectation macros of the gtest test suite (20.08.2014)!")
      errors_are_not_as_expected
  : public Dune::Exception
{};

std::vector< double >
  DUNE_DEPRECATED_MSG("Use the expectation macros of the gtest test suite (20.08.2014)!")
                      truncate_vector(const std::vector< double >& in, const size_t size)
{
  assert(size <= in.size());
  if (size == in.size())
    return in;
  else {
    std::vector< double > ret(size);
    for (size_t ii = 0; ii < size; ++ii)
      ret[ii] = in[ii];
    return ret;
  }
} // ... truncate_vector(...)

int main(int argc, char** argv)
{
#ifdef DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS
  try {
#endif

    testing::InitGoogleTest(&argc, argv);
    DSC_CONFIG.read_options(argc, argv);
#if HAVE_DUNE_FEM
    Dune::Fem::MPIManager::initialize(argc, argv);
#else
    Dune::MPIHelper::instance(argc, argv);
#endif

    DSC::Logger().create(
#ifdef DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING
                         DSC::LOG_CONSOLE | DSC::LOG_INFO | DSC::LOG_ERROR
#else
                         DSC::LOG_CONSOLE | DSC::LOG_ERROR
#endif
                                                                          , "", "", "");

    return RUN_ALL_TESTS();

#ifdef DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS
  } catch (Dune::Exception& e) {
    std::cerr << "\nDune reported error: " << e.what() << std::endl;
    std::abort();
  } catch (std::exception& e) {
    std::cerr << "\n" << e.what() << std::endl;
    std::abort();
  } catch (...) {
    std::cerr << "Unknown exception thrown!" << std::endl;
    std::abort();
  } // try
#endif // DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS
} // ... main(...)

<|endoftext|>


<commit_before>#ifndef BULL_CORE_IMAGE_ABSTRACTIMAGE_HPP
#define BULL_CORE_IMAGE_ABSTRACTIMAGE_HPP

#include <vector>

#include <Bull/Core/Memory/ByteArray.hpp>
#include <Bull/Core/Utility/Size.hpp>

namespace Bull
{
    struct BULL_CORE_API AbstractImage
    {
        /*! \brief Destructor
         *
         */
        virtual ~AbstractImage() = default;

        /*! \brief Create the AbstractImage
         *
         * \param size The size of the AbstractImage
         *
         */
        virtual void create(const Size& size) = 0;

        /*! \brief Create the AbstractImage
         *
         * \param pixels Pixels of the Image
         * \param size   The size of the Image
         *
         */
        virtual void create(const ByteArray& pixels, const Size& size) = 0;

        /*! \brief Get the size of the AbstractImage
         *
         * \return The size
         *
         */
        virtual Size getSize() const = 0;

        /*! \brief
         *
         * \return
         *
         */
        virtual ByteArray getPixels() const = 0;
    };
}

#endif // BULL_CORE_IMAGE_ABSTRACTIMAGE_HPP
<commit_msg>[Core/AbstractImage] Add missing documentation<commit_after>#ifndef BULL_CORE_IMAGE_ABSTRACTIMAGE_HPP
#define BULL_CORE_IMAGE_ABSTRACTIMAGE_HPP

#include <vector>

#include <Bull/Core/Memory/ByteArray.hpp>
#include <Bull/Core/Utility/Size.hpp>

namespace Bull
{
    struct BULL_CORE_API AbstractImage
    {
        /*! \brief Destructor
         *
         */
        virtual ~AbstractImage() = default;

        /*! \brief Create the AbstractImage
         *
         * \param size The size of the AbstractImage
         *
         */
        virtual void create(const Size& size) = 0;

        /*! \brief Create the AbstractImage
         *
         * \param pixels Pixels of the Image
         * \param size   The size of the Image
         *
         */
        virtual void create(const ByteArray& pixels, const Size& size) = 0;

        /*! \brief Get the size of the AbstractImage
         *
         * \return The size
         *
         */
        virtual Size getSize() const = 0;

        /*! \brief Pixels of the AbstractImage
         *
         * \return Pixels
         *
         */
        virtual ByteArray getPixels() const = 0;
    };
}

#endif // BULL_CORE_IMAGE_ABSTRACTIMAGE_HPP
<|endoftext|>


<commit_before>// Copyright (C) 2015 Jrme Leclercq
// This file is part of the "Nazara Engine - Network module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#pragma once

#ifndef NAZARA_ABSTRACTSOCKET_HPP
#define NAZARA_ABSTRACTSOCKET_HPP

#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/Signal.hpp>
#include <Nazara/Network/Config.hpp>
#include <Nazara/Network/Enums.hpp>
#include <Nazara/Network/SocketHandle.hpp>

namespace Nz
{
	class NAZARA_NETWORK_API AbstractSocket
	{
		public:
			AbstractSocket(const AbstractSocket&) = delete;
			AbstractSocket(AbstractSocket&& abstractSocket);
			virtual ~AbstractSocket();

			void Close();

			void EnableBlocking(bool blocking);

			inline SocketError GetLastError() const;
			inline SocketHandle GetNativeHandle() const;
			inline SocketState GetState() const;
			inline SocketType GetType() const;

			inline bool IsBlockingEnabled() const;

			unsigned int QueryAvailableBytes() const;

			// Slots
			NazaraSignal(OnStateChange, const AbstractSocket* /*socket*/, SocketState /*newState*/);

		protected:
			AbstractSocket(SocketType type);

			inline void UpdateState(SocketState newState);

			virtual void OnClose();
			virtual void OnOpened();

			bool Open(NetProtocol protocol);
			void Open(SocketHandle existingHandle);

			NetProtocol m_protocol;
			SocketError m_lastError;
			SocketHandle m_handle;
			SocketState m_state;
			SocketType m_type;
			bool m_isBlockingEnabled;
	};
}

#include <Nazara/Network/AbstractSocket.inl>

#endif // NAZARA_ABSTRACTSOCKET_HPP<commit_msg>Network/AbstractSocket: Fix comment<commit_after>// Copyright (C) 2015 Jrme Leclercq
// This file is part of the "Nazara Engine - Network module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#pragma once

#ifndef NAZARA_ABSTRACTSOCKET_HPP
#define NAZARA_ABSTRACTSOCKET_HPP

#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/Signal.hpp>
#include <Nazara/Network/Config.hpp>
#include <Nazara/Network/Enums.hpp>
#include <Nazara/Network/SocketHandle.hpp>

namespace Nz
{
	class NAZARA_NETWORK_API AbstractSocket
	{
		public:
			AbstractSocket(const AbstractSocket&) = delete;
			AbstractSocket(AbstractSocket&& abstractSocket);
			virtual ~AbstractSocket();

			void Close();

			void EnableBlocking(bool blocking);

			inline SocketError GetLastError() const;
			inline SocketHandle GetNativeHandle() const;
			inline SocketState GetState() const;
			inline SocketType GetType() const;

			inline bool IsBlockingEnabled() const;

			unsigned int QueryAvailableBytes() const;

			// Signals:
			NazaraSignal(OnStateChange, const AbstractSocket* /*socket*/, SocketState /*newState*/);

		protected:
			AbstractSocket(SocketType type);

			inline void UpdateState(SocketState newState);

			virtual void OnClose();
			virtual void OnOpened();

			bool Open(NetProtocol protocol);
			void Open(SocketHandle existingHandle);

			NetProtocol m_protocol;
			SocketError m_lastError;
			SocketHandle m_handle;
			SocketState m_state;
			SocketType m_type;
			bool m_isBlockingEnabled;
	};
}

#include <Nazara/Network/AbstractSocket.inl>

#endif // NAZARA_ABSTRACTSOCKET_HPP<|endoftext|>


<commit_before>/*******************************************************************************
 *
 * An implementation of discrete domains based on Patricia trees.
 *
 * Author: Arnaud J. Venet (arnaud.j.venet@nasa.gov)
 *
 * Notices:
 *
 * Copyright (c) 2011 United States Government as represented by the
 * Administrator of the National Aeronautics and Space Administration.
 * All Rights Reserved.
 *
 * Disclaimers:
 *
 * No Warranty: THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY OF
 * ANY KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED
 * TO, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL CONFORM TO SPECIFICATIONS,
 * ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
 * OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL BE
 * ERROR FREE, OR ANY WARRANTY THAT DOCUMENTATION, IF PROVIDED, WILL CONFORM TO
 * THE SUBJECT SOFTWARE. THIS AGREEMENT DOES NOT, IN ANY MANNER, CONSTITUTE AN
 * ENDORSEMENT BY GOVERNMENT AGENCY OR ANY PRIOR RECIPIENT OF ANY RESULTS,
 * RESULTING DESIGNS, HARDWARE, SOFTWARE PRODUCTS OR ANY OTHER APPLICATIONS
 * RESULTING FROM USE OF THE SUBJECT SOFTWARE.  FURTHER, GOVERNMENT AGENCY
 * DISCLAIMS ALL WARRANTIES AND LIABILITIES REGARDING THIRD-PARTY SOFTWARE,
 * IF PRESENT IN THE ORIGINAL SOFTWARE, AND DISTRIBUTES IT "AS IS."
 *
 * Waiver and Indemnity:  RECIPIENT AGREES TO WAIVE ANY AND ALL CLAIMS AGAINST
 * THE UNITED STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, AS WELL
 * AS ANY PRIOR RECIPIENT.  IF RECIPIENT'S USE OF THE SUBJECT SOFTWARE RESULTS
 * IN ANY LIABILITIES, DEMANDS, DAMAGES, EXPENSES OR LOSSES ARISING FROM SUCH
 * USE, INCLUDING ANY DAMAGES FROM PRODUCTS BASED ON, OR RESULTING FROM,
 * RECIPIENT'S USE OF THE SUBJECT SOFTWARE, RECIPIENT SHALL INDEMNIFY AND HOLD
 * HARMLESS THE UNITED STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS,
 * AS WELL AS ANY PRIOR RECIPIENT, TO THE EXTENT PERMITTED BY LAW.
 * RECIPIENT'S SOLE REMEDY FOR ANY SUCH MATTER SHALL BE THE IMMEDIATE,
 * UNILATERAL TERMINATION OF THIS AGREEMENT.
 *
 ******************************************************************************/

#pragma once

#include <crab/domains/patricia_trees.hpp>
#include <crab/domains/separate_domains.hpp>
#include <crab/support/debug.hpp>

#include <boost/range.hpp>

namespace ikos {

template <typename Element> class discrete_domain {

private:
  using ptset_t = patricia_tree_set<Element>;

public:
  using discrete_domain_t = discrete_domain<Element>;
  using iterator = typename ptset_t::iterator;

private:
  bool _is_top;
  ptset_t _set;

private:
  discrete_domain(bool is_top) : _is_top(is_top) {}

  discrete_domain(ptset_t set) : _is_top(false), _set(set) {}

public:
  static discrete_domain_t bottom() { return discrete_domain_t(false); }

  static discrete_domain_t top() { return discrete_domain_t(true); }

public:
  discrete_domain() : _is_top(true) {}

  discrete_domain(const discrete_domain_t &other)
      : _is_top(other._is_top), _set(other._set) {}

  discrete_domain(Element s) : _is_top(false), _set(s) {}

  template <typename Iterator>
  discrete_domain(Iterator eIt, Iterator eEt) : _is_top(false) {
    for (auto e : boost::make_iterator_range(eIt, eEt)) {
      this->_set += e;
    }
  }

  bool is_top() const { return this->_is_top; }

  bool is_bottom() const { return (!this->_is_top && this->_set.empty()); }

  bool operator<=(const discrete_domain_t &other) const {
    return other._is_top || (!this->_is_top && this->_set <= other._set);
  }

  bool operator==(const discrete_domain_t &other) const {
    return (this->_is_top && other._is_top) || (this->_set == other._set);
  }

  void operator|=(const discrete_domain_t &other) { *this = *this | other; }

  discrete_domain_t operator|(const discrete_domain_t &other) const {
    if (this->_is_top || other._is_top) {
      return discrete_domain_t(true);
    } else {
      return discrete_domain_t(this->_set | other._set);
    }
  }

  discrete_domain_t operator&(const discrete_domain_t &other) const {
    if (this->is_bottom() || other.is_bottom()) {
      return discrete_domain_t(false);
    } else if (this->_is_top) {
      return other;
    } else if (other._is_top) {
      return *this;
    } else {
      return discrete_domain_t(this->_set & other._set);
    }
  }

  discrete_domain_t operator||(const discrete_domain_t &other) const {
    return this->operator|(other);
  }

  discrete_domain_t operator&&(const discrete_domain_t &other) const {
    return this->operator&(other);
  }

  discrete_domain_t &operator+=(Element s) {
    if (!this->_is_top) {
      this->_set += s;
    }
    return *this;
  }

  template <typename Range> discrete_domain_t &operator+=(Range es) {
    if (!this->_is_top)
      for (auto e : es)
        this->_set += e;
    return *this;
  }

  discrete_domain_t operator+(Element s) {
    discrete_domain_t r(*this);
    r.operator+=(s);
    return r;
  }

  template <typename Range> discrete_domain_t operator+(Range es) {
    discrete_domain_t r(*this);
    r.operator+=(es);
    return r;
  }

  discrete_domain_t &operator-=(Element s) {
    if (!this->_is_top) {
      this->_set -= s;
    }
    return *this;
  }

  template <typename Range> discrete_domain_t &operator-=(Range es) {
    if (!this->_is_top)
      for (auto e : es)
        this->_set -= e;
    return *this;
  }

  discrete_domain_t operator-(Element s) {
    discrete_domain_t r(*this);
    r.operator-=(s);
    return r;
  }

  template <typename Range> discrete_domain_t operator-(Range es) {
    discrete_domain_t r(*this);
    r.operator-=(es);
    return r;
  }

  std::size_t size() const {
    if (this->_is_top) {
      CRAB_ERROR("Size for discrete domain TOP is undefined");
    } else {
      return this->_set.size();
    }
  }

  iterator begin() const {
    if (this->_is_top) {
      CRAB_ERROR("Iterator for discrete domain TOP is undefined");
    } else {
      return this->_set.begin();
    }
  }

  iterator end() const {
    if (this->_is_top) {
      CRAB_ERROR("Iterator for discrete domain TOP is undefined");
    } else {
      return this->_set.end();
    }
  }

  void write(crab::crab_os &o) const {
    if (this->_is_top) {
      o << "{...}";
    } else if (this->_set.empty()) {
      o << "_|_";
    } else {
      o << this->_set;
    }
  }

}; // class discrete_domain

template <typename Elem>
inline crab::crab_os &operator<<(crab::crab_os &o,
                                 const discrete_domain<Elem> &d) {
  d.write(o);
  return o;
}

} // namespace ikos
<commit_msg>style(discrete_domains): use m_ for class fields<commit_after>/*******************************************************************************
 *
 * An implementation of discrete domains based on Patricia trees.
 *
 * Author: Arnaud J. Venet (arnaud.j.venet@nasa.gov)
 *
 * Notices:
 *
 * Copyright (c) 2011 United States Government as represented by the
 * Administrator of the National Aeronautics and Space Administration.
 * All Rights Reserved.
 *
 * Disclaimers:
 *
 * No Warranty: THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY OF
 * ANY KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED
 * TO, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL CONFORM TO SPECIFICATIONS,
 * ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
 * OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL BE
 * ERROR FREE, OR ANY WARRANTY THAT DOCUMENTATION, IF PROVIDED, WILL CONFORM TO
 * THE SUBJECT SOFTWARE. THIS AGREEMENT DOES NOT, IN ANY MANNER, CONSTITUTE AN
 * ENDORSEMENT BY GOVERNMENT AGENCY OR ANY PRIOR RECIPIENT OF ANY RESULTS,
 * RESULTING DESIGNS, HARDWARE, SOFTWARE PRODUCTS OR ANY OTHER APPLICATIONS
 * RESULTING FROM USE OF THE SUBJECT SOFTWARE.  FURTHER, GOVERNMENT AGENCY
 * DISCLAIMS ALL WARRANTIES AND LIABILITIES REGARDING THIRD-PARTY SOFTWARE,
 * IF PRESENT IN THE ORIGINAL SOFTWARE, AND DISTRIBUTES IT "AS IS."
 *
 * Waiver and Indemnity:  RECIPIENT AGREES TO WAIVE ANY AND ALL CLAIMS AGAINST
 * THE UNITED STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, AS WELL
 * AS ANY PRIOR RECIPIENT.  IF RECIPIENT'S USE OF THE SUBJECT SOFTWARE RESULTS
 * IN ANY LIABILITIES, DEMANDS, DAMAGES, EXPENSES OR LOSSES ARISING FROM SUCH
 * USE, INCLUDING ANY DAMAGES FROM PRODUCTS BASED ON, OR RESULTING FROM,
 * RECIPIENT'S USE OF THE SUBJECT SOFTWARE, RECIPIENT SHALL INDEMNIFY AND HOLD
 * HARMLESS THE UNITED STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS,
 * AS WELL AS ANY PRIOR RECIPIENT, TO THE EXTENT PERMITTED BY LAW.
 * RECIPIENT'S SOLE REMEDY FOR ANY SUCH MATTER SHALL BE THE IMMEDIATE,
 * UNILATERAL TERMINATION OF THIS AGREEMENT.
 *
 ******************************************************************************/

#pragma once

#include <crab/domains/patricia_trees.hpp>
#include <crab/support/debug.hpp>

#include <boost/range.hpp>

namespace ikos {

template <typename Element> class discrete_domain {

private:
  using ptset_t = patricia_tree_set<Element>;

public:
  using discrete_domain_t = discrete_domain<Element>;
  using iterator = typename ptset_t::iterator;

private:
  bool m_is_top;
  ptset_t m_set;

private:
  discrete_domain(bool is_top) : m_is_top(is_top) {}
  discrete_domain(ptset_t set) : m_is_top(false), m_set(set) {}

public:
  static discrete_domain_t bottom() { return discrete_domain_t(false); }
  static discrete_domain_t top() { return discrete_domain_t(true); }

public:
  discrete_domain() : m_is_top(true) {}

  discrete_domain(const discrete_domain_t &other) = default;
  discrete_domain(discrete_domain_t &&other) = default;
  discrete_domain_t &operator=(const discrete_domain_t &other) = default;
  discrete_domain_t &operator=(discrete_domain_t &&other) = default;

  discrete_domain(Element s) : m_is_top(false), m_set(s) {}

  template <typename Iterator>
  discrete_domain(Iterator eIt, Iterator eEt) : m_is_top(false) {
    for (auto e : boost::make_iterator_range(eIt, eEt)) {
      m_set += e;
    }
  }

  bool is_top() const { return m_is_top; }

  bool is_bottom() const { return (!m_is_top && m_set.empty()); }

  bool operator<=(const discrete_domain_t &other) const {
    return other.m_is_top || (!m_is_top && m_set <= other.m_set);
  }

  bool operator==(const discrete_domain_t &other) const {
    return (m_is_top && other.m_is_top) || (m_set == other.m_set);
  }

  void operator|=(const discrete_domain_t &other) { *this = *this | other; }

  discrete_domain_t operator|(const discrete_domain_t &other) const {
    if (m_is_top || other.m_is_top) {
      return discrete_domain_t(true);
    } else {
      return discrete_domain_t(m_set | other.m_set);
    }
  }

  discrete_domain_t operator&(const discrete_domain_t &other) const {
    if (is_bottom() || other.is_bottom()) {
      return discrete_domain_t(false);
    } else if (m_is_top) {
      return other;
    } else if (other.m_is_top) {
      return *this;
    } else {
      return discrete_domain_t(m_set & other.m_set);
    }
  }

  discrete_domain_t operator||(const discrete_domain_t &other) const {
    return operator|(other);
  }

  discrete_domain_t operator&&(const discrete_domain_t &other) const {
    return operator&(other);
  }

  discrete_domain_t &operator+=(Element s) {
    if (!m_is_top) {
      m_set += s;
    }
    return *this;
  }

  template <typename Range> discrete_domain_t &operator+=(Range es) {
    if (!m_is_top) {
      for (auto e : es) {
        m_set += e;
      }
    }
    return *this;
  }

  discrete_domain_t operator+(Element s) {
    discrete_domain_t r(*this);
    r.operator+=(s);
    return r;
  }

  template <typename Range> discrete_domain_t operator+(Range es) {
    discrete_domain_t r(*this);
    r.operator+=(es);
    return r;
  }

  discrete_domain_t &operator-=(Element s) {
    if (!m_is_top) {
      m_set -= s;
    }
    return *this;
  }

  template <typename Range> discrete_domain_t &operator-=(Range es) {
    if (!m_is_top) {
      for (auto e : es) {
        m_set -= e;
      }
    }
    return *this;
  }

  discrete_domain_t operator-(Element s) {
    discrete_domain_t r(*this);
    r.operator-=(s);
    return r;
  }

  template <typename Range> discrete_domain_t operator-(Range es) {
    discrete_domain_t r(*this);
    r.operator-=(es);
    return r;
  }

  std::size_t size() const {
    if (m_is_top) {
      assert(false);
      CRAB_ERROR("Size for discrete domain TOP is undefined");
    } else {
      return m_set.size();
    }
  }

  iterator begin() const {
    if (m_is_top) {
      assert(false);
      CRAB_ERROR("Iterator for discrete domain TOP is undefined");
    } else {
      return m_set.begin();
    }
  }

  iterator end() const {
    if (m_is_top) {
      assert(false);
      CRAB_ERROR("Iterator for discrete domain TOP is undefined");
    } else {
      return m_set.end();
    }
  }

  void write(crab::crab_os &o) const {
    if (m_is_top) {
      o << "{...}";
    } else if (m_set.empty()) {
      o << "{}";
    } else {
      o << m_set;
    }
  }

}; // class discrete_domain

template <typename Elem>
inline crab::crab_os &operator<<(crab::crab_os &o,
                                 const discrete_domain<Elem> &d) {
  d.write(o);
  return o;
}

} // namespace ikos
<|endoftext|>


<commit_before>// This file is distributed under the MIT license.
// See the LICENSE file for details.

#ifndef VSNRAY_PATHTRACING_INL
#define VSNRAY_PATHTRACING_INL

#include <chrono>
#include <limits>

#ifndef NDEBUG
#include <iostream>
#include <ostream>
#endif

#include <visionaray/generic_prim.h>
#include <visionaray/surface.h>

#include "traverse.h"

namespace visionaray
{
namespace pathtracing
{

template <typename Params>
struct kernel
{

    Params params;

    template <typename R, template <typename> class S>
    VSNRAY_FUNC vector<4, typename R::scalar_type> operator()(R ray, S<typename R::scalar_type>& s) const
    {

        using C = vector<4, typename R::scalar_type>;

        typedef typename R::scalar_type scalar_type;
        typedef typename R::vec_type vec_type;

        /*static*/ const scalar_type scene_epsilon(0.0001);
        /*static*/ const unsigned MaxDepth = 5;

        auto hit_rec        =  closest_hit(ray, params.prims.begin, params.prims.end);
        auto exited         = !hit_rec.hit;
        auto active_rays    =  hit_rec.hit;

        C result(1.0, 1.0, 1.0, 1.0);

        for (unsigned d = 0; d < MaxDepth; ++d)
        {
            if ( any(active_rays) )
            {
                vec_type refl_dir;
                vec_type view_dir = -ray.dir;

                auto surf = get_surface(hit_rec, params);
                auto below = active_rays & (dot(view_dir, surf.normal) < scalar_type(0.0));

                if (any(below))
                {
                    result = mul( result, C(0.0, 0.0, 0.0, 1.0), below, result );
                    active_rays = active_rays & !below;

                    if ( !any(active_rays) )
                    {
                        break;
                    }
                }

                scalar_type pdf(0.0);
                auto sr     = make_shade_record<Params, scalar_type>();
                sr.active   = hit_rec.hit;
                sr.view_dir = view_dir;

                auto color = surf.sample(sr, refl_dir, pdf, s);

                auto emissive = has_emissive_material(surf);
                color = mul( color, dot(surf.normal, refl_dir) / pdf, !emissive, color ); // TODO: maybe have emissive material return refl_dir so that dot(N,R) = 1?
                result = mul( result, C(color, scalar_type(1.0)), active_rays, result );
                active_rays &= !emissive;

                if (!any(active_rays))
                {
                    break;
                }

                auto isect_pos = ray.ori + ray.dir * hit_rec.t; // TODO: store in hit_rec?!?

                ray.ori = isect_pos + refl_dir * scene_epsilon;
                ray.dir = refl_dir;

                hit_rec      = closest_hit(ray, params.prims.begin, params.prims.end);
                exited       = active_rays & !hit_rec.hit;
                active_rays &= hit_rec.hit;
            }

            result = mul( result, C(params.ambient_color), exited, result );
        }

        result = mul( result, C(0.0, 0.0, 0.0, 1.0), active_rays, result );

        return result;
    }
};

} // pathtracing
} // visionaray

#endif // VSNRAY_PATHTRACING_INL
<commit_msg>Mind background color in pathtracer<commit_after>// This file is distributed under the MIT license.
// See the LICENSE file for details.

#ifndef VSNRAY_PATHTRACING_INL
#define VSNRAY_PATHTRACING_INL

#include <chrono>
#include <limits>

#ifndef NDEBUG
#include <iostream>
#include <ostream>
#endif

#include <visionaray/generic_prim.h>
#include <visionaray/surface.h>

#include "traverse.h"

namespace visionaray
{
namespace pathtracing
{

template <typename Params>
struct kernel
{

    Params params;

    template <typename R, template <typename> class S>
    VSNRAY_FUNC vector<4, typename R::scalar_type> operator()(R ray, S<typename R::scalar_type>& s) const
    {

        using C = vector<4, typename R::scalar_type>;

        typedef typename R::scalar_type scalar_type;
        typedef typename R::vec_type vec_type;

        /*static*/ const scalar_type scene_epsilon(0.0001);
        /*static*/ const unsigned MaxDepth = 5;

        auto hit_rec        =  closest_hit(ray, params.prims.begin, params.prims.end);
        auto exited         = !hit_rec.hit;
        auto active_rays    =  hit_rec.hit;

        C result = select( exited, C(params.bg_color), C(1.0) );

        for (unsigned d = 0; d < MaxDepth; ++d)
        {
            if ( any(active_rays) )
            {
                vec_type refl_dir;
                vec_type view_dir = -ray.dir;

                auto surf = get_surface(hit_rec, params);
                auto below = active_rays & (dot(view_dir, surf.normal) < scalar_type(0.0));

                if (any(below))
                {
                    result = mul( result, C(0.0, 0.0, 0.0, 1.0), below, result );
                    active_rays = active_rays & !below;

                    if ( !any(active_rays) )
                    {
                        break;
                    }
                }

                scalar_type pdf(0.0);
                auto sr     = make_shade_record<Params, scalar_type>();
                sr.active   = hit_rec.hit;
                sr.view_dir = view_dir;

                auto color = surf.sample(sr, refl_dir, pdf, s);

                auto emissive = has_emissive_material(surf);
                color = mul( color, dot(surf.normal, refl_dir) / pdf, !emissive, color ); // TODO: maybe have emissive material return refl_dir so that dot(N,R) = 1?
                result = mul( result, C(color, scalar_type(1.0)), active_rays, result );
                active_rays &= !emissive;

                if (!any(active_rays))
                {
                    break;
                }

                auto isect_pos = ray.ori + ray.dir * hit_rec.t; // TODO: store in hit_rec?!?

                ray.ori = isect_pos + refl_dir * scene_epsilon;
                ray.dir = refl_dir;

                hit_rec      = closest_hit(ray, params.prims.begin, params.prims.end);
                exited       = active_rays & !hit_rec.hit;
                active_rays &= hit_rec.hit;
            }

            result = mul( result, C(params.ambient_color), exited, result );
        }

        result = mul( result, C(0.0, 0.0, 0.0, 1.0), active_rays, result );

        return result;
    }
};

} // pathtracing
} // visionaray

#endif // VSNRAY_PATHTRACING_INL
<|endoftext|>


<commit_before>// This file is distributed under the MIT license.
// See the LICENSE file for details.

namespace MATH_NAMESPACE
{

//--------------------------------------------------------------------------------------------------
// matrix members
//

template <size_t N, size_t M, typename T>
MATH_FUNC
inline T* matrix<N, M, T>::data()
{
    return reinterpret_cast<T*>(this);
}

template <size_t N, size_t M, typename T>
MATH_FUNC
inline T const* matrix<N, M, T>::data() const
{
    return reinterpret_cast<T const*>(this);
}

template <size_t N, size_t M, typename T>
MATH_FUNC
inline vector<N, T>& matrix<N, M, T>::operator()(size_t col)
{
    return *(reinterpret_cast<vector<N, T>*>(this) + col);
}

template <size_t N, size_t M, typename T>
MATH_FUNC
inline vector<N, T> const& matrix<N, M, T>::operator()(size_t col) const
{
    return *(reinterpret_cast<vector<N, T> const*>(this) + col);
}

template <size_t N, size_t M, typename T>
MATH_FUNC
inline T& matrix<N, M, T>::operator()(size_t row, size_t col)
{
    return (operator()(col))[row];
}

template <size_t N, size_t M, typename T>
MATH_FUNC
inline T const& matrix<N, M, T>::operator()(size_t row, size_t col) const
{
    return (operator()(col))[row];
}

template <size_t N, size_t M, typename T>
MATH_FUNC
inline matrix<N, M, T> matrix<N, M, T>::identity()
{
    static_assert(N == M, "Matrix not symmetrical");

    matrix<N, M, T> result;

    for (int i = 0; i < N; ++i)
    {
        for (int j = 0; j < M; ++j)
        {
            result(i, j) = i == j ? T(1.0) : T(0.0);
        }
    }

    return result;
}

//--------------------------------------------------------------------------------------------------
// Comparisons
//

template <size_t N, size_t M, typename T>
MATH_FUNC
inline bool operator==(matrix<N, M, T> const& a, matrix<N, M, T> const& b)
{
    for (size_t i = 0; i < N; ++i)
    {
        for (size_t j = 0; j < M; ++j)
        {
            if (a(i, j) != b(i, j))
            {
                return false;
            }
        }
    }

    return true;
}

template <size_t N, size_t M, typename T>
MATH_FUNC
inline bool operator!=(matrix<N, M, T> const& a, matrix<N, M, T> const& b)
{
    return !(a == b);
}

} // MATH_NAMESPACE
<commit_msg>Use 64-bit indices when limits are 64 bit<commit_after>// This file is distributed under the MIT license.
// See the LICENSE file for details.

namespace MATH_NAMESPACE
{

//--------------------------------------------------------------------------------------------------
// matrix members
//

template <size_t N, size_t M, typename T>
MATH_FUNC
inline T* matrix<N, M, T>::data()
{
    return reinterpret_cast<T*>(this);
}

template <size_t N, size_t M, typename T>
MATH_FUNC
inline T const* matrix<N, M, T>::data() const
{
    return reinterpret_cast<T const*>(this);
}

template <size_t N, size_t M, typename T>
MATH_FUNC
inline vector<N, T>& matrix<N, M, T>::operator()(size_t col)
{
    return *(reinterpret_cast<vector<N, T>*>(this) + col);
}

template <size_t N, size_t M, typename T>
MATH_FUNC
inline vector<N, T> const& matrix<N, M, T>::operator()(size_t col) const
{
    return *(reinterpret_cast<vector<N, T> const*>(this) + col);
}

template <size_t N, size_t M, typename T>
MATH_FUNC
inline T& matrix<N, M, T>::operator()(size_t row, size_t col)
{
    return (operator()(col))[row];
}

template <size_t N, size_t M, typename T>
MATH_FUNC
inline T const& matrix<N, M, T>::operator()(size_t row, size_t col) const
{
    return (operator()(col))[row];
}

template <size_t N, size_t M, typename T>
MATH_FUNC
inline matrix<N, M, T> matrix<N, M, T>::identity()
{
    static_assert(N == M, "Matrix not symmetrical");

    matrix<N, M, T> result;

    for (size_t i = 0; i < N; ++i)
    {
        for (size_t j = 0; j < M; ++j)
        {
            result(i, j) = i == j ? T(1.0) : T(0.0);
        }
    }

    return result;
}

//--------------------------------------------------------------------------------------------------
// Comparisons
//

template <size_t N, size_t M, typename T>
MATH_FUNC
inline bool operator==(matrix<N, M, T> const& a, matrix<N, M, T> const& b)
{
    for (size_t i = 0; i < N; ++i)
    {
        for (size_t j = 0; j < M; ++j)
        {
            if (a(i, j) != b(i, j))
            {
                return false;
            }
        }
    }

    return true;
}

template <size_t N, size_t M, typename T>
MATH_FUNC
inline bool operator!=(matrix<N, M, T> const& a, matrix<N, M, T> const& b)
{
    return !(a == b);
}

} // MATH_NAMESPACE
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: basegfxfactory.cxx,v $
 * $Revision: 1.8 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_cppcanvas.hxx"
#include <rtl/instance.hxx>
#include <osl/getglobalmutex.hxx>
#include <osl/diagnose.h>
#include <com/sun/star/rendering/InterpolationMode.hpp>
#include <basegfx/polygon/b2dpolygon.hxx>
#include <basegfx/polygon/b2dpolypolygon.hxx>
#include <basegfx/tools/canvastools.hxx>

#include <cppcanvas/basegfxfactory.hxx>

#include <implpolypolygon.hxx>
#include <implbitmap.hxx>
#include <impltext.hxx>

using namespace ::com::sun::star;

namespace cppcanvas
{
    /* Singleton handling */
    struct InitInstance2
    {
        BaseGfxFactory* operator()()
        {
            return new BaseGfxFactory();
        }
    };

    BaseGfxFactory& BaseGfxFactory::getInstance()
    {
        return *rtl_Instance< BaseGfxFactory, InitInstance2, ::osl::MutexGuard,
            ::osl::GetGlobalMutex >::create(
                InitInstance2(), ::osl::GetGlobalMutex());
    }

    BaseGfxFactory::BaseGfxFactory()
    {
    }

    BaseGfxFactory::~BaseGfxFactory()
    {
    }

    PolyPolygonSharedPtr BaseGfxFactory::createPolyPolygon( const CanvasSharedPtr&          rCanvas,
                                                            const ::basegfx::B2DPolygon&    rPoly ) const
    {
        OSL_ENSURE( rCanvas.get() != NULL &&
                    rCanvas->getUNOCanvas().is(),
                    "BaseGfxFactory::createPolyPolygon(): Invalid canvas" );

        if( rCanvas.get() == NULL )
            return PolyPolygonSharedPtr();

        uno::Reference< rendering::XCanvas > xCanvas( rCanvas->getUNOCanvas() );
        if( !xCanvas.is() )
            return PolyPolygonSharedPtr();

        return PolyPolygonSharedPtr(
            new internal::ImplPolyPolygon( rCanvas,
                                           ::basegfx::unotools::xPolyPolygonFromB2DPolygon(
                                               xCanvas->getDevice(),
                                               rPoly) ) );
    }

    PolyPolygonSharedPtr BaseGfxFactory::createPolyPolygon( const CanvasSharedPtr&              rCanvas,
                                                            const ::basegfx::B2DPolyPolygon&    rPolyPoly ) const
    {
        OSL_ENSURE( rCanvas.get() != NULL &&
                    rCanvas->getUNOCanvas().is(),
                    "BaseGfxFactory::createPolyPolygon(): Invalid canvas" );

        if( rCanvas.get() == NULL )
            return PolyPolygonSharedPtr();

        uno::Reference< rendering::XCanvas > xCanvas( rCanvas->getUNOCanvas() );
        if( !xCanvas.is() )
            return PolyPolygonSharedPtr();

        return PolyPolygonSharedPtr(
            new internal::ImplPolyPolygon( rCanvas,
                                           ::basegfx::unotools::xPolyPolygonFromB2DPolyPolygon(
                                               xCanvas->getDevice(),
                                               rPolyPoly) ) );
    }

    BitmapSharedPtr BaseGfxFactory::createBitmap( const CanvasSharedPtr&    rCanvas,
                                                  const ::basegfx::B2ISize& rSize ) const
    {
        OSL_ENSURE( rCanvas.get() != NULL &&
                    rCanvas->getUNOCanvas().is(),
                    "BaseGfxFactory::createBitmap(): Invalid canvas" );

        if( rCanvas.get() == NULL )
            return BitmapSharedPtr();

        uno::Reference< rendering::XCanvas > xCanvas( rCanvas->getUNOCanvas() );
        if( !xCanvas.is() )
            return BitmapSharedPtr();

        return BitmapSharedPtr(
            new internal::ImplBitmap( rCanvas,
                                      xCanvas->getDevice()->createCompatibleBitmap(
                                          ::basegfx::unotools::integerSize2DFromB2ISize(rSize) ) ) );
    }

    BitmapSharedPtr BaseGfxFactory::createAlphaBitmap( const CanvasSharedPtr&   rCanvas,
                                                       const ::basegfx::B2ISize& rSize ) const
    {
        OSL_ENSURE( rCanvas.get() != NULL &&
                    rCanvas->getUNOCanvas().is(),
                    "BaseGfxFactory::createBitmap(): Invalid canvas" );

        if( rCanvas.get() == NULL )
            return BitmapSharedPtr();

        uno::Reference< rendering::XCanvas > xCanvas( rCanvas->getUNOCanvas() );
        if( !xCanvas.is() )
            return BitmapSharedPtr();

        return BitmapSharedPtr(
            new internal::ImplBitmap( rCanvas,
                                      xCanvas->getDevice()->createCompatibleAlphaBitmap(
                                          ::basegfx::unotools::integerSize2DFromB2ISize(rSize) ) ) );
    }

    TextSharedPtr BaseGfxFactory::createText( const CanvasSharedPtr& rCanvas, const ::rtl::OUString& rText ) const
    {
        return TextSharedPtr( new internal::ImplText( rCanvas,
                                                      rText ) );
    }

}
<commit_msg>INTEGRATION: CWS canvas05 (1.7.38); FILE MERGED 2008/04/21 07:50:36 thb 1.7.38.2: RESYNC: (1.7-1.8); FILE MERGED 2007/10/01 13:41:45 thb 1.7.38.1: #i79258# Merge from CWS picom<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: basegfxfactory.cxx,v $
 * $Revision: 1.9 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_cppcanvas.hxx"

#include <rtl/instance.hxx>
#include <osl/getglobalmutex.hxx>
#include <osl/diagnose.h>

#include <com/sun/star/rendering/InterpolationMode.hpp>

#include <basegfx/polygon/b2dpolygon.hxx>
#include <basegfx/polygon/b2dpolypolygon.hxx>
#include <basegfx/tools/canvastools.hxx>

#include <cppcanvas/basegfxfactory.hxx>

#include "implpolypolygon.hxx"
#include "implbitmap.hxx"
#include "impltext.hxx"

using namespace ::com::sun::star;

namespace cppcanvas
{
    /* Singleton handling */
    struct InitInstance2
    {
        BaseGfxFactory* operator()()
        {
            return new BaseGfxFactory();
        }
    };

    BaseGfxFactory& BaseGfxFactory::getInstance()
    {
        return *rtl_Instance< BaseGfxFactory, InitInstance2, ::osl::MutexGuard,
            ::osl::GetGlobalMutex >::create(
                InitInstance2(), ::osl::GetGlobalMutex());
    }

    BaseGfxFactory::BaseGfxFactory()
    {
    }

    BaseGfxFactory::~BaseGfxFactory()
    {
    }

    PolyPolygonSharedPtr BaseGfxFactory::createPolyPolygon( const CanvasSharedPtr&          rCanvas,
                                                            const ::basegfx::B2DPolygon&    rPoly ) const
    {
        OSL_ENSURE( rCanvas.get() != NULL &&
                    rCanvas->getUNOCanvas().is(),
                    "BaseGfxFactory::createPolyPolygon(): Invalid canvas" );

        if( rCanvas.get() == NULL )
            return PolyPolygonSharedPtr();

        uno::Reference< rendering::XCanvas > xCanvas( rCanvas->getUNOCanvas() );
        if( !xCanvas.is() )
            return PolyPolygonSharedPtr();

        return PolyPolygonSharedPtr(
            new internal::ImplPolyPolygon( rCanvas,
                                           ::basegfx::unotools::xPolyPolygonFromB2DPolygon(
                                               xCanvas->getDevice(),
                                               rPoly) ) );
    }

    PolyPolygonSharedPtr BaseGfxFactory::createPolyPolygon( const CanvasSharedPtr&              rCanvas,
                                                            const ::basegfx::B2DPolyPolygon&    rPolyPoly ) const
    {
        OSL_ENSURE( rCanvas.get() != NULL &&
                    rCanvas->getUNOCanvas().is(),
                    "BaseGfxFactory::createPolyPolygon(): Invalid canvas" );

        if( rCanvas.get() == NULL )
            return PolyPolygonSharedPtr();

        uno::Reference< rendering::XCanvas > xCanvas( rCanvas->getUNOCanvas() );
        if( !xCanvas.is() )
            return PolyPolygonSharedPtr();

        return PolyPolygonSharedPtr(
            new internal::ImplPolyPolygon( rCanvas,
                                           ::basegfx::unotools::xPolyPolygonFromB2DPolyPolygon(
                                               xCanvas->getDevice(),
                                               rPolyPoly) ) );
    }

    BitmapSharedPtr BaseGfxFactory::createBitmap( const CanvasSharedPtr&    rCanvas,
                                                  const ::basegfx::B2ISize& rSize ) const
    {
        OSL_ENSURE( rCanvas.get() != NULL &&
                    rCanvas->getUNOCanvas().is(),
                    "BaseGfxFactory::createBitmap(): Invalid canvas" );

        if( rCanvas.get() == NULL )
            return BitmapSharedPtr();

        uno::Reference< rendering::XCanvas > xCanvas( rCanvas->getUNOCanvas() );
        if( !xCanvas.is() )
            return BitmapSharedPtr();

        return BitmapSharedPtr(
            new internal::ImplBitmap( rCanvas,
                                      xCanvas->getDevice()->createCompatibleBitmap(
                                          ::basegfx::unotools::integerSize2DFromB2ISize(rSize) ) ) );
    }

    BitmapSharedPtr BaseGfxFactory::createAlphaBitmap( const CanvasSharedPtr&   rCanvas,
                                                       const ::basegfx::B2ISize& rSize ) const
    {
        OSL_ENSURE( rCanvas.get() != NULL &&
                    rCanvas->getUNOCanvas().is(),
                    "BaseGfxFactory::createBitmap(): Invalid canvas" );

        if( rCanvas.get() == NULL )
            return BitmapSharedPtr();

        uno::Reference< rendering::XCanvas > xCanvas( rCanvas->getUNOCanvas() );
        if( !xCanvas.is() )
            return BitmapSharedPtr();

        return BitmapSharedPtr(
            new internal::ImplBitmap( rCanvas,
                                      xCanvas->getDevice()->createCompatibleAlphaBitmap(
                                          ::basegfx::unotools::integerSize2DFromB2ISize(rSize) ) ) );
    }

    TextSharedPtr BaseGfxFactory::createText( const CanvasSharedPtr& rCanvas, const ::rtl::OUString& rText ) const
    {
        return TextSharedPtr( new internal::ImplText( rCanvas,
                                                      rText ) );
    }

}
<|endoftext|>


<commit_before>/* testsha1.cpp

Copyright (c) 2005 Michael D. Leonhard

http://tamale.net/

This file is licensed under the terms described in the
accompanying LICENSE file.
*/

#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <fcntl.h>
#include <vector>
#include <iostream>

#include "../src/sha1.h"

int run_tests() {
    int ret = 0;

	// these example text blocks are taken from RFC3174
    std::vector<std::pair<const char*, const char*> > tests;
    tests.push_back(std::pair<const char*, const char*>("abc","a9993e364706816aba3e25717850c26c9cd0d89d"));
    tests.push_back(std::pair<const char*, const char*>("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq","84983e441c3bd26ebaae4aa1f95129e5e54670f1"));
    tests.push_back(std::pair<const char*, const char*>("a","34aa973cd4c4daa4f61eeb2bdbad27316534016f"));
    tests.push_back(std::pair<const char*, const char*>("0123456701234567012345670123456701234567012345670123456701234567","dea356a2cddd90c7a7ecedc5ebb563934f460452"));

    std::vector<unsigned int> multiplier;
    multiplier.push_back(1);
    multiplier.push_back(1);
    multiplier.push_back(1000000);
    multiplier.push_back(10);

    int passed = 0;
    int passed_h = 0;
    int passed_c = 0;

    unsigned char sig[SHA1_SIZE], sig2[SHA1_SIZE];
    char str[SHA1_STRING_SIZE];

    /* run our tests */
    for (unsigned int i = 0; i < tests.size(); i++) {
        bool passed_hash = 0;
        bool passed_convert = 0;

        sha1::sha1_t sha1;

        for (unsigned int j = 0; j < multiplier[i]; j++) {
            sha1.process(tests[i].first, strlen(tests[i].first));
        }

        sha1.finish(sig);

        /* convert from the sig to a string rep */
        sha1::sig_to_string(sig, str, sizeof(str));
        if (strcmp(str, tests[i].second) == 0) {
            passed_hash = true;
            passed_h++;
        }

        /* convert from the string back into a MD5 signature */
        sha1::sig_from_string(sig2, str);
        if (memcmp(sig, sig2, SHA1_SIZE) == 0) {
            passed_convert = true;
            passed_c++;
        }

        if (passed_hash and passed_convert) {
            std::cout << "TEST " << i + 1 << " PASSED" << std::endl;
            passed++;
        } else {
            std::cout << "TEST " << i + 1 << " FAILED" << std::endl;
        }
    }

    std::cout << std::endl << "*******************************" << std::endl
              << "    " << passed << " of " << tests.size() << " tests passed" << std::endl;
    if (passed != tests.size()) {
        ret = 1;
        std::cout << std::endl << "   Please notify developer" << std::endl;
        std::cout << "  " << passed_h << " passed hashing check" << std::endl
                  << "  " << passed_h << " passed comparison check" << std::endl;
    }
    std::cout << "*******************************" << std::endl;

	return ret;
}

int read_input(int argc, char** argv) {
    sha1::sha1_t sha1;
    unsigned char* digest;
    const unsigned int buffer_size = 8192;

    assert( argv[1] );

    if (argv[1][0] == '-') {

    }

    /* open the file */
    int fd = open( argv[1], O_RDONLY | O_BINARY, 0 );
    /* handle open failure */
    if( fd == -1 ) {
        fprintf( stderr, "cannot open file %s\n", argv[1] );
        return 1;
        }

    /* prepare to calculate the SHA-1 hash */
    char* buffer = (char*)malloc( buffer_size );
    assert( buffer );

    /* loop through the file */
    int ret;
    while( true ) {
        /* read a chunk of data */
        ret = read( fd, buffer, buffer_size );
        /* check for error and end of file */
        if( ret < 1 ) break;
        /* run this data through the hash function */
        sha1.process(buffer, ret);
        }

    /* close the file */
    close( fd );

    /* there was an error reading the file */
    if( ret == -1 ) {
        fprintf( stderr, "error reading %s.\n", argv[1] );
        return 1;
        }

    /* get the digest */
    sha1.finish(digest);
    assert( digest );
    /* print it out */
    printf( "%s:", argv[1] );
    printf( "\n" );
    fflush( stdout );
    free( digest );
    return 0;
}

int main(int argc, char* argv[])
{
	if( argc == 2 ) {
        return read_input(argc, argv);
	} else {
        return run_tests();
	}
}

<commit_msg>removes incorrect copyright notice from file's origins<commit_after>#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <fcntl.h>
#include <vector>
#include <iostream>

#include "../src/sha1.h"

int run_tests() {
    int ret = 0;

	// these example text blocks are taken from RFC3174
    std::vector<std::pair<const char*, const char*> > tests;
    tests.push_back(std::pair<const char*, const char*>("abc","a9993e364706816aba3e25717850c26c9cd0d89d"));
    tests.push_back(std::pair<const char*, const char*>("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq","84983e441c3bd26ebaae4aa1f95129e5e54670f1"));
    tests.push_back(std::pair<const char*, const char*>("a","34aa973cd4c4daa4f61eeb2bdbad27316534016f"));
    tests.push_back(std::pair<const char*, const char*>("0123456701234567012345670123456701234567012345670123456701234567","dea356a2cddd90c7a7ecedc5ebb563934f460452"));

    std::vector<unsigned int> multiplier;
    multiplier.push_back(1);
    multiplier.push_back(1);
    multiplier.push_back(1000000);
    multiplier.push_back(10);

    int passed = 0;
    int passed_h = 0;
    int passed_c = 0;

    unsigned char sig[SHA1_SIZE], sig2[SHA1_SIZE];
    char str[SHA1_STRING_SIZE];

    /* run our tests */
    for (unsigned int i = 0; i < tests.size(); i++) {
        bool passed_hash = 0;
        bool passed_convert = 0;

        sha1::sha1_t sha1;

        for (unsigned int j = 0; j < multiplier[i]; j++) {
            sha1.process(tests[i].first, strlen(tests[i].first));
        }

        sha1.finish(sig);

        /* convert from the sig to a string rep */
        sha1::sig_to_string(sig, str, sizeof(str));
        if (strcmp(str, tests[i].second) == 0) {
            passed_hash = true;
            passed_h++;
        }

        /* convert from the string back into a MD5 signature */
        sha1::sig_from_string(sig2, str);
        if (memcmp(sig, sig2, SHA1_SIZE) == 0) {
            passed_convert = true;
            passed_c++;
        }

        if (passed_hash and passed_convert) {
            std::cout << "TEST " << i + 1 << " PASSED" << std::endl;
            passed++;
        } else {
            std::cout << "TEST " << i + 1 << " FAILED" << std::endl;
        }
    }

    std::cout << std::endl << "*******************************" << std::endl
              << "    " << passed << " of " << tests.size() << " tests passed" << std::endl;
    if (passed != tests.size()) {
        ret = 1;
        std::cout << std::endl << "   Please notify developer" << std::endl;
        std::cout << "  " << passed_h << " passed hashing check" << std::endl
                  << "  " << passed_h << " passed comparison check" << std::endl;
    }
    std::cout << "*******************************" << std::endl;

	return ret;
}

int read_input(int argc, char** argv) {
    sha1::sha1_t sha1;
    unsigned char* digest;
    const unsigned int buffer_size = 8192;

    assert( argv[1] );

    if (argv[1][0] == '-') {

    }

    /* open the file */
    int fd = open( argv[1], O_RDONLY | O_BINARY, 0 );
    /* handle open failure */
    if( fd == -1 ) {
        fprintf( stderr, "cannot open file %s\n", argv[1] );
        return 1;
        }

    /* prepare to calculate the SHA-1 hash */
    char* buffer = (char*)malloc( buffer_size );
    assert( buffer );

    /* loop through the file */
    int ret;
    while( true ) {
        /* read a chunk of data */
        ret = read( fd, buffer, buffer_size );
        /* check for error and end of file */
        if( ret < 1 ) break;
        /* run this data through the hash function */
        sha1.process(buffer, ret);
        }

    /* close the file */
    close( fd );

    /* there was an error reading the file */
    if( ret == -1 ) {
        fprintf( stderr, "error reading %s.\n", argv[1] );
        return 1;
        }

    /* get the digest */
    sha1.finish(digest);
    assert( digest );
    /* print it out */
    printf( "%s:", argv[1] );
    printf( "\n" );
    fflush( stdout );
    free( digest );
    return 0;
}

int main(int argc, char* argv[])
{
	if( argc == 2 ) {
        return read_input(argc, argv);
	} else {
        return run_tests();
	}
}

<|endoftext|>


<commit_before>#include <memory>
#include <future>
#include "integration_test_helper.h"
#include "camera_test_helpers.h"

using namespace dronecore;

Camera::Mode get_mode(std::shared_ptr<Camera> camera)
{
    struct PromiseResult {
        Camera::Result result;
        Camera::Mode mode;
    };

    auto prom = std::make_shared<std::promise<PromiseResult>>();
    auto ret = prom->get_future();

    camera->get_mode_async([prom](Camera::Result result, Camera::Mode mode) {
        PromiseResult pr {};
        pr.result = result;
        pr.mode = mode;
        prom->set_value(pr);
    });

    auto status = ret.wait_for(std::chrono::seconds(7));

    EXPECT_EQ(status, std::future_status::ready);

    if (status == std::future_status::ready) {
        PromiseResult new_ret = ret.get();
        EXPECT_EQ(new_ret.result, Camera::Result::SUCCESS);
        EXPECT_NE(new_ret.mode, Camera::Mode::UNKNOWN);
        return new_ret.mode;
    } else {
        return Camera::Mode::UNKNOWN;
    }
}

void set_mode(std::shared_ptr<Camera> camera, Camera::Mode mode)
{
    Camera::Mode mode_already_set = get_mode(camera);

    // FIXME: this should not be required.
    std::this_thread::sleep_for(std::chrono::seconds(2));

    if (mode == mode_already_set) {
        return;
    }

    auto prom = std::make_shared<std::promise<void>>();
    auto ret = prom->get_future();

    camera->set_mode_async(mode, [mode, prom](Camera::Result result,
    Camera::Mode mode_got) {
        EXPECT_EQ(result, Camera::Result::SUCCESS);
        EXPECT_EQ(mode, mode_got);
        prom->set_value();
    });

    auto status = ret.wait_for(std::chrono::seconds(10));

    EXPECT_EQ(status, std::future_status::ready);

    if (status == std::future_status::ready) {
        ret.get();
    }

    // FIXME: this should not be required.
    std::this_thread::sleep_for(std::chrono::seconds(1));
}

Camera::Result set_setting(std::shared_ptr<Camera> camera,
                           const std::string &setting,
                           const std::string &option)
{
    auto prom = std::make_shared<std::promise<Camera::Result>>();
    auto ret = prom->get_future();

    camera->set_option_async(setting, option,
    [prom](Camera::Result result) {
        prom->set_value(result);
    });

    auto status = ret.wait_for(std::chrono::seconds(1));

    EXPECT_EQ(status, std::future_status::ready);

    if (status == std::future_status::ready) {
        return ret.get();
    }
    return Camera::Result::TIMEOUT;
}

dronecore::Camera::Result get_setting(std::shared_ptr<dronecore::Camera> camera,
                                      const std::string &setting,
                                      std::string &option)
{
    struct PromiseResult {
        Camera::Result result;
        std::string value;
    };

    auto prom = std::make_shared<std::promise<PromiseResult>>();
    auto ret = prom->get_future();

    camera->get_option_async(setting,
    [prom](Camera::Result result, const std::string & value) {
        PromiseResult promise_result;
        promise_result.result = result;
        promise_result.value = value;
        prom->set_value(promise_result);
    });

    auto status = ret.wait_for(std::chrono::seconds(1));

    EXPECT_EQ(status, std::future_status::ready);

    if (status == std::future_status::ready) {
        PromiseResult promise_result = ret.get();
        option = promise_result.value;
        return promise_result.result;
    }
    return Camera::Result::TIMEOUT;

}
<commit_msg>camera: get mode before set mode not needed<commit_after>#include <memory>
#include <future>
#include "integration_test_helper.h"
#include "camera_test_helpers.h"

using namespace dronecore;

Camera::Mode get_mode(std::shared_ptr<Camera> camera)
{
    struct PromiseResult {
        Camera::Result result;
        Camera::Mode mode;
    };

    auto prom = std::make_shared<std::promise<PromiseResult>>();
    auto ret = prom->get_future();

    camera->get_mode_async([prom](Camera::Result result, Camera::Mode mode) {
        PromiseResult pr {};
        pr.result = result;
        pr.mode = mode;
        prom->set_value(pr);
    });

    auto status = ret.wait_for(std::chrono::seconds(7));

    EXPECT_EQ(status, std::future_status::ready);

    if (status == std::future_status::ready) {
        PromiseResult new_ret = ret.get();
        EXPECT_EQ(new_ret.result, Camera::Result::SUCCESS);
        EXPECT_NE(new_ret.mode, Camera::Mode::UNKNOWN);
        return new_ret.mode;
    } else {
        return Camera::Mode::UNKNOWN;
    }
}

void set_mode(std::shared_ptr<Camera> camera, Camera::Mode mode)
{
    //// FIXME: this should not be required.
    std::this_thread::sleep_for(std::chrono::seconds(1));

    auto prom = std::make_shared<std::promise<void>>();
    auto ret = prom->get_future();

    camera->set_mode_async(mode, [mode, prom](Camera::Result result,
    Camera::Mode mode_got) {
        EXPECT_EQ(result, Camera::Result::SUCCESS);
        EXPECT_EQ(mode, mode_got);
        prom->set_value();
    });

    auto status = ret.wait_for(std::chrono::seconds(10));

    EXPECT_EQ(status, std::future_status::ready);

    if (status == std::future_status::ready) {
        ret.get();
    }

    // FIXME: this should not be required.
    std::this_thread::sleep_for(std::chrono::seconds(1));
}

Camera::Result set_setting(std::shared_ptr<Camera> camera,
                           const std::string &setting,
                           const std::string &option)
{
    auto prom = std::make_shared<std::promise<Camera::Result>>();
    auto ret = prom->get_future();

    camera->set_option_async(setting, option,
    [prom](Camera::Result result) {
        prom->set_value(result);
    });

    auto status = ret.wait_for(std::chrono::seconds(1));

    EXPECT_EQ(status, std::future_status::ready);

    if (status == std::future_status::ready) {
        return ret.get();
    }
    return Camera::Result::TIMEOUT;
}

dronecore::Camera::Result get_setting(std::shared_ptr<dronecore::Camera> camera,
                                      const std::string &setting,
                                      std::string &option)
{
    struct PromiseResult {
        Camera::Result result;
        std::string value;
    };

    auto prom = std::make_shared<std::promise<PromiseResult>>();
    auto ret = prom->get_future();

    camera->get_option_async(setting,
    [prom](Camera::Result result, const std::string & value) {
        PromiseResult promise_result;
        promise_result.result = result;
        promise_result.value = value;
        prom->set_value(promise_result);
    });

    auto status = ret.wait_for(std::chrono::seconds(1));

    EXPECT_EQ(status, std::future_status::ready);

    if (status == std::future_status::ready) {
        PromiseResult promise_result = ret.get();
        option = promise_result.value;
        return promise_result.result;
    }
    return Camera::Result::TIMEOUT;

}
<|endoftext|>


<commit_before>/***********************************************************************************************************************
 **
 ** Copyright (c) 2011, 2013 ETH Zurich
 ** All rights reserved.
 **
 ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
 ** following conditions are met:
 **
 **    * Redistributions of source code must retain the above copyright notice, this list of conditions and the
 **      following disclaimer.
 **    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
 **      following disclaimer in the documentation and/or other materials provided with the distribution.
 **    * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
 **      derived from this software without specific prior written permission.
 **
 **
 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 **
 **********************************************************************************************************************/

#include "OOReference.h"
#include "../expressions/ReferenceExpression.h"
#include "../declarations/Class.h"
#include "../declarations/Method.h"
#include "../expressions/types/ClassTypeExpression.h"
#include "../expressions/types/ArrayTypeExpression.h"
#include "../expressions/MethodCallExpression.h"
#include "../expressions/AssignmentExpression.h"
#include "../expressions/CastExpression.h"

#include "../types/SymbolProviderType.h"
#include "../types/ErrorType.h"
#include "../typesystem/TypeSystem.h"

#include "ModelBase/src/nodes/TypedListDefinition.h"
DEFINE_TYPED_LIST(OOModel::OOReference)

namespace OOModel {

NODE_DEFINE_EMPTY_CONSTRUCTORS(OOReference)
NODE_DEFINE_TYPE_REGISTRATION_METHODS(OOReference)

bool OOReference::resolve()
{
	// TODO Handle the case where the symbol is defined multiple times in a better way

	// TODO this is not multithread friendly.
	if (resolving_) return false;
	resolving_ = true;

	auto parent = static_cast<ReferenceExpression*>(this->parent());

	SymbolTypes searchForType = ANY_SYMBOL;
	if ( referenceTargetKind() != ReferenceTargetKind::Callable ) searchForType &= ~METHOD;

	QSet<Node*> candidateTargets;
	if (parent->prefix())
	{
		// Perform a downward search starting from the target of the prefix
		auto t = parent->prefix()->type();
		if (auto sp = dynamic_cast<SymbolProviderType*>(t))
		{
			if (sp->symbolProvider())
			{
				// It's important below that we change the source to sp->symbolProvider() in the call to findSymbols.
				// See NameImport.cpp for more info.

				sp->symbolProvider()->findSymbols(candidateTargets, name(), sp->symbolProvider(), SEARCH_DOWN,
						searchForType, searchForType.testFlag(METHOD) ); 	// When search for methods do an exhaustive search.
																							// This is important for overloads.
			}
		}
		SAFE_DELETE(t);
	}
	else
	{
		// Perform an upward search starting from the current node
		// When search for methods do an exhaustive search. This is important for overloads.
		findSymbols(candidateTargets, name(), this, SEARCH_UP,  searchForType, searchForType.testFlag(METHOD));
	}

	setTarget( resolveAmbiguity(candidateTargets) );

	resolving_ = false;
	return isResolved();
}

OOReference::ReferenceTargetKind OOReference::referenceTargetKind()
{
	auto parentRefExpr = static_cast<ReferenceExpression*>(this->parent());
	auto construct = parentRefExpr->parent();

	if (auto refExpr = DCast<ReferenceExpression>(construct))
	{
		// If this reference appears before a '.' operator, it must be a container
		if (parentRefExpr == refExpr->prefix()) return ReferenceTargetKind::Container;
	}
	else if (auto vd = DCast<VariableDeclaration>(construct))
	{
		if (parentRefExpr == vd->typeExpression()) return ReferenceTargetKind::Type;
	}
	else if (auto fr = DCast<FormalResult>(construct))
	{
		if (parentRefExpr == fr->typeExpression()) return ReferenceTargetKind::Type;
	}
	else if (auto fa = DCast<FormalArgument>(construct))
	{
		if (parentRefExpr == fa->typeExpression()) return ReferenceTargetKind::Type;
	}
	else if (auto ate = DCast<ArrayTypeExpression>(construct))
	{
		if (parentRefExpr == ate->typeExpression()) return ReferenceTargetKind::Type;
	}
	else if (auto ce = DCast<CastExpression>(construct))
	{
		if (parentRefExpr == ce->castType()) return ReferenceTargetKind::Type;
	}
	else if (auto cte = DCast<ClassTypeExpression>(construct))
	{
		if (parentRefExpr == cte->typeExpression()) return ReferenceTargetKind::Type;
	}
	else if (auto mce = DCast<MethodCallExpression>(construct))
	{
		if (parentRefExpr == mce->callee()) return ReferenceTargetKind::Callable;
	}
	else if (auto ae = DCast<AssignmentExpression>(construct))
	{
		if (parentRefExpr == ae->left()) return ReferenceTargetKind::Assignable;
	}
	else if (auto el = DCast<Model::TypedList<Expression>>(construct))
	{
		if (auto cl = DCast<Class>(el->parent()))
		{
			if (el == cl->baseClasses()) return ReferenceTargetKind::Container;
		}
		else if (auto refExpr = DCast<ReferenceExpression>(el->parent()))
		{
			if (el == refExpr->typeArguments()) return ReferenceTargetKind::Container;
		}
	}

	return ReferenceTargetKind::Unknown;
}

Model::Node* OOReference::resolveAmbiguity(QSet<Model::Node*>& candidates)
{
	if ( candidates.isEmpty() ) return nullptr;
	if ( candidates.size() == 1) return *candidates.begin(); // TODO: possibly check this for compliance?

	auto parentRefExpr = static_cast<ReferenceExpression*>(this->parent());
	auto construct = parentRefExpr->parent();

	// Looking for Methods
	if (auto mce = DCast<MethodCallExpression>(construct))
	{
		auto methodToCall = resolveAmbiguousMethodCall(candidates, mce);
		if (methodToCall) return methodToCall;
	}

	// Looking for Types, remove variables, fields, etc
	if (referenceTargetKind() == ReferenceTargetKind::Type)
	{
		auto it = candidates.begin();
		while (it != candidates.end())
		{
			if ( DCast<VariableDeclaration>(*it) || DCast<FormalArgument>(*it) || DCast<FormalArgument>(*it))
				it = candidates.erase(it);
			else ++it;
		}
	}
	if (candidates.size() == 1) return *candidates.begin();

	// Looking for Assignables, remove methods, classes, etc
	if (referenceTargetKind() == ReferenceTargetKind::Assignable)
	{
		auto it = candidates.begin();
		while (it != candidates.end())
		{
			if ( DCast<VariableDeclaration>(*it) || DCast<FormalArgument>(*it) || DCast<FormalArgument>(*it))
				++it = candidates.erase(it);
			else it = candidates.erase(it);
		}
	}
	if (candidates.size() == 1) return *candidates.begin();

	//TODO: Resolve additional ambiguities
	return nullptr;
}

Model::Node* OOReference::resolveAmbiguousMethodCall(QSet<Model::Node*>& candidates,
		MethodCallExpression* callExpression)
{
	// TODO: So far this implements only the simpler cases of Java. Complex cases or other languages need to be
	// considered.

	QSet<Method*> filtered;

	// Get all methods and forget about the rest.
	for(auto target : candidates)
		if (auto method = DCast<Method>(target))
			filtered.insert(method);
	if (filtered.size() == 1) return *filtered.begin();
	if (filtered.isEmpty()) return nullptr;

	removeMethodsWithDifferentNumberOfArguments(filtered, callExpression);
	if (filtered.size() == 1) return *filtered.begin();
	if (filtered.isEmpty()) return nullptr;

	removeMethodsWithIncompatibleTypeOfArguments(filtered, callExpression);
	if (filtered.size() == 1) return *filtered.begin();
	if (filtered.isEmpty()) return nullptr;

	removeOverridenMethods(filtered);
	if (filtered.size() == 1) return *filtered.begin();
	if (filtered.isEmpty()) return nullptr;

	removeLessSpecificMethods(filtered);
	if (filtered.size() == 1) return *filtered.begin();

	candidates.clear();
	for(auto m : filtered) candidates.insert(m);
	//TODO: check for correct access of public/private

	return nullptr;
}

void OOReference::removeMethodsWithDifferentNumberOfArguments(QSet<Method*>& methods,
		MethodCallExpression* callExpression)
{
	auto callee = static_cast<ReferenceExpression*>(callExpression->callee());

	// Exclude methods with less type arguments or unequal number of formal arguments
	// TODO: Consider default method arguments and variable method arity.
	auto it = methods.begin();
	while(it != methods.end())
	{
		if ((*it)->typeArguments()->size() < callee->typeArguments()->size()
				|| callExpression->arguments()->size() != (*it)->arguments()->size())
			it = methods.erase(it);
		else ++ it;
	}
}

void OOReference::removeMethodsWithIncompatibleTypeOfArguments(QSet<Method*>& methods,
		MethodCallExpression* callExpression)
{
	int argId = 0;
	for(auto arg: *callExpression->arguments())
	{
		auto actualArgType = arg->type();

		auto it = methods.begin();
		while(it != methods.end())
		{
			auto formalArgType = (*it)->arguments()->at(argId)->typeExpression()->type();

			auto typeRelation = actualArgType->relationTo(formalArgType);
			if ( typeRelation.testFlag(TypeSystem::Equal) || typeRelation.testFlag(TypeSystem::IsSubtype)
					|| typeRelation.testFlag(TypeSystem::IsConvertibleTo))
				++it;
			else it = methods.erase(it);

			SAFE_DELETE(formalArgType);
		}

		SAFE_DELETE(actualArgType);
		++argId;
	}
}

void OOReference::removeOverridenMethods(QSet<Method*>& methods)
{
	QSet<Method*> nonOverriden;
	while (!methods.isEmpty())
	{
		auto m = *methods.begin();
		methods.remove(m);

		bool overriden = false;
		auto it = methods.begin();
		while (it != methods.end())
		{
			if ((*it)->overrides(m))
			{
				overriden = true;
				break;
			}

			if (m->overrides((*it))) it = methods.erase(it);
			else ++it;
		}

		if (!overriden) nonOverriden.insert(m);
	}
	methods = nonOverriden;
}

void OOReference::removeLessSpecificMethods(QSet<Method*>& methods)
{
	QSet<Method*> mostSpecific;
	while(!methods.isEmpty())
	{
		enum Specificity {UNDETERMINED, MORE, LESS, SAME};
		Specificity overallSpecificity = UNDETERMINED;
		auto m = *methods.begin();
		methods.remove(m);

		QList<Type*> filteredTypes;
		for (auto te : *m->arguments()) filteredTypes.append(te->typeExpression()->type());

		// Compare this method to all the ones that are already most specifc.
		// Remove any most specific method that is strictly less specific than the current one.
		auto sIt = mostSpecific.begin();
		while(sIt != mostSpecific.end())
		{
			Specificity specificity = UNDETERMINED;
			for(int argId = 0; argId < filteredTypes.size(); ++argId)
			{
				auto spType = (*sIt)->arguments()->at(argId)->typeExpression()->type();
				auto relation = filteredTypes.at(argId)->relationTo(spType);

				if (relation.testFlag(TypeSystem::Equal)) /* Do nothing*/;
				else if (relation.testFlag(TypeSystem::IsSubtype) && specificity == UNDETERMINED) specificity = MORE;
				else if (relation.testFlag(TypeSystem::IsSubtype) && specificity == MORE) /* Do nothing*/;
				else if (relation.testFlag(TypeSystem::IsSubtype) && specificity == LESS) specificity = SAME;
				else if (relation.testFlag(TypeSystem::IsSupertype) && specificity == UNDETERMINED) specificity = LESS;
				else if (relation.testFlag(TypeSystem::IsSupertype) && specificity == LESS) /* Do nothing*/;
				else if (relation.testFlag(TypeSystem::IsSupertype) && specificity == MORE) specificity = SAME;

				SAFE_DELETE(spType);

				if (specificity == SAME) break;
			}

			if (specificity == MORE)
			{
				sIt = mostSpecific.erase(sIt);
				Q_ASSERT(overallSpecificity != LESS);
				if(overallSpecificity == UNDETERMINED) overallSpecificity = MORE;
			}
			else if (specificity == LESS)
			{
				Q_ASSERT(overallSpecificity != MORE);
				overallSpecificity = LESS;
				break;
			}
			else if (specificity == SAME || specificity == UNDETERMINED)
			{
				// UNDETERMINED means an identical or a completely unrelated signature
				++sIt;
				overallSpecificity = SAME;
			}
		}

		for(auto t : filteredTypes) SAFE_DELETE(t);

		Q_ASSERT(mostSpecific.isEmpty() || overallSpecificity != UNDETERMINED);
		if (overallSpecificity != LESS) mostSpecific.insert(m);
	}
	methods = mostSpecific;
	Q_ASSERT(!methods.isEmpty());
}

} /* namespace OOModel */
<commit_msg>Fix an embarrassing copy/paste bug that makes reference resolution crash<commit_after>/***********************************************************************************************************************
 **
 ** Copyright (c) 2011, 2013 ETH Zurich
 ** All rights reserved.
 **
 ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
 ** following conditions are met:
 **
 **    * Redistributions of source code must retain the above copyright notice, this list of conditions and the
 **      following disclaimer.
 **    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
 **      following disclaimer in the documentation and/or other materials provided with the distribution.
 **    * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
 **      derived from this software without specific prior written permission.
 **
 **
 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 **
 **********************************************************************************************************************/

#include "OOReference.h"
#include "../expressions/ReferenceExpression.h"
#include "../declarations/Class.h"
#include "../declarations/Method.h"
#include "../expressions/types/ClassTypeExpression.h"
#include "../expressions/types/ArrayTypeExpression.h"
#include "../expressions/MethodCallExpression.h"
#include "../expressions/AssignmentExpression.h"
#include "../expressions/CastExpression.h"

#include "../types/SymbolProviderType.h"
#include "../types/ErrorType.h"
#include "../typesystem/TypeSystem.h"

#include "ModelBase/src/nodes/TypedListDefinition.h"
DEFINE_TYPED_LIST(OOModel::OOReference)

namespace OOModel {

NODE_DEFINE_EMPTY_CONSTRUCTORS(OOReference)
NODE_DEFINE_TYPE_REGISTRATION_METHODS(OOReference)

bool OOReference::resolve()
{
	// TODO Handle the case where the symbol is defined multiple times in a better way

	// TODO this is not multithread friendly.
	if (resolving_) return false;
	resolving_ = true;

	auto parent = static_cast<ReferenceExpression*>(this->parent());

	SymbolTypes searchForType = ANY_SYMBOL;
	if ( referenceTargetKind() != ReferenceTargetKind::Callable ) searchForType &= ~METHOD;

	QSet<Node*> candidateTargets;
	if (parent->prefix())
	{
		// Perform a downward search starting from the target of the prefix
		auto t = parent->prefix()->type();
		if (auto sp = dynamic_cast<SymbolProviderType*>(t))
		{
			if (sp->symbolProvider())
			{
				// It's important below that we change the source to sp->symbolProvider() in the call to findSymbols.
				// See NameImport.cpp for more info.

				sp->symbolProvider()->findSymbols(candidateTargets, name(), sp->symbolProvider(), SEARCH_DOWN,
						searchForType, searchForType.testFlag(METHOD) ); 	// When search for methods do an exhaustive search.
																							// This is important for overloads.
			}
		}
		SAFE_DELETE(t);
	}
	else
	{
		// Perform an upward search starting from the current node
		// When search for methods do an exhaustive search. This is important for overloads.
		findSymbols(candidateTargets, name(), this, SEARCH_UP,  searchForType, searchForType.testFlag(METHOD));
	}

	setTarget( resolveAmbiguity(candidateTargets) );

	resolving_ = false;
	return isResolved();
}

OOReference::ReferenceTargetKind OOReference::referenceTargetKind()
{
	auto parentRefExpr = static_cast<ReferenceExpression*>(this->parent());
	auto construct = parentRefExpr->parent();

	if (auto refExpr = DCast<ReferenceExpression>(construct))
	{
		// If this reference appears before a '.' operator, it must be a container
		if (parentRefExpr == refExpr->prefix()) return ReferenceTargetKind::Container;
	}
	else if (auto vd = DCast<VariableDeclaration>(construct))
	{
		if (parentRefExpr == vd->typeExpression()) return ReferenceTargetKind::Type;
	}
	else if (auto fr = DCast<FormalResult>(construct))
	{
		if (parentRefExpr == fr->typeExpression()) return ReferenceTargetKind::Type;
	}
	else if (auto fa = DCast<FormalArgument>(construct))
	{
		if (parentRefExpr == fa->typeExpression()) return ReferenceTargetKind::Type;
	}
	else if (auto ate = DCast<ArrayTypeExpression>(construct))
	{
		if (parentRefExpr == ate->typeExpression()) return ReferenceTargetKind::Type;
	}
	else if (auto ce = DCast<CastExpression>(construct))
	{
		if (parentRefExpr == ce->castType()) return ReferenceTargetKind::Type;
	}
	else if (auto cte = DCast<ClassTypeExpression>(construct))
	{
		if (parentRefExpr == cte->typeExpression()) return ReferenceTargetKind::Type;
	}
	else if (auto mce = DCast<MethodCallExpression>(construct))
	{
		if (parentRefExpr == mce->callee()) return ReferenceTargetKind::Callable;
	}
	else if (auto ae = DCast<AssignmentExpression>(construct))
	{
		if (parentRefExpr == ae->left()) return ReferenceTargetKind::Assignable;
	}
	else if (auto el = DCast<Model::TypedList<Expression>>(construct))
	{
		if (auto cl = DCast<Class>(el->parent()))
		{
			if (el == cl->baseClasses()) return ReferenceTargetKind::Container;
		}
		else if (auto refExpr = DCast<ReferenceExpression>(el->parent()))
		{
			if (el == refExpr->typeArguments()) return ReferenceTargetKind::Container;
		}
	}

	return ReferenceTargetKind::Unknown;
}

Model::Node* OOReference::resolveAmbiguity(QSet<Model::Node*>& candidates)
{
	if ( candidates.isEmpty() ) return nullptr;
	if ( candidates.size() == 1) return *candidates.begin(); // TODO: possibly check this for compliance?

	auto parentRefExpr = static_cast<ReferenceExpression*>(this->parent());
	auto construct = parentRefExpr->parent();

	// Looking for Methods
	if (auto mce = DCast<MethodCallExpression>(construct))
	{
		auto methodToCall = resolveAmbiguousMethodCall(candidates, mce);
		if (methodToCall) return methodToCall;
	}

	// Looking for Types, remove variables, fields, etc
	if (referenceTargetKind() == ReferenceTargetKind::Type)
	{
		auto it = candidates.begin();
		while (it != candidates.end())
		{
			if ( DCast<VariableDeclaration>(*it) || DCast<FormalArgument>(*it) || DCast<FormalArgument>(*it))
				it = candidates.erase(it);
			else ++it;
		}
	}
	if (candidates.size() == 1) return *candidates.begin();

	// Looking for Assignables, remove methods, classes, etc
	if (referenceTargetKind() == ReferenceTargetKind::Assignable)
	{
		auto it = candidates.begin();
		while (it != candidates.end())
		{
			if ( DCast<VariableDeclaration>(*it) || DCast<FormalArgument>(*it) || DCast<FormalArgument>(*it))
				++it;
			else it = candidates.erase(it);
		}
	}
	if (candidates.size() == 1) return *candidates.begin();

	//TODO: Resolve additional ambiguities
	return nullptr;
}

Model::Node* OOReference::resolveAmbiguousMethodCall(QSet<Model::Node*>& candidates,
		MethodCallExpression* callExpression)
{
	// TODO: So far this implements only the simpler cases of Java. Complex cases or other languages need to be
	// considered.

	QSet<Method*> filtered;

	// Get all methods and forget about the rest.
	for(auto target : candidates)
		if (auto method = DCast<Method>(target))
			filtered.insert(method);
	if (filtered.size() == 1) return *filtered.begin();
	if (filtered.isEmpty()) return nullptr;

	removeMethodsWithDifferentNumberOfArguments(filtered, callExpression);
	if (filtered.size() == 1) return *filtered.begin();
	if (filtered.isEmpty()) return nullptr;

	removeMethodsWithIncompatibleTypeOfArguments(filtered, callExpression);
	if (filtered.size() == 1) return *filtered.begin();
	if (filtered.isEmpty()) return nullptr;

	removeOverridenMethods(filtered);
	if (filtered.size() == 1) return *filtered.begin();
	if (filtered.isEmpty()) return nullptr;

	removeLessSpecificMethods(filtered);
	if (filtered.size() == 1) return *filtered.begin();

	candidates.clear();
	for(auto m : filtered) candidates.insert(m);
	//TODO: check for correct access of public/private

	return nullptr;
}

void OOReference::removeMethodsWithDifferentNumberOfArguments(QSet<Method*>& methods,
		MethodCallExpression* callExpression)
{
	auto callee = static_cast<ReferenceExpression*>(callExpression->callee());

	// Exclude methods with less type arguments or unequal number of formal arguments
	// TODO: Consider default method arguments and variable method arity.
	auto it = methods.begin();
	while(it != methods.end())
	{
		if ((*it)->typeArguments()->size() < callee->typeArguments()->size()
				|| callExpression->arguments()->size() != (*it)->arguments()->size())
			it = methods.erase(it);
		else ++ it;
	}
}

void OOReference::removeMethodsWithIncompatibleTypeOfArguments(QSet<Method*>& methods,
		MethodCallExpression* callExpression)
{
	int argId = 0;
	for(auto arg: *callExpression->arguments())
	{
		auto actualArgType = arg->type();

		auto it = methods.begin();
		while(it != methods.end())
		{
			auto formalArgType = (*it)->arguments()->at(argId)->typeExpression()->type();

			auto typeRelation = actualArgType->relationTo(formalArgType);
			if ( typeRelation.testFlag(TypeSystem::Equal) || typeRelation.testFlag(TypeSystem::IsSubtype)
					|| typeRelation.testFlag(TypeSystem::IsConvertibleTo))
				++it;
			else it = methods.erase(it);

			SAFE_DELETE(formalArgType);
		}

		SAFE_DELETE(actualArgType);
		++argId;
	}
}

void OOReference::removeOverridenMethods(QSet<Method*>& methods)
{
	QSet<Method*> nonOverriden;
	while (!methods.isEmpty())
	{
		auto m = *methods.begin();
		methods.remove(m);

		bool overriden = false;
		auto it = methods.begin();
		while (it != methods.end())
		{
			if ((*it)->overrides(m))
			{
				overriden = true;
				break;
			}

			if (m->overrides((*it))) it = methods.erase(it);
			else ++it;
		}

		if (!overriden) nonOverriden.insert(m);
	}
	methods = nonOverriden;
}

void OOReference::removeLessSpecificMethods(QSet<Method*>& methods)
{
	QSet<Method*> mostSpecific;
	while(!methods.isEmpty())
	{
		enum Specificity {UNDETERMINED, MORE, LESS, SAME};
		Specificity overallSpecificity = UNDETERMINED;
		auto m = *methods.begin();
		methods.remove(m);

		QList<Type*> filteredTypes;
		for (auto te : *m->arguments()) filteredTypes.append(te->typeExpression()->type());

		// Compare this method to all the ones that are already most specifc.
		// Remove any most specific method that is strictly less specific than the current one.
		auto sIt = mostSpecific.begin();
		while(sIt != mostSpecific.end())
		{
			Specificity specificity = UNDETERMINED;
			for(int argId = 0; argId < filteredTypes.size(); ++argId)
			{
				auto spType = (*sIt)->arguments()->at(argId)->typeExpression()->type();
				auto relation = filteredTypes.at(argId)->relationTo(spType);

				if (relation.testFlag(TypeSystem::Equal)) /* Do nothing*/;
				else if (relation.testFlag(TypeSystem::IsSubtype) && specificity == UNDETERMINED) specificity = MORE;
				else if (relation.testFlag(TypeSystem::IsSubtype) && specificity == MORE) /* Do nothing*/;
				else if (relation.testFlag(TypeSystem::IsSubtype) && specificity == LESS) specificity = SAME;
				else if (relation.testFlag(TypeSystem::IsSupertype) && specificity == UNDETERMINED) specificity = LESS;
				else if (relation.testFlag(TypeSystem::IsSupertype) && specificity == LESS) /* Do nothing*/;
				else if (relation.testFlag(TypeSystem::IsSupertype) && specificity == MORE) specificity = SAME;

				SAFE_DELETE(spType);

				if (specificity == SAME) break;
			}

			if (specificity == MORE)
			{
				sIt = mostSpecific.erase(sIt);
				Q_ASSERT(overallSpecificity != LESS);
				if(overallSpecificity == UNDETERMINED) overallSpecificity = MORE;
			}
			else if (specificity == LESS)
			{
				Q_ASSERT(overallSpecificity != MORE);
				overallSpecificity = LESS;
				break;
			}
			else if (specificity == SAME || specificity == UNDETERMINED)
			{
				// UNDETERMINED means an identical or a completely unrelated signature
				++sIt;
				overallSpecificity = SAME;
			}
		}

		for(auto t : filteredTypes) SAFE_DELETE(t);

		Q_ASSERT(mostSpecific.isEmpty() || overallSpecificity != UNDETERMINED);
		if (overallSpecificity != LESS) mostSpecific.insert(m);
	}
	methods = mostSpecific;
	Q_ASSERT(!methods.isEmpty());
}

} /* namespace OOModel */
<|endoftext|>


<commit_before>#include <stdlib.h>
#include <fstream>
#include <iostream>
#include <string>
#include <map>
#include <vector>
using namespace std;

char HSH = '#';
string LEN = "len:";
int SEG_LEN;
string ITER = "iter:";
string ROT = "rot:";
string REP = "rep:";
string START = "start:";
// +(theta) turn left by angle theta
char PLS = '+';
// -(theta) turn right by angle theta
char MIN = '-';
// &(theta) pitch down by angle theta
char AMP = '&';
// ^(theta) pitch up by angle theta
char NCH = '^';
// /(theta) roll left by angle theta
char FSL = '/';
// \(theta) roll right by angle theta
char BSL = '\\';
// | is equivalent to +(180) -(180)
char VER = '|';

//couldn't get atoi or stoi to work for me
int ctoi (char c) {
    int i;
    if (c == '1'){
        i = 1;
    } else if (c == '2') {
        i = 2;
    } else if (c == '3') {
        i = 3;
    } else if (c == '4') {
        i = 4;
    } else if (c == '5') {
        i = 5;
    } else if (c == '6') {
        i = 6;
    } else if (c == '7') {
        i = 7;
    } else if (c == '8') {
        i = 8;
    } else if (c == '9') {
        i = 9;
    } else {
        i = -1; //not an int
    }
    return i;
}

void process_line ( string l ) {
    string t; //temp
    int d_pos;
    int d_len;
    int l_length = l.length();
    cout << "l_length = " << l_length << endl;
    string l_sub4 = l.substr(0, 4);
    cout << "l_sub4 = " << l_sub4 << endl;
    if (l[0] == HSH) {
        cout << "comment" << endl;
        return; //ignore comment
    } else if (l_sub4.compare (LEN) == 0) {
        cout << "length" << endl;
        d_pos = 5;
        d_len = l_length - d_pos;
        cout << "d_len = " << d_len << endl;
        if (d_len == 1){
            SEG_LEN = ctoi(l[d_pos]);
        }
        cout << "SEG_LEN = " << SEG_LEN << endl;
        return;
    } else if (l.substr(0, 5).compare (ITER) == 0) {
        cout << "iter" << endl;
        return;
    } else if (l_sub4.compare (ROT) == 0) {
        cout << "rot" << endl;
        return;
    } else if (l_sub4.compare (REP) == 0) {
        cout << "rep" << endl;
        return;
    } else if (l.substr(0, 6).compare (START) == 0 ) {
        cout << "start" << endl;
        return;
    } else {
        //cout << l[i] << endl;
    }
}//process_line

int main ( ) {
    string line;
    string filename = "test/lsys1";
    filename = filename + ".txt";
    cout << filename << endl;
    ifstream in (filename.c_str());
    if (in.is_open ( ) ) {
        cout << "File is open" << endl;
        while(in.good ( ) ) {
            getline (in, line);
            process_line (line);
        }
    } else {
        cout << "The file couldn't open" << endl;
    }
}
<commit_msg>implemented process_line()<commit_after>#include <stdlib.h>
#include <fstream>
#include <iostream>
#include <string>
#include <map>
#include <vector>
using namespace std;

bool start;

char HSH = '#';
char SPACE = ' ';
string LEN = "len:";
int SEG_LEN;
string ITER = "iter:";
int ITERATIONS;
string ROT = "rot:";
vector<float> ROTATIONS;
string REP = "rep:";
string START = "start:";
//"initial turtle string"
string INIT_STR;
// +(theta) turn left by angle theta
char PLS = '+';
// -(theta) turn right by angle theta
char MIN = '-';
// &(theta) pitch down by angle theta
char AMP = '&';
// ^(theta) pitch up by angle theta
char NCH = '^';
// /(theta) roll left by angle theta
char FSL = '/';
// \(theta) roll right by angle theta
char BSL = '\\';
// | is equivalent to +(180) -(180)
char VER = '|';

void process_line ( string l ) {
    if (start) {
        execute(l);
    }

    string t; //temp
    int d_pos;
    int d_len;
    int l_length = l.length( );
    cout << "l_length = " << l_length << endl;
    string l_sub4 = l.substr(0, 4);
    cout << "l_sub4 = " << l_sub4 << endl;
    if (l[0] == HSH) {
        cout << "comment" << endl;
        return; //ignore comment
    } else if (l_sub4.compare(LEN) == 0) {
        cout << "length" << endl;
        d_pos = 5;
        d_len = l_length - d_pos;
        t = l.substr(d_pos, d_len);
        sscanf(t.c_str( ), "%d", &SEG_LEN);
        cout << "SEG_LEN = " <<  SEG_LEN << endl;
        return;
    } else if (l.substr(0, 5).compare (ITER) == 0) {
        cout << "iter" << endl;
        d_pos = 6;
        d_len = l_length - d_pos;
        t = l.substr(d_pos, d_len);
        sscanf(t.c_str( ), "%d", &ITERATIONS);
        cout << "ITERATIONS = " << ITERATIONS << endl;
        return;
    } else if (l_sub4.compare (ROT) == 0) {
        d_pos = 5;
        d_len = l_length - d_pos;
        t = l.substr(d_pos, d_len);
        int count = 0;
        double  current;
        string c = "";
        for (int i = 0; i < t.length(); i++){
            if (t[i] == SPACE) {
                current = ::atof(c.c_str( ));
                cout << "ROT current = " << current << endl;
                ROTATIONS.push_back(current);
                count = 0;
                c = "";
            } else {
                c += t[count++];
            }//if/else
        }//for
        //remove below and turn into while loop for opti
        current = ::atof(c.c_str( ));
        cout << "ROT current = " << current << endl;
        ROTATIONS.push_back(current);
        return;
    } else if (l_sub4.compare (REP) == 0) {
        cout << "rep" << endl;
        return;
    } else if (l.substr(0, 6).compare (START) == 0 ) {
        d_pos = 7;
        d_len = l_length - d_pos;
        INIT_STR = l.substr(d_pos, d_len);
        cout << "INIT_STR = " << INIT_STR << endl;
        start = true;
        return;
    } else {
        //cout << l[i] << endl;
    }//if/else
}//process_line

int main ( ) {
    string line;
    string filename = "test/lsys1";
    filename = filename + ".txt";
    cout << filename << endl;
    ifstream in (filename.c_str());
    if (in.is_open ( ) ) {
        cout << "File is open" << endl;
        start = false;
        while(in.good ( ) ) {
            getline (in, line);
            process_line (line);
        }
    } else {
        cout << "The file couldn't open" << endl;
    }
}
<|endoftext|>