<commit_before>#include "XPathWrapper.hpp"

#include <vector>
#include <cassert>

#if defined(XALAN_OLD_STREAM_HEADERS)
#include <iostream.h>
#else
#include <iostream>
#endif

#include <framework/MemBufInputSource.hpp>
#include <framework/URLInputSource.hpp>
#include <parsers/DOMParser.hpp>
#include <util/PlatformUtils.hpp>

#include <Include/STLHelper.hpp>

#include <XalanDOM/XalanDocument.hpp>
#include <XalanDOM/XalanElement.hpp>

#include <PlatformSupport/DirectoryEnumerator.hpp>
#include <PlatformSupport/DOMStringHelper.hpp>

#include <DOMSupport/DOMServices.hpp>

#include <XPath/XObjectFactoryDefault.hpp>
#include <XPath/XPath.hpp>
#include <XPath/XPathEnvSupportDefault.hpp>
#include <XPath/XPathExecutionContextDefault.hpp>
#include <XPath/XPathInit.hpp>
#include <XPath/XPathProcessorImpl.hpp>
#include <XPath/XPathFactoryDefault.hpp>
#include <XPath/ElementPrefixResolverProxy.hpp>

#include <XalanSourceTree/XalanSourceTreeDOMSupport.hpp>
#include <XalanSourceTree/XalanSourceTreeParserLiaison.hpp>

#if !defined(XALAN_NO_NAMESPACES)
using std::cerr;
using std::endl;
using std::vector;
#endif

////////////////////////////////////////////////////

// the implementation class, that does all calls to XPath and Xerces
class XPathWrapperImpl
{
public:

	XPathWrapper::CharVectorTypeVectorType
	evaluate(
		const CharVectorType&	xml,
		const CharVectorType&	context,
		const CharVectorType&	expr)
	{
		//initialize Xerces...
		try
		{
			XMLPlatformUtils::Initialize();
		}
		catch(const XMLException&)
		{
			cerr << "XMLPlatformUtils::Initialize() failed!" << endl;

			throw;
		}

		XPathWrapper::CharVectorTypeVectorType	theResultList;

		{
			// Initialize the XPath subsystem...
			XPathInit						theInit;

			// We'll use these to parse the XML file.
			XalanSourceTreeDOMSupport		theDOMSupport;
			XalanSourceTreeParserLiaison	theLiaison(theDOMSupport);

			// Hook the two together...
			theDOMSupport.setParserLiaison(&theLiaison);

			XalanElement*	rootElem = 0;

			try
			{
				// parse XML and get root element
				MemBufInputSource inStream((XMLByte*)c_str(xml), xml.size(), "foo", false);

				XalanDocument* const	doc = theLiaison.parseXMLStream(inStream);
				assert(doc != 0);

				rootElem = doc->getDocumentElement();
				assert(rootElem != 0);
			}
			catch(const XMLException&)
			{
				cerr << "Caught XMLExecption..." << endl;

				throw;
			}

			// configure the objects needed for XPath to work with the Xerces DOM
			XPathEnvSupportDefault			theEnvSupport;
			XObjectFactoryDefault			theXObjectFactory;
			XPathExecutionContextDefault	theExecutionContext(theEnvSupport, theDOMSupport, theXObjectFactory);
			XPathFactoryDefault				theXPathFactory;
			XPathProcessorImpl				theXPathProcessor;

			try
			{
				// first get the context nodeset
				XPath* const	contextXPath = theXPathFactory.create();

				theXPathProcessor.initXPath(*contextXPath,
											TranscodeFromLocalCodePage(context),
											ElementPrefixResolverProxy(rootElem, theEnvSupport, theDOMSupport),
											theEnvSupport);

	   			XObjectPtr	xObj =
					contextXPath->execute(rootElem,
										  ElementPrefixResolverProxy(rootElem, theEnvSupport, theDOMSupport),
										  theExecutionContext);

				const NodeRefListBase&	contextNodeList = xObj->nodeset();

				const unsigned int	theLength =
						contextNodeList.getLength();

				if (theLength == 0)
				{
						cerr << "Warning -- No nodes matched the location path \""
							 << context
							 << "\"."
							 << endl
							 << "Execution cannot continue..."
							 << endl
							 << endl;
				}
				else
				{
					if (theLength > 1)
					{
						cerr << "Warning -- More than one node matched the location path \""
							 << context
							 << "\"."
							 << endl
							 << "The first node matched will be used as the context node."
							 << endl
							 << endl;
					}

					// and now get the result of the primary xpath expression
					XPath* const	xpath = theXPathFactory.create();
					theXPathProcessor.initXPath(*xpath,
												TranscodeFromLocalCodePage(expr),
												ElementPrefixResolverProxy(rootElem, theEnvSupport, theDOMSupport),
												theEnvSupport);

					xObj = xpath->execute(contextNodeList.item(0),
										  ElementPrefixResolverProxy(rootElem, theEnvSupport, theDOMSupport),
										  theExecutionContext);

					// now encode the results.  For all types but nodelist, we'll just convert it to a string
					// but, for nodelist, we'll convert each node to a string and return a list of them
					switch (xObj->getType())
					{
						case XObject::eTypeNodeSet:
						{
							const NodeRefListBase& nodeset = xObj->nodeset();
							size_t len = nodeset.getLength();

							for (size_t i=0; i<len; i++)
							{
								XalanNode* const	node = nodeset.item(i);
								XalanDOMString		str;

								const int theType = node->getNodeType();

								if (theType == XalanNode::COMMENT_NODE ||
									theType == XalanNode::PROCESSING_INSTRUCTION_NODE)
									str = node->getNodeValue();
								else if (theType == XalanNode::ELEMENT_NODE)
									str = node->getNodeName();
								else
									DOMServices::getNodeData(*node, str);

								theResultList.push_back(TranscodeToLocalCodePage(str));
							}

							break;
						}

						default:
						{
							theResultList.push_back(TranscodeToLocalCodePage(xObj->str()));

							break;
						}
					}
				}
			}
			catch(const XMLException&)
			{
				cerr << "Caught XMLExecption..." << endl;

				throw;
			}

			// Shut down Xerces...
			XMLPlatformUtils::Initialize();
		}

		return theResultList;
	}
};

////////////////////////////////////////////////////

// The public XPathWrapper methods just delegate to our impl class

XPathWrapper::XPathWrapper() :
	pImpl(new XPathWrapperImpl())
{
}

XPathWrapper::~XPathWrapper()
{
	delete pImpl;
}

XPathWrapper::CharVectorTypeVectorType
XPathWrapper::evaluate(
		const CharVectorType&	xml,
		const CharVectorType&	context,
		const CharVectorType&	path)
{
	return pImpl->evaluate(xml, context, path);
}

<commit_msg>Update for new signature.<commit_after>#include "XPathWrapper.hpp"

#include <vector>
#include <cassert>

#if defined(XALAN_OLD_STREAM_HEADERS)
#include <iostream.h>
#else
#include <iostream>
#endif

#include <framework/MemBufInputSource.hpp>
#include <framework/URLInputSource.hpp>
#include <parsers/DOMParser.hpp>
#include <util/PlatformUtils.hpp>

#include <Include/STLHelper.hpp>

#include <XalanDOM/XalanDocument.hpp>
#include <XalanDOM/XalanElement.hpp>

#include <PlatformSupport/DirectoryEnumerator.hpp>
#include <PlatformSupport/DOMStringHelper.hpp>

#include <DOMSupport/DOMServices.hpp>

#include <XPath/XObjectFactoryDefault.hpp>
#include <XPath/XPath.hpp>
#include <XPath/XPathEnvSupportDefault.hpp>
#include <XPath/XPathExecutionContextDefault.hpp>
#include <XPath/XPathInit.hpp>
#include <XPath/XPathProcessorImpl.hpp>
#include <XPath/XPathFactoryDefault.hpp>
#include <XPath/ElementPrefixResolverProxy.hpp>

#include <XalanSourceTree/XalanSourceTreeDOMSupport.hpp>
#include <XalanSourceTree/XalanSourceTreeParserLiaison.hpp>

#if !defined(XALAN_NO_NAMESPACES)
using std::cerr;
using std::endl;
using std::vector;
#endif

////////////////////////////////////////////////////

// the implementation class, that does all calls to XPath and Xerces
class XPathWrapperImpl
{
public:

	XPathWrapper::CharVectorTypeVectorType
	evaluate(
		const CharVectorType&	xml,
		const CharVectorType&	context,
		const CharVectorType&	expr)
	{
		//initialize Xerces...
		try
		{
			XMLPlatformUtils::Initialize();
		}
		catch(const XMLException&)
		{
			cerr << "XMLPlatformUtils::Initialize() failed!" << endl;

			throw;
		}

		XPathWrapper::CharVectorTypeVectorType	theResultList;

		{
			// Initialize the XPath subsystem...
			XPathInit						theInit;

			// We'll use these to parse the XML file.
			XalanSourceTreeDOMSupport		theDOMSupport;
			XalanSourceTreeParserLiaison	theLiaison(theDOMSupport);

			// Hook the two together...
			theDOMSupport.setParserLiaison(&theLiaison);

			XalanElement*	rootElem = 0;

			try
			{
				// parse XML and get root element
				MemBufInputSource inStream((XMLByte*)c_str(xml), xml.size(), "foo", false);

				XalanDocument* const	doc = theLiaison.parseXMLStream(inStream);
				assert(doc != 0);

				rootElem = doc->getDocumentElement();
				assert(rootElem != 0);
			}
			catch(const XMLException&)
			{
				cerr << "Caught XMLExecption..." << endl;

				throw;
			}

			// configure the objects needed for XPath to work with the Xerces DOM
			XPathEnvSupportDefault			theEnvSupport;
			XObjectFactoryDefault			theXObjectFactory;
			XPathExecutionContextDefault	theExecutionContext(theEnvSupport, theDOMSupport, theXObjectFactory);
			XPathFactoryDefault				theXPathFactory;
			XPathProcessorImpl				theXPathProcessor;

			try
			{
				// first get the context nodeset
				XPath* const	contextXPath = theXPathFactory.create();

				theXPathProcessor.initXPath(*contextXPath,
											TranscodeFromLocalCodePage(context),
											ElementPrefixResolverProxy(rootElem, theEnvSupport, theDOMSupport));

	   			XObjectPtr	xObj =
					contextXPath->execute(rootElem,
										  ElementPrefixResolverProxy(rootElem, theEnvSupport, theDOMSupport),
										  theExecutionContext);

				const NodeRefListBase&	contextNodeList = xObj->nodeset();

				const unsigned int	theLength =
						contextNodeList.getLength();

				if (theLength == 0)
				{
						cerr << "Warning -- No nodes matched the location path \""
							 << context
							 << "\"."
							 << endl
							 << "Execution cannot continue..."
							 << endl
							 << endl;
				}
				else
				{
					if (theLength > 1)
					{
						cerr << "Warning -- More than one node matched the location path \""
							 << context
							 << "\"."
							 << endl
							 << "The first node matched will be used as the context node."
							 << endl
							 << endl;
					}

					// and now get the result of the primary xpath expression
					XPath* const	xpath = theXPathFactory.create();
					theXPathProcessor.initXPath(*xpath,
												TranscodeFromLocalCodePage(expr),
												ElementPrefixResolverProxy(rootElem, theEnvSupport, theDOMSupport));

					xObj = xpath->execute(contextNodeList.item(0),
										  ElementPrefixResolverProxy(rootElem, theEnvSupport, theDOMSupport),
										  theExecutionContext);

					// now encode the results.  For all types but nodelist, we'll just convert it to a string
					// but, for nodelist, we'll convert each node to a string and return a list of them
					switch (xObj->getType())
					{
						case XObject::eTypeNodeSet:
						{
							const NodeRefListBase& nodeset = xObj->nodeset();
							size_t len = nodeset.getLength();

							for (size_t i=0; i<len; i++)
							{
								XalanNode* const	node = nodeset.item(i);
								XalanDOMString		str;

								const int theType = node->getNodeType();

								if (theType == XalanNode::COMMENT_NODE ||
									theType == XalanNode::PROCESSING_INSTRUCTION_NODE)
									str = node->getNodeValue();
								else if (theType == XalanNode::ELEMENT_NODE)
									str = node->getNodeName();
								else
									DOMServices::getNodeData(*node, str);

								theResultList.push_back(TranscodeToLocalCodePage(str));
							}

							break;
						}

						default:
						{
							theResultList.push_back(TranscodeToLocalCodePage(xObj->str()));

							break;
						}
					}
				}
			}
			catch(const XMLException&)
			{
				cerr << "Caught XMLExecption..." << endl;

				throw;
			}

			// Shut down Xerces...
			XMLPlatformUtils::Initialize();
		}

		return theResultList;
	}
};

////////////////////////////////////////////////////

// The public XPathWrapper methods just delegate to our impl class

XPathWrapper::XPathWrapper() :
	pImpl(new XPathWrapperImpl())
{
}

XPathWrapper::~XPathWrapper()
{
	delete pImpl;
}

XPathWrapper::CharVectorTypeVectorType
XPathWrapper::evaluate(
		const CharVectorType&	xml,
		const CharVectorType&	context,
		const CharVectorType&	path)
{
	return pImpl->evaluate(xml, context, path);
}

<|endoftext|>


<commit_before><commit_msg>Adjusted for the orcus interface change on the master branch.<commit_after><|endoftext|>


<commit_before>#include <stdexcept>
#include <string>
#include <iostream>
#include <functional>
#include <chrono>
#include <GL/glew.h>
#include <SDL.h>
#include <glm/glm.hpp>
#include <glm/ext.hpp>
#include <window.h>
#include <input.h>
#include <glbuffer.h>
#include <glvertexarray.h>
#include <glshader.h>
#include <glprogram.h>
#include <gltexture.h>
#include <model.h>
#include <util.h>

//This function demos working usage of ubo for matrices
int uboWorking();

//Note that we build with console as the system so that we'll be able to see
//the debug output and have the window stay open after closing the program
int main(int argc, char** argv){
	return uboWorking();
}

const std::array<glm::vec4, 10> quad = {
	//Vertex positions
	glm::vec4(-1.0, -1.0, 0.0, 1.0),
	glm::vec4(1.0, -1.0, 0.0, 1.0),
	glm::vec4(-1.0, 1.0, 0.0, 1.0),
	glm::vec4(1.0, 1.0, 0.0, 1.0),
	//Vertex colors
	glm::vec4(1.0, 0.0, 0.0, 1.0),
	glm::vec4(0.0, 1.0, 0.0, 1.0),
	glm::vec4(0.0, 0.0, 1.0, 1.0),
	glm::vec4(1.0, 1.0, 0.0, 1.0),
	//Texture UVs, stored 2 to a vec4
	glm::vec4(0.0, 0.0, 1.0, 0.0),
	glm::vec4(0.0, 1.0, 1.0, 1.0),
};
const std::array<unsigned short, 6> quadElems = {
	0, 1, 2,
	1, 3, 2
};

int uboWorking(){
	try {
		Window::init();
	}
	catch (const std::runtime_error &e){
		std::cout << e.what() << std::endl;
	}
	Input::Init();
	Window window("Test", 640, 480);

	//Setup vbo & ebo
	GL::VertexBuffer vbo(quad, GL::USAGE::STATIC_DRAW);
	GL::ElementBuffer ebo(quadElems, GL::USAGE::STATIC_DRAW);

	Util::checkError("VBO & EBO Setup");

	GL::VertexArray vao;
	vao.elementBuffer(ebo);
	Util::checkError("VAO setup");

	//Setup program
	GL::VertexShader vShader("../res/basic.v.glsl");
	if (!vShader.status())
		std::cout << vShader.getLog() << std::endl;
	Util::checkError("Vert shader Setup");

	GL::FragmentShader fShader("../res/basic.f.glsl");
	if (!fShader.status())
		std::cout << fShader.getLog() << std::endl;
	Util::checkError("Frag shader Setup");

	GL::Program program(vShader, fShader);
	Util::checkError("Prog Setup");

	//Pass vertex pos into position attrib
	GLint posAttrib = program.getAttribute("position");
	if (posAttrib == -1)
		std::cout << "Invalid position attrib loc" << std::endl;

	GLint colAttrib = program.getAttribute("color");
	if (colAttrib == -1)
		std::cout << "Invalid color attrib loc" << std::endl;

	GLint uvAttrib = program.getAttribute("texUv");
	if (uvAttrib == -1)
		std::cout << "Invalid uv attrib loc" << std::endl;

	vao.setAttribPointer(vbo, posAttrib, 4, GL_FLOAT);
	vao.setAttribPointer(vbo, colAttrib, 4, GL_FLOAT, GL_FALSE, 0, (void*)(sizeof(glm::vec4) * 4));
	vao.setAttribPointer(vbo, uvAttrib, 2, GL_FLOAT, GL_FALSE, 0, (void*)(sizeof(glm::vec4) * 8));
	Util::checkError("Pos attrib Setup");

	//Set the projection and model matrices
	glm::mat4 proj = glm::perspective(60.0f, 640.f / 480.f, 0.1f, 100.0f)
		* glm::lookAt(glm::vec3(0.f, 1.f, 2.f), glm::vec3(0.f, -1.f, -1.f), glm::vec3(0.f, 1.f, 0.f));
	glm::mat4 model = glm::translate(0.f, -1.f, 0.f) * glm::rotate(-90.f, glm::vec3(1.f, 0.f, 0.f));
	std::array<glm::mat4, 2> matrices = { proj, model };

	GL::UniformBuffer ubo(matrices, GL::USAGE::STATIC_DRAW);
	program.bindUniformBlock("Mat", ubo);
	Util::checkError("quad buf setup");

	//Creating the texture binds it to TEXTURE_2D so no need to bind again
	GL::Texture<GL::TEXTURE::T2D> texture("../res/map.png");
	texture.bind(GL_TEXTURE0);
	program.uniform1i("tex2D", 0);

	//Setup a simple cube model to draw
	GL::VertexArray cubeVAO;
	GL::VertexBuffer cubeVBO;
	Model::loadObj("../res/cube.obj", cubeVAO, cubeVBO);

	GL::Program cubeProg("../res/cube_simple.v.glsl", "../res/cube_simple.f.glsl");
	cubeVAO.setAttribPointer(cubeVBO, cubeProg.getAttribute("position"), 3, GL_FLOAT, GL_FALSE, 3 * sizeof(glm::vec3));

	std::array<glm::mat4, 2> cubeMats = { proj,
		glm::translate(0.f, -0.5f, 0.f) * glm::rotate(45.f, glm::vec3(0.f, 1.f, 0.f)) * glm::scale(0.3f, 0.3f, 0.3f)
	};
	GL::UniformBuffer cubeUBO(cubeMats, GL::USAGE::STATIC_DRAW);
	window.logMessage("SETTING CUBE UBO");
	cubeProg.bindUniformBlock("Mat", cubeUBO);

	//Testing an idea
	GLuint quadMatBind = program.getUniformBlockIndex("Mat");
	GLuint cubeMatBind = cubeProg.getUniformBlockIndex("Mat");

	//It seems that uniform block indices are a global thing, similar to how TEXTURE0 and such work
	glUniformBlockBinding(program, quadMatBind, 0);
	glBindBufferBase(static_cast<GLenum>(GL::BUFFER::UNIFORM), 0, ubo);
	glUniformBlockBinding(cubeProg, cubeMatBind, 1);
	glBindBufferBase(static_cast<GLenum>(GL::BUFFER::UNIFORM), 1, cubeUBO);

	std::cout << "cube ubo #: " << static_cast<GLuint>(cubeUBO)
		<< " cube ubo idx: " << cubeProg.getUniformBlockIndex("Mat") << "\n"
		<< "quad ubo #: " << static_cast<GLenum>(ubo)
		<< " quad ubo idx: " << program.getUniformBlockIndex("Mat") << std::endl;

	Util::checkError("cube setup");

	while (!Input::Quit()){
		Input::PollEvents();
		if (Input::KeyDown(SDL_SCANCODE_ESCAPE))
			Input::Quit(true);

		window.clear();

		program.use();
		glBindVertexArray(vao);
		glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0);

		cubeProg.use();
		glBindVertexArray(cubeVAO);
		glDrawElements(GL_TRIANGLES, cubeVAO.numElements(), GL_UNSIGNED_SHORT, 0);

		window.present();
	}
	Window::quit();

	return 0;
}
<commit_msg>Cleaning up some code, since I've got debug output I should get detailed info on errors and not need a bunch of these checks and such<commit_after>#include <stdexcept>
#include <string>
#include <iostream>
#include <functional>
#include <chrono>
#include <GL/glew.h>
#include <SDL.h>
#include <glm/glm.hpp>
#include <glm/ext.hpp>
#include <window.h>
#include <input.h>
#include <glbuffer.h>
#include <glvertexarray.h>
#include <glshader.h>
#include <glprogram.h>
#include <gltexture.h>
#include <model.h>
#include <util.h>

//This function demos working usage of ubo for matrices
int uboWorking();

//Note that we build with console as the system so that we'll be able to see
//the debug output and have the window stay open after closing the program
int main(int argc, char** argv){
	return uboWorking();
}

const std::array<glm::vec4, 10> quad = {
	//Vertex positions
	glm::vec4(-1.0, -1.0, 0.0, 1.0),
	glm::vec4(1.0, -1.0, 0.0, 1.0),
	glm::vec4(-1.0, 1.0, 0.0, 1.0),
	glm::vec4(1.0, 1.0, 0.0, 1.0),
	//Vertex colors
	glm::vec4(1.0, 0.0, 0.0, 1.0),
	glm::vec4(0.0, 1.0, 0.0, 1.0),
	glm::vec4(0.0, 0.0, 1.0, 1.0),
	glm::vec4(1.0, 1.0, 0.0, 1.0),
	//Texture UVs, stored 2 to a vec4
	glm::vec4(0.0, 0.0, 1.0, 0.0),
	glm::vec4(0.0, 1.0, 1.0, 1.0),
};
const std::array<unsigned short, 6> quadElems = {
	0, 1, 2,
	1, 3, 2
};

int uboWorking(){
	try {
		Window::init();
	}
	catch (const std::runtime_error &e){
		std::cout << e.what() << std::endl;
	}
	Input::Init();
	Window window("Test", 640, 480);

	//Setup vbo & ebo
	GL::VertexBuffer vbo(quad, GL::USAGE::STATIC_DRAW);
	GL::ElementBuffer ebo(quadElems, GL::USAGE::STATIC_DRAW);
	GL::VertexArray vao;
	vao.elementBuffer(ebo);

	GL::Program program("../res/basic.v.glsl", "../res/basic.f.glsl");
	vao.setAttribPointer(vbo, program.getAttribute("position"), 4, GL_FLOAT);
	vao.setAttribPointer(vbo, program.getAttribute("color"), 4, GL_FLOAT, GL_FALSE, 0, (void*)(sizeof(glm::vec4) * 4));
	vao.setAttribPointer(vbo, program.getAttribute("texUv"), 2, GL_FLOAT, GL_FALSE, 0, (void*)(sizeof(glm::vec4) * 8));

	//Set the projection and model matrices
	glm::mat4 proj = glm::perspective(60.0f, 640.f / 480.f, 0.1f, 100.0f)
		* glm::lookAt(glm::vec3(0.f, 1.f, 2.f), glm::vec3(0.f, -1.f, -1.f), glm::vec3(0.f, 1.f, 0.f));
	glm::mat4 model = glm::translate(0.f, -1.f, 0.f) * glm::rotate(-90.f, glm::vec3(1.f, 0.f, 0.f));
	std::array<glm::mat4, 2> matrices = { proj, model };
	GL::UniformBuffer ubo(matrices, GL::USAGE::STATIC_DRAW);

	//Creating the texture binds it to TEXTURE_2D so no need to bind again
	GL::Texture<GL::TEXTURE::T2D> texture("../res/map.png");
	texture.bind(GL_TEXTURE0);
	program.uniform1i("tex2D", 0);

	//Setup a simple cube model to draw
	GL::VertexArray cubeVAO;
	GL::VertexBuffer cubeVBO;
	Model::loadObj("../res/cube.obj", cubeVAO, cubeVBO);

	GL::Program cubeProg("../res/cube_simple.v.glsl", "../res/cube_simple.f.glsl");
	cubeVAO.setAttribPointer(cubeVBO, cubeProg.getAttribute("position"), 3, GL_FLOAT, GL_FALSE, 3 * sizeof(glm::vec3));

	std::array<glm::mat4, 2> cubeMats = { proj,
		glm::translate(0.f, -0.5f, 0.f) * glm::rotate(45.f, glm::vec3(0.f, 1.f, 0.f)) * glm::scale(0.3f, 0.3f, 0.3f)
	};
	GL::UniformBuffer cubeUBO(cubeMats, GL::USAGE::STATIC_DRAW);

	//Testing an idea
	GLuint quadMatBind = program.getUniformBlockIndex("Mat");
	GLuint cubeMatBind = cubeProg.getUniformBlockIndex("Mat");

	//It seems that uniform block indices are a global thing, similar to how TEXTURE0 and such work
	//How can I make this more general? I'd need to track how many UBOs were active or something
	glUniformBlockBinding(program, quadMatBind, 0);
	glBindBufferBase(static_cast<GLenum>(GL::BUFFER::UNIFORM), 0, ubo);
	glUniformBlockBinding(cubeProg, cubeMatBind, 1);
	glBindBufferBase(static_cast<GLenum>(GL::BUFFER::UNIFORM), 1, cubeUBO);

	Util::checkError("cube setup");

	while (!Input::Quit()){
		Input::PollEvents();
		if (Input::KeyDown(SDL_SCANCODE_ESCAPE))
			Input::Quit(true);

		window.clear();

		program.use();
		glBindVertexArray(vao);
		glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0);

		cubeProg.use();
		glBindVertexArray(cubeVAO);
		glDrawElements(GL_TRIANGLES, cubeVAO.numElements(), GL_UNSIGNED_SHORT, 0);

		window.present();
	}
	Window::quit();

	return 0;
}
<|endoftext|>


<commit_before>
// Copyright (c) 2015 Pierre MOULON.

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "openMVG/matching_image_collection/Cascade_Hashing_Matcher_Regions_AllInMemory.hpp"
#include "openMVG/matching/matcher_cascade_hashing.hpp"
#include "openMVG/matching/indMatchDecoratorXY.hpp"
#include "openMVG/matching/matching_filters.hpp"

#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"
#include "third_party/progress/progress.hpp"

namespace openMVG {
namespace matching_image_collection {

using namespace openMVG::matching;
using namespace openMVG::features;

Cascade_Hashing_Matcher_Regions_AllInMemory
::Cascade_Hashing_Matcher_Regions_AllInMemory
(
  float distRatio
):Matcher(), f_dist_ratio_(distRatio)
{
}

namespace impl
{
template <typename ScalarT>
void Match
(
  const sfm::SfM_Data & sfm_data,
  const sfm::Regions_Provider & regions_provider,
  const Pair_Set & pairs,
  float fDistRatio,
  PairWiseMatches & map_PutativesMatches // the pairwise photometric corresponding points
)
{
  C_Progress_display my_progress_bar( pairs.size() );

  // Collect used view indexes
  std::set<IndexT> used_index;
  // Sort pairs according the first index to minimize later memory swapping
  typedef std::map<IndexT, std::vector<IndexT> > Map_vectorT;
  Map_vectorT map_Pairs;
  for (Pair_Set::const_iterator iter = pairs.begin(); iter != pairs.end(); ++iter)
  {
    map_Pairs[iter->first].push_back(iter->second);
    used_index.insert(iter->first);
    used_index.insert(iter->second);
  }

  typedef Eigen::Matrix<ScalarT, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> BaseMat;

  // Init the cascade hasher
  CascadeHasher cascade_hasher;
  if (!used_index.empty())
  {
    const IndexT I = *used_index.begin();
    const features::Regions &regionsI = *regions_provider.regions_per_view.at(I).get();
    const size_t dimension = regionsI.DescriptorLength();
    cascade_hasher.Init(dimension);
  }

  std::map<IndexT, HashedDescriptions> hashed_base_;

  // Compute the zero mean descriptor that will be used for hashing (one for all the image regions)
  Eigen::VectorXf zero_mean_descriptor;
  {
    Eigen::MatrixXf matForZeroMean;
    for (int i =0; i < used_index.size(); ++i)
    {
      std::set<IndexT>::const_iterator iter = used_index.begin();
      std::advance(iter, i);
      const IndexT I = *iter;
      const features::Regions &regionsI = *regions_provider.regions_per_view.at(I).get();
      const ScalarT * tabI =
        reinterpret_cast<const ScalarT*>(regionsI.DescriptorRawData());
      const size_t dimension = regionsI.DescriptorLength();
      if (i==0)
      {
        matForZeroMean.resize(used_index.size(), dimension);
      }
      Eigen::Map<BaseMat> mat_I( (ScalarT*)tabI, regionsI.RegionCount(), dimension);
      matForZeroMean.row(i) = CascadeHasher::GetZeroMeanDescriptor(mat_I);
    }
    zero_mean_descriptor = CascadeHasher::GetZeroMeanDescriptor(matForZeroMean);
  }

  // Index the input regions
#ifdef OPENMVG_USE_OPENMP
  #pragma omp parallel for schedule(dynamic)
#endif
  for (int i =0; i < used_index.size(); ++i)
  {
    std::set<IndexT>::const_iterator iter = used_index.begin();
    std::advance(iter, i);
    const IndexT I = *iter;
    const features::Regions &regionsI = *regions_provider.regions_per_view.at(I).get();
    const ScalarT * tabI =
      reinterpret_cast<const ScalarT*>(regionsI.DescriptorRawData());
    const size_t dimension = regionsI.DescriptorLength();

    Eigen::Map<BaseMat> mat_I( (ScalarT*)tabI, regionsI.RegionCount(), dimension);
    const HashedDescriptions hashed_description = cascade_hasher.CreateHashedDescriptions(mat_I,
      //CascadeHasher::GetZeroMeanDescriptor(mat_I));
      zero_mean_descriptor);
#ifdef OPENMVG_USE_OPENMP
    #pragma omp critical
#endif
    {
      hashed_base_[I] = std::move(hashed_description);
    }
  }

  // Perform matching between all the pairs
  for (Map_vectorT::const_iterator iter = map_Pairs.begin();
    iter != map_Pairs.end(); ++iter)
  {
    const IndexT I = iter->first;
    const std::vector<IndexT> & indexToCompare = iter->second;

    const features::Regions &regionsI = *regions_provider.regions_per_view.at(I).get();
    const std::vector<features::PointFeature> pointFeaturesI = regionsI.GetRegionsPositions();
    const ScalarT * tabI =
      reinterpret_cast<const ScalarT*>(regionsI.DescriptorRawData());
    const size_t dimension = regionsI.DescriptorLength();
    Eigen::Map<BaseMat> mat_I( (ScalarT*)tabI, regionsI.RegionCount(), dimension);

#ifdef OPENMVG_USE_OPENMP
    #pragma omp parallel for schedule(dynamic)
#endif
    for (int j = 0; j < (int)indexToCompare.size(); ++j)
    {
      const size_t J = indexToCompare[j];
      const features::Regions &regionsJ = *regions_provider.regions_per_view.at(J).get();

      if (regions_provider.regions_per_view.count(J) == 0
          || regionsI.Type_id() != regionsJ.Type_id())
      {
#ifdef OPENMVG_USE_OPENMP
        #pragma omp critical
#endif
        ++my_progress_bar;
        continue;
      }

      // Matrix representation of the query input data;
      const ScalarT * tabJ = reinterpret_cast<const ScalarT*>(regionsJ.DescriptorRawData());
      Eigen::Map<BaseMat> mat_J( (ScalarT*)tabJ, regionsJ.RegionCount(), dimension);

      IndMatches pvec_indices;
      typedef typename Accumulator<ScalarT>::Type ResultType;
      std::vector<ResultType> pvec_distances;
      pvec_distances.reserve(regionsJ.RegionCount() * 2);
      pvec_indices.reserve(regionsJ.RegionCount() * 2);

      // Match the query descriptors to the database
      cascade_hasher.Match_HashedDescriptions<BaseMat, ResultType>(
        hashed_base_[J], mat_J,
        hashed_base_[I], mat_I,
        &pvec_indices, &pvec_distances);

      std::vector<int> vec_nn_ratio_idx;
      // Filter the matches using a distance ratio test:
      //   The probability that a match is correct is determined by taking
      //   the ratio of distance from the closest neighbor to the distance
      //   of the second closest.
      matching::NNdistanceRatio(
        pvec_distances.begin(), // distance start
        pvec_distances.end(),   // distance end
        2, // Number of neighbor in iterator sequence (minimum required 2)
        vec_nn_ratio_idx, // output (indices that respect the distance Ratio)
        Square(fDistRatio));

      matching::IndMatches vec_putative_matches;
      vec_putative_matches.reserve(vec_nn_ratio_idx.size());
      for (size_t k=0; k < vec_nn_ratio_idx.size(); ++k)
      {
        const size_t index = vec_nn_ratio_idx[k];
        vec_putative_matches.emplace_back(pvec_indices[index*2]._j, pvec_indices[index*2]._i);
      }

      // Remove duplicates
      matching::IndMatch::getDeduplicated(vec_putative_matches);

      // Remove matches that have the same (X,Y) coordinates
      const std::vector<features::PointFeature> pointFeaturesJ = regionsJ.GetRegionsPositions();
      matching::IndMatchDecorator<float> matchDeduplicator(vec_putative_matches,
        pointFeaturesI, pointFeaturesJ);
      matchDeduplicator.getDeduplicated(vec_putative_matches);

#ifdef OPENMVG_USE_OPENMP
#pragma omp critical
#endif
      {
        ++my_progress_bar;
        if (!vec_putative_matches.empty())
        {
          map_PutativesMatches.insert( make_pair( make_pair(I,J), std::move(vec_putative_matches) ));
        }
      }
    }
  }
}
} // namespace impl

void Cascade_Hashing_Matcher_Regions_AllInMemory::Match
(
  const sfm::SfM_Data & sfm_data,
  const std::shared_ptr<sfm::Regions_Provider> & regions_provider,
  const Pair_Set & pairs,
  PairWiseMatches & map_PutativesMatches // the pairwise photometric corresponding points
)const
{
#ifdef OPENMVG_USE_OPENMP
  std::cout << "Using the OPENMP thread interface" << std::endl;
#endif

  if (regions_provider->regions_per_view.empty())
    return;

  const features::Regions &regions = *regions_provider->regions_per_view.begin()->second.get();

  if (regions.IsBinary())
    return;

  if(regions.Type_id() == typeid(unsigned char).name())
  {
    impl::Match<unsigned char>(
      sfm_data,
      *regions_provider.get(),
      pairs,
      f_dist_ratio_,
      map_PutativesMatches);
  }
  else
  if(regions.Type_id() == typeid(float).name())
  {
    impl::Match<float>(
      sfm_data,
      *regions_provider.get(),
      pairs,
      f_dist_ratio_,
      map_PutativesMatches);
  }
  else
  {
    std::cerr << "Matcher not implemented for this region type" << std::endl;
  }
}

} // namespace openMVG
} // namespace matching_image_collection
<commit_msg>Enhance robustness to view with empty regions. #272<commit_after>
// Copyright (c) 2015 Pierre MOULON.

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "openMVG/matching_image_collection/Cascade_Hashing_Matcher_Regions_AllInMemory.hpp"
#include "openMVG/matching/matcher_cascade_hashing.hpp"
#include "openMVG/matching/indMatchDecoratorXY.hpp"
#include "openMVG/matching/matching_filters.hpp"

#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"
#include "third_party/progress/progress.hpp"

namespace openMVG {
namespace matching_image_collection {

using namespace openMVG::matching;
using namespace openMVG::features;

Cascade_Hashing_Matcher_Regions_AllInMemory
::Cascade_Hashing_Matcher_Regions_AllInMemory
(
  float distRatio
):Matcher(), f_dist_ratio_(distRatio)
{
}

namespace impl
{
template <typename ScalarT>
void Match
(
  const sfm::SfM_Data & sfm_data,
  const sfm::Regions_Provider & regions_provider,
  const Pair_Set & pairs,
  float fDistRatio,
  PairWiseMatches & map_PutativesMatches // the pairwise photometric corresponding points
)
{
  C_Progress_display my_progress_bar( pairs.size() );

  // Collect used view indexes
  std::set<IndexT> used_index;
  // Sort pairs according the first index to minimize later memory swapping
  typedef std::map<IndexT, std::vector<IndexT> > Map_vectorT;
  Map_vectorT map_Pairs;
  for (Pair_Set::const_iterator iter = pairs.begin(); iter != pairs.end(); ++iter)
  {
    map_Pairs[iter->first].push_back(iter->second);
    used_index.insert(iter->first);
    used_index.insert(iter->second);
  }

  typedef Eigen::Matrix<ScalarT, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> BaseMat;

  // Init the cascade hasher
  CascadeHasher cascade_hasher;
  if (!used_index.empty())
  {
    const IndexT I = *used_index.begin();
    const features::Regions &regionsI = *regions_provider.regions_per_view.at(I).get();
    const size_t dimension = regionsI.DescriptorLength();
    cascade_hasher.Init(dimension);
  }

  std::map<IndexT, HashedDescriptions> hashed_base_;

  // Compute the zero mean descriptor that will be used for hashing (one for all the image regions)
  Eigen::VectorXf zero_mean_descriptor;
  {
    Eigen::MatrixXf matForZeroMean;
    for (int i =0; i < used_index.size(); ++i)
    {
      std::set<IndexT>::const_iterator iter = used_index.begin();
      std::advance(iter, i);
      const IndexT I = *iter;
      const features::Regions &regionsI = *regions_provider.regions_per_view.at(I).get();
      const ScalarT * tabI =
        reinterpret_cast<const ScalarT*>(regionsI.DescriptorRawData());
      const size_t dimension = regionsI.DescriptorLength();
      if (i==0)
      {
        matForZeroMean.resize(used_index.size(), dimension);
        matForZeroMean.fill(0.0f);
      }
      if (regionsI.RegionCount() > 0)
      {
        Eigen::Map<BaseMat> mat_I( (ScalarT*)tabI, regionsI.RegionCount(), dimension);
        matForZeroMean.row(i) = CascadeHasher::GetZeroMeanDescriptor(mat_I);
      }
    }
    zero_mean_descriptor = CascadeHasher::GetZeroMeanDescriptor(matForZeroMean);
  }

  // Index the input regions
#ifdef OPENMVG_USE_OPENMP
  #pragma omp parallel for schedule(dynamic)
#endif
  for (int i =0; i < used_index.size(); ++i)
  {
    std::set<IndexT>::const_iterator iter = used_index.begin();
    std::advance(iter, i);
    const IndexT I = *iter;
    const features::Regions &regionsI = *regions_provider.regions_per_view.at(I).get();
    const ScalarT * tabI =
      reinterpret_cast<const ScalarT*>(regionsI.DescriptorRawData());
    const size_t dimension = regionsI.DescriptorLength();

    Eigen::Map<BaseMat> mat_I( (ScalarT*)tabI, regionsI.RegionCount(), dimension);
    const HashedDescriptions hashed_description = cascade_hasher.CreateHashedDescriptions(mat_I,
      //CascadeHasher::GetZeroMeanDescriptor(mat_I));
      zero_mean_descriptor);
#ifdef OPENMVG_USE_OPENMP
    #pragma omp critical
#endif
    {
      hashed_base_[I] = std::move(hashed_description);
    }
  }

  // Perform matching between all the pairs
  for (Map_vectorT::const_iterator iter = map_Pairs.begin();
    iter != map_Pairs.end(); ++iter)
  {
    const IndexT I = iter->first;
    const std::vector<IndexT> & indexToCompare = iter->second;

    const features::Regions &regionsI = *regions_provider.regions_per_view.at(I).get();
    if (regionsI.RegionCount() == 0)
    {
      my_progress_bar += indexToCompare.size();
      continue;
    }

    const std::vector<features::PointFeature> pointFeaturesI = regionsI.GetRegionsPositions();
    const ScalarT * tabI =
      reinterpret_cast<const ScalarT*>(regionsI.DescriptorRawData());
    const size_t dimension = regionsI.DescriptorLength();
    Eigen::Map<BaseMat> mat_I( (ScalarT*)tabI, regionsI.RegionCount(), dimension);

#ifdef OPENMVG_USE_OPENMP
    #pragma omp parallel for schedule(dynamic)
#endif
    for (int j = 0; j < (int)indexToCompare.size(); ++j)
    {
      const size_t J = indexToCompare[j];
      const features::Regions &regionsJ = *regions_provider.regions_per_view.at(J).get();

      if (regions_provider.regions_per_view.count(J) == 0
          || regionsI.Type_id() != regionsJ.Type_id())
      {
#ifdef OPENMVG_USE_OPENMP
        #pragma omp critical
#endif
        ++my_progress_bar;
        continue;
      }

      // Matrix representation of the query input data;
      const ScalarT * tabJ = reinterpret_cast<const ScalarT*>(regionsJ.DescriptorRawData());
      Eigen::Map<BaseMat> mat_J( (ScalarT*)tabJ, regionsJ.RegionCount(), dimension);

      IndMatches pvec_indices;
      typedef typename Accumulator<ScalarT>::Type ResultType;
      std::vector<ResultType> pvec_distances;
      pvec_distances.reserve(regionsJ.RegionCount() * 2);
      pvec_indices.reserve(regionsJ.RegionCount() * 2);

      // Match the query descriptors to the database
      cascade_hasher.Match_HashedDescriptions<BaseMat, ResultType>(
        hashed_base_[J], mat_J,
        hashed_base_[I], mat_I,
        &pvec_indices, &pvec_distances);

      std::vector<int> vec_nn_ratio_idx;
      // Filter the matches using a distance ratio test:
      //   The probability that a match is correct is determined by taking
      //   the ratio of distance from the closest neighbor to the distance
      //   of the second closest.
      matching::NNdistanceRatio(
        pvec_distances.begin(), // distance start
        pvec_distances.end(),   // distance end
        2, // Number of neighbor in iterator sequence (minimum required 2)
        vec_nn_ratio_idx, // output (indices that respect the distance Ratio)
        Square(fDistRatio));

      matching::IndMatches vec_putative_matches;
      vec_putative_matches.reserve(vec_nn_ratio_idx.size());
      for (size_t k=0; k < vec_nn_ratio_idx.size(); ++k)
      {
        const size_t index = vec_nn_ratio_idx[k];
        vec_putative_matches.emplace_back(pvec_indices[index*2]._j, pvec_indices[index*2]._i);
      }

      // Remove duplicates
      matching::IndMatch::getDeduplicated(vec_putative_matches);

      // Remove matches that have the same (X,Y) coordinates
      const std::vector<features::PointFeature> pointFeaturesJ = regionsJ.GetRegionsPositions();
      matching::IndMatchDecorator<float> matchDeduplicator(vec_putative_matches,
        pointFeaturesI, pointFeaturesJ);
      matchDeduplicator.getDeduplicated(vec_putative_matches);

#ifdef OPENMVG_USE_OPENMP
#pragma omp critical
#endif
      {
        ++my_progress_bar;
        if (!vec_putative_matches.empty())
        {
          map_PutativesMatches.insert( make_pair( make_pair(I,J), std::move(vec_putative_matches) ));
        }
      }
    }
  }
}
} // namespace impl

void Cascade_Hashing_Matcher_Regions_AllInMemory::Match
(
  const sfm::SfM_Data & sfm_data,
  const std::shared_ptr<sfm::Regions_Provider> & regions_provider,
  const Pair_Set & pairs,
  PairWiseMatches & map_PutativesMatches // the pairwise photometric corresponding points
)const
{
#ifdef OPENMVG_USE_OPENMP
  std::cout << "Using the OPENMP thread interface" << std::endl;
#endif

  if (regions_provider->regions_per_view.empty())
    return;

  const features::Regions &regions = *regions_provider->regions_per_view.begin()->second.get();

  if (regions.IsBinary())
    return;

  if(regions.Type_id() == typeid(unsigned char).name())
  {
    impl::Match<unsigned char>(
      sfm_data,
      *regions_provider.get(),
      pairs,
      f_dist_ratio_,
      map_PutativesMatches);
  }
  else
  if(regions.Type_id() == typeid(float).name())
  {
    impl::Match<float>(
      sfm_data,
      *regions_provider.get(),
      pairs,
      f_dist_ratio_,
      map_PutativesMatches);
  }
  else
  {
    std::cerr << "Matcher not implemented for this region type" << std::endl;
  }
}

} // namespace openMVG
} // namespace matching_image_collection
<|endoftext|>


<commit_before>/*
 * Copyright 2011 Intel Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 */

#include <QtCore>
#include <QSettings>
#include <MGConfItem>
#include <stdio.h>
#include <QX11Info>
#include <QInputContext>
#include <QInputContextFactory>
#include <cstdlib>

// Mobility
#include <QOrientationReading>
#include <QOrientationSensor>

#include "launcherapp.h"
#include "launcherwindow.h"
#include "appadaptor.h"
#include "appproxy.h"

#include <X11/extensions/XInput2.h>
#include "launcheratoms.h" // pulls in X11 headers, so this *must* be last otherwise it might cause odd conflicts with Qt headers

// Tap detection: press/release within 150ms and 20 pixels
#define TAP_TIME_MS 150
#define TAP_SIZE 20

// Dismiss the keyboard after 200ms if nothing tries to use it
#define KEYBOARD_DISMISS_TIMEOUT 200

void messageHandler(QtMsgType type, const char *msg)
{
    switch (type) {
    case QtDebugMsg:
        fprintf(stderr, "Debug: %s\n", msg);
        break;
    case QtWarningMsg:
        fprintf(stderr, "Warning: %s\n", msg);
        break;
    case QtCriticalMsg:
        fprintf(stderr, "Critical: %s\n", msg);
        break;
    case QtFatalMsg:
        fprintf(stderr, "Fatal: %s\n", msg);
        abort();
    }
}

LauncherApp::LauncherApp(int &argc, char **argv) :
    QApplication(argc, argv),
    orientation(1),
    foregroundWindow(0)
{
    connect(&orientationSensor, SIGNAL(readingChanged()), SLOT(onOrientationChanged()));
    orientationSensor.start();

    QString theme = MGConfItem("/meego/ux/theme").value().toString();
    QString themeFile = QString("/usr/share/themes/") + theme + "/theme.ini";
    if(!QFile::exists(themeFile))
    {
        // fallback
        themeFile = QString("/usr/share/themes/1024-600-10/theme.ini");
    }
    themeConfig = new QSettings(themeFile, QSettings::NativeFormat, this);

    setFont(QFont(themeConfig->value("fontFamily").toString(), themeConfig->value("fontPixelSizeMedium").toInt()));

    QInputContext *ic = QInputContextFactory::create("MInputContext", 0);
    if(ic) {
        setInputContext(ic);
        connect(ic, SIGNAL(keyboardActive()), this, SLOT(keyboardActive()));
    }

    qInstallMsgHandler(messageHandler);

    int dummy;
    if(!XQueryExtension(QX11Info::display(), "XInputExtension",
                        &xinputOpcode, &dummy, &dummy))
        xinputOpcode = -1;

    // Brutal hack: MTF (underneath the input context somewhere)
    // registers a duplicate session on a default name (sucked from
    // QApplication I guess) that collides.  We don't need it, so drop
    // it.
    QDBusConnection::sessionBus().unregisterService("com.nokia.meego-qml-launcher");

    // Enable dynamic switching between gl and software rendering on systems
    // with graphics architectures that see a benifit in memory usage.
    MGConfItem *enableSwapItem = new MGConfItem("/meego/ux/EnableDynamicRendering");
    m_enableRenderingSwap = enableSwapItem->value().toBool();
    delete enableSwapItem;
}

void LauncherApp::dbusInit(int argc, char** argv)
{
    QString service = "com.meego.launcher." + applicationName();
    QString object = "/com/meego/launcher";

    QDBusConnection bus = QDBusConnection::sessionBus();
    if(!bus.isConnected())
        return;

    // Are we the first app of our kind?
    new MeeGoAppAdaptor(this);
    if(bus.registerService(service) && bus.registerObject(object, this))
        return;

    // Nope: send a "raise" command to whoever owns the object and bail
    QStringList args;
    for(int i=0; i<argc; i++)
        args << argv[i];
    MeeGoAppProxy(service, object, bus).raise(args);

    std::exit(0);
}

void LauncherApp::raise(const QStringList& parameters)
{
    //So we can launch an app without bringing it to the front...
    bool noRaise = parameters.contains("--noraise");

    foreach (QWidget *widget, QApplication::topLevelWidgets())
    {
        if (!noRaise) {
            widget->show();
            widget->activateWindow();
            widget->raise();
        }

        QStringList args;
        for (int i = 0; i < parameters.length(); i++)
        {
            if (parameters[i] == "--cmd" && i + 1 < parameters.length())
                args << parameters[++i];
            else if (parameters[i] == "--cdata" && i + 1 < parameters.length())
                args << parameters[++i];
        }

        LauncherWindow *w = static_cast<LauncherWindow *>(widget);
        w->forwardCall(args);
    }
}

void LauncherApp::hide()
{
    foreach (QWidget *widget, QApplication::topLevelWidgets())
    {
        widget->hide();
    }
}

void LauncherApp::appPageLoaded()
{
    qint64 time = QDateTime::currentDateTime().toMSecsSinceEpoch();

    QFile file(QDir::homePath() + "/.config/qml-launcher/" + applicationName());
    if(!file.exists()) return;

    if(!file.open(QIODevice::WriteOnly | QIODevice::QIODevice::Append)) return;

    file.write("end: " + QString::number(time).toAscii() +"\n");
    file.close();
}

void LauncherApp::keyboardActive()
{
    keyboardIsActive = true;
}

void LauncherApp::keyboardTimeout()
{
    // If we get here and the keyboard hasn't shown "active", then the
    // user has done a tap (at least, a tap visible to us), and the
    // actions associated with that tap don't involve communication
    // with the VKB server.  We take that to mean that it's an
    // interaction with some *other* part of the interface, which
    // means we should release focus and dismiss the keyboard.
    if(!keyboardIsActive)
        emit dismissKeyboard();
}

bool LauncherApp::x11EventFilter(XEvent *event)
{
    Display *dpy = QX11Info::display();

    // Detect a "tap" anywhere in the app (uses any button ID, not
    // just the first: you can "tap" with a second finger for example,
    // not sure if that's semantically correct or not...) by snooping
    // the events.  Use this to dismiss the virtual keyboard.
    //
    // Note: we have to use XInput2 here, because that's what the Qt
    // is selecting for.  And the interaction is subtle: XInput2
    // requires that there be a XGetEventData() call to retrieve the
    // new-style/big event structure, and while we're at the head of
    // the event handling here, Qt has *already* called this.  So the
    // XGenericEventCookie::data field is already populated.  Seems
    // fragile, but works...
    if(event->type == GenericEvent && event->xcookie.extension == xinputOpcode)
    {
        XIDeviceEvent *xi = (XIDeviceEvent*)event->xcookie.data;
        if(xi->evtype == XI_ButtonPress)
        {
            lastButtonTime = xi->time;
            lastButtonX = xi->root_x;
            lastButtonY = xi->root_y;
            keyboardIsActive = false;
        }
        else if(xi->evtype == XI_ButtonRelease)
        {
            unsigned long dt = xi->time - lastButtonTime;
            int dx = abs(xi->root_x - lastButtonX);
            int dy = abs(xi->root_y - lastButtonY);
            if(dt < TAP_TIME_MS && dx < TAP_SIZE && dy < TAP_SIZE)
            {
                keyboardTimer.singleShot(KEYBOARD_DISMISS_TIMEOUT, this,
                                         SLOT(keyboardTimeout()));
            }
        }
    }

    Atom activeWindowAtom = getAtom(ATOM_NET_ACTIVE_WINDOW);

    // Foreground window detection
    if (event->type == PropertyNotify &&
            event->xproperty.atom == activeWindowAtom)
    {
        Atom actualType;
        int actualFormat;
        unsigned long numWindowItems, bytesLeft;
        unsigned char *data = NULL;

        int result = XGetWindowProperty(dpy,
                                        DefaultRootWindow(dpy),
                                        activeWindowAtom,
                                        0, 0x7fffffff,
                                        false, XA_WINDOW,
                                        &actualType,
                                        &actualFormat,
                                        &numWindowItems,
                                        &bytesLeft,
                                        &data);

        if (result == Success && data != None)
        {
            Window w = *(Window *)data;
            foregroundWindow = (int)w;
            XFree(data);
            emit foregroundWindowChanged();

            if (m_enableRenderingSwap)
            {
                // Find out if we're in the foreground, and if so, switch to GL
                // rendering. If we're not, switch to software rendering.
                //
                // This is particularly helpful on ARM w/ SGX drivers, where holding
                // a GL context will reserve a large chunk of RAM (around 10mb per
                // process) which is very, very painful when you've got a lot of
                // running processes.
                foreach (QWidget *widget, QApplication::topLevelWidgets())
                {
                    LauncherWindow *lw = qobject_cast<LauncherWindow *>(widget);

                    if (!lw)
                        continue;

                    if (widget->winId() == w)
                    {
                        lw->switchToGLRendering();
                    }
                    else
                    {
                        lw->switchToSoftwareRendering();
                    }
                }
            }
        }
    }

    return QApplication::x11EventFilter(event);
}

void LauncherApp::setOrientationLocked(bool locked)
{
    orientationLocked = locked;
    setOrientationSensorOn(!locked);
}

// Copied from libmeegotouch, which we don't link against.  We need it
// defined so we can connect a signal to the MInputContext object
// (loaded from a plugin) that uses this type.
namespace M {
    enum OrientationAngle { Angle0=0, Angle90=90, Angle180=180, Angle270=270 };
}

void LauncherApp::onOrientationChanged()
{
    int orientation = orientationSensor.reading()->orientation();

    qDebug("Handling orientation %d", orientation);
    int qmlOrient;
    M::OrientationAngle mtfOrient;
    switch (orientation)
    {
    case QOrientationReading::LeftUp:
        mtfOrient = M::Angle270;
        qmlOrient = 2;
        break;
    case QOrientationReading::TopDown:
        mtfOrient = M::Angle180;
        qmlOrient = 3;
        break;
    case QOrientationReading::RightUp:
        mtfOrient = M::Angle90;
        qmlOrient = 0;
        break;
    default: // assume QOrientationReading::TopUp
        mtfOrient = M::Angle0;
        qmlOrient = 1;
        break;
    }

    ((LauncherApp*)qApp)->setOrientation(qmlOrient);

    // Need to tell the MInputContext plugin to rotate the VKB too
    QMetaObject::invokeMethod(inputContext(),
                              "notifyOrientationChanged",
                              Q_ARG(M::OrientationAngle, mtfOrient));
}

void LauncherApp::setOrientationSensorOn(bool value)
{
    if (value && !orientationSensor.isActive())
    {
        orientationSensor.start();
    }
    else if(!value && orientationSensor.isActive())
    {
        orientationSensor.stop();
    }
}
<commit_msg>Fix BMC #18854<commit_after>/*
 * Copyright 2011 Intel Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 */

#include <QtCore>
#include <QSettings>
#include <MGConfItem>
#include <stdio.h>
#include <QX11Info>
#include <QInputContext>
#include <QInputContextFactory>
#include <cstdlib>

// Mobility
#include <QOrientationReading>
#include <QOrientationSensor>

#include "launcherapp.h"
#include "launcherwindow.h"
#include "appadaptor.h"
#include "appproxy.h"

#include <X11/extensions/XInput2.h>
#include "launcheratoms.h" // pulls in X11 headers, so this *must* be last otherwise it might cause odd conflicts with Qt headers

// Tap detection: press/release within 150ms and 20 pixels
#define TAP_TIME_MS 150
#define TAP_SIZE 20

// Dismiss the keyboard after 200ms if nothing tries to use it
#define KEYBOARD_DISMISS_TIMEOUT 200

void messageHandler(QtMsgType type, const char *msg)
{
    switch (type) {
    case QtDebugMsg:
        fprintf(stderr, "Debug: %s\n", msg);
        break;
    case QtWarningMsg:
        fprintf(stderr, "Warning: %s\n", msg);
        break;
    case QtCriticalMsg:
        fprintf(stderr, "Critical: %s\n", msg);
        break;
    case QtFatalMsg:
        fprintf(stderr, "Fatal: %s\n", msg);
        abort();
    }
}

LauncherApp::LauncherApp(int &argc, char **argv) :
    QApplication(argc, argv),
    orientation(1),
    foregroundWindow(0)
{
    connect(&orientationSensor, SIGNAL(readingChanged()), SLOT(onOrientationChanged()));
    orientationSensor.start();

    QString theme = MGConfItem("/meego/ux/theme").value().toString();
    QString themeFile = QString("/usr/share/themes/") + theme + "/theme.ini";
    if(!QFile::exists(themeFile))
    {
        // fallback
        themeFile = QString("/usr/share/themes/1024-600-10/theme.ini");
    }
    themeConfig = new QSettings(themeFile, QSettings::NativeFormat, this);

    setFont(QFont(themeConfig->value("fontFamily").toString(), themeConfig->value("fontPixelSizeMedium").toInt()));

    QInputContext *ic = QInputContextFactory::create("MInputContext", 0);
    if(ic) {
        setInputContext(ic);
        connect(ic, SIGNAL(keyboardActive()), this, SLOT(keyboardActive()));
    }

    qInstallMsgHandler(messageHandler);

    int dummy;
    if(!XQueryExtension(QX11Info::display(), "XInputExtension",
                        &xinputOpcode, &dummy, &dummy))
        xinputOpcode = -1;

    // Brutal hack: MTF (underneath the input context somewhere)
    // registers a duplicate session on a default name (sucked from
    // QApplication I guess) that collides.  We don't need it, so drop
    // it.
    QDBusConnection::sessionBus().unregisterService("com.nokia.meego-qml-launcher");

    // Enable dynamic switching between gl and software rendering on systems
    // with graphics architectures that see a benifit in memory usage.
    MGConfItem *enableSwapItem = new MGConfItem("/meego/ux/EnableDynamicRendering");
    m_enableRenderingSwap = enableSwapItem->value().toBool();
    delete enableSwapItem;
}

void LauncherApp::dbusInit(int argc, char** argv)
{
    QString service = "com.meego.launcher." + applicationName();
    QString object = "/com/meego/launcher";

    QDBusConnection bus = QDBusConnection::sessionBus();
    if(!bus.isConnected())
        return;

    // Are we the first app of our kind?
    new MeeGoAppAdaptor(this);
    if(bus.registerService(service) && bus.registerObject(object, this))
        return;

    // Nope: send a "raise" command to whoever owns the object and bail
    QStringList args;
    for(int i=0; i<argc; i++)
        args << argv[i];
    MeeGoAppProxy(service, object, bus).raise(args);

    std::exit(0);
}

void LauncherApp::raise(const QStringList& parameters)
{
    //So we can launch an app without bringing it to the front...
    bool noRaise = parameters.contains("--noraise");

    foreach (QWidget *widget, QApplication::topLevelWidgets())
    {
        if (!noRaise) {
            widget->show();
            widget->activateWindow();
            widget->raise();
        }

        QStringList args;
        for (int i = 0; i < parameters.length(); i++)
        {
            if (parameters[i] == "--cmd" && i + 1 < parameters.length())
                args << parameters[++i];
            else if (parameters[i] == "--cdata" && i + 1 < parameters.length())
                args << parameters[++i];
        }

        LauncherWindow *w = static_cast<LauncherWindow *>(widget);
        w->forwardCall(args);
    }
}

void LauncherApp::hide()
{
    foreach (QWidget *widget, QApplication::topLevelWidgets())
    {
        widget->hide();
    }
}

void LauncherApp::appPageLoaded()
{
    qint64 time = QDateTime::currentDateTime().toMSecsSinceEpoch();

    QFile file(QDir::homePath() + "/.config/qml-launcher/" + applicationName());
    if(!file.exists()) return;

    if(!file.open(QIODevice::WriteOnly | QIODevice::QIODevice::Append)) return;

    file.write("end: " + QString::number(time).toAscii() +"\n");
    file.close();
}

void LauncherApp::keyboardActive()
{
    keyboardIsActive = true;
}

void LauncherApp::keyboardTimeout()
{
    // If we get here and the keyboard hasn't shown "active", then the
    // user has done a tap (at least, a tap visible to us), and the
    // actions associated with that tap don't involve communication
    // with the VKB server.  We take that to mean that it's an
    // interaction with some *other* part of the interface, which
    // means we should release focus and dismiss the keyboard.
    if(!keyboardIsActive)
        emit dismissKeyboard();
}

bool LauncherApp::x11EventFilter(XEvent *event)
{
    Display *dpy = QX11Info::display();

    // Detect a "tap" anywhere in the app (uses any button ID, not
    // just the first: you can "tap" with a second finger for example,
    // not sure if that's semantically correct or not...) by snooping
    // the events.  Use this to dismiss the virtual keyboard.
    //
    // Note: we have to use XInput2 here, because that's what the Qt
    // is selecting for.  And the interaction is subtle: XInput2
    // requires that there be a XGetEventData() call to retrieve the
    // new-style/big event structure, and while we're at the head of
    // the event handling here, Qt has *already* called this.  So the
    // XGenericEventCookie::data field is already populated.  Seems
    // fragile, but works...
    if(event->type == GenericEvent && event->xcookie.extension == xinputOpcode)
    {
        XIDeviceEvent *xi = (XIDeviceEvent*)event->xcookie.data;
        if(xi->evtype == XI_ButtonPress)
        {
            lastButtonTime = xi->time;
            lastButtonX = xi->root_x;
            lastButtonY = xi->root_y;
            keyboardIsActive = false;
        }
        else if(xi->evtype == XI_ButtonRelease)
        {
            unsigned long dt = xi->time - lastButtonTime;
            int dx = abs(xi->root_x - lastButtonX);
            int dy = abs(xi->root_y - lastButtonY);
            if(dt < TAP_TIME_MS && dx < TAP_SIZE && dy < TAP_SIZE)
            {
                keyboardTimer.singleShot(KEYBOARD_DISMISS_TIMEOUT, this,
                                         SLOT(keyboardTimeout()));
            }
        }
    }

    Atom activeWindowAtom = getAtom(ATOM_NET_ACTIVE_WINDOW);

    // Foreground window detection
    if (event->type == PropertyNotify &&
            event->xproperty.atom == activeWindowAtom)
    {
        Atom actualType;
        int actualFormat;
        unsigned long numWindowItems, bytesLeft;
        unsigned char *data = NULL;

        int result = XGetWindowProperty(dpy,
                                        DefaultRootWindow(dpy),
                                        activeWindowAtom,
                                        0, 0x7fffffff,
                                        false, XA_WINDOW,
                                        &actualType,
                                        &actualFormat,
                                        &numWindowItems,
                                        &bytesLeft,
                                        &data);

        if (result == Success && data != None)
        {
            Window w = *(Window *)data;
            foregroundWindow = (int)w;
            XFree(data);
            emit foregroundWindowChanged();

            if (m_enableRenderingSwap)
            {
                // Find out if we're in the foreground, and if so, switch to GL
                // rendering. If we're not, switch to software rendering.
                //
                // This is particularly helpful on ARM w/ SGX drivers, where holding
                // a GL context will reserve a large chunk of RAM (around 10mb per
                // process) which is very, very painful when you've got a lot of
                // running processes.
                foreach (QWidget *widget, QApplication::topLevelWidgets())
                {
                    LauncherWindow *lw = qobject_cast<LauncherWindow *>(widget);

                    if (!lw)
                        continue;

                    if (widget->winId() == w)
                    {
                        lw->switchToGLRendering();
                    }
                    else
                    {
                        lw->switchToSoftwareRendering();
                    }
                }
            }
        }
    }

    return QApplication::x11EventFilter(event);
}

void LauncherApp::setOrientationLocked(bool locked)
{
    orientationLocked = locked;
    setOrientationSensorOn(!locked);
}

// Copied from libmeegotouch, which we don't link against.  We need it
// defined so we can connect a signal to the MInputContext object
// (loaded from a plugin) that uses this type.
namespace M {
    enum OrientationAngle { Angle0=0, Angle90=90, Angle180=180, Angle270=270 };
}

void LauncherApp::onOrientationChanged()
{
    int orientation = orientationSensor.reading()->orientation();

    int qmlOrient = -1;
    M::OrientationAngle mtfOrient;
    switch (orientation)
    {
    case QOrientationReading::LeftUp:
        mtfOrient = M::Angle270;
        qmlOrient = 2;
        break;
    case QOrientationReading::TopDown:
        mtfOrient = M::Angle180;
        qmlOrient = 3;
        break;
    case QOrientationReading::RightUp:
        mtfOrient = M::Angle90;
        qmlOrient = 0;
        break;
    case QOrientationReading::TopUp:
        mtfOrient = M::Angle0;
        qmlOrient = 1;
        break;
    default:
        // ignore faceup and facedown events
        break;
    }

    if (qmlOrient == -1)
        return;

    ((LauncherApp*)qApp)->setOrientation(qmlOrient);

    // Need to tell the MInputContext plugin to rotate the VKB too
    QMetaObject::invokeMethod(inputContext(),
                              "notifyOrientationChanged",
                              Q_ARG(M::OrientationAngle, mtfOrient));
}

void LauncherApp::setOrientationSensorOn(bool value)
{
    if (value && !orientationSensor.isActive())
    {
        orientationSensor.start();
    }
    else if(!value && orientationSensor.isActive())
    {
        orientationSensor.stop();
    }
}
<|endoftext|>


<commit_before>/*
 * Vulkan
 *
 * Copyright (C) 2014 LunarG, Inc.
 *
 * 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 <string.h>
#include <stdlib.h>
#include <assert.h>
#include "loader_platform.h"
#include "vk_dispatch_table_helper.h"
#include "vkLayer.h"
#include "layers_table.h"
// The following is #included again to catch certain OS-specific functions
// being used:
#include "loader_platform.h"

VK_LAYER_EXPORT VkResult VKAPI vkLayerExtension1(VkDevice device)
{
    printf("In vkLayerExtension1() call w/ device: %p\n", (void*)device);
    printf("vkLayerExtension1 returning SUCCESS\n");
    return VK_SUCCESS;
}

#define BASIC_LAYER_EXT_ARRAY_SIZE 2

static const VkExtensionProperties basicExts[BASIC_LAYER_EXT_ARRAY_SIZE] = {
    {
        VK_STRUCTURE_TYPE_EXTENSION_PROPERTIES,
        "Basic",
        0x10,
        "Sample layer: Basic ",
//        0,
//        NULL,
    },
    {
        VK_STRUCTURE_TYPE_EXTENSION_PROPERTIES,
        "vkLayerExtension1",
        0x10,
        "Sample layer: Basic",
//        0,
//        NULL,
    }
};

VK_LAYER_EXPORT VkResult VKAPI vkGetGlobalExtensionProperties(
                                               uint32_t extensionIndex,
                                               VkExtensionProperties*    pData)
{
    /* This entrypoint is NOT going to init it's own dispatch table since loader calls here early */
    uint32_t *count;

    if (extensionIndex >= BASIC_LAYER_EXT_ARRAY_SIZE)
        return VK_ERROR_INVALID_VALUE;
    memcpy((VkExtensionProperties *) pData, &basicExts[extensionIndex], sizeof(VkExtensionProperties));

    return VK_SUCCESS;
}

VK_LAYER_EXPORT VkResult VKAPI vkGetGlobalExtensionCount(uint32_t* pCount)
{
    *pCount = BASIC_LAYER_EXT_ARRAY_SIZE;
    return VK_SUCCESS;
}

VK_LAYER_EXPORT VkResult VKAPI vkEnumeratePhysicalDevices(
                                            VkInstance instance,
                                            uint32_t* pPhysicalDeviceCount,
                                            VkPhysicalDevice* pPhysicalDevices)
{
    printf("At start of wrapped vkEnumeratePhysicalDevices() call w/ inst: %p\n", (void*)instance);
    VkResult result = instance_dispatch_table(instance)->EnumeratePhysicalDevices(instance, pPhysicalDeviceCount, pPhysicalDevices);
    printf("Completed wrapped vkEnumeratePhysicalDevices() call w/ count %u\n", *pPhysicalDeviceCount);
    return result;
}

VK_LAYER_EXPORT VkResult VKAPI vkCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo* pCreateInfo, VkDevice* pDevice)
{
    printf("At start of wrapped vkCreateDevice() call w/ gpu: %p\n", (void*)gpu);
    VkResult result = device_dispatch_table(*pDevice)->CreateDevice(gpu, pCreateInfo, pDevice);
    printf("Completed wrapped vkCreateDevice() call w/ pDevice, Device %p: %p\n", (void*)pDevice, (void *) *pDevice);
    return result;
}

/* hook DestroyDevice to remove tableMap entry */
VK_LAYER_EXPORT VkResult VKAPI vkDestroyDevice(VkDevice device)
{
    dispatch_key key = get_dispatch_key(device);
    VkResult res = device_dispatch_table(device)->DestroyDevice(device);
    destroy_device_dispatch_table(key);
    return res;
}

/* hook DestroyInstance to remove tableInstanceMap entry */
VK_LAYER_EXPORT VkResult VKAPI vkDestroyInstance(VkInstance instance)
{
    dispatch_key key = get_dispatch_key(instance);
    VkResult res = instance_dispatch_table(instance)->DestroyInstance(instance);
    destroy_instance_dispatch_table(key);
    return res;
}

VK_LAYER_EXPORT VkResult VKAPI vkGetPhysicalDeviceFormatInfo(VkPhysicalDevice gpu, VkFormat format, VkFormatProperties *pFormatInfo)
{
    printf("At start of wrapped vkGetPhysicalDeviceFormatInfo() call w/ gpu: %p\n", (void*)gpu);
    VkResult result = instance_dispatch_table(gpu)->GetPhysicalDeviceFormatInfo(gpu, format, pFormatInfo);
    printf("Completed wrapped vkGetPhysicalDeviceFormatInfo() call w/ gpu: %p\n", (void*)gpu);
    return result;
}

VK_LAYER_EXPORT void * VKAPI vkGetDeviceProcAddr(VkDevice device, const char* pName)
{
    if (device == NULL)
        return NULL;

    /* loader uses this to force layer initialization; device object is wrapped */
    if (!strcmp("vkGetDeviceProcAddr", pName)) {
        initDeviceTable((const VkBaseLayerObject *) device);
        return (void *) vkGetDeviceProcAddr;
    }

    if (!strcmp("vkCreateDevice", pName))
        return (void *) vkCreateDevice;
    if (!strcmp("vkDestroyDevice", pName))
        return (void *) vkDestroyDevice;
    if (!strcmp("vkLayerExtension1", pName))
        return (void *) vkLayerExtension1;
    else
    {
        if (device_dispatch_table(device)->GetDeviceProcAddr == NULL)
            return NULL;
        return device_dispatch_table(device)->GetDeviceProcAddr(device, pName);
    }
}

VK_LAYER_EXPORT void * VKAPI vkGetInstanceProcAddr(VkInstance instance, const char* pName)
{
    if (instance == NULL)
        return NULL;

    /* loader uses this to force layer initialization; instance object is wrapped */
    if (!strcmp("vkGetInstanceProcAddr", pName)) {
        initInstanceTable((const VkBaseLayerObject *) instance);
        return (void *) vkGetInstanceProcAddr;
    }
    if (!strcmp("vkGetPhysicalDeviceFormatInfo", pName))
        return (void *) vkGetPhysicalDeviceFormatInfo;

    if (!strcmp("vkDestroyInstance", pName))
        return (void *) vkDestroyInstance;
    if (!strcmp("vkCreateDevice", pName))
        return (void *) vkCreateDevice;
    if (!strcmp("vkEnumeratePhysicalDevices", pName))
        return (void*) vkEnumeratePhysicalDevices;
    if (!strcmp("vkGetGlobalExtensionCount", pName))
        return (void*) vkGetGlobalExtensionCount;
    if (!strcmp("vkGetGlobalExtensionProperties", pName))
        return (void*) vkGetGlobalExtensionProperties;
    else
    {
        if (instance_dispatch_table(instance)->GetInstanceProcAddr == NULL)
            return NULL;
        return instance_dispatch_table(instance)->GetInstanceProcAddr(instance, pName);
    }

}
<commit_msg>Revert "loader: Remove CreateDevice from loader's instance"<commit_after>/*
 * Vulkan
 *
 * Copyright (C) 2014 LunarG, Inc.
 *
 * 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 <string.h>
#include <stdlib.h>
#include <assert.h>
#include "loader_platform.h"
#include "vk_dispatch_table_helper.h"
#include "vkLayer.h"
#include "layers_table.h"
// The following is #included again to catch certain OS-specific functions
// being used:
#include "loader_platform.h"

VK_LAYER_EXPORT VkResult VKAPI vkLayerExtension1(VkDevice device)
{
    printf("In vkLayerExtension1() call w/ device: %p\n", (void*)device);
    printf("vkLayerExtension1 returning SUCCESS\n");
    return VK_SUCCESS;
}

#define BASIC_LAYER_EXT_ARRAY_SIZE 2

static const VkExtensionProperties basicExts[BASIC_LAYER_EXT_ARRAY_SIZE] = {
    {
        VK_STRUCTURE_TYPE_EXTENSION_PROPERTIES,
        "Basic",
        0x10,
        "Sample layer: Basic ",
//        0,
//        NULL,
    },
    {
        VK_STRUCTURE_TYPE_EXTENSION_PROPERTIES,
        "vkLayerExtension1",
        0x10,
        "Sample layer: Basic",
//        0,
//        NULL,
    }
};

VK_LAYER_EXPORT VkResult VKAPI vkGetGlobalExtensionProperties(
                                               uint32_t extensionIndex,
                                               VkExtensionProperties*    pData)
{
    /* This entrypoint is NOT going to init it's own dispatch table since loader calls here early */
    uint32_t *count;

    if (extensionIndex >= BASIC_LAYER_EXT_ARRAY_SIZE)
        return VK_ERROR_INVALID_VALUE;
    memcpy((VkExtensionProperties *) pData, &basicExts[extensionIndex], sizeof(VkExtensionProperties));

    return VK_SUCCESS;
}

VK_LAYER_EXPORT VkResult VKAPI vkGetGlobalExtensionCount(uint32_t* pCount)
{
    *pCount = BASIC_LAYER_EXT_ARRAY_SIZE;
    return VK_SUCCESS;
}

VK_LAYER_EXPORT VkResult VKAPI vkEnumeratePhysicalDevices(
                                            VkInstance instance,
                                            uint32_t* pPhysicalDeviceCount,
                                            VkPhysicalDevice* pPhysicalDevices)
{
    printf("At start of wrapped vkEnumeratePhysicalDevices() call w/ inst: %p\n", (void*)instance);
    VkResult result = instance_dispatch_table(instance)->EnumeratePhysicalDevices(instance, pPhysicalDeviceCount, pPhysicalDevices);
    printf("Completed wrapped vkEnumeratePhysicalDevices() call w/ count %u\n", *pPhysicalDeviceCount);
    return result;
}

VK_LAYER_EXPORT VkResult VKAPI vkCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo* pCreateInfo, VkDevice* pDevice)
{
    printf("At start of wrapped vkCreateDevice() call w/ gpu: %p\n", (void*)gpu);
    VkResult result = device_dispatch_table(*pDevice)->CreateDevice(gpu, pCreateInfo, pDevice);
    printf("Completed wrapped vkCreateDevice() call w/ pDevice, Device %p: %p\n", (void*)pDevice, (void *) *pDevice);
    return result;
}

/* hook DestroyDevice to remove tableMap entry */
VK_LAYER_EXPORT VkResult VKAPI vkDestroyDevice(VkDevice device)
{
    dispatch_key key = get_dispatch_key(device);
    VkResult res = device_dispatch_table(device)->DestroyDevice(device);
    destroy_device_dispatch_table(key);
    return res;
}

/* hook DestroyInstance to remove tableInstanceMap entry */
VK_LAYER_EXPORT VkResult VKAPI vkDestroyInstance(VkInstance instance)
{
    dispatch_key key = get_dispatch_key(instance);
    VkResult res = instance_dispatch_table(instance)->DestroyInstance(instance);
    destroy_instance_dispatch_table(key);
    return res;
}

VK_LAYER_EXPORT VkResult VKAPI vkGetPhysicalDeviceFormatInfo(VkPhysicalDevice gpu, VkFormat format, VkFormatProperties *pFormatInfo)
{
    printf("At start of wrapped vkGetPhysicalDeviceFormatInfo() call w/ gpu: %p\n", (void*)gpu);
    VkResult result = instance_dispatch_table(gpu)->GetPhysicalDeviceFormatInfo(gpu, format, pFormatInfo);
    printf("Completed wrapped vkGetPhysicalDeviceFormatInfo() call w/ gpu: %p\n", (void*)gpu);
    return result;
}

VK_LAYER_EXPORT void * VKAPI vkGetDeviceProcAddr(VkDevice device, const char* pName)
{
    if (device == NULL)
        return NULL;

    /* loader uses this to force layer initialization; device object is wrapped */
    if (!strcmp("vkGetDeviceProcAddr", pName)) {
        initDeviceTable((const VkBaseLayerObject *) device);
        return (void *) vkGetDeviceProcAddr;
    }

    if (!strcmp("vkCreateDevice", pName))
        return (void *) vkCreateDevice;
    if (!strcmp("vkDestroyDevice", pName))
        return (void *) vkDestroyDevice;
    if (!strcmp("vkLayerExtension1", pName))
        return (void *) vkLayerExtension1;
    else
    {
        if (device_dispatch_table(device)->GetDeviceProcAddr == NULL)
            return NULL;
        return device_dispatch_table(device)->GetDeviceProcAddr(device, pName);
    }
}

VK_LAYER_EXPORT void * VKAPI vkGetInstanceProcAddr(VkInstance instance, const char* pName)
{
    if (instance == NULL)
        return NULL;

    /* loader uses this to force layer initialization; instance object is wrapped */
    if (!strcmp("vkGetInstanceProcAddr", pName)) {
        initInstanceTable((const VkBaseLayerObject *) instance);
        return (void *) vkGetInstanceProcAddr;
    }
    if (!strcmp("vkGetPhysicalDeviceFormatInfo", pName))
        return (void *) vkGetPhysicalDeviceFormatInfo;

    if (!strcmp("vkDestroyInstance", pName))
        return (void *) vkDestroyInstance;
    if (!strcmp("vkEnumeratePhysicalDevices", pName))
        return (void*) vkEnumeratePhysicalDevices;
    if (!strcmp("vkGetGlobalExtensionCount", pName))
        return (void*) vkGetGlobalExtensionCount;
    if (!strcmp("vkGetGlobalExtensionProperties", pName))
        return (void*) vkGetGlobalExtensionProperties;
    else
    {
        if (instance_dispatch_table(instance)->GetInstanceProcAddr == NULL)
            return NULL;
        return instance_dispatch_table(instance)->GetInstanceProcAddr(instance, pName);
    }

}
<|endoftext|>


<commit_before>#include "fastext/FASTex.hpp"
#include <fmo/detector.hpp>
#include <fmo/processing.hpp>

namespace fmo {
    const int THRESHOLD = 19;
    const bool NON_MAX_SUP = false;
    const size_t LEVELS = 6;
    const size_t SKIPPED_LEVELS = 1;
    const size_t PROCESSED_LEVELS = LEVELS - SKIPPED_LEVELS;

    /// Implementation details of class Detector.
    struct Detector::Impl {
        Impl() : fastText(THRESHOLD, NON_MAX_SUP, cmp::FastFeatureDetectorC::KEY_POINTS_WHITE) {
            keypoints.resize(PROCESSED_LEVELS);
            debugVis.resize(PROCESSED_LEVELS);
        }

        void setInput(const Mat& src) {
            fmo::pyramid(src, cascade, LEVELS);
            cv::Mat noMask;

            for (size_t i = 0; i < PROCESSED_LEVELS; i++) {
                Image& image = cascade[i + SKIPPED_LEVELS];
                auto& imageKeypoints = keypoints[i];
                fastText.detect(image.wrap(), imageKeypoints, noMask);
            }
        }

        const std::vector<Image>& getDebugImages() {
            Image temp;
            for (size_t i = 0; i < PROCESSED_LEVELS; i++) {
                Image& image = cascade[i + SKIPPED_LEVELS];
                Image& out = debugVis[i];
                fmo::less_than(image, temp, THRESHOLD);
                fmo::convert(temp, out, Format::BGR);

                // draw keypoints
                cv::Mat outMat = out.wrap();
                for (auto& keypoint : keypoints[i]) {
                    cv::Point pt{static_cast<int>(keypoint.pt.x), static_cast<int>(keypoint.pt.y)};
                    outMat.at<cv::Vec3b>(pt) = cv::Vec3b(0, 0, 255);
                }
            }
            return debugVis;
        }

    private:
        std::vector<Image> cascade;
        std::vector<Image> debugVis;
        cmp::FASTextGray fastText;
        std::vector<std::vector<cmp::FastKeyPoint>> keypoints;
    };

    Detector::~Detector() = default;
    Detector::Detector() : mImpl(new Impl) {}
    Detector::Detector(Detector&&) = default;
    Detector& Detector::operator=(Detector&&) = default;
    void Detector::setInput(const Mat& src) { mImpl->setInput(src); }
    const std::vector<Image>& Detector::getDebugImages() { return mImpl->getDebugImages(); }
}
<commit_msg>Visualize using a diff image<commit_after>#include "fastext/FASTex.hpp"
#include <fmo/detector.hpp>
#include <fmo/processing.hpp>

namespace fmo {
    const int THRESHOLD = 19;
    const bool NON_MAX_SUP = false;
    const size_t LEVELS = 6;
    const size_t SKIPPED_LEVELS = 1;
    const size_t PROCESSED_LEVELS = LEVELS - SKIPPED_LEVELS;

    /// Implementation details of class Detector.
    struct Detector::Impl {
        Impl() : fastText(THRESHOLD, NON_MAX_SUP, cmp::FastFeatureDetectorC::KEY_POINTS_WHITE) {
            keypoints.resize(PROCESSED_LEVELS);
            debugVis.resize(PROCESSED_LEVELS);
        }

        void setInput(const Mat& src) {
            fmo::pyramid(src, cascade, LEVELS);
            cv::Mat noMask;

            for (size_t i = 0; i < PROCESSED_LEVELS; i++) {
                Image& image = cascade[i + SKIPPED_LEVELS];
                auto& imageKeypoints = keypoints[i];
                fastText.detect(image.wrap(), imageKeypoints, noMask);
            }
        }

        const std::vector<Image>& getDebugImages() {
            for (size_t i = 0; i < PROCESSED_LEVELS; i++) {
                Image& image = cascade[i + SKIPPED_LEVELS];
                Image& out = debugVis[i];
                fmo::convert(image, out, Format::BGR);

                // draw keypoints
                cv::Mat outMat = out.wrap();
                for (auto& keypoint : keypoints[i]) {
                    cv::Point pt{static_cast<int>(keypoint.pt.x), static_cast<int>(keypoint.pt.y)};
                    outMat.at<cv::Vec3b>(pt) = cv::Vec3b(0, 0, 255);
                }
            }
            return debugVis;
        }

    private:
        std::vector<Image> cascade;
        std::vector<Image> debugVis;
        cmp::FASTextGray fastText;
        std::vector<std::vector<cmp::FastKeyPoint>> keypoints;
    };

    Detector::~Detector() = default;
    Detector::Detector() : mImpl(new Impl) {}
    Detector::Detector(Detector&&) = default;
    Detector& Detector::operator=(Detector&&) = default;
    void Detector::setInput(const Mat& src) { mImpl->setInput(src); }
    const std::vector<Image>& Detector::getDebugImages() { return mImpl->getDebugImages(); }
}
<|endoftext|>


<commit_before>#include "layers/loss.h"

namespace marian {

Ptr<LossBase> LossFactory(Ptr<Options> options, bool inference) {
  float smoothing = inference ? 0.f : options->get<float>("label-smoothing");
  std::string costType = options->get<std::string>("cost-type", "ce-mean");
  if(costType == "ce-mean" || costType == "cross-entropy") {
    return New<CrossEntropyMeanLoss>(smoothing);
  } else if(costType == "ce-mean-words") {
    return New<CrossEntropyMeanWordsLoss>(smoothing);
  } else if(costType == "ce-sum") {
    return New<CrossEntropySumLoss>(smoothing);
  } else if(costType == "perplexity") {
    return New<PerplexityLoss>(smoothing);
  } else if(costType == "ce-rescore") {
    return New<CrossEntropyRescoreLoss>(smoothing);
  } else {  // same as ce-mean
    return New<CrossEntropyMeanLoss>(smoothing);
  }
}

Expr LossBase::getCrossEntropy(Expr logits,
                               Expr indices,
                               Expr mask,
                               Expr weights) {
  auto ce = cross_entropy(logits, indices);

  if(smoothing_ > 0) {
    // @TODO: add this to CE kernels instead
    auto ceq = mean(logsoftmax(logits), /*axis=*/ -1);
    ce = (1 - smoothing_) * ce - smoothing_ * ceq;
  }

  if(mask)
    ce = ce * mask;

  if(weights)
    ce = ce * weights;

  return ce;
}

Expr CrossEntropyMeanLoss::getCost(Expr logits,
                                   Expr indices,
                                   Expr mask,
                                   Expr weights) {
  auto ce = getCrossEntropy(logits, indices, mask, weights);
  // Time axis (words): -3
  // Batch axis (sentences): -2
  if(weights) {
    return mean(sum(ce, /*axis =*/ -3) / sum(weights, -3), /*axis =*/ -2);
  }
  else {
    return mean(sum(ce, /*axis =*/ -3), /*axis =*/ -2);
  }
}

Expr CrossEntropyMeanWordsLoss::getCost(Expr logits,
                                        Expr indices,
                                        Expr mask,
                                        Expr weights) {
  auto ce = getCrossEntropy(logits, indices, mask, weights);
  if(weights) {
    return sum(sum(ce, /*axis =*/ -3), /*axis =*/ -2)
           / sum(sum(mask * weights, /*axis =*/ -3), /*axis =*/ -2);
  }
  else {
    return sum(sum(ce, /*axis =*/ -3), /*axis =*/ -2)
           / sum(sum(mask, /*axis =*/ -3), /*axis =*/ -2);
  }
}

Expr CrossEntropySumLoss::getCost(Expr logits,
                                  Expr indices,
                                  Expr mask,
                                  Expr weights) {
  auto ce = getCrossEntropy(logits, indices, mask, weights);
  if(weights) {
    return sum(sum(ce, /*axis =*/ -3) / sum(weights, /*axis =*/ -3), /*axis =*/ -2);
  }
  else {
    return sum(sum(ce, /*axis =*/ -3), /*axis =*/ -2);
  }
}

Expr PerplexityLoss::getCost(Expr logits,
                             Expr indices,
                             Expr mask,
                             Expr weights) {
  auto ce = getCrossEntropy(logits, indices, mask, weights);
  if(weights) {
    return exp(sum(sum(ce, /*axis =*/ -3), /*axis =*/ -2)
               / sum(sum(mask * weights, /*axis =*/ -3), /*axis =*/ -2));
  }
  else {
    return exp(sum(sum(ce, /*axis =*/ -3), /*axis =*/ -2)
               / sum(sum(mask, /*axis =*/ -3), /*axis =*/ -2));
  }
}

Expr CrossEntropyRescoreLoss::getCost(Expr logits,
                                      Expr indices,
                                      Expr mask,
                                      Expr weights) {
  auto ce = getCrossEntropy(logits, indices, mask, weights);
  return -sum(ce, /*axis =*/ -3);
}
}  // namespace marian
<commit_msg>weight sentences only<commit_after>#include "layers/loss.h"

namespace marian {

Ptr<LossBase> LossFactory(Ptr<Options> options, bool inference) {
  float smoothing = inference ? 0.f : options->get<float>("label-smoothing");
  std::string costType = options->get<std::string>("cost-type", "ce-mean");
  if(costType == "ce-mean" || costType == "cross-entropy") {
    return New<CrossEntropyMeanLoss>(smoothing);
  } else if(costType == "ce-mean-words") {
    return New<CrossEntropyMeanWordsLoss>(smoothing);
  } else if(costType == "ce-sum") {
    return New<CrossEntropySumLoss>(smoothing);
  } else if(costType == "perplexity") {
    return New<PerplexityLoss>(smoothing);
  } else if(costType == "ce-rescore") {
    return New<CrossEntropyRescoreLoss>(smoothing);
  } else {  // same as ce-mean
    return New<CrossEntropyMeanLoss>(smoothing);
  }
}

Expr LossBase::getCrossEntropy(Expr logits,
                               Expr indices,
                               Expr mask,
                               Expr weights) {
  auto ce = cross_entropy(logits, indices);

  if(smoothing_ > 0) {
    // @TODO: add this to CE kernels instead
    auto ceq = mean(logsoftmax(logits), /*axis=*/ -1);
    ce = (1 - smoothing_) * ce - smoothing_ * ceq;
  }

  if(mask)
    ce = ce * mask;

  if(weights)
    ce = ce * weights;

  return ce;
}

Expr CrossEntropyMeanLoss::getCost(Expr logits,
                                   Expr indices,
                                   Expr mask,
                                   Expr weights) {
  auto ce = getCrossEntropy(logits, indices, mask, weights);
  // Time axis (words): -3
  // Batch axis (sentences): -2
  if(weights) {
    return mean(sum(ce, /*axis =*/ -3) / sum(weights, -3), /*axis =*/ -2);
  }
  else {
    return mean(sum(ce, /*axis =*/ -3), /*axis =*/ -2);
  }
}

Expr CrossEntropyMeanWordsLoss::getCost(Expr logits,
                                        Expr indices,
                                        Expr mask,
                                        Expr weights) {
  auto ce = getCrossEntropy(logits, indices, mask, weights);
  if(weights) {
    // @TODO: this only works for sentence weights now
    return sum(sum(ce, /*axis =*/ -3), /*axis =*/ -2)
           / (sum(sum(mask, /*axis =*/ -3), /*axis =*/ -2) * sum(sum(weights, /*axis =*/ -3), /*axis =*/ -2));
  }
  else {
    return sum(sum(ce, /*axis =*/ -3), /*axis =*/ -2)
           / sum(sum(mask, /*axis =*/ -3), /*axis =*/ -2);
  }
}

Expr CrossEntropySumLoss::getCost(Expr logits,
                                  Expr indices,
                                  Expr mask,
                                  Expr weights) {
  auto ce = getCrossEntropy(logits, indices, mask, weights);
  if(weights) {
    return sum(sum(ce, /*axis =*/ -3) / sum(weights, /*axis =*/ -3), /*axis =*/ -2);
  }
  else {
    return sum(sum(ce, /*axis =*/ -3), /*axis =*/ -2);
  }
}

Expr PerplexityLoss::getCost(Expr logits,
                             Expr indices,
                             Expr mask,
                             Expr weights) {
  auto ce = getCrossEntropy(logits, indices, mask, weights);
  if(weights) {
    return exp(sum(sum(ce, /*axis =*/ -3), /*axis =*/ -2)
               / sum(sum(mask * weights, /*axis =*/ -3), /*axis =*/ -2));
  }
  else {
    return exp(sum(sum(ce, /*axis =*/ -3), /*axis =*/ -2)
               / sum(sum(mask, /*axis =*/ -3), /*axis =*/ -2));
  }
}

Expr CrossEntropyRescoreLoss::getCost(Expr logits,
                                      Expr indices,
                                      Expr mask,
                                      Expr weights) {
  auto ce = getCrossEntropy(logits, indices, mask, weights);
  return -sum(ce, /*axis =*/ -3);
}
}  // namespace marian
<|endoftext|>


<commit_before>#include "IconManager.hpp"

IconManager::IconManager(const std::vector<std::pair<Icon::bonus_t ,sf::Vector2i>>& positions)
{

    for(auto& var: positions)
    {
        availablePositions[Utilities::vecToPair<int>(var.second)] =
                {var.first, std::make_shared<Icon>(
                        var.first,
                        *iconTextures.get(mv::constants::path::ICON_TEXTURE_ATLAS),
                        sf::Vector2f{mv::constants::defaults::ICON_DIMENSIONS.x*var.second.x,
                                     mv::constants::defaults::ICON_DIMENSIONS.y*var.second.y})};
    }
}

void IconManager::update()
{
    if(!requests.empty() && timer.getElapsedTime().asSeconds() >= mv::constants::icon::respawnTime)
    {
            availablePositions[Utilities::vecToPair<int>(requests.front())].second->getComponent<ProperBody>()->setVisible(true);
            requests.pop();
            timer.restart();
    }

}

std::shared_ptr<Icon> IconManager::getTouchedIcon(const sf::Vector2i &unitPos)
{
    auto itr = availablePositions.find(Utilities::vecToPair<int>(unitPos));
    if(itr == availablePositions.end())
    {
        return nullptr;
    }

    return itr->second.second;
}

<commit_msg>[T-18] Added invisible case<commit_after>#include "IconManager.hpp"

IconManager::IconManager(const std::vector<std::pair<Icon::bonus_t ,sf::Vector2i>>& positions)
{

    for(auto& var: positions)
    {
        availablePositions[Utilities::vecToPair<int>(var.second)] =
                {var.first, std::make_shared<Icon>(
                        var.first,
                        *iconTextures.get(mv::constants::path::ICON_TEXTURE_ATLAS),
                        sf::Vector2f{mv::constants::defaults::ICON_DIMENSIONS.x*var.second.x,
                                     mv::constants::defaults::ICON_DIMENSIONS.y*var.second.y})};
    }
}

void IconManager::update()
{
    if(!requests.empty() && timer.getElapsedTime().asSeconds() >= mv::constants::icon::respawnTime)
    {
            availablePositions[Utilities::vecToPair<int>(requests.front())].second->
            getComponent<ProperBody>()->setVisible(true);
            requests.pop();
            timer.restart();
    }

}

std::shared_ptr<Icon> IconManager::getTouchedIcon(const sf::Vector2i &unitPos)
{
    auto itr = availablePositions.find(Utilities::vecToPair<int>(unitPos));
    if(itr == availablePositions.end())
    {
        return nullptr;
    }

    return itr->second.second->getComponent<ProperBody>()->isVisible() ? itr->second.second : nullptr;
}

<|endoftext|>


<commit_before>
#include "cmdline/cmdline.h"
#include "mhap/overlap.h"
#include "mhap/parser.h"
#include "ra/include/ra/ra.hpp"
#include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>

using std::cerr;
using std::cin;
using std::cout;
using std::endl;
using std::fstream;
using std::max;
using std::string;
using std::vector;

// map reads so we can access reads with mapped[read_id]
void map_reads(vector<Read*>* mapped, vector<Read*>& reads) {

  int max_id = -1;
  for (auto r: reads) {
    max_id = max(max_id, r->getId());
  }

  mapped->resize(max_id + 1, nullptr);
  for (auto r: reads) {
    (*mapped)[r->getId()] = r;
  }
}

int main(int argc, char **argv) {

  cmdline::parser args;
  args.add<string>("reads", 'r', "reads file", true);
  args.add<string>("overlaps", 'x', "overlaps file", true);
  args.add<bool>("verbose", 'v', "verbose output");
  args.add<string>("overlaps_format", 'f', "overlaps file format; supported: afg, mhap", false, "afg");
  args.parse_check(argc, argv);

  const int thread_num = std::max(std::thread::hardware_concurrency(), 1U);
  const string format = args.get<string>("overlaps_format");
  const string reads_filename = args.get<string>("reads");
  const string overlaps_filename = args.get<string>("overlaps");
  const bool verbose_output = args.get<bool>("verbose");

  vector<Overlap*> overlaps, filtered;
  vector<Read*> reads;
  vector<Read*> reads_mapped;

  readAfgReads(reads, reads_filename.c_str());
  map_reads(&reads_mapped, reads);

  std::cerr << "Read " << reads.size() << " reads" << std::endl;

  if (format == "afg") {
    readAfgOverlaps(overlaps, overlaps_filename.c_str());
  } else if (format == "mhap") {
    fstream overlaps_file(overlaps_filename);
    MHAP::read_overlaps(overlaps_file, &overlaps);
    overlaps_file.close();
  }

  for (auto o: overlaps) {
    const auto a = o->getA();
    const auto b = o->getB();
    assert(reads_mapped[a] != nullptr);
    assert(reads_mapped[b] != nullptr);
  }

  vector<Overlap*> nocontainments;
  filterContainedOverlaps(nocontainments, overlaps, reads_mapped, true);

  {
    int filtered = nocontainments.size() - overlaps.size();
    cerr << "Removed " << filtered << " overlaps as contained "
      << "(" << (1.*filtered)/overlaps.size() << ")" << endl;
  }

  if (verbose_output) {
    writeAfgOverlaps(nocontainments, "nocont.afg");
  }

  vector<Overlap*> notransitives;
  filterTransitiveOverlaps(notransitives, nocontainments, thread_num, true);

  {
    int filtered = notransitives.size() - nocontainments.size();
    cerr << "Removed " << filtered << " overlaps as transitive "
      << "(" << (1.*filtered)/nocontainments.size() << ")" << endl;
  }

  if (verbose_output) {
    writeAfgOverlaps(notransitives, "nocont.notran.afg");
  }

  createReverseComplements(reads, thread_num);

  StringGraph* graph = new StringGraph(reads, notransitives);
  graph->simplify();

  std::vector<StringGraphComponent*> components;
  graph->extractComponents(components);

  std::vector<Contig*> contigs;

  for (const auto& component : components) {

    Contig* contig = component->createContig();

    if (contig != nullptr) {
      contigs.emplace_back(contig);
    }
  }

  std::cerr << "number of contigs " << contigs.size() << std::endl;

  writeAfgContigs(contigs, "contigs.afg");

  for (auto r: reads)      delete r;
  for (auto o: overlaps)   delete o;
  for (auto c: components) delete c;
  for (auto c: contigs)    delete c;

  delete graph;

  return 0;
}
<commit_msg>verbose flag made optional<commit_after>
#include "cmdline/cmdline.h"
#include "mhap/overlap.h"
#include "mhap/parser.h"
#include "ra/include/ra/ra.hpp"
#include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>

using std::cerr;
using std::cin;
using std::cout;
using std::endl;
using std::fstream;
using std::max;
using std::string;
using std::vector;

// map reads so we can access reads with mapped[read_id]
void map_reads(vector<Read*>* mapped, vector<Read*>& reads) {

  int max_id = -1;
  for (auto r: reads) {
    max_id = max(max_id, r->getId());
  }

  mapped->resize(max_id + 1, nullptr);
  for (auto r: reads) {
    (*mapped)[r->getId()] = r;
  }
}

int main(int argc, char **argv) {

  cmdline::parser args;
  args.add<string>("reads", 'r', "reads file", true);
  args.add<string>("overlaps", 'x', "overlaps file", true);
  args.add<bool>("verbose", 'v', "verbose output", false);
  args.add<string>("overlaps_format", 'f', "overlaps file format; supported: afg, mhap", false, "afg");
  args.parse_check(argc, argv);

  const int thread_num = std::max(std::thread::hardware_concurrency(), 1U);
  const string format = args.get<string>("overlaps_format");
  const string reads_filename = args.get<string>("reads");
  const string overlaps_filename = args.get<string>("overlaps");
  const bool verbose_output = args.get<bool>("verbose");

  vector<Overlap*> overlaps, filtered;
  vector<Read*> reads;
  vector<Read*> reads_mapped;

  readAfgReads(reads, reads_filename.c_str());
  map_reads(&reads_mapped, reads);

  std::cerr << "Read " << reads.size() << " reads" << std::endl;

  if (format == "afg") {
    readAfgOverlaps(overlaps, overlaps_filename.c_str());
  } else if (format == "mhap") {
    fstream overlaps_file(overlaps_filename);
    MHAP::read_overlaps(overlaps_file, &overlaps);
    overlaps_file.close();
  }

  for (auto o: overlaps) {
    const auto a = o->getA();
    const auto b = o->getB();
    assert(reads_mapped[a] != nullptr);
    assert(reads_mapped[b] != nullptr);
  }

  vector<Overlap*> nocontainments;
  filterContainedOverlaps(nocontainments, overlaps, reads_mapped, true);

  {
    int filtered = nocontainments.size() - overlaps.size();
    cerr << "Removed " << filtered << " overlaps as contained "
      << "(" << (1.*filtered)/overlaps.size() << ")" << endl;
  }

  if (verbose_output) {
    writeAfgOverlaps(nocontainments, "nocont.afg");
  }

  vector<Overlap*> notransitives;
  filterTransitiveOverlaps(notransitives, nocontainments, thread_num, true);

  {
    int filtered = notransitives.size() - nocontainments.size();
    cerr << "Removed " << filtered << " overlaps as transitive "
      << "(" << (1.*filtered)/nocontainments.size() << ")" << endl;
  }

  if (verbose_output) {
    writeAfgOverlaps(notransitives, "nocont.notran.afg");
  }

  createReverseComplements(reads, thread_num);

  StringGraph* graph = new StringGraph(reads, notransitives);
  graph->simplify();

  std::vector<StringGraphComponent*> components;
  graph->extractComponents(components);

  std::vector<Contig*> contigs;

  for (const auto& component : components) {

    Contig* contig = component->createContig();

    if (contig != nullptr) {
      contigs.emplace_back(contig);
    }
  }

  std::cerr << "number of contigs " << contigs.size() << std::endl;

  writeAfgContigs(contigs, "contigs.afg");

  for (auto r: reads)      delete r;
  for (auto o: overlaps)   delete o;
  for (auto c: components) delete c;
  for (auto c: contigs)    delete c;

  delete graph;

  return 0;
}
<|endoftext|>