<commit_before>/*
Copyright (C) Gbor "Razzie" Grzsny

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE
*/

#pragma once

#include <iosfwd>
#include <locale>
#include <sstream>
#include <stdexcept>
#include <string>
#include <type_traits>

namespace raz
{
	template<class To, class From>
	To lexical_cast(const From& from)
	{
		To to;
		std::sstream ss;
		ss << from;
		ss >> to;
		return to;
	}

	template<class T>
	class StreamManipulator
	{
	public:
		typedef std::ios&(*Manipulator)(std::ios&, T);

		explicit StreamManipulator(Manipulator m, T t) :
			m_manip(m), m_value(t)
		{
		}

		friend std::ios& operator<< (std::ios& io, const StreamManipulator<T>& m)
		{
			return m.m_manip(io, m.m_value);
		}

	private:
		Manipulator m_manip;
		T m_value;
	};

	template<class T>
	class IstreamManipulator
	{
	public:
		typedef std::istream&(*Manipulator)(std::istream&, T);

		explicit IstreamManipulator(Manipulator m, T t) :
			m_manip(m), m_value(t)
		{
		}

		friend std::istream& operator<< (std::istream& io, const IstreamManipulator<T>& m)
		{
			return m.m_manip(io, m.m_value);
		}

	private:
		Manipulator m_manip;
		T m_value;
	};

	template<class T>
	class OstreamManipulator
	{
	public:
		typedef std::ostream&(*Manipulator)(std::ostream&, T);

		explicit OstreamManipulator(Manipulator m, T t) :
			m_manip(m), m_value(t)
		{
		}

		friend std::ostream& operator<< (std::ostream& io, const OstreamManipulator<T>& m)
		{
			return m.m_manip(io, m.m_value);
		}

	private:
		Manipulator m_manip;
		T m_value;
	};

	template<class T>
	OstreamManipulator<T> hex(T t)
	{
		OstreamManipulator<T>::Manipulator m =
			[](std::ostream& o, T t) -> std::ostream&
			{
				const char map[] = "0123456789abcdef";
				const unsigned char* ptr = reinterpret_cast<const unsigned char*>(&t);
				for (size_t i = 0; i < sizeof(T); ++i)
				{
					unsigned first = ptr[i] / 16;
					unsigned second = ptr[i] - (first * 16);
					o << map[first] << map[second];
				}
				return o;
			};

		return OstreamManipulator<T>(m, t);
	}

	inline OstreamManipulator<const char*> format(const char* f)
	{
		OstreamManipulator<const char*>::Manipulator m =
			[](std::ostream& os, const char* fmt) -> std::ostream&
			{
				std::locale& loc = os.getloc();
				int i = 0;
				while (fmt[i] != 0)
				{
					if (fmt[i] != '%')
					{
						os << fmt[i];
						i++;
					}
					else
					{
						i++;
						if (fmt[i] == '%')
						{
							os << fmt[i];
							i++;
						}
						else
						{
							bool ok = true;
							int istart = i;
							bool more = true;
							int width = 0;
							int precision = 6;
							std::ios_base::fmtflags flags;
							char fill = ' ';
							bool alternate = false;
							while (more)
							{
								switch (fmt[i])
								{
								case '+':
									flags |= std::ios::showpos;
									break;
								case '-':
									flags |= std::ios::left;
									break;
								case '0':
									flags |= std::ios::internal;
									fill = '0';
									break;
								case '#':
									alternate = true;
									break;
								case ' ':
									break;
								default:
									more = false;
									break;
								}
								if (more) i++;
							}
							if (std::isdigit(fmt[i], loc))
							{
								width = std::atoi(fmt + i);
								do i++;
								while (std::isdigit(fmt[i], loc));
							}
							if (fmt[i] == '.')
							{
								i++;
								precision = std::atoi(fmt + i);
								while (std::isdigit(fmt[i], loc)) i++;
							}
							switch (fmt[i])
							{
							case 'd':
								flags |= std::ios::dec;
								break;
							case 'x':
								flags |= std::ios::hex;
								if (alternate) flags |= std::ios::showbase;
								break;
							case 'X':
								flags |= std::ios::hex | std::ios::uppercase;
								if (alternate) flags |= std::ios::showbase;
								break;
							case 'o':
								flags |= std::ios::hex;
								if (alternate) flags |= std::ios::showbase;
								break;
							case 'f':
								flags |= std::ios::fixed;
								if (alternate) flags |= std::ios::showpoint;
								break;
							case 'e':
								flags |= std::ios::scientific;
								if (alternate) flags |= std::ios::showpoint;
								break;
							case 'E':
								flags |= std::ios::scientific | std::ios::uppercase;
								if (alternate) flags |= std::ios::showpoint;
								break;
							case 'g':
								if (alternate) flags |= std::ios::showpoint;
								break;
							case 'G':
								flags |= std::ios::uppercase;
								if (alternate) flags |= std::ios::showpoint;
								break;
							default:
								ok = false;
								break;
							}
							i++;
							if (fmt[i] != 0) ok = false;
							if (ok)
							{
								os.unsetf(std::ios::adjustfield | std::ios::basefield |
									std::ios::floatfield);
								os.setf(flags);
								os.width(width);
								os.precision(precision);
								os.fill(fill);
							}
							else i = istart;
						}
					}
				}
				return os;
			};

		return OstreamManipulator<const char*>(m, f);
	}

	inline IstreamManipulator<char> delimiter(char d)
	{
		struct CustomLocale : std::ctype<char>
		{
			std::ctype_base::mask m_rc[table_size];

			CustomLocale(char delim) :
				std::ctype<char>(get_table(static_cast<unsigned char>(delim)))
			{
			}

			const std::ctype_base::mask* get_table(unsigned char delim)
			{
				memset(m_rc, 0, sizeof(std::ctype_base::mask) * table_size);
				m_rc[delim] = std::ctype_base::space;
				m_rc['\n'] = std::ctype_base::space;
				return &m_rc[0];
			}
		};

		IstreamManipulator<char>::Manipulator m =
			[](std::istream& i, char d) -> std::istream&
			{
				i.imbue(std::locale(i.getloc(), new CustomLocale(d)));
				return i;
			};

		return IstreamManipulator<char>(m, d);
	}

	inline IstreamManipulator<char> next(char d)
	{
		IstreamManipulator<char>::Manipulator m =
			[](std::istream& i, char d) -> std::istream&
			{
#pragma push_macro("__raz")
#undef max
				i.ignore(std::numeric_limits<std::streamsize>::max(), d);
#pragma pop_macro("__raz")
				return i;
			};

		return IstreamManipulator<char>(m, d);
	}

	inline std::istream& nextLine(std::istream& i)
	{
		return (i << next('\n'));
	}

	template<class Param>
	std::tuple<Param> parse(std::istream& i, char* d = nullptr)
	{
		Param p;
		if (d) i << delimiter(*d);
		if (!static_cast<bool>(i >> extract(p)))
			throw std::logic_error("parse error: " + typeid(Param).name());
		return std::tuple<Param> { p };
	}

	template<class Param1, class Param2, class... Params>
	std::tuple<Param1, Param2, Params...> parse(std::istream& i, char* d = nullptr)
	{
		if (d) i << delimiter(*d);
		auto a = parse<Param1>(i);
		auto b = parse<Param2, Params...>(i);
		return std::tuple_cat(a, b);
	}

	template<class... Params>
	std::tuple<Params...> parse(std::string str, char* d = nullptr)
	{
		std::stringstream ss(str);
		if (d) ss << delimiter(*d);
		return parse<Params...>(ss);
	}

	namespace __fallback
	{
		struct Dummy {};

		template<class T>
		Dummy operator<< (std::ostream&, const T&);

		template<class T>
		Dummy operator>> (std::istream&, T&);
	}

	template<class T>
	class HasStreamInserter
	{
		static std::true_type  test(std::ostream&);
		static std::false_type test(...);

		static std::ostream &s;
		static std::remove_reference_t<T>& t;

		static constexpr bool check()
		{
			using namespace __fallback;
			return decltype(test(s << t))::value;
		}

	public:
		static bool const value = check();
	};

	template<class T>
	class HasStreamExtractor
	{
		static std::true_type  test(std::istream&);
		static std::false_type test(...);

		static std::istream &s;
		static std::remove_reference_t<T>& t;

		static constexpr bool check()
		{
			using namespace __fallback;
			return decltype(test(s >> t))::value;
		}

	public:
		static const bool value = check();
	};

	template<class T>
	class StreamInsert
	{
		template<class U, bool>
		struct Insert
		{
			static std::ostream& apply(std::ostream& s, const U& value)
			{
				s << value;
				return s;
			}
		};

		template<class U>
		struct Insert<U, false>
		{
			static std::ostream& apply(std::ostream& s, const U& value)
			{
				s << typeid(T).name();
				return s;
			}
		};

	public:
		static std::ostream& apply(std::ostream& s, const T& value)
		{
			return Insert<T, HasStreamInserter<T>::value>::apply(s, value);
		}

		class Wrapper
		{
		public:
			Wrapper(const T& value) : m_value(value)
			{
			}

			friend std::ostream& operator<< (std::ostream& s, const Wrapper& w)
			{
				return apply(s, w.m_value);
			}

		private:
			const T& m_value;
		};
	};

	template<class T>
	typename StreamInsert<T>::Wrapper insert(const T& value)
	{
		return typename StreamInsert<T>::Wrapper(value);
	}

	template<class T>
	class StreamExtract
	{
		template<class U, bool>
		struct Extract
		{
			static std::istream& apply(std::istream& s, U& value)
			{
				s >> value;
				return s;
			}
		};

		// special case for std::string
		template<>
		struct Extract<std::string, true>
		{
			static std::istream& apply(std::istream& s, std::string& value)
			{
				std::getline(s, value);
				return s;
			}
		};

		template<class U>
		struct Extract<U, false>
		{
			static std::istream& apply(std::istream& s, U& value)
			{
				return s;
			}
		};

	public:
		static std::istream& apply(std::istream& s, T& value)
		{
			return Extract<T, HasStreamExtractor<T>::value>::apply(s, value);
		}

		class Wrapper
		{
		public:
			Wrapper(T& value) : m_value(value)
			{
			}

			friend std::istream& operator>> (std::istream& s, Wrapper& w)
			{
				return apply(s, w.m_value);
			}

		private:
			T& m_value;
		};
	};

	template<class T>
	typename StreamExtract<T>::Wrapper extract(T& value)
	{
		return typename StreamExtract<T>::Wrapper(value);
	}
};
<commit_msg>Reworked raz::insert and raz::extract stream helpers<commit_after>/*
Copyright (C) Gbor "Razzie" Grzsny

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE
*/

#pragma once

#include <iosfwd>
#include <locale>
#include <sstream>
#include <stdexcept>
#include <string>
#include <type_traits>

namespace raz
{
	template<class T>
	class HasStreamInserter
	{
		template<class U>
		static constexpr auto test() -> decltype(bool(std::declval<std::ostream&>() << std::declval<const U&>()))
		{
			return true;
		}

		template<class U>
		static constexpr bool test(...)
		{
			return false;
		}

	public:
		constexpr static bool value = test<T>();
	};

	template<class T>
	class HasStreamExtractor
	{
		template<class U>
		static constexpr auto test() -> decltype(bool(std::declval<std::ostream&>() >> std::declval<U&>()))
		{
			return true;
		}

		template<class U>
		static constexpr bool test(...)
		{
			return false;
		}

	public:
		constexpr static bool value = test<T>();
	};

	struct __FallbackType
	{
		template<class T>
		__FallbackType(const T&) : type(&typeid(T))
		{
		}

		friend std::ostream& operator<< (std::ostream& os, const __FallbackType& t)
		{
			os << t.type->name();
			return os;
		}

		friend std::istream& operator>> (std::istream& is, __FallbackType&)
		{
			return is;
		}

		const std::type_info* type;
	};

	template<class T>
	std::conditional_t<HasStreamInserter<T>::value, const T&, __FallbackType> insert(const T& t)
	{
		return { t };
	}

	template<class T>
	std::conditional_t<HasStreamExtractor<T>::value, T&, __FallbackType> extract(T& t)
	{
		return { t };
	}

	template<class To, class From>
	To lexical_cast(const From& from)
	{
		To to;
		std::sstream ss;
		ss << from;
		ss >> to;
		return to;
	}

	template<class T>
	class StreamManipulator
	{
	public:
		typedef std::ios&(*Manipulator)(std::ios&, T);

		explicit StreamManipulator(Manipulator m, T t) :
			m_manip(m), m_value(t)
		{
		}

		friend std::ios& operator<< (std::ios& io, const StreamManipulator<T>& m)
		{
			return m.m_manip(io, m.m_value);
		}

	private:
		Manipulator m_manip;
		T m_value;
	};

	template<class T>
	class IstreamManipulator
	{
	public:
		typedef std::istream&(*Manipulator)(std::istream&, T);

		explicit IstreamManipulator(Manipulator m, T t) :
			m_manip(m), m_value(t)
		{
		}

		friend std::istream& operator<< (std::istream& io, const IstreamManipulator<T>& m)
		{
			return m.m_manip(io, m.m_value);
		}

	private:
		Manipulator m_manip;
		T m_value;
	};

	template<class T>
	class OstreamManipulator
	{
	public:
		typedef std::ostream&(*Manipulator)(std::ostream&, T);

		explicit OstreamManipulator(Manipulator m, T t) :
			m_manip(m), m_value(t)
		{
		}

		friend std::ostream& operator<< (std::ostream& io, const OstreamManipulator<T>& m)
		{
			return m.m_manip(io, m.m_value);
		}

	private:
		Manipulator m_manip;
		T m_value;
	};

	template<class T>
	OstreamManipulator<T> hex(T t)
	{
		OstreamManipulator<T>::Manipulator m =
			[](std::ostream& o, T t) -> std::ostream&
			{
				const char map[] = "0123456789abcdef";
				const unsigned char* ptr = reinterpret_cast<const unsigned char*>(&t);
				for (size_t i = 0; i < sizeof(T); ++i)
				{
					unsigned first = ptr[i] / 16;
					unsigned second = ptr[i] - (first * 16);
					o << map[first] << map[second];
				}
				return o;
			};

		return OstreamManipulator<T>(m, t);
	}

	inline OstreamManipulator<const char*> format(const char* f)
	{
		OstreamManipulator<const char*>::Manipulator m =
			[](std::ostream& os, const char* fmt) -> std::ostream&
			{
				std::locale& loc = os.getloc();
				int i = 0;
				while (fmt[i] != 0)
				{
					if (fmt[i] != '%')
					{
						os << fmt[i];
						i++;
					}
					else
					{
						i++;
						if (fmt[i] == '%')
						{
							os << fmt[i];
							i++;
						}
						else
						{
							bool ok = true;
							int istart = i;
							bool more = true;
							int width = 0;
							int precision = 6;
							std::ios_base::fmtflags flags;
							char fill = ' ';
							bool alternate = false;
							while (more)
							{
								switch (fmt[i])
								{
								case '+':
									flags |= std::ios::showpos;
									break;
								case '-':
									flags |= std::ios::left;
									break;
								case '0':
									flags |= std::ios::internal;
									fill = '0';
									break;
								case '#':
									alternate = true;
									break;
								case ' ':
									break;
								default:
									more = false;
									break;
								}
								if (more) i++;
							}
							if (std::isdigit(fmt[i], loc))
							{
								width = std::atoi(fmt + i);
								do i++;
								while (std::isdigit(fmt[i], loc));
							}
							if (fmt[i] == '.')
							{
								i++;
								precision = std::atoi(fmt + i);
								while (std::isdigit(fmt[i], loc)) i++;
							}
							switch (fmt[i])
							{
							case 'd':
								flags |= std::ios::dec;
								break;
							case 'x':
								flags |= std::ios::hex;
								if (alternate) flags |= std::ios::showbase;
								break;
							case 'X':
								flags |= std::ios::hex | std::ios::uppercase;
								if (alternate) flags |= std::ios::showbase;
								break;
							case 'o':
								flags |= std::ios::hex;
								if (alternate) flags |= std::ios::showbase;
								break;
							case 'f':
								flags |= std::ios::fixed;
								if (alternate) flags |= std::ios::showpoint;
								break;
							case 'e':
								flags |= std::ios::scientific;
								if (alternate) flags |= std::ios::showpoint;
								break;
							case 'E':
								flags |= std::ios::scientific | std::ios::uppercase;
								if (alternate) flags |= std::ios::showpoint;
								break;
							case 'g':
								if (alternate) flags |= std::ios::showpoint;
								break;
							case 'G':
								flags |= std::ios::uppercase;
								if (alternate) flags |= std::ios::showpoint;
								break;
							default:
								ok = false;
								break;
							}
							i++;
							if (fmt[i] != 0) ok = false;
							if (ok)
							{
								os.unsetf(std::ios::adjustfield | std::ios::basefield |
									std::ios::floatfield);
								os.setf(flags);
								os.width(width);
								os.precision(precision);
								os.fill(fill);
							}
							else i = istart;
						}
					}
				}
				return os;
			};

		return OstreamManipulator<const char*>(m, f);
	}

	inline IstreamManipulator<char> delimiter(char d)
	{
		struct CustomLocale : std::ctype<char>
		{
			std::ctype_base::mask m_rc[table_size];

			CustomLocale(char delim) :
				std::ctype<char>(get_table(static_cast<unsigned char>(delim)))
			{
			}

			const std::ctype_base::mask* get_table(unsigned char delim)
			{
				memset(m_rc, 0, sizeof(std::ctype_base::mask) * table_size);
				m_rc[delim] = std::ctype_base::space;
				m_rc['\n'] = std::ctype_base::space;
				return &m_rc[0];
			}
		};

		IstreamManipulator<char>::Manipulator m =
			[](std::istream& i, char d) -> std::istream&
			{
				i.imbue(std::locale(i.getloc(), new CustomLocale(d)));
				return i;
			};

		return IstreamManipulator<char>(m, d);
	}

	inline IstreamManipulator<char> next(char d)
	{
		IstreamManipulator<char>::Manipulator m =
			[](std::istream& i, char d) -> std::istream&
			{
#pragma push_macro("__raz")
#undef max
				i.ignore(std::numeric_limits<std::streamsize>::max(), d);
#pragma pop_macro("__raz")
				return i;
			};

		return IstreamManipulator<char>(m, d);
	}

	inline std::istream& nextLine(std::istream& i)
	{
		return (i << next('\n'));
	}

	template<class Param>
	std::tuple<Param> parse(std::istream& i, char* d = nullptr)
	{
		Param p;
		if (d) i << delimiter(*d);
		if (!static_cast<bool>(i >> extract(p)))
			throw std::logic_error("parse error: " + typeid(Param).name());
		return std::tuple<Param> { p };
	}

	template<class Param1, class Param2, class... Params>
	std::tuple<Param1, Param2, Params...> parse(std::istream& i, char* d = nullptr)
	{
		if (d) i << delimiter(*d);
		auto a = parse<Param1>(i);
		auto b = parse<Param2, Params...>(i);
		return std::tuple_cat(a, b);
	}

	template<class... Params>
	std::tuple<Params...> parse(std::string str, char* d = nullptr)
	{
		std::stringstream ss(str);
		if (d) ss << delimiter(*d);
		return parse<Params...>(ss);
	}
};
<|endoftext|>


<commit_before><commit_msg>VCL: final movement of text and font functions in outdev.hxx<commit_after><|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2015, Image Engine Design Inc. 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 John Haddon nor the names of
//        any other contributors to this software may be used to endorse or
//        promote products derived from this software without specific prior
//        written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "IECore/Camera.h"
#include "IECore/Light.h"
#include "IECore/ExternalProcedural.h"

#include "GafferScene/Parameters.h"

using namespace IECore;
using namespace Gaffer;
using namespace GafferScene;

IE_CORE_DEFINERUNTIMETYPED( Parameters );

size_t Parameters::g_firstPlugIndex = 0;

Parameters::Parameters( const std::string &name )
	:	SceneElementProcessor( name, Filter::NoMatch )
{
	storeIndexOfNextChild( g_firstPlugIndex );
	addChild( new CompoundDataPlug( "parameters" ) );

	// Fast pass-throughs for things we don't modify
	outPlug()->attributesPlug()->setInput( inPlug()->attributesPlug() );
	outPlug()->transformPlug()->setInput( inPlug()->transformPlug() );
	outPlug()->boundPlug()->setInput( inPlug()->boundPlug() );
}

Parameters::~Parameters()
{
}

Gaffer::CompoundDataPlug *Parameters::parametersPlug()
{
	return getChild<CompoundDataPlug>( g_firstPlugIndex );
}

const Gaffer::CompoundDataPlug *Parameters::parametersPlug() const
{
	return getChild<CompoundDataPlug>( g_firstPlugIndex );
}

void Parameters::affects( const Gaffer::Plug *input, AffectedPlugsContainer &outputs ) const
{
	SceneElementProcessor::affects( input, outputs );

	if( parametersPlug()->isAncestorOf( input ) )
	{
		outputs.push_back( outPlug()->objectPlug() );
	}
}

bool Parameters::processesObject() const
{
	return true;
}

void Parameters::hashProcessedObject( const ScenePath &path, const Gaffer::Context *context, IECore::MurmurHash &h ) const
{
	parametersPlug()->hash( h );
}

IECore::ConstObjectPtr Parameters::computeProcessedObject( const ScenePath &path, const Gaffer::Context *context, IECore::ConstObjectPtr inputObject ) const
{
	if( !parametersPlug()->children().size() )
	{
		return inputObject;
	}

	ConstObjectPtr outputObject = inputObject;
	CompoundData *outputParameters = NULL;
	switch( inputObject->typeId() )
	{
		case IECore::CameraTypeId : {
			CameraPtr camera = boost::static_pointer_cast<Camera>( inputObject->copy() );
			outputObject = camera;
			outputParameters = camera->parametersData();
			break;
		}
		case IECore::LightTypeId : {
			LightPtr light = boost::static_pointer_cast<Light>( inputObject->copy() );
			outputObject = light;
			outputParameters = light->parametersData().get();
			break;
		}
		case IECore::ExternalProceduralTypeId : {
			ExternalProceduralPtr procedural = boost::static_pointer_cast<ExternalProcedural>( inputObject->copy() );
			outputObject = procedural;
			outputParameters = procedural->parameters();
			break;
		}

		default :
			outputParameters = NULL;
	}

	if( outputParameters )
	{
		parametersPlug()->fillCompoundData( outputParameters->writable() );
	}

	return outputObject;
}
<commit_msg>made Parameters work with objects derived from Light/Camera/ExternalProcedural<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2015, Image Engine Design Inc. 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 John Haddon nor the names of
//        any other contributors to this software may be used to endorse or
//        promote products derived from this software without specific prior
//        written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "IECore/Camera.h"
#include "IECore/Light.h"
#include "IECore/ExternalProcedural.h"

#include "GafferScene/Parameters.h"

using namespace IECore;
using namespace Gaffer;
using namespace GafferScene;

IE_CORE_DEFINERUNTIMETYPED( Parameters );

size_t Parameters::g_firstPlugIndex = 0;

Parameters::Parameters( const std::string &name )
	:	SceneElementProcessor( name, Filter::NoMatch )
{
	storeIndexOfNextChild( g_firstPlugIndex );
	addChild( new CompoundDataPlug( "parameters" ) );

	// Fast pass-throughs for things we don't modify
	outPlug()->attributesPlug()->setInput( inPlug()->attributesPlug() );
	outPlug()->transformPlug()->setInput( inPlug()->transformPlug() );
	outPlug()->boundPlug()->setInput( inPlug()->boundPlug() );
}

Parameters::~Parameters()
{
}

Gaffer::CompoundDataPlug *Parameters::parametersPlug()
{
	return getChild<CompoundDataPlug>( g_firstPlugIndex );
}

const Gaffer::CompoundDataPlug *Parameters::parametersPlug() const
{
	return getChild<CompoundDataPlug>( g_firstPlugIndex );
}

void Parameters::affects( const Gaffer::Plug *input, AffectedPlugsContainer &outputs ) const
{
	SceneElementProcessor::affects( input, outputs );

	if( parametersPlug()->isAncestorOf( input ) )
	{
		outputs.push_back( outPlug()->objectPlug() );
	}
}

bool Parameters::processesObject() const
{
	return true;
}

void Parameters::hashProcessedObject( const ScenePath &path, const Gaffer::Context *context, IECore::MurmurHash &h ) const
{
	parametersPlug()->hash( h );
}

IECore::ConstObjectPtr Parameters::computeProcessedObject( const ScenePath &path, const Gaffer::Context *context, IECore::ConstObjectPtr inputObject ) const
{
	if( !parametersPlug()->children().size() )
	{
		return inputObject;
	}

	ConstObjectPtr outputObject = inputObject;
	CompoundData *outputParameters = NULL;

	if( const Camera *camera = runTimeCast<const Camera>( inputObject.get() ) )
	{
		CameraPtr cameraCopy = camera->copy();
		outputParameters = cameraCopy->parametersData();
		outputObject = cameraCopy;
	}
	else if( const Light *light = runTimeCast<const Light>( inputObject.get() ) )
	{
		LightPtr lightCopy = light->copy();
		outputParameters = lightCopy->parametersData().get();
		outputObject = lightCopy;
	}
	else if( const ExternalProcedural *procedural = runTimeCast<const ExternalProcedural>( inputObject.get() ) )
	{
		ExternalProceduralPtr proceduralCopy = procedural->copy();
		outputParameters = proceduralCopy->parameters();
		outputObject = proceduralCopy;
	}

	if( outputParameters )
	{
		parametersPlug()->fillCompoundData( outputParameters->writable() );
	}

	return outputObject;
}
<|endoftext|>


<commit_before>///
/// @file    popcount64.hpp
/// @brief   Count the number of 1 bits inside a 64-bit word.
///          If HAVE_POPCNT is defined then popcount64(x) uses the
///          POPCNT instruction (requires SSE4.2 for x86 & x64).
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#ifndef POPCOUNT64_HPP
#define POPCOUNT64_HPP

#if !defined(__STDC_CONSTANT_MACROS)
  #define __STDC_CONSTANT_MACROS
#endif

#include <stdint.h>

#if defined(HAVE_POPCNT)

#if defined(_MSC_VER) && defined(_WIN64)

#include <nmmintrin.h>

inline uint64_t popcount64(uint64_t x)
{
  return _mm_popcnt_u64(x);
}

#elif defined(_MSC_VER) && defined(_WIN32)

#include <nmmintrin.h>

inline uint64_t popcount64(uint64_t x)
{
  return _mm_popcnt_u32((uint32_t) x) +
         _mm_popcnt_u32((uint32_t)(x >> 32));
}

#elif defined(HAVE___BUILTIN_POPCOUNT) && defined(__i386__)

inline uint64_t popcount64(uint64_t x)
{
  return __builtin_popcount((uint32_t) x) +
         __builtin_popcount((uint32_t)(x >> 32));
}

#elif defined(HAVE___BUILTIN_POPCOUNTLL)

inline uint64_t popcount64(uint64_t x)
{
  return __builtin_popcountll(x);
}

#else /* Error */

#if defined(_MSC_VER)
  #pragma error( "POPCNT not supported, remove \"/D HAVE_POPCNT\" from Makefile.msvc" )
#else
  #error "POPCNT not supported, don't use --enable-popcnt"
#endif

#endif /* HAVE_POPCNT */

#elif !defined(HAVE_POPCNT)

/// Count the number of 1 bits in x.
/// This implementation uses only 12 arithmetic operations.
/// http://en.wikipedia.org/wiki/Hamming_weight#Efficient_implementation
///
inline uint64_t popcount64(uint64_t x)
{
  const uint64_t m1  = UINT64_C(0x5555555555555555);
  const uint64_t m2  = UINT64_C(0x3333333333333333);
  const uint64_t m4  = UINT64_C(0x0f0f0f0f0f0f0f0f);
  const uint64_t h01 = UINT64_C(0x0101010101010101);

  x -= (x >> 1) & m1;
  x = (x & m2) + ((x >> 2) & m2);
  x = (x + (x >> 4)) & m4;
  return (x * h01) >> 56;
}

#endif

#endif /* POPCOUNT64_HPP */
<commit_msg>Update error message<commit_after>///
/// @file    popcount64.hpp
/// @brief   Count the number of 1 bits inside a 64-bit word.
///          If HAVE_POPCNT is defined then popcount64(x) uses the
///          POPCNT instruction (requires SSE4.2 for x86 & x64).
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#ifndef POPCOUNT64_HPP
#define POPCOUNT64_HPP

#if !defined(__STDC_CONSTANT_MACROS)
  #define __STDC_CONSTANT_MACROS
#endif

#include <stdint.h>

#if defined(HAVE_POPCNT)

#if defined(_MSC_VER) && defined(_WIN64)

#include <nmmintrin.h>

inline uint64_t popcount64(uint64_t x)
{
  return _mm_popcnt_u64(x);
}

#elif defined(_MSC_VER) && defined(_WIN32)

#include <nmmintrin.h>

inline uint64_t popcount64(uint64_t x)
{
  return _mm_popcnt_u32((uint32_t) x) +
         _mm_popcnt_u32((uint32_t)(x >> 32));
}

#elif defined(HAVE___BUILTIN_POPCOUNT) && defined(__i386__)

inline uint64_t popcount64(uint64_t x)
{
  return __builtin_popcount((uint32_t) x) +
         __builtin_popcount((uint32_t)(x >> 32));
}

#elif defined(HAVE___BUILTIN_POPCOUNTLL)

inline uint64_t popcount64(uint64_t x)
{
  return __builtin_popcountll(x);
}

#else /* Error */

#if defined(_MSC_VER)
  #pragma error( "POPCNT not supported, remove \"/D HAVE_POPCNT\" from Makefile.msvc" )
#else
  #error "POPCNT not supported, use --disable-popcnt"
#endif

#endif /* HAVE_POPCNT */

#elif !defined(HAVE_POPCNT)

/// Count the number of 1 bits in x.
/// This implementation uses only 12 arithmetic operations.
/// http://en.wikipedia.org/wiki/Hamming_weight#Efficient_implementation
///
inline uint64_t popcount64(uint64_t x)
{
  const uint64_t m1  = UINT64_C(0x5555555555555555);
  const uint64_t m2  = UINT64_C(0x3333333333333333);
  const uint64_t m4  = UINT64_C(0x0f0f0f0f0f0f0f0f);
  const uint64_t h01 = UINT64_C(0x0101010101010101);

  x -= (x >> 1) & m1;
  x = (x & m2) + ((x >> 2) & m2);
  x = (x + (x >> 4)) & m4;
  return (x * h01) >> 56;
}

#endif

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


<commit_before>#ifndef RAINBACK_PROXY_FONT_HEADER
#define RAINBACK_PROXY_FONT_HEADER

#include <QObject>
#include <QFont>
#include <memory>

#include <lua-cxx/LuaStack.hpp>
#include <lua-cxx/userdata.hpp>

namespace rainback {
namespace proxy {

class Font : public QObject
{
    Q_OBJECT

    QFont _font;
public:
    Font();
    Font(const QString& fontFamily);
    Font(const QString& fontFamily, const int size);

    const QFont& getFont() const;

    Q_PROPERTY(QString family READ family WRITE setFamily)
    Q_PROPERTY(int pointSize READ pointSize WRITE setPointSize)

public slots:
    QString family() const;
    void setFamily(const QString& font);

    int pointSize() const;
    void setPointSize(const int size);

    int height(LuaStack& stack) const;
    int height(const QString& text, const int width) const;

    int width(const QString& text) const;
};

} // namespace proxy
} // namespace rainback

namespace lua {

template<>
struct UserdataType<rainback::proxy::Font>
{
    constexpr static const char* name = "rainback::proxy::Font";

    static void initialize(LuaStack& stack, rainback::proxy::Font& font)
    {
        lua::qobject(stack, font);
    }
};

} // namespace lua

#endif // RAINBACK_PROXY_FONT_HEADER

// vim: set ts=4 sw=4 :
<commit_msg>Use a cleaner version of initializing QObjects<commit_after>#ifndef RAINBACK_PROXY_FONT_HEADER
#define RAINBACK_PROXY_FONT_HEADER

#include <QObject>
#include <QFont>
#include <memory>

#include <lua-cxx/LuaStack.hpp>
#include <lua-cxx/userdata.hpp>

namespace rainback {
namespace proxy {

class Font : public QObject
{
    Q_OBJECT

    QFont _font;
public:
    Font();
    Font(const QString& fontFamily);
    Font(const QString& fontFamily, const int size);

    const QFont& getFont() const;

    Q_PROPERTY(QString family READ family WRITE setFamily)
    Q_PROPERTY(int pointSize READ pointSize WRITE setPointSize)

public slots:
    QString family() const;
    void setFamily(const QString& font);

    int pointSize() const;
    void setPointSize(const int size);

    int height(LuaStack& stack) const;
    int height(const QString& text, const int width) const;

    int width(const QString& text) const;
};

} // namespace proxy
} // namespace rainback

namespace lua {

template<>
struct UserdataType<rainback::proxy::Font>
{
    constexpr static const char* name = "rainback::proxy::Font";

    static void initialize(LuaStack& stack, rainback::proxy::Font& font)
    {
        lua::UserdataType<QObject>::initialize(stack, font);
    }
};

} // namespace lua

#endif // RAINBACK_PROXY_FONT_HEADER

// vim: set ts=4 sw=4 :
<|endoftext|>


<commit_before>/*
 * RAFT protocol for fault-tolerant DIF internal components.
 *
 * Copyright (C) 2017 Nextworks
 * Author: Vincenzo Maffione <v.maffione@gmail.com>
 *
 * This file is part of rlite.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA
 */

#ifndef __RAFT_H__
#define __RAFT_H__

#include <cstdint>
#include <string>
#include <list>
#include <map>
#include <fstream>
#include <iostream>
#include <memory>
#include <chrono>

namespace raft {

using Term      = uint32_t;
using LogIndex  = uint32_t;
using ReplicaId = std::string;

/* Base class for all the Raft messages. */
struct RaftMessage {
    Term term;
    virtual ~RaftMessage() {} /* make it polymorphic */
};

struct RaftRequestVote : public RaftMessage {
    /* RaftMessage::term is candidate's term. */

    /* Candidate requesting vote. */
    ReplicaId candidate_id;

    /* Index of candidate's last log entry. */
    LogIndex last_log_index;

    /* Term of candidate's last log entry. */
    Term last_log_term;
};

struct RaftRequestVoteResp : public RaftMessage {
    /* RaftMessage::term is the current term as known by
     * the peer, for the candidate to update itself. */

    /* Vote response: true means candidate received vote. */
    bool vote_granted;
};

struct RaftAppendEntries : public RaftMessage {
    /* RaftMessage::term is the current term as known by the leader. */

    /* Id of the leader, so that followers can redirect clients. */
    ReplicaId leader_id;

    /* Leader's commit index. */
    LogIndex leader_commit;

    /* Index of the log entry immediately preceding new ones. */
    LogIndex prev_log_index;

    /* Term of prev_log_index entry. */
    Term prev_log_term;

    /* Log entries to store (empty for heartbeat). There may be
     * more than one for efficiency. */
    std::list<std::pair<Term, std::unique_ptr<char[]>>> entries;
};

struct RaftAppendEntriesResp : public RaftMessage {
    /* RaftMessage::term is the current term as known by
     * the peer, for the leader to update itself. */

    /* Id of the responding follower. */
    ReplicaId follower_id;

    /* On success, the new last log index of the follower.
     * On failure, it matches the prev_log_index field of
     * the corresponding AppendEntries request.
     * In both cases this field is used by the leader to
     * update next_index_acked and next_index_unacked. */
    LogIndex log_index;

    /* True if the follower's last entry matched prev_log_index
     * and prev_log_term as specified in the request. If false
     * the leader should retry with an older log entry. */
    bool success;
};

enum class RaftTimerType {
    Invalid = 0,
    Election,
    HeartBeat,
    LogReplication,
};

enum class RaftTimerAction {
    Invalid = 0,
    Restart,
    Stop,
};

class RaftSM;

struct RaftTimerCmd {
    RaftSM *sm                             = nullptr;
    RaftTimerType type                     = RaftTimerType::Invalid;
    RaftTimerAction action                 = RaftTimerAction::Invalid;
    std::chrono::milliseconds milliseconds = std::chrono::milliseconds(0);

    RaftTimerCmd(RaftSM *_sm, RaftTimerType ty, RaftTimerAction act,
                 std::chrono::milliseconds ms = std::chrono::milliseconds(0))
        : sm(_sm), type(ty), action(act), milliseconds(ms)
    {
    }
};

/* The output of an invocation of the Raft state machine. May contain
 * some messages to send to the other replicas, commands to start
 * or stop some timers, and log entries that have been commited to
 * the replicated state machine. */
struct RaftSMOutput {
    RaftSMOutput()                     = default;
    RaftSMOutput(const RaftSMOutput &) = delete;
    RaftSMOutput &operator=(const RaftSMOutput &) = delete;
    RaftSMOutput(RaftSMOutput &&)                 = default;
    RaftSMOutput &operator=(RaftSMOutput &&) = default;

    std::list<std::pair<ReplicaId, std::unique_ptr<RaftMessage>>>
        output_messages;
    std::list<RaftTimerCmd> timer_commands;
};

enum class RaftState {
    Follower = 0,
    Candidate,
    Leader,
};

/* Raft state machine. */
class RaftSM {
    /* =================================================================
     * Persistent state on all servers. Updated to stable storage before
     * responding to RPCs. Here we keep shadow copies.
     */

    /* Latest term this replica has seen. Initialized to 0 on first
     * boot (when there is no persistent file), then it increases
     * monotonically. */
    Term current_term = 0;

    /* Identifier of the candidate that received vote in current
     * term (or NULL if none). */
    ReplicaId voted_for;

    /* Log entries (only on disc). Each entry contains a command for the
     * replicated state machine and the term when entry was received by the
     * leader. The first index in the log is 1 (and not 0). */

    /* =================================================================
     * Volatile state for leaders.
     */

    struct Server {
        /* For each replica, next_index is the index of the next log entry to
         * send to that server. Initialized to leader's last log index + 1. We
         * make a slight variation to allow to pipeline RaftAppendEntries
         * messages towards the same replica:
         *   - on client submit or retransmission we send the log entry
         *     indexed by next_index_unacked and we increment it right away
         *   - on positive/negative response we update next_index_acked as
         * described by the algorithm (for next_index)
         *   - on negative response we also reset next_index_unacked to
         *     next_index_acked (after the latter has been decremented)
         * In this way we split next_index into two separate variables: the
         * meaning of next_index_acked is "the first log entry still to be
         * acked"; the meaning of next_index_unacked is "the next log entry to
         * be sent". In the paper next_index has both meanings, preventing
         * pipelining.
         */
        LogIndex next_index_acked;
        LogIndex next_index_unacked;

        /* For each replica, index of highest log entry known to
         * be replicated on that replica. Initialized to 0, increases
         * monotonically. */
        LogIndex match_index;

        /* We record the last time we sent a RaftAppendEntries message with
         * one or more entries. This is used to avoid useless retransmissions
         * that closely follow a submit(). */
        std::chrono::system_clock::time_point last_ae_time;
    };

    std::map<ReplicaId, Server> servers;

    /* =================================================================
     * Volatile state common to all the replicas.
     */

    /* Current state for the Raft state machine. */
    RaftState state = RaftState::Follower;

    /* Index of the highest log entry known to be committed.
     * Initialized to 0, increases monotonically. */
    LogIndex commit_index = 0;

    /* Index of the highest entry fed to the local replica of the state
     * machine. Initialized to 0, increases monotonically. */
    LogIndex last_applied = 0;

    /* A name for this SM, just for logging purposes. */
    const std::string name;

    /* My identifier. */
    const ReplicaId local_id;

    /* Id of the leader, useful to redirect clients. */
    ReplicaId leader_id;

    /* Index of the last entry written in the local log. */
    LogIndex last_log_index = 0;

    /* Term of the last log entry. */
    Term last_log_term = 0;

    /* How many votes we collected as a candidate. */
    unsigned int votes_collected = 0;

    /* Name of the log file. */
    const std::string logfilename;

    /* File descriptor for the log file. */
    std::fstream logfile;

    /* Size of a log entry (with and without term info). */
    const size_t log_entry_size   = sizeof(Term);
    const size_t log_command_size = 0;

    /* For logging of Raft internal operations. */
    std::ostream &ios_err;
    std::ostream &ios_inf;

    static constexpr uint32_t kLogMagicNumber         = 0x89ae01caU;
    static constexpr unsigned long kLogMagicOfs       = 0;
    static constexpr unsigned long kLogCurrentTermOfs = 4;
    static constexpr unsigned long kLogVotedForOfs    = 8;
    static constexpr unsigned long kLogEntriesOfs     = 128;
    static constexpr size_t kLogVotedForSize = kLogEntriesOfs - kLogVotedForOfs;

    /* Argument for RaftSM::prepare_append_entries() that specifies
     * its behaviour (send all the unacked log entries or only the
     * ones that have not been sent yet). */
    enum class LogReplicateStrategy {
        Unacked = 0,
        Unsent,
    };

    /* Getter/setters for replica persistent state. */
    int log_u32_write(unsigned long pos, uint32_t val);
    int log_u32_read(unsigned long pos, uint32_t *val);
    int log_buf_write(unsigned long pos, const char *buf, size_t len);
    int log_buf_read(unsigned long pos, char *buf, size_t len);
    int magic_check();
    int log_open(bool first_boot);
    int log_disk_flush();
    int log_truncate(LogIndex index);

    /* Logging helpers. */
    std::string curtime_string(void)
    {
        time_t ctime = time(nullptr);
        struct tm *time_info;
        char tbuf[9];

        time_info = localtime(&ctime);
        strftime(tbuf, sizeof(tbuf), "%H:%M:%S", time_info);

        return std::string(tbuf);
    }

    std::ostream &IOS_ERR()
    {
        return ios_err << "[" << curtime_string() << "](" << name << ") ";
    }
    std::ostream &IOS_INF()
    {
        return ios_inf << "[" << curtime_string() << "](" << name << ") ";
    }

    int check_output_arg(RaftSMOutput *out);
    std::chrono::milliseconds rand_time_in_range(
        std::chrono::milliseconds left, std::chrono::milliseconds right);
    void switch_state(RaftState next);
    std::string state_repr(RaftState st) const;
    int vote_for_candidate(ReplicaId candidate);
    int catch_up_term(Term term, RaftSMOutput *out);
    int back_to_follower(RaftSMOutput *out);
    unsigned int quorum() const;
    int prepare_append_entries(LogReplicateStrategy strategy,
                               RaftSMOutput *out);
    int log_entry_get_term(LogIndex index, Term *term);
    int log_entry_get_command(LogIndex index, char *const serbuf);
    int append_log_entry(const Term term, const char *serbuf);
    int apply_committed_entries();

    std::chrono::milliseconds ElectionTimeoutMin =
        std::chrono::milliseconds(int(kElectionTimeoutMinMsecs));
    std::chrono::milliseconds ElectionTimeoutMax =
        std::chrono::milliseconds(int(kElectionTimeoutMinMsecs * 3));
    std::chrono::milliseconds HeartbeatTimeout =
        std::chrono::milliseconds(int(kHeartBeatTimeoutMsecs));
    std::chrono::milliseconds RtxTimeout =
        std::chrono::milliseconds(int(kRtxTimeoutMsecs));

    unsigned int verbosity = kVerboseVery;

    /* Statistics. */
    struct Stats {
        /* Number of discarded log entries, due to partial replication. */
        unsigned int discarded = 0;
    } stats;

public:
    RaftSM(const std::string &smname, const ReplicaId &myname,
           std::string logname, size_t cmd_size, std::ostream &ioe,
           std::ostream &ioi)
        : name(smname),
          local_id(myname),
          logfilename(logname),
          log_entry_size(sizeof(Term) + cmd_size),
          log_command_size(cmd_size),
          ios_err(ioe),
          ios_inf(ioi)
    {
    }
    int init(const std::list<ReplicaId> peers, RaftSMOutput *out);

    /* The user doesn't need this Raft SM anymore. Delete the log on disk. */
    void shutdown();

    /* Called by the user when the corresponding message is
     * received. Returns results in the 'out' argument. */
    int request_vote_input(const RaftRequestVote &msg, RaftSMOutput *out);
    int request_vote_resp_input(const RaftRequestVoteResp &msg,
                                RaftSMOutput *out);
    int append_entries_input(const RaftAppendEntries &msg, RaftSMOutput *out);
    int append_entries_resp_input(const RaftAppendEntriesResp &msg,
                                  RaftSMOutput *out);

    /* Called by the user when a timer requested by Raft expired. */
    int timer_expired(RaftTimerType, RaftSMOutput *out);

    /* Called by the user when it wants to submit a new log entry to
     * the replicated state machine. If 'log_index_p' is not nullptr,
     * it is filled with the index of the log entry allocated for
     * this request. */
    int submit(const char *const serbuf, LogIndex *log_index_p,
               RaftSMOutput *out);

    /* Called by the Raft state machine when a log entry needs to
     * be applied to the replicated state machine. */
    virtual int apply(LogIndex index, const char *const serbuf) = 0;
    virtual ~RaftSM();

    /* True if this Raft SM is the current leader. */
    bool leader() const { return state == RaftState::Leader; }

    /* Name of the current leader (if we know it). */
    ReplicaId leader_name() const { return leader_id; }

    bool leader_elected() const { return !leader_id.empty(); }

    std::string local_name() const { return local_id; }
    std::string sm_name() const { return name; }

    int set_election_timeout(std::chrono::milliseconds tmin,
                             std::chrono::milliseconds tmax)
    {
        if (tmin > tmax) {
            return -1;
        }

        ElectionTimeoutMin = tmin;
        ElectionTimeoutMax = tmax;

        return 0;
    }

    std::chrono::milliseconds get_election_timeout_max() const
    {
        return ElectionTimeoutMax;
    }

    void set_heartbeat_timeout(std::chrono::milliseconds t)
    {
        HeartbeatTimeout = t;
    }

    std::chrono::milliseconds get_heartbeat_timeout() const
    {
        return HeartbeatTimeout;
    }

    Stats get_stats() { return stats; };

    static constexpr unsigned int kVerboseQuiet = 0;
    static constexpr unsigned int kVerboseInfo  = 6;
    static constexpr unsigned int kVerboseVery  = 10;

    void set_verbosity(unsigned int level)
    {
        verbosity = level; /* no need to check */
    }

    /* At most 1000 bytes of log chunk per each RaftAppendEntries
     * message. */
    static constexpr size_t kMaxLogChunkBytes = 1000;

    void set_retransmission_timeout(std::chrono::milliseconds t)
    {
        RtxTimeout = t;
    }

    static constexpr int kElectionTimeoutMinMsecs = 200;
    static constexpr int kHeartBeatTimeoutMsecs   = 100;
    static constexpr int kRtxTimeoutMsecs         = 2000;
};

} /* namespace raft */

#endif /* __RAFT_H__ */
<commit_msg>lib: raft: add curr_term() method to return current term<commit_after>/*
 * RAFT protocol for fault-tolerant DIF internal components.
 *
 * Copyright (C) 2017 Nextworks
 * Author: Vincenzo Maffione <v.maffione@gmail.com>
 *
 * This file is part of rlite.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA
 */

#ifndef __RAFT_H__
#define __RAFT_H__

#include <cstdint>
#include <string>
#include <list>
#include <map>
#include <fstream>
#include <iostream>
#include <memory>
#include <chrono>

namespace raft {

using Term      = uint32_t;
using LogIndex  = uint32_t;
using ReplicaId = std::string;

/* Base class for all the Raft messages. */
struct RaftMessage {
    Term term;
    virtual ~RaftMessage() {} /* make it polymorphic */
};

struct RaftRequestVote : public RaftMessage {
    /* RaftMessage::term is candidate's term. */

    /* Candidate requesting vote. */
    ReplicaId candidate_id;

    /* Index of candidate's last log entry. */
    LogIndex last_log_index;

    /* Term of candidate's last log entry. */
    Term last_log_term;
};

struct RaftRequestVoteResp : public RaftMessage {
    /* RaftMessage::term is the current term as known by
     * the peer, for the candidate to update itself. */

    /* Vote response: true means candidate received vote. */
    bool vote_granted;
};

struct RaftAppendEntries : public RaftMessage {
    /* RaftMessage::term is the current term as known by the leader. */

    /* Id of the leader, so that followers can redirect clients. */
    ReplicaId leader_id;

    /* Leader's commit index. */
    LogIndex leader_commit;

    /* Index of the log entry immediately preceding new ones. */
    LogIndex prev_log_index;

    /* Term of prev_log_index entry. */
    Term prev_log_term;

    /* Log entries to store (empty for heartbeat). There may be
     * more than one for efficiency. */
    std::list<std::pair<Term, std::unique_ptr<char[]>>> entries;
};

struct RaftAppendEntriesResp : public RaftMessage {
    /* RaftMessage::term is the current term as known by
     * the peer, for the leader to update itself. */

    /* Id of the responding follower. */
    ReplicaId follower_id;

    /* On success, the new last log index of the follower.
     * On failure, it matches the prev_log_index field of
     * the corresponding AppendEntries request.
     * In both cases this field is used by the leader to
     * update next_index_acked and next_index_unacked. */
    LogIndex log_index;

    /* True if the follower's last entry matched prev_log_index
     * and prev_log_term as specified in the request. If false
     * the leader should retry with an older log entry. */
    bool success;
};

enum class RaftTimerType {
    Invalid = 0,
    Election,
    HeartBeat,
    LogReplication,
};

enum class RaftTimerAction {
    Invalid = 0,
    Restart,
    Stop,
};

class RaftSM;

struct RaftTimerCmd {
    RaftSM *sm                             = nullptr;
    RaftTimerType type                     = RaftTimerType::Invalid;
    RaftTimerAction action                 = RaftTimerAction::Invalid;
    std::chrono::milliseconds milliseconds = std::chrono::milliseconds(0);

    RaftTimerCmd(RaftSM *_sm, RaftTimerType ty, RaftTimerAction act,
                 std::chrono::milliseconds ms = std::chrono::milliseconds(0))
        : sm(_sm), type(ty), action(act), milliseconds(ms)
    {
    }
};

/* The output of an invocation of the Raft state machine. May contain
 * some messages to send to the other replicas, commands to start
 * or stop some timers, and log entries that have been commited to
 * the replicated state machine. */
struct RaftSMOutput {
    RaftSMOutput()                     = default;
    RaftSMOutput(const RaftSMOutput &) = delete;
    RaftSMOutput &operator=(const RaftSMOutput &) = delete;
    RaftSMOutput(RaftSMOutput &&)                 = default;
    RaftSMOutput &operator=(RaftSMOutput &&) = default;

    std::list<std::pair<ReplicaId, std::unique_ptr<RaftMessage>>>
        output_messages;
    std::list<RaftTimerCmd> timer_commands;
};

enum class RaftState {
    Follower = 0,
    Candidate,
    Leader,
};

/* Raft state machine. */
class RaftSM {
    /* =================================================================
     * Persistent state on all servers. Updated to stable storage before
     * responding to RPCs. Here we keep shadow copies.
     */

    /* Latest term this replica has seen. Initialized to 0 on first
     * boot (when there is no persistent file), then it increases
     * monotonically. */
    Term current_term = 0;

    /* Identifier of the candidate that received vote in current
     * term (or NULL if none). */
    ReplicaId voted_for;

    /* Log entries (only on disc). Each entry contains a command for the
     * replicated state machine and the term when entry was received by the
     * leader. The first index in the log is 1 (and not 0). */

    /* =================================================================
     * Volatile state for leaders.
     */

    struct Server {
        /* For each replica, next_index is the index of the next log entry to
         * send to that server. Initialized to leader's last log index + 1. We
         * make a slight variation to allow to pipeline RaftAppendEntries
         * messages towards the same replica:
         *   - on client submit or retransmission we send the log entry
         *     indexed by next_index_unacked and we increment it right away
         *   - on positive/negative response we update next_index_acked as
         * described by the algorithm (for next_index)
         *   - on negative response we also reset next_index_unacked to
         *     next_index_acked (after the latter has been decremented)
         * In this way we split next_index into two separate variables: the
         * meaning of next_index_acked is "the first log entry still to be
         * acked"; the meaning of next_index_unacked is "the next log entry to
         * be sent". In the paper next_index has both meanings, preventing
         * pipelining.
         */
        LogIndex next_index_acked;
        LogIndex next_index_unacked;

        /* For each replica, index of highest log entry known to
         * be replicated on that replica. Initialized to 0, increases
         * monotonically. */
        LogIndex match_index;

        /* We record the last time we sent a RaftAppendEntries message with
         * one or more entries. This is used to avoid useless retransmissions
         * that closely follow a submit(). */
        std::chrono::system_clock::time_point last_ae_time;
    };

    std::map<ReplicaId, Server> servers;

    /* =================================================================
     * Volatile state common to all the replicas.
     */

    /* Current state for the Raft state machine. */
    RaftState state = RaftState::Follower;

    /* Index of the highest log entry known to be committed.
     * Initialized to 0, increases monotonically. */
    LogIndex commit_index = 0;

    /* Index of the highest entry fed to the local replica of the state
     * machine. Initialized to 0, increases monotonically. */
    LogIndex last_applied = 0;

    /* A name for this SM, just for logging purposes. */
    const std::string name;

    /* My identifier. */
    const ReplicaId local_id;

    /* Id of the leader, useful to redirect clients. */
    ReplicaId leader_id;

    /* Index of the last entry written in the local log. */
    LogIndex last_log_index = 0;

    /* Term of the last log entry. */
    Term last_log_term = 0;

    /* How many votes we collected as a candidate. */
    unsigned int votes_collected = 0;

    /* Name of the log file. */
    const std::string logfilename;

    /* File descriptor for the log file. */
    std::fstream logfile;

    /* Size of a log entry (with and without term info). */
    const size_t log_entry_size   = sizeof(Term);
    const size_t log_command_size = 0;

    /* For logging of Raft internal operations. */
    std::ostream &ios_err;
    std::ostream &ios_inf;

    static constexpr uint32_t kLogMagicNumber         = 0x89ae01caU;
    static constexpr unsigned long kLogMagicOfs       = 0;
    static constexpr unsigned long kLogCurrentTermOfs = 4;
    static constexpr unsigned long kLogVotedForOfs    = 8;
    static constexpr unsigned long kLogEntriesOfs     = 128;
    static constexpr size_t kLogVotedForSize = kLogEntriesOfs - kLogVotedForOfs;

    /* Argument for RaftSM::prepare_append_entries() that specifies
     * its behaviour (send all the unacked log entries or only the
     * ones that have not been sent yet). */
    enum class LogReplicateStrategy {
        Unacked = 0,
        Unsent,
    };

    /* Getter/setters for replica persistent state. */
    int log_u32_write(unsigned long pos, uint32_t val);
    int log_u32_read(unsigned long pos, uint32_t *val);
    int log_buf_write(unsigned long pos, const char *buf, size_t len);
    int log_buf_read(unsigned long pos, char *buf, size_t len);
    int magic_check();
    int log_open(bool first_boot);
    int log_disk_flush();
    int log_truncate(LogIndex index);

    /* Logging helpers. */
    std::string curtime_string(void)
    {
        time_t ctime = time(nullptr);
        struct tm *time_info;
        char tbuf[9];

        time_info = localtime(&ctime);
        strftime(tbuf, sizeof(tbuf), "%H:%M:%S", time_info);

        return std::string(tbuf);
    }

    std::ostream &IOS_ERR()
    {
        return ios_err << "[" << curtime_string() << "](" << name << ") ";
    }
    std::ostream &IOS_INF()
    {
        return ios_inf << "[" << curtime_string() << "](" << name << ") ";
    }

    int check_output_arg(RaftSMOutput *out);
    std::chrono::milliseconds rand_time_in_range(
        std::chrono::milliseconds left, std::chrono::milliseconds right);
    void switch_state(RaftState next);
    std::string state_repr(RaftState st) const;
    int vote_for_candidate(ReplicaId candidate);
    int catch_up_term(Term term, RaftSMOutput *out);
    int back_to_follower(RaftSMOutput *out);
    unsigned int quorum() const;
    int prepare_append_entries(LogReplicateStrategy strategy,
                               RaftSMOutput *out);
    int log_entry_get_term(LogIndex index, Term *term);
    int log_entry_get_command(LogIndex index, char *const serbuf);
    int append_log_entry(const Term term, const char *serbuf);
    int apply_committed_entries();

    std::chrono::milliseconds ElectionTimeoutMin =
        std::chrono::milliseconds(int(kElectionTimeoutMinMsecs));
    std::chrono::milliseconds ElectionTimeoutMax =
        std::chrono::milliseconds(int(kElectionTimeoutMinMsecs * 3));
    std::chrono::milliseconds HeartbeatTimeout =
        std::chrono::milliseconds(int(kHeartBeatTimeoutMsecs));
    std::chrono::milliseconds RtxTimeout =
        std::chrono::milliseconds(int(kRtxTimeoutMsecs));

    unsigned int verbosity = kVerboseVery;

    /* Statistics. */
    struct Stats {
        /* Number of discarded log entries, due to partial replication. */
        unsigned int discarded = 0;
    } stats;

public:
    RaftSM(const std::string &smname, const ReplicaId &myname,
           std::string logname, size_t cmd_size, std::ostream &ioe,
           std::ostream &ioi)
        : name(smname),
          local_id(myname),
          logfilename(logname),
          log_entry_size(sizeof(Term) + cmd_size),
          log_command_size(cmd_size),
          ios_err(ioe),
          ios_inf(ioi)
    {
    }
    int init(const std::list<ReplicaId> peers, RaftSMOutput *out);

    /* The user doesn't need this Raft SM anymore. Delete the log on disk. */
    void shutdown();

    /* Called by the user when the corresponding message is
     * received. Returns results in the 'out' argument. */
    int request_vote_input(const RaftRequestVote &msg, RaftSMOutput *out);
    int request_vote_resp_input(const RaftRequestVoteResp &msg,
                                RaftSMOutput *out);
    int append_entries_input(const RaftAppendEntries &msg, RaftSMOutput *out);
    int append_entries_resp_input(const RaftAppendEntriesResp &msg,
                                  RaftSMOutput *out);

    /* Called by the user when a timer requested by Raft expired. */
    int timer_expired(RaftTimerType, RaftSMOutput *out);

    /* Called by the user when it wants to submit a new log entry to
     * the replicated state machine. If 'log_index_p' is not nullptr,
     * it is filled with the index of the log entry allocated for
     * this request. */
    int submit(const char *const serbuf, LogIndex *log_index_p,
               RaftSMOutput *out);

    /* Called by the Raft state machine when a log entry needs to
     * be applied to the replicated state machine. */
    virtual int apply(LogIndex index, const char *const serbuf) = 0;
    virtual ~RaftSM();

    /* True if this Raft SM is the current leader. */
    bool leader() const { return state == RaftState::Leader; }

    /* Name of the current leader (if we know it). */
    ReplicaId leader_name() const { return leader_id; }

    bool leader_elected() const { return !leader_id.empty(); }

    std::string local_name() const { return local_id; }
    std::string sm_name() const { return name; }

    Term curr_term() const { return current_term; }

    int set_election_timeout(std::chrono::milliseconds tmin,
                             std::chrono::milliseconds tmax)
    {
        if (tmin > tmax) {
            return -1;
        }

        ElectionTimeoutMin = tmin;
        ElectionTimeoutMax = tmax;

        return 0;
    }

    std::chrono::milliseconds get_election_timeout_max() const
    {
        return ElectionTimeoutMax;
    }

    void set_heartbeat_timeout(std::chrono::milliseconds t)
    {
        HeartbeatTimeout = t;
    }

    std::chrono::milliseconds get_heartbeat_timeout() const
    {
        return HeartbeatTimeout;
    }

    Stats get_stats() { return stats; };

    static constexpr unsigned int kVerboseQuiet = 0;
    static constexpr unsigned int kVerboseInfo  = 6;
    static constexpr unsigned int kVerboseVery  = 10;

    void set_verbosity(unsigned int level)
    {
        verbosity = level; /* no need to check */
    }

    /* At most 1000 bytes of log chunk per each RaftAppendEntries
     * message. */
    static constexpr size_t kMaxLogChunkBytes = 1000;

    void set_retransmission_timeout(std::chrono::milliseconds t)
    {
        RtxTimeout = t;
    }

    static constexpr int kElectionTimeoutMinMsecs = 200;
    static constexpr int kHeartBeatTimeoutMsecs   = 100;
    static constexpr int kRtxTimeoutMsecs         = 2000;
};

} /* namespace raft */

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


<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2007-2008, Image Engine Design Inc. 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 Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

// System includes

// External includes
#include <boost/python.hpp>

// Local includes
#include "IECore/bindings/RefCountedBinding.h"
#include "IECore/bindings/RunTimeTypedBinding.h"
#include "IECore/bindings/ExceptionBinding.h"
#include "IECore/bindings/ImathBinding.h"
#include "IECore/bindings/KDTreeBinding.h"
#include "IECore/bindings/IndexedIOInterfaceBinding.h"
#include "IECore/bindings/DataBinding.h"
#include "IECore/bindings/SimpleTypedDataBinding.h"
#include "IECore/bindings/VectorTypedDataBinding.h"
#include "IECore/bindings/ObjectBinding.h"
#include "IECore/bindings/TypeIdBinding.h"
#include "IECore/bindings/CompoundDataBinding.h"
#include "IECore/bindings/MessageHandlerBinding.h"
#include "IECore/bindings/AttributeCacheBinding.h"
#include "IECore/bindings/ReaderBinding.h"
#include "IECore/bindings/ParticleReaderBinding.h"
#include "IECore/bindings/PDCParticleReaderBinding.h"
#include "IECore/bindings/BlindDataHolderBinding.h"
#include "IECore/bindings/RenderableBinding.h"
#include "IECore/bindings/VisibleRenderableBinding.h"
#include "IECore/bindings/StateRenderableBinding.h"
#include "IECore/bindings/RendererBinding.h"
#include "IECore/bindings/WriterBinding.h"
#include "IECore/bindings/ParticleWriterBinding.h"
#include "IECore/bindings/PDCParticleWriterBinding.h"
#include "IECore/bindings/ParameterBinding.h"
#include "IECore/bindings/NumericParameterBinding.h"
#include "IECore/bindings/TypedParameterBinding.h"
#include "IECore/bindings/CompoundParameterBinding.h"
#include "IECore/bindings/ValidatedStringParameterBinding.h"
#include "IECore/bindings/PathParameterBinding.h"
#include "IECore/bindings/FileNameParameterBinding.h"
#include "IECore/bindings/DirNameParameterBinding.h"
#include "IECore/bindings/CompoundObjectBinding.h"
#include "IECore/bindings/ObjectReaderBinding.h"
#include "IECore/bindings/ObjectWriterBinding.h"
#include "IECore/bindings/PrimitiveBinding.h"
#include "IECore/bindings/PrimitiveVariableBinding.h"
#include "IECore/bindings/PointsPrimitiveBinding.h"
#include "IECore/bindings/TimerBinding.h"
#include "IECore/bindings/TurbulenceBinding.h"
#include "IECore/bindings/ShaderBinding.h"
#include "IECore/bindings/SearchPathBinding.h"
#include "IECore/bindings/CachedReaderBinding.h"
#include "IECore/bindings/ParameterisedBinding.h"
#include "IECore/bindings/OpBinding.h"
#include "IECore/bindings/ObjectParameterBinding.h"
#include "IECore/bindings/ModifyOpBinding.h"
#include "IECore/bindings/PrimitiveOpBinding.h"
#include "IECore/bindings/ImagePrimitiveBinding.h"
#include "IECore/bindings/ImageReaderBinding.h"
#include "IECore/bindings/ImageWriterBinding.h"
#include "IECore/bindings/PerlinNoiseBinding.h"
#include "IECore/bindings/EXRImageReaderBinding.h"
#include "IECore/bindings/EXRImageWriterBinding.h"
#include "IECore/bindings/HalfBinding.h"
#include "IECore/bindings/TIFFImageReaderBinding.h"
#include "IECore/bindings/TIFFImageWriterBinding.h"
#include "IECore/bindings/CINImageReaderBinding.h"
#include "IECore/bindings/CINImageWriterBinding.h"
#include "IECore/bindings/DPXImageReaderBinding.h"
#include "IECore/bindings/DPXImageWriterBinding.h"
#include "IECore/bindings/JPEGImageReaderBinding.h"
#include "IECore/bindings/JPEGImageWriterBinding.h"
#include "IECore/bindings/MeshPrimitiveBinding.h"
#include "IECore/bindings/MotionPrimitiveBinding.h"
#include "IECore/bindings/TransformBinding.h"
#include "IECore/bindings/MatrixTransformBinding.h"
#include "IECore/bindings/GroupBinding.h"
#include "IECore/bindings/AttributeStateBinding.h"
#include "IECore/bindings/MatrixMotionTransformBinding.h"
#include "IECore/bindings/OBJReaderBinding.h"
#include "IECore/bindings/NullObjectBinding.h"
#include "IECore/bindings/ObjectInterpolatorBinding.h"
#include "IECore/bindings/PointNormalsOpBinding.h"
#include "IECore/bindings/PointDensitiesOpBinding.h"
#include "IECore/bindings/InterpolatedCacheBinding.h"
#include "IECore/bindings/TransformationMatrixBinding.h"
#include "IECore/bindings/TransformationMatrixDataBinding.h"
#include "IECore/bindings/HierarchicalCacheBinding.h"
#include "IECore/bindings/BoundedKDTreeBinding.h"
#include "IECore/bindings/VectorDataFilterOpBinding.h"
#include "IECore/bindings/TypedObjectParameterBinding.h"
#include "IECore/bindings/HeaderGeneratorBinding.h"
#include "IECore/bindings/PreWorldRenderableBinding.h"
#include "IECore/bindings/CameraBinding.h"
#include "IECore/bindings/NURBSPrimitiveBinding.h"
#include "IECore/bindings/DataCastOpBinding.h"
#include "IECore/bindings/DataPromoteOpBinding.h"
#include "IECore/bindings/MatrixMultiplyOpBinding.h"
#include "IECore/bindings/PointBoundsOpBinding.h"
#include "IECore/bindings/ImathRandomBinding.h"
#include "IECore/bindings/RandomRotationOpBinding.h"
#include "IECore/bindings/ImplicitSurfaceFunctionBinding.h"
#include "IECore/bindings/CachedImplicitSurfaceFunctionBinding.h"
#include "IECore/bindings/MeshPrimitiveBuilderBinding.h"
#include "IECore/bindings/MarchingCubesBinding.h"
#include "IECore/bindings/PointMeshOpBinding.h"
#include "IECore/bindings/CSGImplicitSurfaceFunctionBinding.h"
#include "IECore/bindings/SphereImplicitSurfaceFunctionBinding.h"
#include "IECore/bindings/PlaneImplicitSurfaceFunctionBinding.h"
#include "IECore/bindings/BlobbyImplicitSurfaceFunctionBinding.h"
#include "IECore/bindings/ParticleMeshOpBinding.h"
#include "IECore/bindings/TypedPrimitiveOpBinding.h"
#include "IECore/bindings/PrimitiveEvaluatorBinding.h"
#include "IECore/bindings/MeshPrimitiveEvaluatorBinding.h"
#include "IECore/bindings/PrimitiveImplicitSurfaceFunctionBinding.h"
#include "IECore/bindings/MeshPrimitiveImplicitSurfaceFunctionBinding.h"
#include "IECore/bindings/MeshPrimitiveImplicitSurfaceOpBinding.h"
#include "IECore/bindings/TriangulateOpBinding.h"
#include "IECore/bindings/InternedBinding.h"
#include "IECore/bindings/SpherePrimitiveBinding.h"
#include "IECore/bindings/SpherePrimitiveEvaluatorBinding.h"
#include "IECore/bindings/InverseDistanceWeightedInterpolationBinding.h"
#include "IECore/bindings/ImageCropOpBinding.h"
#include "IECore/bindings/MeshPrimitiveShrinkWrapOpBinding.h"
#include "IECore/bindings/ImagePrimitiveEvaluatorBinding.h"
#include "IECore/bindings/MathBinding.h"
#include "IECore/IECore.h"

using namespace IECore;
using namespace boost::python;

// Module declaration

BOOST_PYTHON_MODULE(_IECore)
{
	bindRefCounted();
	bindRunTimeTyped();
	bindException();
	bindImath();
	bindKDTree();
	bindObject();
	bindTypeId();
	bindData();
	bindAllSimpleTypedData();
	bindAllVectorTypedData();
	bindCompoundData();
	bindIndexedIO();
	bindMessageHandler();
	bindAttributeCache();
	bindParameterised();
	bindOp();
	bindReader();
	bindParticleReader();
	bindPDCParticleReader();
	bindBlindDataHolder();
	bindRenderable();
	bindStateRenderable();
	bindVisibleRenderable();
	bindRenderer();
	bindWriter();
	bindParticleWriter();
	bindPDCParticleWriter();
	bindObjectReader();
	bindObjectWriter();
	bindParameter();
	bindNumericParameter();
	bindTypedParameter();
	bindCompoundParameter();
	bindValidatedStringParameter();
	bindPathParameter();
	bindFileNameParameter();
	bindDirNameParameter();
	bindCompoundObject();
	bindPrimitive();
	bindPrimitiveVariable();
	bindPointsPrimitive();
	bindPerlinNoise();
	bindHalf();
	bindTimer();
	bindTurbulence();
	bindShader();
	bindSearchPath();
	bindCachedReader();
	bindObjectParameter();
	bindModifyOp();
	bindPrimitiveOp();
	bindImagePrimitive();
	bindImageReader();
	bindImageWriter();
	bindEXRImageReader();
	bindEXRImageWriter();

#ifdef IECORE_WITH_TIFF
	bindTIFFImageReader();
	bindTIFFImageWriter();
#endif

	bindCINImageReader();
	bindCINImageWriter();
	bindDPXImageReader();
	bindDPXImageWriter();

#ifdef IECORE_WITH_JPEG
	bindJPEGImageReader();
	bindJPEGImageWriter();
#endif

	bindMeshPrimitive();
	bindMotionPrimitive();
	bindTransform();
	bindMatrixTransform();
	bindMatrixMotionTransform();
	bindGroup();
	bindAttributeState();
	bindOBJReader();
	bindNullObject();
	bindObjectInterpolator();
	bindPointNormalsOp();
	bindPointDensitiesOp();
	bindInterpolatedCache();
	bindTransformationMatrix();
	bindTransformationMatrixData();
	bindHierarchicalCache();
	bindBoundedKDTree();
	bindVectorDataFilterOp();
	bindTypedObjectParameter();
	bindHeaderGenerator();
	bindPreWorldRenderable();
	bindCamera();
	bindNURBSPrimitive();
	bindDataCastOp();
	bindDataPromoteOp();
	bindMatrixMultiplyOp();
	bindPointBoundsOp();
	bindImathRandom();
	bindRandomRotationOp();
	bindImplicitSurfaceFunction();
	bindCachedImplicitSurfaceFunction();
	bindMeshPrimitiveBuilder();
	bindMarchingCubes();
	bindPointMeshOp();
	bindCSGImplicitSurfaceFunction();
	bindSphereImplicitSurfaceFunction();
	bindPlaneImplicitSurfaceFunction();
	bindBlobbyImplicitSurfaceFunction();
	bindParticleMeshOp();
	bindTypedPrimitiveOp();
	bindPrimitiveEvaluator();
	bindMeshPrimitiveEvaluator();
	bindPrimitiveImplicitSurfaceFunction();
	bindMeshPrimitiveImplicitSurfaceFunction();
	bindMeshPrimitiveImplicitSurfaceOp();
	bindTriangulateOp();
	bindInterned();
	bindSpherePrimitive();
	bindSpherePrimitiveEvaluator();
	bindInverseDistanceWeightedInterpolation();
	bindImageCropOp();
	bindMeshPrimitiveShrinkWrapOp();
	bindImagePrimitiveEvaluator();
	bindMath();

	def( "majorVersion", &IECore::majorVersion );
	def( "minorVersion", &IECore::minorVersion );
	def( "patchVersion", &IECore::patchVersion );
	def( "versionString", &IECore::versionString, return_value_policy<copy_const_reference>() );
	def( "withTIFF", &IECore::withTIFF );
	def( "withJPEG", &IECore::withJPEG );
	def( "withSQLite", &IECore::withSQLite );
}
<commit_msg>Added ScopedMessageHandler binding<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2007-2008, Image Engine Design Inc. 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 Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

// System includes

// External includes
#include <boost/python.hpp>

// Local includes
#include "IECore/bindings/RefCountedBinding.h"
#include "IECore/bindings/RunTimeTypedBinding.h"
#include "IECore/bindings/ExceptionBinding.h"
#include "IECore/bindings/ImathBinding.h"
#include "IECore/bindings/KDTreeBinding.h"
#include "IECore/bindings/IndexedIOInterfaceBinding.h"
#include "IECore/bindings/DataBinding.h"
#include "IECore/bindings/SimpleTypedDataBinding.h"
#include "IECore/bindings/VectorTypedDataBinding.h"
#include "IECore/bindings/ObjectBinding.h"
#include "IECore/bindings/TypeIdBinding.h"
#include "IECore/bindings/CompoundDataBinding.h"
#include "IECore/bindings/MessageHandlerBinding.h"
#include "IECore/bindings/AttributeCacheBinding.h"
#include "IECore/bindings/ReaderBinding.h"
#include "IECore/bindings/ParticleReaderBinding.h"
#include "IECore/bindings/PDCParticleReaderBinding.h"
#include "IECore/bindings/BlindDataHolderBinding.h"
#include "IECore/bindings/RenderableBinding.h"
#include "IECore/bindings/VisibleRenderableBinding.h"
#include "IECore/bindings/StateRenderableBinding.h"
#include "IECore/bindings/RendererBinding.h"
#include "IECore/bindings/WriterBinding.h"
#include "IECore/bindings/ParticleWriterBinding.h"
#include "IECore/bindings/PDCParticleWriterBinding.h"
#include "IECore/bindings/ParameterBinding.h"
#include "IECore/bindings/NumericParameterBinding.h"
#include "IECore/bindings/TypedParameterBinding.h"
#include "IECore/bindings/CompoundParameterBinding.h"
#include "IECore/bindings/ValidatedStringParameterBinding.h"
#include "IECore/bindings/PathParameterBinding.h"
#include "IECore/bindings/FileNameParameterBinding.h"
#include "IECore/bindings/DirNameParameterBinding.h"
#include "IECore/bindings/CompoundObjectBinding.h"
#include "IECore/bindings/ObjectReaderBinding.h"
#include "IECore/bindings/ObjectWriterBinding.h"
#include "IECore/bindings/PrimitiveBinding.h"
#include "IECore/bindings/PrimitiveVariableBinding.h"
#include "IECore/bindings/PointsPrimitiveBinding.h"
#include "IECore/bindings/TimerBinding.h"
#include "IECore/bindings/TurbulenceBinding.h"
#include "IECore/bindings/ShaderBinding.h"
#include "IECore/bindings/SearchPathBinding.h"
#include "IECore/bindings/CachedReaderBinding.h"
#include "IECore/bindings/ParameterisedBinding.h"
#include "IECore/bindings/OpBinding.h"
#include "IECore/bindings/ObjectParameterBinding.h"
#include "IECore/bindings/ModifyOpBinding.h"
#include "IECore/bindings/PrimitiveOpBinding.h"
#include "IECore/bindings/ImagePrimitiveBinding.h"
#include "IECore/bindings/ImageReaderBinding.h"
#include "IECore/bindings/ImageWriterBinding.h"
#include "IECore/bindings/PerlinNoiseBinding.h"
#include "IECore/bindings/EXRImageReaderBinding.h"
#include "IECore/bindings/EXRImageWriterBinding.h"
#include "IECore/bindings/HalfBinding.h"
#include "IECore/bindings/TIFFImageReaderBinding.h"
#include "IECore/bindings/TIFFImageWriterBinding.h"
#include "IECore/bindings/CINImageReaderBinding.h"
#include "IECore/bindings/CINImageWriterBinding.h"
#include "IECore/bindings/DPXImageReaderBinding.h"
#include "IECore/bindings/DPXImageWriterBinding.h"
#include "IECore/bindings/JPEGImageReaderBinding.h"
#include "IECore/bindings/JPEGImageWriterBinding.h"
#include "IECore/bindings/MeshPrimitiveBinding.h"
#include "IECore/bindings/MotionPrimitiveBinding.h"
#include "IECore/bindings/TransformBinding.h"
#include "IECore/bindings/MatrixTransformBinding.h"
#include "IECore/bindings/GroupBinding.h"
#include "IECore/bindings/AttributeStateBinding.h"
#include "IECore/bindings/MatrixMotionTransformBinding.h"
#include "IECore/bindings/OBJReaderBinding.h"
#include "IECore/bindings/NullObjectBinding.h"
#include "IECore/bindings/ObjectInterpolatorBinding.h"
#include "IECore/bindings/PointNormalsOpBinding.h"
#include "IECore/bindings/PointDensitiesOpBinding.h"
#include "IECore/bindings/InterpolatedCacheBinding.h"
#include "IECore/bindings/TransformationMatrixBinding.h"
#include "IECore/bindings/TransformationMatrixDataBinding.h"
#include "IECore/bindings/HierarchicalCacheBinding.h"
#include "IECore/bindings/BoundedKDTreeBinding.h"
#include "IECore/bindings/VectorDataFilterOpBinding.h"
#include "IECore/bindings/TypedObjectParameterBinding.h"
#include "IECore/bindings/HeaderGeneratorBinding.h"
#include "IECore/bindings/PreWorldRenderableBinding.h"
#include "IECore/bindings/CameraBinding.h"
#include "IECore/bindings/NURBSPrimitiveBinding.h"
#include "IECore/bindings/DataCastOpBinding.h"
#include "IECore/bindings/DataPromoteOpBinding.h"
#include "IECore/bindings/MatrixMultiplyOpBinding.h"
#include "IECore/bindings/PointBoundsOpBinding.h"
#include "IECore/bindings/ImathRandomBinding.h"
#include "IECore/bindings/RandomRotationOpBinding.h"
#include "IECore/bindings/ImplicitSurfaceFunctionBinding.h"
#include "IECore/bindings/CachedImplicitSurfaceFunctionBinding.h"
#include "IECore/bindings/MeshPrimitiveBuilderBinding.h"
#include "IECore/bindings/MarchingCubesBinding.h"
#include "IECore/bindings/PointMeshOpBinding.h"
#include "IECore/bindings/CSGImplicitSurfaceFunctionBinding.h"
#include "IECore/bindings/SphereImplicitSurfaceFunctionBinding.h"
#include "IECore/bindings/PlaneImplicitSurfaceFunctionBinding.h"
#include "IECore/bindings/BlobbyImplicitSurfaceFunctionBinding.h"
#include "IECore/bindings/ParticleMeshOpBinding.h"
#include "IECore/bindings/TypedPrimitiveOpBinding.h"
#include "IECore/bindings/PrimitiveEvaluatorBinding.h"
#include "IECore/bindings/MeshPrimitiveEvaluatorBinding.h"
#include "IECore/bindings/PrimitiveImplicitSurfaceFunctionBinding.h"
#include "IECore/bindings/MeshPrimitiveImplicitSurfaceFunctionBinding.h"
#include "IECore/bindings/MeshPrimitiveImplicitSurfaceOpBinding.h"
#include "IECore/bindings/TriangulateOpBinding.h"
#include "IECore/bindings/InternedBinding.h"
#include "IECore/bindings/SpherePrimitiveBinding.h"
#include "IECore/bindings/SpherePrimitiveEvaluatorBinding.h"
#include "IECore/bindings/InverseDistanceWeightedInterpolationBinding.h"
#include "IECore/bindings/ImageCropOpBinding.h"
#include "IECore/bindings/MeshPrimitiveShrinkWrapOpBinding.h"
#include "IECore/bindings/ImagePrimitiveEvaluatorBinding.h"
#include "IECore/bindings/ScopedMessageHandlerBinding.h"
#include "IECore/bindings/MathBinding.h"
#include "IECore/IECore.h"

using namespace IECore;
using namespace boost::python;

// Module declaration

BOOST_PYTHON_MODULE(_IECore)
{
	bindRefCounted();
	bindRunTimeTyped();
	bindException();
	bindImath();
	bindKDTree();
	bindObject();
	bindTypeId();
	bindData();
	bindAllSimpleTypedData();
	bindAllVectorTypedData();
	bindCompoundData();
	bindIndexedIO();
	bindMessageHandler();
	bindAttributeCache();
	bindParameterised();
	bindOp();
	bindReader();
	bindParticleReader();
	bindPDCParticleReader();
	bindBlindDataHolder();
	bindRenderable();
	bindStateRenderable();
	bindVisibleRenderable();
	bindRenderer();
	bindWriter();
	bindParticleWriter();
	bindPDCParticleWriter();
	bindObjectReader();
	bindObjectWriter();
	bindParameter();
	bindNumericParameter();
	bindTypedParameter();
	bindCompoundParameter();
	bindValidatedStringParameter();
	bindPathParameter();
	bindFileNameParameter();
	bindDirNameParameter();
	bindCompoundObject();
	bindPrimitive();
	bindPrimitiveVariable();
	bindPointsPrimitive();
	bindPerlinNoise();
	bindHalf();
	bindTimer();
	bindTurbulence();
	bindShader();
	bindSearchPath();
	bindCachedReader();
	bindObjectParameter();
	bindModifyOp();
	bindPrimitiveOp();
	bindImagePrimitive();
	bindImageReader();
	bindImageWriter();
	bindEXRImageReader();
	bindEXRImageWriter();

#ifdef IECORE_WITH_TIFF
	bindTIFFImageReader();
	bindTIFFImageWriter();
#endif

	bindCINImageReader();
	bindCINImageWriter();
	bindDPXImageReader();
	bindDPXImageWriter();

#ifdef IECORE_WITH_JPEG
	bindJPEGImageReader();
	bindJPEGImageWriter();
#endif

	bindMeshPrimitive();
	bindMotionPrimitive();
	bindTransform();
	bindMatrixTransform();
	bindMatrixMotionTransform();
	bindGroup();
	bindAttributeState();
	bindOBJReader();
	bindNullObject();
	bindObjectInterpolator();
	bindPointNormalsOp();
	bindPointDensitiesOp();
	bindInterpolatedCache();
	bindTransformationMatrix();
	bindTransformationMatrixData();
	bindHierarchicalCache();
	bindBoundedKDTree();
	bindVectorDataFilterOp();
	bindTypedObjectParameter();
	bindHeaderGenerator();
	bindPreWorldRenderable();
	bindCamera();
	bindNURBSPrimitive();
	bindDataCastOp();
	bindDataPromoteOp();
	bindMatrixMultiplyOp();
	bindPointBoundsOp();
	bindImathRandom();
	bindRandomRotationOp();
	bindImplicitSurfaceFunction();
	bindCachedImplicitSurfaceFunction();
	bindMeshPrimitiveBuilder();
	bindMarchingCubes();
	bindPointMeshOp();
	bindCSGImplicitSurfaceFunction();
	bindSphereImplicitSurfaceFunction();
	bindPlaneImplicitSurfaceFunction();
	bindBlobbyImplicitSurfaceFunction();
	bindParticleMeshOp();
	bindTypedPrimitiveOp();
	bindPrimitiveEvaluator();
	bindMeshPrimitiveEvaluator();
	bindPrimitiveImplicitSurfaceFunction();
	bindMeshPrimitiveImplicitSurfaceFunction();
	bindMeshPrimitiveImplicitSurfaceOp();
	bindTriangulateOp();
	bindInterned();
	bindSpherePrimitive();
	bindSpherePrimitiveEvaluator();
	bindInverseDistanceWeightedInterpolation();
	bindImageCropOp();
	bindMeshPrimitiveShrinkWrapOp();
	bindImagePrimitiveEvaluator();
	bindScopedMessageHandler();
	bindMath();

	def( "majorVersion", &IECore::majorVersion );
	def( "minorVersion", &IECore::minorVersion );
	def( "patchVersion", &IECore::patchVersion );
	def( "versionString", &IECore::versionString, return_value_policy<copy_const_reference>() );
	def( "withTIFF", &IECore::withTIFF );
	def( "withJPEG", &IECore::withJPEG );
	def( "withSQLite", &IECore::withSQLite );
}
<|endoftext|>


<commit_before><commit_msg>Group OutputDevice masking functions together in outdev.hxx<commit_after><|endoftext|>


<commit_before><commit_msg>VCL: make all private functions SAL_DLLPRIVATE visibility<commit_after><|endoftext|>