<commit_before>/*
 * Copyright (C) 2015 Cloudius Systems, Ltd.
 */

#pragma once

#include "types.hh"
#include "net/ip.hh"
#include "util/serialization.hh"
#include <sstream>

namespace gms {

class inet_address {
private:
    // FIXME: ipv6
    net::ipv4_address _addr;
public:
    inet_address() = default;
    inet_address(int32_t ip)
        : _addr(uint32_t(ip)) {
    }
    inet_address(const sstring& addr)
        : _addr(addr) {
    }
    bool is_broadcast_address() {
        return _addr == net::ipv4::broadcast_address();
    }
    void serialize(bytes::iterator& out) const {
        int8_t inet_address_size = sizeof(inet_address);
        serialize_int8(out, inet_address_size);
        serialize_int32(out, _addr.ip);
    }
    static inet_address deserialize(bytes_view& v) {
        int8_t inet_address_size = read_simple<int8_t>(v);
        assert(inet_address_size == sizeof(inet_address));
        return inet_address(read_simple<int32_t>(v));
    }
    size_t serialized_size() const {
        return serialize_int8_size + serialize_int32_size;
    }
    friend inline bool operator<(const inet_address& x, const inet_address& y) {
        return x._addr.ip < y._addr.ip;
    }
    friend inline std::ostream& operator<<(std::ostream& os, const inet_address& x) {
        return os << x._addr;
    }
};

}
<commit_msg>gossip: Add operator== for inet_address<commit_after>/*
 * Copyright (C) 2015 Cloudius Systems, Ltd.
 */

#pragma once

#include "types.hh"
#include "net/ip.hh"
#include "util/serialization.hh"
#include <sstream>

namespace gms {

class inet_address {
private:
    // FIXME: ipv6
    net::ipv4_address _addr;
public:
    inet_address() = default;
    inet_address(int32_t ip)
        : _addr(uint32_t(ip)) {
    }
    inet_address(const sstring& addr)
        : _addr(addr) {
    }
    bool is_broadcast_address() {
        return _addr == net::ipv4::broadcast_address();
    }
    void serialize(bytes::iterator& out) const {
        int8_t inet_address_size = sizeof(inet_address);
        serialize_int8(out, inet_address_size);
        serialize_int32(out, _addr.ip);
    }
    static inet_address deserialize(bytes_view& v) {
        int8_t inet_address_size = read_simple<int8_t>(v);
        assert(inet_address_size == sizeof(inet_address));
        return inet_address(read_simple<int32_t>(v));
    }
    size_t serialized_size() const {
        return serialize_int8_size + serialize_int32_size;
    }
    friend inline bool operator==(const inet_address& x, const inet_address& y) {
        return x._addr == y._addr;
    }
    friend inline bool operator<(const inet_address& x, const inet_address& y) {
        return x._addr.ip < y._addr.ip;
    }
    friend inline std::ostream& operator<<(std::ostream& os, const inet_address& x) {
        return os << x._addr;
    }
};

}
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2017, 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.
//
//////////////////////////////////////////////////////////////////////////

#include "IECoreScene/MeshAlgo.h"
#include "IECoreScene/private/PrimitiveVariableAlgos.h"

#include "IECore/DespatchTypedData.h"
#include "IECore/DataAlgo.h"

using namespace Imath;
using namespace IECore;
using namespace IECoreScene;

//////////////////////////////////////////////////////////////////////////
// Delete Faces
//////////////////////////////////////////////////////////////////////////

namespace
{

void deleteCorners( MeshPrimitive *out, const MeshPrimitive *in, const std::vector<int> &remapping )
{
	const auto &ids = in->cornerIds()->readable();
	if( ids.empty() )
	{
		return;
	}

	const auto &sharpnesses = in->cornerSharpnesses()->readable();

	IntVectorDataPtr outIdData = new IntVectorData;
	auto &outIds = outIdData->writable();

	FloatVectorDataPtr outSharpnessData = new FloatVectorData;
	auto &outSharpnesses = outSharpnessData->writable();

	for( size_t i = 0; i < ids.size(); ++i )
	{
		int id = remapping[ ids[i] ];
		if( id != -1 )
		{
			outIds.push_back( id );
			outSharpnesses.push_back( sharpnesses[i] );
		}
	}

	out->setCorners( outIdData.get(), outSharpnessData.get() );
};

void deleteCreases( MeshPrimitive *out, const MeshPrimitive *in, const std::vector<int> &remapping )
{
	const auto &lengths = in->creaseLengths()->readable();
	if( lengths.empty() )
	{
		return;
	}

	const auto &ids = in->creaseIds()->readable();
	const auto &sharpnesses = in->creaseSharpnesses()->readable();

	IntVectorDataPtr outLengthData = new IntVectorData;
	auto &outLengths = outLengthData->writable();

	IntVectorDataPtr outIdData = new IntVectorData;
	auto &outIds = outIdData->writable();

	FloatVectorDataPtr outSharpnessData = new FloatVectorData;
	auto &outSharpnesses = outSharpnessData->writable();

	int creaseIdOffset = 0;
	for( size_t i = 0; i < lengths.size(); ++i )
	{
		int outLength = 0;
		for( int j = 0; j < lengths[i]; ++j )
		{
			int id = remapping[ ids[creaseIdOffset + j] ];
			if( id != -1 )
			{
				outIds.push_back( id );
				++outLength;
			}

		}

		if( outLength > 0 )
		{
			outLengths.push_back( outLength );
			outSharpnesses.push_back( sharpnesses[i] );
		}

		creaseIdOffset += lengths[i];
	}

	out->setCreases( outLengthData.get(), outIdData.get(), outSharpnessData.get() );
};

template<typename T>
MeshPrimitivePtr deleteFaces( const MeshPrimitive *meshPrimitive, PrimitiveVariable::IndexedView<T> &deleteFlagView, bool invert )
{
	// construct 3 functors for deleting (uniform, vertex & face varying) primvars
	IECoreScene::PrimitiveVariableAlgos::DeleteFlaggedUniformFunctor<T> uniformFunctor( deleteFlagView, invert );
	IECoreScene::PrimitiveVariableAlgos::DeleteFlaggedFaceVaryingFunctor<T> faceVaryingFunctor( deleteFlagView, meshPrimitive->verticesPerFace(), invert );
	IECoreScene::PrimitiveVariableAlgos::DeleteFlaggedVertexFunctor<T> vertexFunctor(
		meshPrimitive->variableSize( PrimitiveVariable::Vertex ), meshPrimitive->vertexIds(), meshPrimitive->verticesPerFace(), deleteFlagView, invert );

	// filter verticesPerFace using DeleteFlaggedUniformFunctor
	const IECore::Data *inputVerticesPerFace = IECore::runTimeCast<const IECore::Data>( meshPrimitive->verticesPerFace() );
	uniformFunctor.setIndices( nullptr );
	IECoreScene::PrimitiveVariableAlgos::IndexedData outputVerticesPerFace = dispatch( inputVerticesPerFace, uniformFunctor );
	IntVectorDataPtr verticesPerFace = IECore::runTimeCast<IECore::IntVectorData>( outputVerticesPerFace.data );

	// filter VertexIds using DeleteFlaggedFaceVaryingFunctor
	const IECore::Data *inputVertexIds = IECore::runTimeCast<const IECore::Data>( meshPrimitive->vertexIds() );
	faceVaryingFunctor.setIndices( nullptr );
	IECoreScene::PrimitiveVariableAlgos::IndexedData outputVertexIds = dispatch( inputVertexIds, faceVaryingFunctor );

	// remap the indices also
	ConstIntVectorDataPtr remappingData = vertexFunctor.getRemapping();
	const std::vector<int> &remapping = remappingData->readable();
	IntVectorDataPtr vertexIdsData = IECore::runTimeCast<IECore::IntVectorData>( outputVertexIds.data );
	IntVectorData::ValueType &vertexIds = vertexIdsData->writable();
	for( size_t i = 0; i < vertexIds.size(); ++i )
	{
		vertexIds[i] = remapping[vertexIds[i]];
	}

	// construct mesh without positions as they'll be set when filtering the primvars
	MeshPrimitivePtr outMeshPrimitive = new MeshPrimitive( verticesPerFace, vertexIdsData, meshPrimitive->interpolation() );

	deleteCorners( outMeshPrimitive.get(), meshPrimitive, remapping );
	deleteCreases( outMeshPrimitive.get(), meshPrimitive, remapping );

	for( PrimitiveVariableMap::const_iterator it = meshPrimitive->variables.begin(), e = meshPrimitive->variables.end(); it != e; ++it )
	{
		switch( it->second.interpolation )
		{
			case PrimitiveVariable::Uniform:
			{
				const IECore::Data *inputData = it->second.data.get();
				uniformFunctor.setIndices( it->second.indices.get() );
				IECoreScene::PrimitiveVariableAlgos::IndexedData outputData = dispatch( inputData, uniformFunctor );
				outMeshPrimitive->variables[it->first] = PrimitiveVariable( it->second.interpolation, outputData.data, outputData.indices );
				break;
			}
			case PrimitiveVariable::Vertex:
			case PrimitiveVariable::Varying:
			{
				const IECore::Data *inputData = it->second.data.get();
				vertexFunctor.setIndices( it->second.indices.get() );
				IECoreScene::PrimitiveVariableAlgos::IndexedData outputData = dispatch( inputData, vertexFunctor );
				outMeshPrimitive->variables[it->first] = PrimitiveVariable( it->second.interpolation, outputData.data, outputData.indices );
				break;
			}

			case PrimitiveVariable::FaceVarying:
			{
				const IECore::Data *inputData = it->second.data.get();
				faceVaryingFunctor.setIndices( it->second.indices.get() );
				IECoreScene::PrimitiveVariableAlgos::IndexedData outputData = dispatch(inputData, faceVaryingFunctor );
				outMeshPrimitive->variables[it->first] = PrimitiveVariable( it->second.interpolation, outputData.data, outputData.indices );
				break;
			}
			case PrimitiveVariable::Constant:
			case PrimitiveVariable::Invalid:
			{
				outMeshPrimitive->variables[it->first] = it->second;
				break;
			}
		}
	}
	return outMeshPrimitive;
}

} // namespace

MeshPrimitivePtr IECoreScene::MeshAlgo::deleteFaces( const MeshPrimitive *meshPrimitive, const PrimitiveVariable &facesToDelete, bool invert )
{

	if( facesToDelete.interpolation != PrimitiveVariable::Uniform )
	{
		throw InvalidArgumentException( "MeshAlgo::deleteFaces requires an Uniform [Int|Bool|Float]VectorData primitiveVariable " );
	}

	const IntVectorData *intDeleteFlagData = runTimeCast<const IntVectorData>( facesToDelete.data.get() );

	if( intDeleteFlagData )
	{
		PrimitiveVariable::IndexedView<int> deleteFlagView( facesToDelete );
		return ::deleteFaces( meshPrimitive, deleteFlagView, invert );
	}

	const BoolVectorData *boolDeleteFlagData = runTimeCast<const BoolVectorData>( facesToDelete.data.get() );

	if( boolDeleteFlagData )
	{
		PrimitiveVariable::IndexedView<bool> deleteFlagView( facesToDelete );
		return ::deleteFaces( meshPrimitive, deleteFlagView, invert );
	}

	const FloatVectorData *floatDeleteFlagData = runTimeCast<const FloatVectorData>( facesToDelete.data.get() );

	if( floatDeleteFlagData )
	{
		PrimitiveVariable::IndexedView<float> deleteFlagView( facesToDelete );
		return ::deleteFaces( meshPrimitive, deleteFlagView, invert );
	}

	throw InvalidArgumentException( "MeshAlgo::deleteFaces requires an Uniform [Int|Bool|Float]VectorData primitiveVariable " );

}
<commit_msg>MeshAlgo::deleteFaces : Add todo<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2017, 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.
//
//////////////////////////////////////////////////////////////////////////

#include "IECoreScene/MeshAlgo.h"
#include "IECoreScene/private/PrimitiveVariableAlgos.h"

#include "IECore/DespatchTypedData.h"
#include "IECore/DataAlgo.h"

using namespace Imath;
using namespace IECore;
using namespace IECoreScene;

//////////////////////////////////////////////////////////////////////////
// Delete Faces
//////////////////////////////////////////////////////////////////////////

namespace
{

void deleteCorners( MeshPrimitive *out, const MeshPrimitive *in, const std::vector<int> &remapping )
{
	const auto &ids = in->cornerIds()->readable();
	if( ids.empty() )
	{
		return;
	}

	const auto &sharpnesses = in->cornerSharpnesses()->readable();

	IntVectorDataPtr outIdData = new IntVectorData;
	auto &outIds = outIdData->writable();

	FloatVectorDataPtr outSharpnessData = new FloatVectorData;
	auto &outSharpnesses = outSharpnessData->writable();

	for( size_t i = 0; i < ids.size(); ++i )
	{
		int id = remapping[ ids[i] ];
		if( id != -1 )
		{
			outIds.push_back( id );
			outSharpnesses.push_back( sharpnesses[i] );
		}
	}

	out->setCorners( outIdData.get(), outSharpnessData.get() );
};

void deleteCreases( MeshPrimitive *out, const MeshPrimitive *in, const std::vector<int> &remapping )
{
	const auto &lengths = in->creaseLengths()->readable();
	if( lengths.empty() )
	{
		return;
	}

	const auto &ids = in->creaseIds()->readable();
	const auto &sharpnesses = in->creaseSharpnesses()->readable();

	IntVectorDataPtr outLengthData = new IntVectorData;
	auto &outLengths = outLengthData->writable();

	IntVectorDataPtr outIdData = new IntVectorData;
	auto &outIds = outIdData->writable();

	FloatVectorDataPtr outSharpnessData = new FloatVectorData;
	auto &outSharpnesses = outSharpnessData->writable();

	int creaseIdOffset = 0;
	for( size_t i = 0; i < lengths.size(); ++i )
	{
		int outLength = 0;
		for( int j = 0; j < lengths[i]; ++j )
		{
			int id = remapping[ ids[creaseIdOffset + j] ];
			if( id != -1 )
			{
				// \todo: This is not strictly correct. We might be adding creases
				// for edges that no longer exist (ie when a particular creased face
				// was deleted, but all of its original vertices remain).
				outIds.push_back( id );
				++outLength;
			}

		}

		if( outLength > 0 )
		{
			outLengths.push_back( outLength );
			outSharpnesses.push_back( sharpnesses[i] );
		}

		creaseIdOffset += lengths[i];
	}

	out->setCreases( outLengthData.get(), outIdData.get(), outSharpnessData.get() );
};

template<typename T>
MeshPrimitivePtr deleteFaces( const MeshPrimitive *meshPrimitive, PrimitiveVariable::IndexedView<T> &deleteFlagView, bool invert )
{
	// construct 3 functors for deleting (uniform, vertex & face varying) primvars
	IECoreScene::PrimitiveVariableAlgos::DeleteFlaggedUniformFunctor<T> uniformFunctor( deleteFlagView, invert );
	IECoreScene::PrimitiveVariableAlgos::DeleteFlaggedFaceVaryingFunctor<T> faceVaryingFunctor( deleteFlagView, meshPrimitive->verticesPerFace(), invert );
	IECoreScene::PrimitiveVariableAlgos::DeleteFlaggedVertexFunctor<T> vertexFunctor(
		meshPrimitive->variableSize( PrimitiveVariable::Vertex ), meshPrimitive->vertexIds(), meshPrimitive->verticesPerFace(), deleteFlagView, invert );

	// filter verticesPerFace using DeleteFlaggedUniformFunctor
	const IECore::Data *inputVerticesPerFace = IECore::runTimeCast<const IECore::Data>( meshPrimitive->verticesPerFace() );
	uniformFunctor.setIndices( nullptr );
	IECoreScene::PrimitiveVariableAlgos::IndexedData outputVerticesPerFace = dispatch( inputVerticesPerFace, uniformFunctor );
	IntVectorDataPtr verticesPerFace = IECore::runTimeCast<IECore::IntVectorData>( outputVerticesPerFace.data );

	// filter VertexIds using DeleteFlaggedFaceVaryingFunctor
	const IECore::Data *inputVertexIds = IECore::runTimeCast<const IECore::Data>( meshPrimitive->vertexIds() );
	faceVaryingFunctor.setIndices( nullptr );
	IECoreScene::PrimitiveVariableAlgos::IndexedData outputVertexIds = dispatch( inputVertexIds, faceVaryingFunctor );

	// remap the indices also
	ConstIntVectorDataPtr remappingData = vertexFunctor.getRemapping();
	const std::vector<int> &remapping = remappingData->readable();
	IntVectorDataPtr vertexIdsData = IECore::runTimeCast<IECore::IntVectorData>( outputVertexIds.data );
	IntVectorData::ValueType &vertexIds = vertexIdsData->writable();
	for( size_t i = 0; i < vertexIds.size(); ++i )
	{
		vertexIds[i] = remapping[vertexIds[i]];
	}

	// construct mesh without positions as they'll be set when filtering the primvars
	MeshPrimitivePtr outMeshPrimitive = new MeshPrimitive( verticesPerFace, vertexIdsData, meshPrimitive->interpolation() );

	deleteCorners( outMeshPrimitive.get(), meshPrimitive, remapping );
	deleteCreases( outMeshPrimitive.get(), meshPrimitive, remapping );

	for( PrimitiveVariableMap::const_iterator it = meshPrimitive->variables.begin(), e = meshPrimitive->variables.end(); it != e; ++it )
	{
		switch( it->second.interpolation )
		{
			case PrimitiveVariable::Uniform:
			{
				const IECore::Data *inputData = it->second.data.get();
				uniformFunctor.setIndices( it->second.indices.get() );
				IECoreScene::PrimitiveVariableAlgos::IndexedData outputData = dispatch( inputData, uniformFunctor );
				outMeshPrimitive->variables[it->first] = PrimitiveVariable( it->second.interpolation, outputData.data, outputData.indices );
				break;
			}
			case PrimitiveVariable::Vertex:
			case PrimitiveVariable::Varying:
			{
				const IECore::Data *inputData = it->second.data.get();
				vertexFunctor.setIndices( it->second.indices.get() );
				IECoreScene::PrimitiveVariableAlgos::IndexedData outputData = dispatch( inputData, vertexFunctor );
				outMeshPrimitive->variables[it->first] = PrimitiveVariable( it->second.interpolation, outputData.data, outputData.indices );
				break;
			}

			case PrimitiveVariable::FaceVarying:
			{
				const IECore::Data *inputData = it->second.data.get();
				faceVaryingFunctor.setIndices( it->second.indices.get() );
				IECoreScene::PrimitiveVariableAlgos::IndexedData outputData = dispatch(inputData, faceVaryingFunctor );
				outMeshPrimitive->variables[it->first] = PrimitiveVariable( it->second.interpolation, outputData.data, outputData.indices );
				break;
			}
			case PrimitiveVariable::Constant:
			case PrimitiveVariable::Invalid:
			{
				outMeshPrimitive->variables[it->first] = it->second;
				break;
			}
		}
	}
	return outMeshPrimitive;
}

} // namespace

MeshPrimitivePtr IECoreScene::MeshAlgo::deleteFaces( const MeshPrimitive *meshPrimitive, const PrimitiveVariable &facesToDelete, bool invert )
{

	if( facesToDelete.interpolation != PrimitiveVariable::Uniform )
	{
		throw InvalidArgumentException( "MeshAlgo::deleteFaces requires an Uniform [Int|Bool|Float]VectorData primitiveVariable " );
	}

	const IntVectorData *intDeleteFlagData = runTimeCast<const IntVectorData>( facesToDelete.data.get() );

	if( intDeleteFlagData )
	{
		PrimitiveVariable::IndexedView<int> deleteFlagView( facesToDelete );
		return ::deleteFaces( meshPrimitive, deleteFlagView, invert );
	}

	const BoolVectorData *boolDeleteFlagData = runTimeCast<const BoolVectorData>( facesToDelete.data.get() );

	if( boolDeleteFlagData )
	{
		PrimitiveVariable::IndexedView<bool> deleteFlagView( facesToDelete );
		return ::deleteFaces( meshPrimitive, deleteFlagView, invert );
	}

	const FloatVectorData *floatDeleteFlagData = runTimeCast<const FloatVectorData>( facesToDelete.data.get() );

	if( floatDeleteFlagData )
	{
		PrimitiveVariable::IndexedView<float> deleteFlagView( facesToDelete );
		return ::deleteFaces( meshPrimitive, deleteFlagView, invert );
	}

	throw InvalidArgumentException( "MeshAlgo::deleteFaces requires an Uniform [Int|Bool|Float]VectorData primitiveVariable " );

}
<|endoftext|>


<commit_before>#include "execthread.h"

void SuspendThreads(DWORD ProcessId, DWORD ExceptThreadId)
{
	HANDLE Snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
	if (Snapshot != INVALID_HANDLE_VALUE)
	{
		THREADENTRY32 ThreadEntry;
		ThreadEntry.dwSize = sizeof(ThreadEntry);
		if (Thread32First(Snapshot, &ThreadEntry))
		{
			do
			{
				if (ThreadEntry.dwSize >= FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID) + sizeof(ThreadEntry.th32OwnerProcessID))
				{
					if (ThreadEntry.th32ThreadID != ExceptThreadId && ThreadEntry.th32OwnerProcessID == ProcessId)
					{
						HANDLE Thread = OpenThread(THREAD_ALL_ACCESS, FALSE, ThreadEntry.th32ThreadID);
						if (Thread != NULL)
						{
							SuspendThread(Thread);
							CloseHandle(Thread);
						}
					}
				}
				ThreadEntry.dwSize = sizeof(ThreadEntry);
			} while (Thread32Next(Snapshot, &ThreadEntry));
		}
		CloseHandle(Snapshot);
	}
}

void ResumeThreads(DWORD ProcessId, DWORD ExceptThreadId)
{
	HANDLE Snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
	if (Snapshot != INVALID_HANDLE_VALUE)
	{
		THREADENTRY32 ThreadEntry;
		ThreadEntry.dwSize = sizeof(ThreadEntry);
		if (Thread32First(Snapshot, &ThreadEntry))
		{
			do
			{
				if (ThreadEntry.dwSize >= FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID) + sizeof(ThreadEntry.th32OwnerProcessID))
				{
					if (ThreadEntry.th32ThreadID != ExceptThreadId && ThreadEntry.th32OwnerProcessID == ProcessId)
					{
						HANDLE Thread = OpenThread(THREAD_ALL_ACCESS, FALSE, ThreadEntry.th32ThreadID);
						if (Thread != NULL)
						{
							ResumeThread(Thread);
							CloseHandle(Thread);
						}
					}
				}
				ThreadEntry.dwSize = sizeof(ThreadEntry);
			} while (Thread32Next(Snapshot, &ThreadEntry));
		}
		CloseHandle(Snapshot);
	}
}
<commit_msg>[refactor] execthread.cpp<commit_after>#include "stdafx.h"
#include "execthread.h"

void suspend_threads(std::uint32_t process_id, std::uint32_t except_thread_id)
{
	HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
	if (snapshot != INVALID_HANDLE_VALUE)
	{
		THREADENTRY32 thread_entry;
		thread_entry.dwSize = sizeof(thread_entry);
		if (Thread32First(snapshot, &thread_entry))
		{
			do
			{
				if (thread_entry.dwSize >= FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID) + sizeof(thread_entry.th32OwnerProcessID))
				{
					if (thread_entry.th32ThreadID != except_thread_id && thread_entry.th32OwnerProcessID == process_id)
					{
						HANDLE thread = OpenThread(THREAD_ALL_ACCESS, static_cast<std::uint8_t>(false), thread_entry.th32ThreadID);
						if (thread != nullptr)
						{
							SuspendThread(thread);
							CloseHandle(thread);
						}
					}
				}
				thread_entry.dwSize = sizeof(thread_entry);
			} while (Thread32Next(snapshot, &thread_entry));
		}
		CloseHandle(snapshot);
	}
}

void resume_threads(std::uint32_t process_id, std::uint32_t except_thread_id)
{
	HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
	if (snapshot != INVALID_HANDLE_VALUE)
	{
		THREADENTRY32 thread_entry;
		thread_entry.dwSize = sizeof(thread_entry);
		if (Thread32First(snapshot, &thread_entry))
		{
			do
			{
				if (thread_entry.dwSize >= FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID) + sizeof(thread_entry.th32OwnerProcessID))
				{
					if (thread_entry.th32ThreadID != except_thread_id && thread_entry.th32OwnerProcessID == process_id)
					{
						HANDLE thread = OpenThread(THREAD_ALL_ACCESS, static_cast<std::uint8_t>(false), thread_entry.th32ThreadID);
						if (thread != nullptr)
						{
							ResumeThread(thread);
							CloseHandle(thread);
						}
					}
				}
				thread_entry.dwSize = sizeof(thread_entry);
			} while (Thread32Next(snapshot, &thread_entry));
		}
		CloseHandle(snapshot);
	}
}

<|endoftext|>


<commit_before>/*
    This file is part of Magnum.

    Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016
              Vladimír Vondruš <mosra@centrum.cz>
    Copyright © 2016 Jonathan Hale <squareys@googlemail.com>

    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.
*/

#include "GlfwApplication.h"

#include <tuple>

#include "Magnum/Version.h"
#include "Magnum/Platform/Context.h"
#include "Magnum/Platform/ScreenedApplication.hpp"

namespace Magnum { namespace Platform {

GlfwApplication* GlfwApplication::_instance = nullptr;

#ifdef GLFW_TRUE
/* The docs say that it's the same, verify that just in case */
static_assert(GLFW_TRUE == true && GLFW_FALSE == false, "GLFW does not have sane bool values");
#endif

#ifndef DOXYGEN_GENERATING_OUTPUT
GlfwApplication::GlfwApplication(const Arguments& arguments): GlfwApplication{arguments, Configuration{}} {}
#endif

GlfwApplication::GlfwApplication(const Arguments& arguments, const Configuration& configuration): GlfwApplication{arguments, nullptr} {
    createContext(configuration);
}

GlfwApplication::GlfwApplication(const Arguments& arguments, std::nullptr_t):
    _context{new Context{NoCreate, arguments.argc, arguments.argv}},
    _needsRedraw(true)
{
    /* Save global instance */
    _instance = this;

    /* Init GLFW */
    glfwSetErrorCallback(staticErrorCallback);

    if(!glfwInit()) {
        Error() << "Could not initialize GLFW";
        std::exit(8);
    }
}

void GlfwApplication::createContext() { createContext({}); }

void GlfwApplication::createContext(const Configuration& configuration) {
    if(!tryCreateContext(configuration)) std::exit(1);
}

bool GlfwApplication::tryCreateContext(const Configuration& configuration) {
    CORRADE_ASSERT(_context->version() == Version::None, "Platform::GlfwApplication::tryCreateContext(): context already created", false);

    /* Window flags */
    GLFWmonitor* monitor = nullptr; /* Needed for setting fullscreen */
    if (configuration.windowFlags() >= Configuration::WindowFlag::Fullscreen) {
        monitor = glfwGetPrimaryMonitor();
        glfwWindowHint(GLFW_AUTO_ICONIFY, configuration.windowFlags() >= Configuration::WindowFlag::AutoIconify);
    } else {
        const Configuration::WindowFlags& flags = configuration.windowFlags();
        glfwWindowHint(GLFW_RESIZABLE, flags >= Configuration::WindowFlag::Resizeable);
        glfwWindowHint(GLFW_VISIBLE, !(flags >= Configuration::WindowFlag::Hidden));
        #ifdef GLFW_MAXIMIZED
        glfwWindowHint(GLFW_MAXIMIZED, flags >= Configuration::WindowFlag::Maximized);
        #endif
        glfwWindowHint(GLFW_ICONIFIED, flags >= Configuration::WindowFlag::Minimized);
        glfwWindowHint(GLFW_FLOATING, flags >= Configuration::WindowFlag::Floating);
    }
    glfwWindowHint(GLFW_FLOATING, configuration.windowFlags() >= Configuration::WindowFlag::Focused);

    /* Context window hints */
    glfwWindowHint(GLFW_SAMPLES, configuration.sampleCount());
    glfwWindowHint(GLFW_SRGB_CAPABLE, configuration.isSRGBCapable());

    const Configuration::Flags& flags = configuration.flags();
    #ifdef GLFW_CONTEXT_NO_ERROR
    glfwWindowHint(GLFW_CONTEXT_NO_ERROR, flags >= Configuration::Flag::NoError);
    #endif
    glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, flags >= Configuration::Flag::Debug);
    glfwWindowHint(GLFW_STEREO, flags >= Configuration::Flag::Stereo);

    /* Cursor flags */
    glfwWindowHint(GLFW_CURSOR, Int(configuration.cursorMode()));

    /* Set context version, if requested */
    if(configuration.version() != Version::None) {
        Int major, minor;
        std::tie(major, minor) = version(configuration.version());
        glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, major);
        glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, minor);
        #ifndef MAGNUM_TARGET_GLES
        if(configuration.version() >= Version::GL310) {
            glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, true);
            glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
        }
        #else
        glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API);
        #endif
    }

    /* Set context flags */
    _window = glfwCreateWindow(configuration.size().x(), configuration.size().y(), configuration.title().c_str(), monitor, nullptr);
    if(!_window) {
        Error() << "Platform::GlfwApplication::tryCreateContext(): cannot create context";
        glfwTerminate();
        return false;
    }

    /* Set callbacks */
    glfwSetFramebufferSizeCallback(_window, staticViewportEvent);
    glfwSetKeyCallback(_window, staticKeyEvent);
    glfwSetCursorPosCallback(_window, staticMouseMoveEvent);
    glfwSetMouseButtonCallback(_window, staticMouseEvent);
    glfwSetScrollCallback(_window, staticMouseScrollEvent);

    glfwMakeContextCurrent(_window);

    /* Return true if the initialization succeeds */
    return _context->tryCreate();
}

GlfwApplication::~GlfwApplication() {
    glfwDestroyWindow(_window);
    glfwTerminate();
}

void GlfwApplication::setSwapInterval(const Int interval) {
    glfwSwapInterval(interval);
}

int GlfwApplication::exec() {
    while(!glfwWindowShouldClose(_window)) {
        if(_needsRedraw) {
            drawEvent();
        }
        glfwPollEvents();
    }
    return 0;
}

void GlfwApplication::staticKeyEvent(GLFWwindow*, int key, int, int action, int mods) {
    KeyEvent e(static_cast<KeyEvent::Key>(key), {static_cast<InputEvent::Modifier>(mods)});

    if(action == GLFW_PRESS) {
        _instance->keyPressEvent(e);
    } else if(action == GLFW_RELEASE) {
        _instance->keyReleaseEvent(e);
    } /* we don't handle GLFW_REPEAT */
}

void GlfwApplication::staticMouseMoveEvent(GLFWwindow* window, double x, double y) {
    MouseMoveEvent e{Vector2i{Int(x), Int(y)}, KeyEvent::getCurrentGlfwModifiers(window)};
    _instance->mouseMoveEvent(e);
}

void GlfwApplication::staticMouseEvent(GLFWwindow*, int button, int action, int mods) {
    MouseEvent e(static_cast<MouseEvent::Button>(button), {static_cast<InputEvent::Modifier>(mods)});

    if(action == GLFW_PRESS) {
        _instance->mousePressEvent(e);
    } else if(action == GLFW_RELEASE) {
        _instance->mouseReleaseEvent(e);
    } /* we don't handle GLFW_REPEAT */
}

void GlfwApplication::staticMouseScrollEvent(GLFWwindow* window, double xoffset, double yoffset) {
    MouseScrollEvent e(Vector2d{xoffset, yoffset}, KeyEvent::getCurrentGlfwModifiers(window));
    _instance->mouseScrollEvent(e);

    if(yoffset != 0.0) {
        MouseEvent e1((yoffset > 0.0) ? MouseEvent::Button::WheelUp : MouseEvent::Button::WheelDown, KeyEvent::getCurrentGlfwModifiers(window));
        _instance->mousePressEvent(e1);
    }
}

void GlfwApplication::staticErrorCallback(int, const char* description) {
    Error() << description;
}

auto GlfwApplication::KeyEvent::getCurrentGlfwModifiers(GLFWwindow* window) -> Modifiers {
    static_assert(GLFW_PRESS == true && GLFW_RELEASE == false,
        "GLFW press and release constants do not correspond to bool values");

    Modifiers mods;
    if(glfwGetKey(window, Int(Key::LeftShift)) || glfwGetKey(window, Int(Key::RightShift)))
        mods |= Modifier::Shift;
    if(glfwGetKey(window, Int(Key::LeftAlt)) || glfwGetKey(window, Int(Key::RightAlt)))
        mods |= Modifier::Alt;
    if(glfwGetKey(window, Int(Key::LeftCtrl)) || glfwGetKey(window, Int(Key::RightCtrl)))
        mods |= Modifier::Ctrl;
    if(glfwGetKey(window, Int(Key::RightSuper)))
        mods |= Modifier::AltGr;

    return mods;
}

void GlfwApplication::viewportEvent(const Vector2i&) {}
void GlfwApplication::keyPressEvent(KeyEvent&) {}
void GlfwApplication::keyReleaseEvent(KeyEvent&) {}
void GlfwApplication::mousePressEvent(MouseEvent&) {}
void GlfwApplication::mouseReleaseEvent(MouseEvent&) {}
void GlfwApplication::mouseMoveEvent(MouseMoveEvent&) {}
void GlfwApplication::mouseScrollEvent(MouseScrollEvent&) {}

GlfwApplication::Configuration::Configuration():
    _title{"Magnum GLFW Application"},
    _size{800, 600}, _sampleCount{0},
    _version{Version::None},
    _windowFlags{WindowFlag::Focused},
    _cursorMode{CursorMode::Normal} {}

GlfwApplication::Configuration::~Configuration() = default;

template class BasicScreen<GlfwApplication>;
template class BasicScreenedApplication<GlfwApplication>;

}}
<commit_msg>Platform: fix copypaste error in GLFW application.<commit_after>/*
    This file is part of Magnum.

    Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016
              Vladimír Vondruš <mosra@centrum.cz>
    Copyright © 2016 Jonathan Hale <squareys@googlemail.com>

    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.
*/

#include "GlfwApplication.h"

#include <tuple>

#include "Magnum/Version.h"
#include "Magnum/Platform/Context.h"
#include "Magnum/Platform/ScreenedApplication.hpp"

namespace Magnum { namespace Platform {

GlfwApplication* GlfwApplication::_instance = nullptr;

#ifdef GLFW_TRUE
/* The docs say that it's the same, verify that just in case */
static_assert(GLFW_TRUE == true && GLFW_FALSE == false, "GLFW does not have sane bool values");
#endif

#ifndef DOXYGEN_GENERATING_OUTPUT
GlfwApplication::GlfwApplication(const Arguments& arguments): GlfwApplication{arguments, Configuration{}} {}
#endif

GlfwApplication::GlfwApplication(const Arguments& arguments, const Configuration& configuration): GlfwApplication{arguments, nullptr} {
    createContext(configuration);
}

GlfwApplication::GlfwApplication(const Arguments& arguments, std::nullptr_t):
    _context{new Context{NoCreate, arguments.argc, arguments.argv}},
    _needsRedraw(true)
{
    /* Save global instance */
    _instance = this;

    /* Init GLFW */
    glfwSetErrorCallback(staticErrorCallback);

    if(!glfwInit()) {
        Error() << "Could not initialize GLFW";
        std::exit(8);
    }
}

void GlfwApplication::createContext() { createContext({}); }

void GlfwApplication::createContext(const Configuration& configuration) {
    if(!tryCreateContext(configuration)) std::exit(1);
}

bool GlfwApplication::tryCreateContext(const Configuration& configuration) {
    CORRADE_ASSERT(_context->version() == Version::None, "Platform::GlfwApplication::tryCreateContext(): context already created", false);

    /* Window flags */
    GLFWmonitor* monitor = nullptr; /* Needed for setting fullscreen */
    if (configuration.windowFlags() >= Configuration::WindowFlag::Fullscreen) {
        monitor = glfwGetPrimaryMonitor();
        glfwWindowHint(GLFW_AUTO_ICONIFY, configuration.windowFlags() >= Configuration::WindowFlag::AutoIconify);
    } else {
        const Configuration::WindowFlags& flags = configuration.windowFlags();
        glfwWindowHint(GLFW_RESIZABLE, flags >= Configuration::WindowFlag::Resizeable);
        glfwWindowHint(GLFW_VISIBLE, !(flags >= Configuration::WindowFlag::Hidden));
        #ifdef GLFW_MAXIMIZED
        glfwWindowHint(GLFW_MAXIMIZED, flags >= Configuration::WindowFlag::Maximized);
        #endif
        glfwWindowHint(GLFW_ICONIFIED, flags >= Configuration::WindowFlag::Minimized);
        glfwWindowHint(GLFW_FLOATING, flags >= Configuration::WindowFlag::Floating);
    }
    glfwWindowHint(GLFW_FOCUSED, configuration.windowFlags() >= Configuration::WindowFlag::Focused);

    /* Context window hints */
    glfwWindowHint(GLFW_SAMPLES, configuration.sampleCount());
    glfwWindowHint(GLFW_SRGB_CAPABLE, configuration.isSRGBCapable());

    const Configuration::Flags& flags = configuration.flags();
    #ifdef GLFW_CONTEXT_NO_ERROR
    glfwWindowHint(GLFW_CONTEXT_NO_ERROR, flags >= Configuration::Flag::NoError);
    #endif
    glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, flags >= Configuration::Flag::Debug);
    glfwWindowHint(GLFW_STEREO, flags >= Configuration::Flag::Stereo);

    /* Cursor flags */
    glfwWindowHint(GLFW_CURSOR, Int(configuration.cursorMode()));

    /* Set context version, if requested */
    if(configuration.version() != Version::None) {
        Int major, minor;
        std::tie(major, minor) = version(configuration.version());
        glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, major);
        glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, minor);
        #ifndef MAGNUM_TARGET_GLES
        if(configuration.version() >= Version::GL310) {
            glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, true);
            glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
        }
        #else
        glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API);
        #endif
    }

    /* Set context flags */
    _window = glfwCreateWindow(configuration.size().x(), configuration.size().y(), configuration.title().c_str(), monitor, nullptr);
    if(!_window) {
        Error() << "Platform::GlfwApplication::tryCreateContext(): cannot create context";
        glfwTerminate();
        return false;
    }

    /* Set callbacks */
    glfwSetFramebufferSizeCallback(_window, staticViewportEvent);
    glfwSetKeyCallback(_window, staticKeyEvent);
    glfwSetCursorPosCallback(_window, staticMouseMoveEvent);
    glfwSetMouseButtonCallback(_window, staticMouseEvent);
    glfwSetScrollCallback(_window, staticMouseScrollEvent);

    glfwMakeContextCurrent(_window);

    /* Return true if the initialization succeeds */
    return _context->tryCreate();
}

GlfwApplication::~GlfwApplication() {
    glfwDestroyWindow(_window);
    glfwTerminate();
}

void GlfwApplication::setSwapInterval(const Int interval) {
    glfwSwapInterval(interval);
}

int GlfwApplication::exec() {
    while(!glfwWindowShouldClose(_window)) {
        if(_needsRedraw) {
            drawEvent();
        }
        glfwPollEvents();
    }
    return 0;
}

void GlfwApplication::staticKeyEvent(GLFWwindow*, int key, int, int action, int mods) {
    KeyEvent e(static_cast<KeyEvent::Key>(key), {static_cast<InputEvent::Modifier>(mods)});

    if(action == GLFW_PRESS) {
        _instance->keyPressEvent(e);
    } else if(action == GLFW_RELEASE) {
        _instance->keyReleaseEvent(e);
    } /* we don't handle GLFW_REPEAT */
}

void GlfwApplication::staticMouseMoveEvent(GLFWwindow* window, double x, double y) {
    MouseMoveEvent e{Vector2i{Int(x), Int(y)}, KeyEvent::getCurrentGlfwModifiers(window)};
    _instance->mouseMoveEvent(e);
}

void GlfwApplication::staticMouseEvent(GLFWwindow*, int button, int action, int mods) {
    MouseEvent e(static_cast<MouseEvent::Button>(button), {static_cast<InputEvent::Modifier>(mods)});

    if(action == GLFW_PRESS) {
        _instance->mousePressEvent(e);
    } else if(action == GLFW_RELEASE) {
        _instance->mouseReleaseEvent(e);
    } /* we don't handle GLFW_REPEAT */
}

void GlfwApplication::staticMouseScrollEvent(GLFWwindow* window, double xoffset, double yoffset) {
    MouseScrollEvent e(Vector2d{xoffset, yoffset}, KeyEvent::getCurrentGlfwModifiers(window));
    _instance->mouseScrollEvent(e);

    if(yoffset != 0.0) {
        MouseEvent e1((yoffset > 0.0) ? MouseEvent::Button::WheelUp : MouseEvent::Button::WheelDown, KeyEvent::getCurrentGlfwModifiers(window));
        _instance->mousePressEvent(e1);
    }
}

void GlfwApplication::staticErrorCallback(int, const char* description) {
    Error() << description;
}

auto GlfwApplication::KeyEvent::getCurrentGlfwModifiers(GLFWwindow* window) -> Modifiers {
    static_assert(GLFW_PRESS == true && GLFW_RELEASE == false,
        "GLFW press and release constants do not correspond to bool values");

    Modifiers mods;
    if(glfwGetKey(window, Int(Key::LeftShift)) || glfwGetKey(window, Int(Key::RightShift)))
        mods |= Modifier::Shift;
    if(glfwGetKey(window, Int(Key::LeftAlt)) || glfwGetKey(window, Int(Key::RightAlt)))
        mods |= Modifier::Alt;
    if(glfwGetKey(window, Int(Key::LeftCtrl)) || glfwGetKey(window, Int(Key::RightCtrl)))
        mods |= Modifier::Ctrl;
    if(glfwGetKey(window, Int(Key::RightSuper)))
        mods |= Modifier::AltGr;

    return mods;
}

void GlfwApplication::viewportEvent(const Vector2i&) {}
void GlfwApplication::keyPressEvent(KeyEvent&) {}
void GlfwApplication::keyReleaseEvent(KeyEvent&) {}
void GlfwApplication::mousePressEvent(MouseEvent&) {}
void GlfwApplication::mouseReleaseEvent(MouseEvent&) {}
void GlfwApplication::mouseMoveEvent(MouseMoveEvent&) {}
void GlfwApplication::mouseScrollEvent(MouseScrollEvent&) {}

GlfwApplication::Configuration::Configuration():
    _title{"Magnum GLFW Application"},
    _size{800, 600}, _sampleCount{0},
    _version{Version::None},
    _windowFlags{WindowFlag::Focused},
    _cursorMode{CursorMode::Normal} {}

GlfwApplication::Configuration::~Configuration() = default;

template class BasicScreen<GlfwApplication>;
template class BasicScreenedApplication<GlfwApplication>;

}}
<|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.
//
//////////////////////////////////////////////////////////////////////////

#include "IECore/ImagePrimitive.h"
#include "IECore/MessageHandler.h"
#include "IECore/Renderer.h"

using namespace std;
using namespace IECore;
using namespace Imath;
using namespace boost;

const unsigned int ImagePrimitive::m_ioVersion = 0;
IE_CORE_DEFINEOBJECTTYPEDESCRIPTION(ImagePrimitive);

ImagePrimitive::ImagePrimitive()
{
}

ImagePrimitive::ImagePrimitive(Box2i datawindow, Box2i displaywindow)
	: m_dataWindow(datawindow), m_displayWindow(displaywindow)
{
}

Box3f ImagePrimitive::bound() const
{
	/// \todo We might need to include any pixel aspect ratio in this bound

	/// We add one here because the displayWindow is measured in pixels, and is inclusive. That is, an image
	/// which has a displayWindow of (0,0)->(0,0) contains exactly one pixel.
	return Box3f(
		V3f( m_displayWindow.min.x, m_displayWindow.min.y, 0.0 ),
		V3f( 1.0f + m_displayWindow.max.x, 1.0f + m_displayWindow.max.y, 0.0 )
	);
}

const Box2i &ImagePrimitive::getDataWindow() const
{
	return m_dataWindow;
}

void ImagePrimitive::setDataWindow(const Box2i &dw)
{
	m_dataWindow = dw;
}

const Box2i &ImagePrimitive::getDisplayWindow() const
{
	return m_displayWindow;
}

void ImagePrimitive::setDisplayWindow(const Box2i &dw)
{
	m_displayWindow = dw;
}

const int ImagePrimitive::width() const
{
	return 1 + m_dataWindow.max.x - m_dataWindow.min.x;
}

const int ImagePrimitive::height() const
{
	return 1 + m_dataWindow.max.y - m_dataWindow.min.y;
}

const int ImagePrimitive::area() const
{
	return width() * height();
}

const int ImagePrimitive::x() const
{
	return m_dataWindow.min.x;
}

const int ImagePrimitive::y() const
{
	return m_dataWindow.min.y;
}

void ImagePrimitive::channelNames(vector<string> &names) const
{
	// copy in the names of channels from the map
	names.clear();
	PrimitiveVariableMap::const_iterator i = variables.begin();
	while(i != variables.end()) {
		names.push_back(i->first);
		++i;
	}
}

// give the size of the image
size_t ImagePrimitive::variableSize(PrimitiveVariable::Interpolation interpolation)
{

	switch(interpolation) {

	case PrimitiveVariable::Vertex:
	case PrimitiveVariable::Varying:
	case PrimitiveVariable::FaceVarying:
		return area();

	default:
		return 1;

	}
}

void ImagePrimitive::render(RendererPtr renderer)
{
	renderer->image(m_dataWindow, m_displayWindow, variables);
}

//
// handling for serialization
//
void ImagePrimitive::copyFrom(ConstObjectPtr rhs, IECore::Object::CopyContext *context ) {
	Primitive::copyFrom(rhs, context);
	const ImagePrimitive *p_rhs = static_cast<const ImagePrimitive *>(rhs.get());

	m_displayWindow = p_rhs->getDisplayWindow();
	m_dataWindow = p_rhs->getDataWindow();
}

void ImagePrimitive::save(IECore::Object::SaveContext *context) const {
	Primitive::save(context);
	IndexedIOInterfacePtr container = context->container(staticTypeName(), m_ioVersion);

	container->write("displayWindowMinX", m_displayWindow.min.x);
	container->write("displayWindowMinY", m_displayWindow.min.y);
	container->write("displayWindowMaxX", m_displayWindow.max.x);
	container->write("displayWindowMaxY", m_displayWindow.max.y);
}

void ImagePrimitive::load(IECore::Object::LoadContextPtr context) {
	Primitive::load(context);
	unsigned int v = m_ioVersion;

	IndexedIOInterfacePtr container = context->container(staticTypeName(), v);

	container->read("displayWindowMinX", m_displayWindow.min.x);
	container->read("displayWindowMinY", m_displayWindow.min.y);
	container->read("displayWindowMaxX", m_displayWindow.max.x);
	container->read("displayWindowMaxY", m_displayWindow.max.y);
}

bool ImagePrimitive::isEqualTo(ConstObjectPtr rhs) const {
	if(!Primitive::isEqualTo(rhs)) return false;

	const ImagePrimitive *p_rhs = static_cast<const ImagePrimitive *>(rhs.get());

	// return true iff we have the same data window.
	// this is not complete
	return m_dataWindow == p_rhs->getDataWindow() && m_displayWindow == p_rhs->getDisplayWindow();
}

void ImagePrimitive::memoryUsage( Object::MemoryAccumulator &a ) const
{
	Primitive::memoryUsage( a );
	a.accumulate( sizeof(m_displayWindow) );
	a.accumulate( sizeof(m_dataWindow) );
}
<commit_msg>Fixed formatting<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.
//
//////////////////////////////////////////////////////////////////////////

#include "IECore/ImagePrimitive.h"
#include "IECore/MessageHandler.h"
#include "IECore/Renderer.h"

using namespace std;
using namespace IECore;
using namespace Imath;
using namespace boost;

const unsigned int ImagePrimitive::m_ioVersion = 0;
IE_CORE_DEFINEOBJECTTYPEDESCRIPTION(ImagePrimitive);

ImagePrimitive::ImagePrimitive()
{
}

ImagePrimitive::ImagePrimitive(Box2i datawindow, Box2i displaywindow)
		: m_dataWindow(datawindow), m_displayWindow(displaywindow)
{
}

Box3f ImagePrimitive::bound() const
{
	/// \todo We might need to include any pixel aspect ratio in this bound

	/// We add one here because the displayWindow is measured in pixels, and is inclusive. That is, an image
	/// which has a displayWindow of (0,0)->(0,0) contains exactly one pixel.
	return Box3f(
	               V3f( m_displayWindow.min.x, m_displayWindow.min.y, 0.0 ),
	               V3f( 1.0f + m_displayWindow.max.x, 1.0f + m_displayWindow.max.y, 0.0 )
	       );
}

const Box2i &ImagePrimitive::getDataWindow() const
{
	return m_dataWindow;
}

void ImagePrimitive::setDataWindow(const Box2i &dw)
{
	m_dataWindow = dw;
}

const Box2i &ImagePrimitive::getDisplayWindow() const
{
	return m_displayWindow;
}

void ImagePrimitive::setDisplayWindow(const Box2i &dw)
{
	m_displayWindow = dw;
}

const int ImagePrimitive::width() const
{
	return 1 + m_dataWindow.max.x - m_dataWindow.min.x;
}

const int ImagePrimitive::height() const
{
	return 1 + m_dataWindow.max.y - m_dataWindow.min.y;
}

const int ImagePrimitive::area() const
{
	return width() * height();
}

const int ImagePrimitive::x() const
{
	return m_dataWindow.min.x;
}

const int ImagePrimitive::y() const
{
	return m_dataWindow.min.y;
}

void ImagePrimitive::channelNames(vector<string> &names) const
{
	// copy in the names of channels from the map
	names.clear();
	PrimitiveVariableMap::const_iterator i = variables.begin();
	while (i != variables.end())
	{
		names.push_back(i->first);
		++i;
	}
}

// give the size of the image
size_t ImagePrimitive::variableSize(PrimitiveVariable::Interpolation interpolation)
{
	switch (interpolation)
	{

	case PrimitiveVariable::Vertex:
	case PrimitiveVariable::Varying:
	case PrimitiveVariable::FaceVarying:
		return area();

	default:
		return 1;

	}
}

void ImagePrimitive::render(RendererPtr renderer)
{
	renderer->image(m_dataWindow, m_displayWindow, variables);
}

//
// handling for serialization
//
void ImagePrimitive::copyFrom(ConstObjectPtr rhs, IECore::Object::CopyContext *context )
{
	Primitive::copyFrom(rhs, context);
	const ImagePrimitive *p_rhs = static_cast<const ImagePrimitive *>(rhs.get());

	m_displayWindow = p_rhs->getDisplayWindow();
	m_dataWindow = p_rhs->getDataWindow();
}

void ImagePrimitive::save(IECore::Object::SaveContext *context) const
{
	Primitive::save(context);
	IndexedIOInterfacePtr container = context->container(staticTypeName(), m_ioVersion);

	container->write("displayWindowMinX", m_displayWindow.min.x);
	container->write("displayWindowMinY", m_displayWindow.min.y);
	container->write("displayWindowMaxX", m_displayWindow.max.x);
	container->write("displayWindowMaxY", m_displayWindow.max.y);
}

void ImagePrimitive::load(IECore::Object::LoadContextPtr context)
{
	Primitive::load(context);
	unsigned int v = m_ioVersion;

	IndexedIOInterfacePtr container = context->container(staticTypeName(), v);

	container->read("displayWindowMinX", m_displayWindow.min.x);
	container->read("displayWindowMinY", m_displayWindow.min.y);
	container->read("displayWindowMaxX", m_displayWindow.max.x);
	container->read("displayWindowMaxY", m_displayWindow.max.y);
}

bool ImagePrimitive::isEqualTo(ConstObjectPtr rhs) const
{
	if (!Primitive::isEqualTo(rhs))
	{
		return false;
	}

	const ImagePrimitive *p_rhs = static_cast<const ImagePrimitive *>(rhs.get());

	// return true iff we have the same data window.
	// this is not complete
	return m_dataWindow == p_rhs->getDataWindow() && m_displayWindow == p_rhs->getDisplayWindow();
}

void ImagePrimitive::memoryUsage( Object::MemoryAccumulator &a ) const
{
	Primitive::memoryUsage( a );
	a.accumulate( sizeof(m_displayWindow) );
	a.accumulate( sizeof(m_dataWindow) );
}
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2007, 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.
//
//////////////////////////////////////////////////////////////////////////

#include "IECore/TypedParameter.h"
#include "IECore/CompoundObject.h"

using namespace std;
using namespace IECore;
using namespace boost;
using namespace Imath;

/////////////////////////////////////////////////////////////////////////////////////
// constructor stuff
/////////////////////////////////////////////////////////////////////////////////////

template<typename T>
static Parameter::PresetsMap convertPresets( const typename TypedParameter<T>::PresetsMap p )
{
	Parameter::PresetsMap result;
	for( typename TypedParameter<T>::PresetsMap::const_iterator it=p.begin(); it!=p.end(); it++ )
	{
		result.insert( typename Parameter::PresetsMap::value_type( it->first, new TypedData<T>( it->second ) ) );
	}
	return result;
}

template<typename T>
static Parameter::PresetsMap convertPresets( const typename TypedParameter<T>::ObjectPresetsMap p )
{
	Parameter::PresetsMap result;
	for( typename TypedParameter<T>::ObjectPresetsMap::const_iterator it=p.begin(); it!=p.end(); it++ )
	{
		result.insert( typename Parameter::PresetsMap::value_type( it->first, it->second ) );
	}
	return result;
}

template<typename T>
TypedParameter<T>::TypedParameter( const std::string &name, const std::string &description, const T &defaultValue,
	const PresetsMap &presets, bool presetsOnly, ConstCompoundObjectPtr userData )
	:	Parameter( name, description, new ObjectType( defaultValue ), convertPresets<T>( presets ), presetsOnly, userData )
{
}

template<typename T>
TypedParameter<T>::TypedParameter( const std::string &name, const std::string &description, ObjectTypePtr defaultValue,
	const ObjectPresetsMap &presets, bool presetsOnly, ConstCompoundObjectPtr userData )
	:	Parameter( name, description, defaultValue, convertPresets<T>( presets ), presetsOnly, userData )
{
}

/////////////////////////////////////////////////////////////////////////////////////
// runtimetyped stuff
/////////////////////////////////////////////////////////////////////////////////////

template <class T>
TypeId TypedParameter<T>::typeId() const
{
	return staticTypeId();
}

template <class T>
TypeId TypedParameter<T>::staticTypeId()
{
	assert( 0 ); // this function must be specialised for each type!
	return InvalidTypeId;
}

template <class T>
std::string TypedParameter<T>::typeName() const
{
	return staticTypeName();
}

template <class T>
std::string TypedParameter<T>::staticTypeName()
{
	assert( 0 ); // this function must be specialised for each type!
	return "";
}

template<class T>
bool TypedParameter<T>::isInstanceOf( TypeId typeId ) const
{
	if( typeId==staticTypeId() )
	{
		return true;
	}
	return Parameter::isInstanceOf( typeId );
}

template<class T>
bool TypedParameter<T>::isInstanceOf( const std::string &typeName ) const
{
	if( typeName==staticTypeName() )
	{
		return true;
	}
	return Parameter::isInstanceOf( typeName );
}

template<class T>
bool TypedParameter<T>::inheritsFrom( TypeId typeId )
{
	return Parameter::staticTypeId()==typeId ? true : Parameter::inheritsFrom( typeId );
}

template<class T>
bool TypedParameter<T>::inheritsFrom( const std::string &typeName )
{
	return Parameter::staticTypeName()==typeName ? true : Parameter::inheritsFrom( typeName );
}

/////////////////////////////////////////////////////////////////////////////////////
// other stuff
/////////////////////////////////////////////////////////////////////////////////////

template<typename T>
bool TypedParameter<T>::valueValid( ConstObjectPtr value, std::string *reason ) const
{
	if( !Parameter::valueValid( value, reason ) )
	{
		return false;
	}
	ConstObjectTypePtr tValue = runTimeCast<const ObjectType>( value );
	if( !tValue )
	{
		if( reason )
		{
			*reason = string( "Value is not an instance of \"" ) + ObjectType::staticTypeName() + "\"";
		}
		return false;
	}
	return true;
}

template<typename T>
const typename TypedParameter<T>::ValueType &TypedParameter<T>::typedDefaultValue() const
{
	return static_pointer_cast<const TypedData<T> >( defaultValue() )->readable();
}

template<typename T>
const typename TypedParameter<T>::ValueType &TypedParameter<T>::getTypedValue() const
{
	ConstObjectTypePtr tValue = runTimeCast<const ObjectType>( getValue() );
	if( !tValue )
	{
		throw Exception( string( "Value is not an instance of \"" ) + ObjectType::staticTypeName() + "\"");
	}
	return static_pointer_cast<const TypedData<T> >( getValue() )->readable();
}

template<typename T>
void TypedParameter<T>::setTypedValue( const T &value )
{
	setValue( new TypedData<T>( value ) );
}

/////////////////////////////////////////////////////////////////////////////////////
// specialisation and template instantiation
/////////////////////////////////////////////////////////////////////////////////////

#define IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( T, TNAME )						\
																					\
	template<>																		\
	TypeId TypedParameter<T>::staticTypeId()										\
	{																				\
		return TNAME ## TypeId;														\
	}																				\
																					\
	template<>																		\
	std::string TypedParameter<T>::staticTypeName()									\
	{																				\
		return # TNAME;																\
	}																				\
																					\
	template class TypedParameter<T>;

namespace IECore
{
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( bool, BoolParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( string, StringParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( V2i, V2iParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( V3i, V3iParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( V2f, V2fParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( V3f, V3fParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( V2d, V2dParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( V3d, V3dParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( Color3f, Color3fParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( Color4f, Color4fParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( Box2i, Box2iParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( Box3i, Box3iParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( Box2f, Box2fParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( Box3f, Box3fParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( Box2d, Box2dParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( Box3d, Box3dParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( M44f, M44fParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( M44d, M44dParameter )

IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( vector<int>, IntVectorParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( vector<float>, FloatVectorParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( vector<double>, DoubleVectorParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( vector<string>, StringVectorParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( vector<V2f>, V2fVectorParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( vector<V3f>, V3fVectorParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( vector<V2d>, V2dVectorParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( vector<V3d>, V3dVectorParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( vector<Box3f>, Box3fVectorParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( vector<Box3d>, Box3dVectorParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( vector<M33f>, M33fVectorParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( vector<M44f>, M44fVectorParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( vector<M33d>, M33dVectorParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( vector<M44d>, M44dVectorParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( vector<Quatf>, QuatfVectorParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( vector<Quatd>, QuatdVectorParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( vector<Color3f>, Color3fVectorParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( vector<Color4f>, Color4fVectorParameter )
}
<commit_msg>Swapped some runtime asserts for compile-time asserts<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.
//
//////////////////////////////////////////////////////////////////////////

#include "boost/static_assert.hpp"

#include "IECore/TypedParameter.h"
#include "IECore/CompoundObject.h"

using namespace std;
using namespace IECore;
using namespace boost;
using namespace Imath;

/////////////////////////////////////////////////////////////////////////////////////
// constructor stuff
/////////////////////////////////////////////////////////////////////////////////////

template<typename T>
static Parameter::PresetsMap convertPresets( const typename TypedParameter<T>::PresetsMap p )
{
	Parameter::PresetsMap result;
	for( typename TypedParameter<T>::PresetsMap::const_iterator it=p.begin(); it!=p.end(); it++ )
	{
		result.insert( typename Parameter::PresetsMap::value_type( it->first, new TypedData<T>( it->second ) ) );
	}
	return result;
}

template<typename T>
static Parameter::PresetsMap convertPresets( const typename TypedParameter<T>::ObjectPresetsMap p )
{
	Parameter::PresetsMap result;
	for( typename TypedParameter<T>::ObjectPresetsMap::const_iterator it=p.begin(); it!=p.end(); it++ )
	{
		result.insert( typename Parameter::PresetsMap::value_type( it->first, it->second ) );
	}
	return result;
}

template<typename T>
TypedParameter<T>::TypedParameter( const std::string &name, const std::string &description, const T &defaultValue,
	const PresetsMap &presets, bool presetsOnly, ConstCompoundObjectPtr userData )
	:	Parameter( name, description, new ObjectType( defaultValue ), convertPresets<T>( presets ), presetsOnly, userData )
{
}

template<typename T>
TypedParameter<T>::TypedParameter( const std::string &name, const std::string &description, ObjectTypePtr defaultValue,
	const ObjectPresetsMap &presets, bool presetsOnly, ConstCompoundObjectPtr userData )
	:	Parameter( name, description, defaultValue, convertPresets<T>( presets ), presetsOnly, userData )
{
}

/////////////////////////////////////////////////////////////////////////////////////
// runtimetyped stuff
/////////////////////////////////////////////////////////////////////////////////////

template <class T>
TypeId TypedParameter<T>::typeId() const
{
	return staticTypeId();
}

template <class T>
TypeId TypedParameter<T>::staticTypeId()
{
	BOOST_STATIC_ASSERT( sizeof(T) == 0 ); // this function must be specialised for each type!
	return InvalidTypeId;
}

template <class T>
std::string TypedParameter<T>::typeName() const
{
	return staticTypeName();
}

template <class T>
std::string TypedParameter<T>::staticTypeName()
{
	BOOST_STATIC_ASSERT( sizeof(T) == 0 ); // this function must be specialised for each type!
	return "";
}

template<class T>
bool TypedParameter<T>::isInstanceOf( TypeId typeId ) const
{
	if( typeId==staticTypeId() )
	{
		return true;
	}
	return Parameter::isInstanceOf( typeId );
}

template<class T>
bool TypedParameter<T>::isInstanceOf( const std::string &typeName ) const
{
	if( typeName==staticTypeName() )
	{
		return true;
	}
	return Parameter::isInstanceOf( typeName );
}

template<class T>
bool TypedParameter<T>::inheritsFrom( TypeId typeId )
{
	return Parameter::staticTypeId()==typeId ? true : Parameter::inheritsFrom( typeId );
}

template<class T>
bool TypedParameter<T>::inheritsFrom( const std::string &typeName )
{
	return Parameter::staticTypeName()==typeName ? true : Parameter::inheritsFrom( typeName );
}

/////////////////////////////////////////////////////////////////////////////////////
// other stuff
/////////////////////////////////////////////////////////////////////////////////////

template<typename T>
bool TypedParameter<T>::valueValid( ConstObjectPtr value, std::string *reason ) const
{
	if( !Parameter::valueValid( value, reason ) )
	{
		return false;
	}
	ConstObjectTypePtr tValue = runTimeCast<const ObjectType>( value );
	if( !tValue )
	{
		if( reason )
		{
			*reason = string( "Value is not an instance of \"" ) + ObjectType::staticTypeName() + "\"";
		}
		return false;
	}
	return true;
}

template<typename T>
const typename TypedParameter<T>::ValueType &TypedParameter<T>::typedDefaultValue() const
{
	return static_pointer_cast<const TypedData<T> >( defaultValue() )->readable();
}

template<typename T>
const typename TypedParameter<T>::ValueType &TypedParameter<T>::getTypedValue() const
{
	ConstObjectTypePtr tValue = runTimeCast<const ObjectType>( getValue() );
	if( !tValue )
	{
		throw Exception( string( "Value is not an instance of \"" ) + ObjectType::staticTypeName() + "\"");
	}
	return static_pointer_cast<const TypedData<T> >( getValue() )->readable();
}

template<typename T>
void TypedParameter<T>::setTypedValue( const T &value )
{
	setValue( new TypedData<T>( value ) );
}

/////////////////////////////////////////////////////////////////////////////////////
// specialisation and template instantiation
/////////////////////////////////////////////////////////////////////////////////////

#define IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( T, TNAME )						\
																					\
	template<>																		\
	TypeId TypedParameter<T>::staticTypeId()										\
	{																				\
		return TNAME ## TypeId;														\
	}																				\
																					\
	template<>																		\
	std::string TypedParameter<T>::staticTypeName()									\
	{																				\
		return # TNAME;																\
	}																				\
																					\
	template class TypedParameter<T>;

namespace IECore
{
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( bool, BoolParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( string, StringParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( V2i, V2iParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( V3i, V3iParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( V2f, V2fParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( V3f, V3fParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( V2d, V2dParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( V3d, V3dParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( Color3f, Color3fParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( Color4f, Color4fParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( Box2i, Box2iParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( Box3i, Box3iParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( Box2f, Box2fParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( Box3f, Box3fParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( Box2d, Box2dParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( Box3d, Box3dParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( M44f, M44fParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( M44d, M44dParameter )

IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( vector<int>, IntVectorParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( vector<float>, FloatVectorParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( vector<double>, DoubleVectorParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( vector<string>, StringVectorParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( vector<V2f>, V2fVectorParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( vector<V3f>, V3fVectorParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( vector<V2d>, V2dVectorParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( vector<V3d>, V3dVectorParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( vector<Box3f>, Box3fVectorParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( vector<Box3d>, Box3dVectorParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( vector<M33f>, M33fVectorParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( vector<M44f>, M44fVectorParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( vector<M33d>, M33dVectorParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( vector<M44d>, M44dVectorParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( vector<Quatf>, QuatfVectorParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( vector<Quatd>, QuatdVectorParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( vector<Color3f>, Color3fVectorParameter )
IE_CORE_DEFINETYPEDPARAMETERSPECIALISATION( vector<Color4f>, Color4fVectorParameter )
}
<|endoftext|>


<commit_before>/*
    Copyright © 2010, 2011, 2012 Vladimír Vondruš <mosra@centrum.cz>

    This file is part of Magnum.

    Magnum 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.

    Magnum 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.
*/

#include "TgaImporter.h"

#include "Utility/Endianness.h"
#include "Math/Vector2.h"
#include "Trade/ImageData.h"

using namespace std;
using namespace Corrade::Utility;

namespace Magnum { namespace Trade { namespace TgaImporter {

#ifndef DOXYGEN_GENERATING_OUTPUT
static_assert(sizeof(TgaImporter::Header) == 18, "TgaImporter: header size is not 18 bytes");
#endif

bool TgaImporter::TgaImporter::open(const string& filename, const string& name) {
    ifstream in(filename.c_str());
    if(!in.good()) {
        Error() << "TgaImporter: cannot open file" << filename;
        return false;
    }
    bool status = open(in, name);
    in.close();
    return status;
}

bool TgaImporter::open(istream& in, const string& name) {
    if(_image) close();
    if(!in.good()) {
        Error() << "TgaImporter: cannot read input stream";
        return false;
    }

    /* Check if the file is long enough */
    in.seekg(0, istream::end);
    streampos filesize = in.tellg();
    in.seekg(0, istream::beg);
    if(filesize < streampos(sizeof(Header))) {
        Error() << "TgaImporter: the file is too short:" << filesize << "bytes";
        return false;
    }

    Header header;
    in.read(reinterpret_cast<char*>(&header), sizeof(Header));

    /* Convert to machine endian */
    header.width = Endianness::littleEndian<unsigned short>(header.width);
    header.height = Endianness::littleEndian<unsigned short>(header.height);

    if(header.colorMapType != 0) {
        Error() << "TgaImporter: paletted files are not supported";
        return false;
    }

    if(header.imageType != 2) {
        Error() << "TgaImporter: non-RGB files are not supported";
        return false;
    }

    AbstractImage::Components components;
    switch(header.bpp) {
        case 24:
            components = AbstractImage::Components::BGR;
            break;
        case 32:
            components = AbstractImage::Components::BGRA;
            break;
        default:
            Error() << "TgaImporter: unsupported bits-per-pixel:" << int(header.bpp);
            return false;
    }

    size_t size = header.width*header.height*header.bpp/8;
    GLubyte* buffer = new GLubyte[size];
    in.read(reinterpret_cast<char*>(buffer), size);

    Math::Vector2<GLsizei> dimensions(header.width, header.height);

    _image = new ImageData2D(name, dimensions, components, buffer);
    return true;
}

void TgaImporter::close() {
    /** @todo fixme: delete it only if it wasn't retrieved by user */
    //delete _image;
    _image = nullptr;
}

ImageData2D* TgaImporter::image2D(unsigned int) {
    return _image;
}

}}}
<commit_msg>Treat Corrade includes as real, not internal dependency.<commit_after>/*
    Copyright © 2010, 2011, 2012 Vladimír Vondruš <mosra@centrum.cz>

    This file is part of Magnum.

    Magnum 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.

    Magnum 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.
*/

#include "TgaImporter.h"

#include <Utility/Endianness.h>

#include "Math/Vector2.h"
#include "Trade/ImageData.h"

using namespace std;
using namespace Corrade::Utility;

namespace Magnum { namespace Trade { namespace TgaImporter {

#ifndef DOXYGEN_GENERATING_OUTPUT
static_assert(sizeof(TgaImporter::Header) == 18, "TgaImporter: header size is not 18 bytes");
#endif

bool TgaImporter::TgaImporter::open(const string& filename, const string& name) {
    ifstream in(filename.c_str());
    if(!in.good()) {
        Error() << "TgaImporter: cannot open file" << filename;
        return false;
    }
    bool status = open(in, name);
    in.close();
    return status;
}

bool TgaImporter::open(istream& in, const string& name) {
    if(_image) close();
    if(!in.good()) {
        Error() << "TgaImporter: cannot read input stream";
        return false;
    }

    /* Check if the file is long enough */
    in.seekg(0, istream::end);
    streampos filesize = in.tellg();
    in.seekg(0, istream::beg);
    if(filesize < streampos(sizeof(Header))) {
        Error() << "TgaImporter: the file is too short:" << filesize << "bytes";
        return false;
    }

    Header header;
    in.read(reinterpret_cast<char*>(&header), sizeof(Header));

    /* Convert to machine endian */
    header.width = Endianness::littleEndian<unsigned short>(header.width);
    header.height = Endianness::littleEndian<unsigned short>(header.height);

    if(header.colorMapType != 0) {
        Error() << "TgaImporter: paletted files are not supported";
        return false;
    }

    if(header.imageType != 2) {
        Error() << "TgaImporter: non-RGB files are not supported";
        return false;
    }

    AbstractImage::Components components;
    switch(header.bpp) {
        case 24:
            components = AbstractImage::Components::BGR;
            break;
        case 32:
            components = AbstractImage::Components::BGRA;
            break;
        default:
            Error() << "TgaImporter: unsupported bits-per-pixel:" << int(header.bpp);
            return false;
    }

    size_t size = header.width*header.height*header.bpp/8;
    GLubyte* buffer = new GLubyte[size];
    in.read(reinterpret_cast<char*>(buffer), size);

    Math::Vector2<GLsizei> dimensions(header.width, header.height);

    _image = new ImageData2D(name, dimensions, components, buffer);
    return true;
}

void TgaImporter::close() {
    /** @todo fixme: delete it only if it wasn't retrieved by user */
    //delete _image;
    _image = nullptr;
}

ImageData2D* TgaImporter::image2D(unsigned int) {
    return _image;
}

}}}
<|endoftext|>