<commit_before>#include <debugger/bridge/delayload.h>
#include <debugger/lua.h>
#include <debugger/debugger.h>
#include <debugger/io/socket.h>
#include <memory>
#include <intrin.h>

namespace luaw {
	struct ud {
		std::unique_ptr<vscode::io::socket> io;
		std::unique_ptr<vscode::debugger> dbg;

		void listen(const char* ip, uint16_t port)
		{
			if (io || dbg) return;
			io.reset(new vscode::io::socket(ip, port));
			dbg.reset(new vscode::debugger(io.get(), vscode::threadmode::async));
		}
	};

	static std::unique_ptr<ud> global;

	static ud& to(lua_State* L, int idx)
	{
		return *global;
	}

	static int constructor(lua_State* L)
	{
		if (!global) {
			global.reset(new ud);
		}
		lua_newuserdata(L, 1);
		luaL_setmetatable(L, "vscode::debugger");
		return 1;
	}

	static int listen(lua_State* L)
	{
		ud& self = to(L, 1);
		self.listen(luaL_checkstring(L, 2), (uint16_t)luaL_checkinteger(L, 3));
		if (self.dbg) {
			self.dbg->attach_lua(L);
		}
		return 0;
	}

	static int start(lua_State* L)
	{
		ud& self = to(L, 1);
		if (!self.dbg) {
			return 0;
		}
		self.dbg->detach_lua(L);
		self.dbg->wait_attach();
		self.dbg->attach_lua(L);
		return 0;
	}

	static int port(lua_State* L)
	{
		ud& self = to(L, 1);
		if (!self.io) {
			return 0;
		}
		lua_pushinteger(L, self.io->get_port());
		return 1;
	}

	static int config(lua_State* L)
	{
		ud& self = to(L, 1);
		if (!self.dbg) {
			return 0;
		}
		if (lua_type(L, 2) == LUA_TSTRING) {
			size_t len = 0;
			const char* str = luaL_checklstring(L, 2, &len);
			std::string err = "unknown";
			if (!self.dbg->set_config(0, std::string(str, len), err)) {
				lua_pushlstring(L, err.data(), err.size());
				return lua_error(L);
			}
		}
		if (lua_type(L, 3) == LUA_TSTRING) {
			size_t len = 0;
			const char* str = luaL_checklstring(L, 3, &len);
			std::string err = "unknown";
			if (!self.dbg->set_config(2, std::string(str, len), err)) {
				lua_pushlstring(L, err.data(), err.size());
				return lua_error(L);
			}
		}
		return 0;
	}

	static int mt_gc(lua_State* L)
	{
		ud& self = to(L, 1);
		if (self.dbg) {
			self.dbg->detach_lua(L);
		}
		return 0;
	}

	int open(lua_State* L)
	{
		luaL_checkversion(L);
		luaL_Reg mt[] = {
			{ "listen", listen },
			{ "start", start },
			{ "port", port },
			{ "config", config },
			{ "__gc", mt_gc },
			{ NULL, NULL },
		};
		luaL_newmetatable(L, "vscode::debugger");
		luaL_setfuncs(L, mt, 0);
		lua_pushvalue(L, -1);
		lua_setfield(L, -2, "__index");
		return constructor(L);
	}
}

#if defined(DEBUGGER_BRIDGE)
static void caller_is_luadll(void* callerAddress)
{
	HMODULE  caller = NULL;
	if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCTSTR)callerAddress, &caller) && caller)
	{
		if (GetProcAddress(caller, "lua_newstate"))
		{
			delayload::set_luadll(caller, ::GetProcAddress);
		}
	}
}
#endif

int __cdecl luaopen_debugger(lua_State* L)
{
#if defined(DEBUGGER_BRIDGE)
	caller_is_luadll(_ReturnAddress());
#endif
	return luaw::open(L);
}
<commit_msg>移除port<commit_after>#include <debugger/bridge/delayload.h>
#include <debugger/lua.h>
#include <debugger/debugger.h>
#include <debugger/io/socket.h>
#include <memory>
#include <intrin.h>

namespace luaw {
	struct ud {
		std::unique_ptr<vscode::io::socket> io;
		std::unique_ptr<vscode::debugger> dbg;

		uint16_t listen(const char* ip, uint16_t port)
		{
			if (io) return io->get_port();
			if (dbg) return 0;
			io.reset(new vscode::io::socket(ip, port));
			dbg.reset(new vscode::debugger(io.get(), vscode::threadmode::async));
			return io->get_port();
		}
	};

	static std::unique_ptr<ud> global;

	static ud& to(lua_State* L, int idx)
	{
		return *global;
	}

	static int constructor(lua_State* L)
	{
		if (!global) {
			global.reset(new ud);
		}
		lua_newuserdata(L, 1);
		luaL_setmetatable(L, "vscode::debugger");
		return 1;
	}

	static int listen(lua_State* L)
	{
		ud& self = to(L, 1);
		self.listen(luaL_checkstring(L, 2), (uint16_t)luaL_checkinteger(L, 3));
		if (self.dbg) {
			self.dbg->attach_lua(L);
		}
		return 0;
	}

	static int start(lua_State* L)
	{
		ud& self = to(L, 1);
		if (!self.dbg) {
			return 0;
		}
		self.dbg->detach_lua(L);
		self.dbg->wait_attach();
		self.dbg->attach_lua(L);
		return 0;
	}

	static int config(lua_State* L)
	{
		ud& self = to(L, 1);
		if (!self.dbg) {
			return 0;
		}
		if (lua_type(L, 2) == LUA_TSTRING) {
			size_t len = 0;
			const char* str = luaL_checklstring(L, 2, &len);
			std::string err = "unknown";
			if (!self.dbg->set_config(0, std::string(str, len), err)) {
				lua_pushlstring(L, err.data(), err.size());
				return lua_error(L);
			}
		}
		if (lua_type(L, 3) == LUA_TSTRING) {
			size_t len = 0;
			const char* str = luaL_checklstring(L, 3, &len);
			std::string err = "unknown";
			if (!self.dbg->set_config(2, std::string(str, len), err)) {
				lua_pushlstring(L, err.data(), err.size());
				return lua_error(L);
			}
		}
		return 0;
	}

	static int mt_gc(lua_State* L)
	{
		ud& self = to(L, 1);
		if (self.dbg) {
			self.dbg->detach_lua(L);
		}
		return 0;
	}

	int open(lua_State* L)
	{
		luaL_checkversion(L);
		luaL_Reg mt[] = {
			{ "listen", listen },
			{ "start", start },
			{ "config", config },
			{ "__gc", mt_gc },
			{ NULL, NULL },
		};
		luaL_newmetatable(L, "vscode::debugger");
		luaL_setfuncs(L, mt, 0);
		lua_pushvalue(L, -1);
		lua_setfield(L, -2, "__index");
		return constructor(L);
	}
}

#if defined(DEBUGGER_BRIDGE)
static void caller_is_luadll(void* callerAddress)
{
	HMODULE  caller = NULL;
	if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCTSTR)callerAddress, &caller) && caller)
	{
		if (GetProcAddress(caller, "lua_newstate"))
		{
			delayload::set_luadll(caller, ::GetProcAddress);
		}
	}
}
#endif

int __cdecl luaopen_debugger(lua_State* L)
{
#if defined(DEBUGGER_BRIDGE)
	caller_is_luadll(_ReturnAddress());
#endif
	return luaw::open(L);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: pamain.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: obo $ $Date: 2004-03-18 12:13:00 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <stdio.h>
#include <unistd.h>

#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _SV_WRKWIN_HXX
#include <vcl/wrkwin.hxx>
#endif
#ifndef _VCL_UNOWRAP_HXX
#include <vcl/unowrap.hxx>
#endif
#ifndef _PAD_PADIALOG_HXX_
#include <padialog.hxx>
#endif
#ifndef _PAD_HELPER_HXX_
#include <helper.hxx>
#endif

#ifndef _CPPUHELPER_BOOTSTRAP_HXX_
#include <cppuhelper/bootstrap.hxx>
#endif

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#ifndef _UCBHELPER_CONTENTBROKER_HXX
#include <ucbhelper/contentbroker.hxx>
#endif

#ifndef _UCBHELPER_CONFIGURATIONKEYS_HXX_
#include <ucbhelper/configurationkeys.hxx>
#endif

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

using namespace padmin;
using namespace rtl;
using namespace cppu;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace comphelper;

// -----------------------------------------------------------------------

class MyApp : public Application
{
public:
    void            Main();
    virtual USHORT  Exception( USHORT nError );
};

MyApp aMyApp;

// -----------------------------------------------------------------------

USHORT MyApp::Exception( USHORT nError )
{
    switch( nError & EXC_MAJORTYPE )
    {
        case EXC_RSCNOTLOADED:
            Abort( String::CreateFromAscii( "Error: could not load language resources.\nPlease check your installation.\n" ) );
            break;
    }
    return 0;
}

void MyApp::Main()
{
    PADialog* pPADialog;

    //-------------------------------------------------
    // create the global service-manager
    //-------------------------------------------------
    Reference< XComponentContext > xCtx;
    Reference< XMultiServiceFactory > xFactory;
    try
    {
        Reference< XComponentContext > xCtx = defaultBootstrap_InitialComponentContext();
        xFactory = Reference< XMultiServiceFactory >(  xCtx->getServiceManager(), UNO_QUERY );
        if( xFactory.is() )
            setProcessServiceFactory( xFactory );
    }
    catch( com::sun::star::uno::Exception& rExc)
    {
    }

    if( ! xFactory.is() )
    {
        fprintf( stderr, "Could not bootstrap UNO, installation must be in disorder. Exiting.\n" );
        exit( 1 );
    }

    /*
     *  Create UCB.
     */
    Sequence< Any > aArgs( 2 );
    aArgs[ 0 ] <<= OUString::createFromAscii( UCB_CONFIGURATION_KEY1_LOCAL );
    aArgs[ 1 ] <<= OUString::createFromAscii( UCB_CONFIGURATION_KEY2_OFFICE );
#if OSL_DEBUG_LEVEL > 1
    sal_Bool bSuccess =
#endif
        ::ucb::ContentBroker::initialize( xFactory, aArgs );

#if OSL_DEBUG_LEVEL > 1
    if ( !bSuccess )
    {
        fprintf( stderr, "Error creating UCB, installation must be in disorder. Exiting.\n" );
        exit( 1 );
    }
#endif

    pPADialog = PADialog::Create( NULL , FALSE );
    Application::SetDisplayName( pPADialog->GetText() );
    pPADialog->Execute();
    delete pPADialog;

    /*
     *  clean up UCB
     */
    ::ucb::ContentBroker::deinitialize();

}
<commit_msg>INTEGRATION: CWS gh6 (1.6.14); FILE MERGED 2004/05/12 11:31:59 gh 1.6.14.1: #111796#make spadmin testable by testtool<commit_after>/*************************************************************************
 *
 *  $RCSfile: pamain.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: rt $ $Date: 2004-06-17 11:48:26 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <stdio.h>
#include <unistd.h>

#ifndef _TOOLS_TESTTOOLLOADER_HXX_
#include <tools/testtoolloader.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _SV_WRKWIN_HXX
#include <vcl/wrkwin.hxx>
#endif
#ifndef _VCL_UNOWRAP_HXX
#include <vcl/unowrap.hxx>
#endif
#ifndef _PAD_PADIALOG_HXX_
#include <padialog.hxx>
#endif
#ifndef _PAD_HELPER_HXX_
#include <helper.hxx>
#endif

#ifndef _CPPUHELPER_BOOTSTRAP_HXX_
#include <cppuhelper/bootstrap.hxx>
#endif

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#ifndef _UCBHELPER_CONTENTBROKER_HXX
#include <ucbhelper/contentbroker.hxx>
#endif

#ifndef _UCBHELPER_CONFIGURATIONKEYS_HXX_
#include <ucbhelper/configurationkeys.hxx>
#endif

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

using namespace padmin;
using namespace rtl;
using namespace cppu;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace comphelper;

// -----------------------------------------------------------------------

class MyApp : public Application
{
public:
    void            Main();
    virtual USHORT  Exception( USHORT nError );
};

MyApp aMyApp;

// -----------------------------------------------------------------------

USHORT MyApp::Exception( USHORT nError )
{
    switch( nError & EXC_MAJORTYPE )
    {
        case EXC_RSCNOTLOADED:
            Abort( String::CreateFromAscii( "Error: could not load language resources.\nPlease check your installation.\n" ) );
            break;
    }
    return 0;
}

void MyApp::Main()
{
    PADialog* pPADialog;

    EnableAutoHelpId();

    //-------------------------------------------------
    // create the global service-manager
    //-------------------------------------------------
    Reference< XComponentContext > xCtx;
    Reference< XMultiServiceFactory > xFactory;
    try
    {
        Reference< XComponentContext > xCtx = defaultBootstrap_InitialComponentContext();
        xFactory = Reference< XMultiServiceFactory >(  xCtx->getServiceManager(), UNO_QUERY );
        if( xFactory.is() )
            setProcessServiceFactory( xFactory );
    }
    catch( com::sun::star::uno::Exception& rExc)
    {
    }

    if( ! xFactory.is() )
    {
        fprintf( stderr, "Could not bootstrap UNO, installation must be in disorder. Exiting.\n" );
        exit( 1 );
    }

    /*
     *  Create UCB.
     */
    Sequence< Any > aArgs( 2 );
    aArgs[ 0 ] <<= OUString::createFromAscii( UCB_CONFIGURATION_KEY1_LOCAL );
    aArgs[ 1 ] <<= OUString::createFromAscii( UCB_CONFIGURATION_KEY2_OFFICE );
#if OSL_DEBUG_LEVEL > 1
    sal_Bool bSuccess =
#endif
        ::ucb::ContentBroker::initialize( xFactory, aArgs );

#if OSL_DEBUG_LEVEL > 1
    if ( !bSuccess )
    {
        fprintf( stderr, "Error creating UCB, installation must be in disorder. Exiting.\n" );
        exit( 1 );
    }
#endif

    // initialize test-tool library (if available)
    tools::InitTestToolLib();

    pPADialog = PADialog::Create( NULL , FALSE );
    Application::SetDisplayName( pPADialog->GetText() );
    pPADialog->Execute();
    delete pPADialog;

    tools::DeInitTestToolLib();

    /*
     *  clean up UCB
     */
    ::ucb::ContentBroker::deinitialize();

}
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999-2004 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

#include "XPathWrapper.hpp"

#include <xercesc/util/XMLException.hpp>

#include <xalanc/PlatformSupport/DOMStringHelper.hpp>

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

int
main(
			int		argc,
			char*	argv[])
{
	XALAN_USING_STD(cerr)
	XALAN_USING_STD(cout)
	XALAN_USING_STD(endl)
	XALAN_USING_STD(ifstream)

	if (argc < 4)
	{
		cerr << "Usage: TestDriver XMLFilePath Context XPathExpression" << endl;
		return -1;
	}

	XPathWrapper::ChVectorType	theXML;

	ifstream	in(argv[1]);

	// slow and dirty dump of the xml file into a buffer
	char c;
	while(in.get(c))
		theXML.push_back(c);
	theXML.push_back('\0');

	///////////////////////////////////////////..

	// create your XPath helper object
	XPathWrapper helper;

	try
	{
		// call evaluate, passing in the XML string, the context string and the xpath string
		const XPathWrapper::CharVectorTypeVectorType	result = helper.evaluate(&*theXML.begin(), argv[2], argv[3]);

		// take the resulting string vector	and do whatever you want with it:
		size_t len = result.size();

		cout << "the result set has " << len << " strings\n";

		for (size_t i=0; i<len; i++)
			cout << "item " << (i+1) << "= \"" << &*result[i].begin() << "\"" << endl;
	}
	catch(const XERCES_CPP_NAMESPACE_QUALIFIER XMLException&)
	{
		cerr << "Exception caught!  Exiting..." << endl;
	}

	return 0;
}
<commit_msg>Turned on leak detection in debug build.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999-2004 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

#include "XPathWrapper.hpp"

#include <xercesc/util/XMLException.hpp>

#include <xalanc/PlatformSupport/DOMStringHelper.hpp>

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

// This is here for memory leak testing.
#if !defined(NDEBUG) && defined(_MSC_VER)
#include <crtdbg.h>
#endif

int
main(
			int		argc,
			char*	argv[])
{
#if !defined(NDEBUG) && defined(_MSC_VER)
	_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
	_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
	_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
#endif

    XALAN_USING_STD(cerr)
	XALAN_USING_STD(cout)
	XALAN_USING_STD(endl)
	XALAN_USING_STD(ifstream)

	if (argc < 4)
	{
		cerr << "Usage: TestDriver XMLFilePath Context XPathExpression" << endl;
		return -1;
	}

	XPathWrapper::ChVectorType	theXML;

	ifstream	in(argv[1]);

	// slow and dirty dump of the xml file into a buffer
	char c;
	while(in.get(c))
		theXML.push_back(c);
	theXML.push_back('\0');

	///////////////////////////////////////////..

	// create your XPath helper object
	XPathWrapper helper;

	try
	{
		// call evaluate, passing in the XML string, the context string and the xpath string
		const XPathWrapper::CharVectorTypeVectorType	result = helper.evaluate(&*theXML.begin(), argv[2], argv[3]);

		// take the resulting string vector	and do whatever you want with it:
		size_t len = result.size();

		cout << "the result set has " << len << " strings\n";

		for (size_t i=0; i<len; i++)
			cout << "item " << (i+1) << "= \"" << &*result[i].begin() << "\"" << endl;
	}
	catch(const XERCES_CPP_NAMESPACE_QUALIFIER XMLException&)
	{
		cerr << "Exception caught!  Exiting..." << endl;
	}

	return 0;
}
<|endoftext|>


<commit_before>#include "TATUInterpreter.h"

void TATUInterpreter::Interpreter(unsigned char *string, unsigned int length){
    switch(string[0]){
        case COMMAND_SET:
            cmd.OBJ.TYPE = TATU_SET;

            if(string[4] == CODE_INFO){
                cmd.OBJ.CODE = TATU_CODE_INFO;
                // Not implemented yet
            }
            else if(string[4] == CODE_STATE){
                cmd.OBJ.CODE = TATU_CODE_STATE;
                cmd.OBJ.PIN = ((unsigned int) string[10]) - 49;
                cmd.OBJ.STATE = ((unsigned int) string[12]) - 49;
            }
            else break;

            ERROR = false;
            return;
        case cmd_GET:
            cmd.OBJ.TYPE = TATU_GET;

            if(string[4] == CODE_ALL){
                cmd.OBJ.CODE = TATU_CODE_ALL;
            }
            else if(string[4] == CODE_INFO){
                cmd.OBJ.CODE = TATU_CODE_INFO;
                // Not implemented yet
            }
            else if(string[4] == CODE_STATE){
                cmd.OBJ.CODE = TATU_CODE_STATE;
                cmd.OBJ.PIN = ((unsigned int) string[9]) - 49;
            }
            else break;

            ERROR = false;
            return;
        case cmd_EDIT:
            cmd.OBJ.TYPE = TATU_EDIT;
            if(string[5] == CODE_INFO){
                cmd.OBJ.CODE = TATU_CODE_INFO;
                // Not implemented yet
            }
            else if(string[5] == CODE_STATE){
                cmd.OBJ.CODE = TATU_CODE_STATE;
                cmd.OBJ.PIN = ((unsigned int) string[11]) - 49;
                cmd.OBJ.STATE = ((unsigned int) string[13]) - 49;
            }
            else break;

            ERROR = false;
            return;
        case cmd_POST:
            cmd.OBJ.TYPE = TATU_POST;
            ERROR = false;
            return;
    }

    ERROR = true;
}

bool TATUInterpreter::getERROR(){
    return ERROR;
}
<commit_msg>Update TATUInterpreter.cpp<commit_after>#include "TATUInterpreter.h"

void TATUInterpreter::parse(unsigned char *string, unsigned int length){
    switch(string[0]){
        case COMMAND_SET:
            cmd.OBJ.TYPE = TATU_SET;

            if(string[4] == CODE_INFO){
                cmd.OBJ.CODE = TATU_CODE_INFO;
                // Not implemented yet
            }
            else if(string[4] == CODE_STATE){
                cmd.OBJ.CODE = TATU_CODE_STATE;
                cmd.OBJ.PIN = ((unsigned int) string[10]) - 49;
                cmd.OBJ.STATE = ((unsigned int) string[12]) - 49;
            }
            else break;

            ERROR = false;
            return;
        case cmd_GET:
            cmd.OBJ.TYPE = TATU_GET;

            if(string[4] == CODE_ALL){
                cmd.OBJ.CODE = TATU_CODE_ALL;
            }
            else if(string[4] == CODE_INFO){
                cmd.OBJ.CODE = TATU_CODE_INFO;
                // Not implemented yet
            }
            else if(string[4] == CODE_STATE){
                cmd.OBJ.CODE = TATU_CODE_STATE;
                cmd.OBJ.PIN = ((unsigned int) string[9]) - 49;
            }
            else break;

            ERROR = false;
            return;
        case cmd_EDIT:
            cmd.OBJ.TYPE = TATU_EDIT;
            if(string[5] == CODE_INFO){
                cmd.OBJ.CODE = TATU_CODE_INFO;
                // Not implemented yet
            }
            else if(string[5] == CODE_STATE){
                cmd.OBJ.CODE = TATU_CODE_STATE;
                cmd.OBJ.PIN = ((unsigned int) string[11]) - 49;
                cmd.OBJ.STATE = ((unsigned int) string[13]) - 49;
            }
            else break;

            ERROR = false;
            return;
        case cmd_POST:
            cmd.OBJ.TYPE = TATU_POST;
            ERROR = false;
            return;
    }

    ERROR = true;
}

bool TATUInterpreter::getERROR(){
    return ERROR;
}
<|endoftext|>


<commit_before>/**
*  Copyright (C) 2015 3D Repo Ltd
*
*  This program is free software: you can redistribute it and/or modify
*  it under the terms of the GNU Affero General Public License as
*  published by the Free Software Foundation, either version 3 of the
*  License, or (at your option) any later version.
*
*  This program is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU Affero General Public License for more details.
*
*  You should have received a copy of the GNU Affero General Public License
*  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

/**
* Allows geometry creation using ifcopenshell
*/

#include "repo_ifc_utils_geometry.h"
#include "../../../core/model/bson/repo_bson_factory.h"
#include <boost/filesystem.hpp>

using namespace repo::manipulator::modelconvertor;

IFCUtilsGeometry::IFCUtilsGeometry(const std::string &file) :
file(file)
{
}

IFCUtilsGeometry::~IFCUtilsGeometry()
{
}

repo_material_t IFCUtilsGeometry::createMaterial(
	const IfcGeom::Material &material)
{
	repo_material_t matProp;
	if (material.hasDiffuse())
	{
		auto diffuse = material.diffuse();
		matProp.diffuse = { (float)diffuse[0], (float)diffuse[1], (float)diffuse[2] };
	}

	if (material.hasSpecular())
	{
		auto specular = material.specular();
		matProp.specular = { (float)specular[0], (float)specular[1], (float)specular[2] };
	}

	if (material.hasSpecularity())
	{
		matProp.shininess = material.specularity();
	}
	else
	{
		matProp.shininess = NAN;
	}

	matProp.shininessStrength = NAN;

	if (material.hasTransparency())
	{
		matProp.opacity = 1. - material.transparency();
	}
	else
	{
		matProp.opacity = 1.;
	}
	return matProp;
}

IfcGeom::IteratorSettings IFCUtilsGeometry::createSettings()
{
	IfcGeom::IteratorSettings settings;
	settings.set(IfcGeom::IteratorSettings::APPLY_DEFAULT_MATERIALS, true);
	settings.set(IfcGeom::IteratorSettings::DISABLE_OPENING_SUBTRACTIONS, false);
	settings.set(IfcGeom::IteratorSettings::NO_NORMALS, false);
	settings.set(IfcGeom::IteratorSettings::WELD_VERTICES, false);
	settings.set(IfcGeom::IteratorSettings::GENERATE_UVS, true);
	settings.set(IfcGeom::IteratorSettings::USE_WORLD_COORDS, true);

	return settings;
}

bool IFCUtilsGeometry::generateGeometry(std::string &errMsg)
{
	repoInfo << "Initialising Geometry....." << std::endl;

	auto settings = createSettings();

	IfcGeom::Iterator<double> contextIterator(settings, file);

	std::set<std::string> exclude_entities;
	//Do not generate geometry for openings and spaces
	exclude_entities.insert("IfcOpeningElement");
	//exclude_entities.insert("IfcSpace");
	contextIterator.excludeEntities(exclude_entities);

	repoTrace << "Initialising Geom iterator";
	if (contextIterator.initialize())
	{
		repoTrace << "Geom Iterator initialized";
	}
	else
	{
		errMsg = "Failed to initialised Geom Iterator";
		return false;
	}

	std::vector<std::vector<repo_face_t>> allFaces;
	std::vector<std::vector<double>> allVertices;
	std::vector<std::vector<double>> allNormals;
	std::vector<std::vector<double>> allUVs;
	std::vector<std::string> allIds, allNames, allMaterials;

	retrieveGeometryFromIterator(contextIterator, settings.get(IfcGeom::IteratorSettings::USE_MATERIAL_NAMES),
		allVertices, allFaces, allNormals, allUVs, allIds, allNames, allMaterials);

	//now we have found all meshes, take the minimum bounding box of the scene as offset
	//and create repo meshes
	repoTrace << "Finished iterating. number of meshes found: " << allVertices.size();
	repoTrace << "Finished iterating. number of materials found: " << materials.size();

	std::map<std::string, std::vector<repoUUID>> materialParent;
	for (int i = 0; i < allVertices.size(); ++i)
	{
		std::vector<repo_vector_t> vertices, normals;
		std::vector<repo_vector2d_t> uvs;
		std::vector<repo_face_t> faces;
		std::vector<std::vector<float>> boundingBox;
		for (int j = 0; j < allVertices[i].size(); j += 3)
		{
			vertices.push_back({ (float)(allVertices[i][j] - offset[0]), (float)(allVertices[i][j + 1] - offset[1]), (float)(allVertices[i][j + 2] - offset[2]) });
			if (allNormals[i].size())
				normals.push_back({ (float)allNormals[i][j], (float)allNormals[i][j + 1], (float)allNormals[i][j + 2] });

			auto vertex = vertices.back();
			if (j == 0)
			{
				boundingBox.push_back({ vertex.x, vertex.y, vertex.z });
				boundingBox.push_back({ vertex.x, vertex.y, vertex.z });
			}
			else
			{
				boundingBox[0][0] = boundingBox[0][0] > vertex.x ? vertex.x : boundingBox[0][0];
				boundingBox[0][1] = boundingBox[0][1] > vertex.y ? vertex.y : boundingBox[0][1];
				boundingBox[0][2] = boundingBox[0][2] > vertex.z ? vertex.z : boundingBox[0][2];

				boundingBox[1][0] = boundingBox[1][0] < vertex.x ? vertex.x : boundingBox[1][0];
				boundingBox[1][1] = boundingBox[1][1] < vertex.y ? vertex.y : boundingBox[1][1];
				boundingBox[1][2] = boundingBox[1][2] < vertex.z ? vertex.z : boundingBox[1][2];
			}
		}

		for (int j = 0; j < allUVs[i].size(); j += 2)
		{
			uvs.push_back({ (float)allUVs[i][j], (float)allUVs[i][j + 1] });
		}

		std::vector < std::vector<repo_vector2d_t>> uvChannels;
		if (uvs.size())
			uvChannels.push_back(uvs);

		auto mesh = repo::core::model::RepoBSONFactory::makeMeshNode(vertices, allFaces[i], normals, boundingBox, uvChannels,
			std::vector<repo_color4d_t>(), std::vector<std::vector<float>>());

		if (meshes.find(allIds[i]) == meshes.end())
		{
			meshes[allIds[i]] = std::vector<repo::core::model::MeshNode*>();
		}
		meshes[allIds[i]].push_back(new repo::core::model::MeshNode(mesh));

		if (allMaterials[i] != "")
		{
			if (materialParent.find(allMaterials[i]) == materialParent.end())
			{
				materialParent[allMaterials[i]] = std::vector<repoUUID>();
			}

			materialParent[allMaterials[i]].push_back(mesh.getSharedID());
		}
	}

	repoTrace << "Meshes constructed. Wiring materials to parents...";

	for (const auto &pair : materialParent)
	{
		auto matIt = materials.find(pair.first);
		if (matIt != materials.end())
		{
			*(matIt->second) = matIt->second->cloneAndAddParent(pair.second);
		}
	}

	return true;
}

void IFCUtilsGeometry::retrieveGeometryFromIterator(
	IfcGeom::Iterator<double> &contextIterator,
	const bool useMaterialNames,
	std::vector < std::vector<double>> &allVertices,
	std::vector<std::vector<repo_face_t>> &allFaces,
	std::vector < std::vector<double>> &allNormals,
	std::vector < std::vector<double>> &allUVs,
	std::vector<std::string> &allIds,
	std::vector<std::string> &allNames,
	std::vector<std::string> &allMaterials)
{
	repoTrace << "Iterating through Geom Iterator.";
	do
	{
		IfcGeom::Element<double> *ob = contextIterator.get();
		auto ob_geo = static_cast<const IfcGeom::TriangulationElement<double>*>(ob);
		if (ob_geo)
		{
			auto faces = ob_geo->geometry().faces();
			auto vertices = ob_geo->geometry().verts();
			auto normals = ob_geo->geometry().normals();
			auto uvs = ob_geo->geometry().uvs();
			std::unordered_map<int, std::unordered_map<int, int>>  indexMapping;
			std::unordered_map<int, int> vertexCount;
			std::unordered_map<int, std::vector<double>> post_vertices, post_normals, post_uvs;
			std::unordered_map<int, std::vector<repo_face_t>> post_faces;

			auto matIndIt = ob_geo->geometry().material_ids().begin();

			for (int i = 0; i < vertices.size(); i += 3)
			{
				for (int j = 0; j < 3; ++j)
				{
					int index = j + i;
					if (offset.size() < j + 1)
					{
						offset.push_back(vertices[index]);
					}
					else
					{
						offset[j] = offset[j] > vertices[index] ? vertices[index] : offset[j];
					}
				}
			}

			for (int iface = 0; iface < faces.size(); iface += 3)
			{
				auto matInd = *matIndIt;
				if (indexMapping.find(matInd) == indexMapping.end())
				{
					//new material
					indexMapping[matInd] = std::unordered_map<int, int>();
					vertexCount[matInd] = 0;

					std::unordered_map<int, std::vector<double>> post_vertices, post_normals, post_uvs;
					std::unordered_map<int, std::vector<repo_face_t>> post_faces;

					post_vertices[matInd] = std::vector<double>();
					post_normals[matInd] = std::vector<double>();
					post_uvs[matInd] = std::vector<double>();
					post_faces[matInd] = std::vector<repo_face_t>();

					auto material = ob_geo->geometry().materials()[matInd];
					std::string matName = useMaterialNames ? material.original_name() : material.name();
					allMaterials.push_back(matName);
					if (materials.find(matName) == materials.end())
					{
						//new material, add it to the vector
						repo_material_t matProp = createMaterial(material);
						materials[matName] = new repo::core::model::MaterialNode(repo::core::model::RepoBSONFactory::makeMaterialNode(matProp, matName));
					}
				}

				repo_face_t face;
				for (int j = 0; j < 3; ++j)
				{
					auto vIndex = faces[iface + j];
					if (indexMapping[matInd].find(vIndex) == indexMapping[matInd].end())
					{
						//new index. create a mapping
						indexMapping[matInd][vIndex] = vertexCount[matInd]++;
						for (int ivert = 0; ivert < 3; ++ivert)
						{
							auto bufferInd = ivert + vIndex * 3;
							post_vertices[matInd].push_back(vertices[bufferInd]);

							if (normals.size())
								post_normals[matInd].push_back(normals[bufferInd]);

							if (uvs.size() && ivert < 2)
							{
								auto uvbufferInd = ivert + vIndex * 2;
								post_uvs[matInd].push_back(uvs[uvbufferInd]);
							}
						}
					}
					face.push_back(indexMapping[matInd][vIndex]);
				}

				post_faces[matInd].push_back(face);

				++matIndIt;
			}

			auto guid = ob_geo->guid();
			auto name = ob_geo->name();
			for (const auto& pair : post_faces)
			{
				auto index = pair.first;
				allVertices.push_back(post_vertices[index]);
				allNormals.push_back(post_normals[index]);
				allFaces.push_back(pair.second);
				allUVs.push_back(post_uvs[index]);

				allIds.push_back(guid);
				allNames.push_back(name);
			}
		}
		if (allIds.size() % 100 == 0)
			repoInfo << allIds.size() << " meshes created";
	} while (contextIterator.next());
}<commit_msg>#152 filter out IFCMember but include IFCSpace<commit_after>/**
*  Copyright (C) 2015 3D Repo Ltd
*
*  This program is free software: you can redistribute it and/or modify
*  it under the terms of the GNU Affero General Public License as
*  published by the Free Software Foundation, either version 3 of the
*  License, or (at your option) any later version.
*
*  This program is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU Affero General Public License for more details.
*
*  You should have received a copy of the GNU Affero General Public License
*  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

/**
* Allows geometry creation using ifcopenshell
*/

#include "repo_ifc_utils_geometry.h"
#include "../../../core/model/bson/repo_bson_factory.h"
#include <boost/filesystem.hpp>

using namespace repo::manipulator::modelconvertor;

IFCUtilsGeometry::IFCUtilsGeometry(const std::string &file) :
file(file)
{
}

IFCUtilsGeometry::~IFCUtilsGeometry()
{
}

repo_material_t IFCUtilsGeometry::createMaterial(
	const IfcGeom::Material &material)
{
	repo_material_t matProp;
	if (material.hasDiffuse())
	{
		auto diffuse = material.diffuse();
		matProp.diffuse = { (float)diffuse[0], (float)diffuse[1], (float)diffuse[2] };
	}

	if (material.hasSpecular())
	{
		auto specular = material.specular();
		matProp.specular = { (float)specular[0], (float)specular[1], (float)specular[2] };
	}

	if (material.hasSpecularity())
	{
		matProp.shininess = material.specularity();
	}
	else
	{
		matProp.shininess = NAN;
	}

	matProp.shininessStrength = NAN;

	if (material.hasTransparency())
	{
		matProp.opacity = 1. - material.transparency();
	}
	else
	{
		matProp.opacity = 1.;
	}
	return matProp;
}

IfcGeom::IteratorSettings IFCUtilsGeometry::createSettings()
{
	IfcGeom::IteratorSettings settings;
	settings.set(IfcGeom::IteratorSettings::APPLY_DEFAULT_MATERIALS, true);
	settings.set(IfcGeom::IteratorSettings::DISABLE_OPENING_SUBTRACTIONS, false);
	settings.set(IfcGeom::IteratorSettings::NO_NORMALS, false);
	settings.set(IfcGeom::IteratorSettings::WELD_VERTICES, false);
	settings.set(IfcGeom::IteratorSettings::GENERATE_UVS, true);
	settings.set(IfcGeom::IteratorSettings::USE_WORLD_COORDS, true);

	return settings;
}

bool IFCUtilsGeometry::generateGeometry(std::string &errMsg)
{
	repoInfo << "Initialising Geometry....." << std::endl;

	auto settings = createSettings();

	IfcGeom::Iterator<double> contextIterator(settings, file);

	std::set<std::string> exclude_entities;
	exclude_entities.insert("IfcOpeningElement");
	exclude_entities.insert("IfcMember");
	contextIterator.excludeEntities(exclude_entities);

	repoTrace << "Initialising Geom iterator";
	if (contextIterator.initialize())
	{
		repoTrace << "Geom Iterator initialized";
	}
	else
	{
		errMsg = "Failed to initialised Geom Iterator";
		return false;
	}

	std::vector<std::vector<repo_face_t>> allFaces;
	std::vector<std::vector<double>> allVertices;
	std::vector<std::vector<double>> allNormals;
	std::vector<std::vector<double>> allUVs;
	std::vector<std::string> allIds, allNames, allMaterials;

	retrieveGeometryFromIterator(contextIterator, settings.get(IfcGeom::IteratorSettings::USE_MATERIAL_NAMES),
		allVertices, allFaces, allNormals, allUVs, allIds, allNames, allMaterials);

	//now we have found all meshes, take the minimum bounding box of the scene as offset
	//and create repo meshes
	repoTrace << "Finished iterating. number of meshes found: " << allVertices.size();
	repoTrace << "Finished iterating. number of materials found: " << materials.size();

	std::map<std::string, std::vector<repoUUID>> materialParent;
	for (int i = 0; i < allVertices.size(); ++i)
	{
		std::vector<repo_vector_t> vertices, normals;
		std::vector<repo_vector2d_t> uvs;
		std::vector<repo_face_t> faces;
		std::vector<std::vector<float>> boundingBox;
		for (int j = 0; j < allVertices[i].size(); j += 3)
		{
			vertices.push_back({ (float)(allVertices[i][j] - offset[0]), (float)(allVertices[i][j + 1] - offset[1]), (float)(allVertices[i][j + 2] - offset[2]) });
			if (allNormals[i].size())
				normals.push_back({ (float)allNormals[i][j], (float)allNormals[i][j + 1], (float)allNormals[i][j + 2] });

			auto vertex = vertices.back();
			if (j == 0)
			{
				boundingBox.push_back({ vertex.x, vertex.y, vertex.z });
				boundingBox.push_back({ vertex.x, vertex.y, vertex.z });
			}
			else
			{
				boundingBox[0][0] = boundingBox[0][0] > vertex.x ? vertex.x : boundingBox[0][0];
				boundingBox[0][1] = boundingBox[0][1] > vertex.y ? vertex.y : boundingBox[0][1];
				boundingBox[0][2] = boundingBox[0][2] > vertex.z ? vertex.z : boundingBox[0][2];

				boundingBox[1][0] = boundingBox[1][0] < vertex.x ? vertex.x : boundingBox[1][0];
				boundingBox[1][1] = boundingBox[1][1] < vertex.y ? vertex.y : boundingBox[1][1];
				boundingBox[1][2] = boundingBox[1][2] < vertex.z ? vertex.z : boundingBox[1][2];
			}
		}

		for (int j = 0; j < allUVs[i].size(); j += 2)
		{
			uvs.push_back({ (float)allUVs[i][j], (float)allUVs[i][j + 1] });
		}

		std::vector < std::vector<repo_vector2d_t>> uvChannels;
		if (uvs.size())
			uvChannels.push_back(uvs);

		auto mesh = repo::core::model::RepoBSONFactory::makeMeshNode(vertices, allFaces[i], normals, boundingBox, uvChannels,
			std::vector<repo_color4d_t>(), std::vector<std::vector<float>>());

		if (meshes.find(allIds[i]) == meshes.end())
		{
			meshes[allIds[i]] = std::vector<repo::core::model::MeshNode*>();
		}
		meshes[allIds[i]].push_back(new repo::core::model::MeshNode(mesh));

		if (allMaterials[i] != "")
		{
			if (materialParent.find(allMaterials[i]) == materialParent.end())
			{
				materialParent[allMaterials[i]] = std::vector<repoUUID>();
			}

			materialParent[allMaterials[i]].push_back(mesh.getSharedID());
		}
	}

	repoTrace << "Meshes constructed. Wiring materials to parents...";

	for (const auto &pair : materialParent)
	{
		auto matIt = materials.find(pair.first);
		if (matIt != materials.end())
		{
			*(matIt->second) = matIt->second->cloneAndAddParent(pair.second);
		}
	}

	return true;
}

void IFCUtilsGeometry::retrieveGeometryFromIterator(
	IfcGeom::Iterator<double> &contextIterator,
	const bool useMaterialNames,
	std::vector < std::vector<double>> &allVertices,
	std::vector<std::vector<repo_face_t>> &allFaces,
	std::vector < std::vector<double>> &allNormals,
	std::vector < std::vector<double>> &allUVs,
	std::vector<std::string> &allIds,
	std::vector<std::string> &allNames,
	std::vector<std::string> &allMaterials)
{
	repoTrace << "Iterating through Geom Iterator.";
	do
	{
		IfcGeom::Element<double> *ob = contextIterator.get();
		auto ob_geo = static_cast<const IfcGeom::TriangulationElement<double>*>(ob);
		if (ob_geo)
		{
			auto faces = ob_geo->geometry().faces();
			auto vertices = ob_geo->geometry().verts();
			auto normals = ob_geo->geometry().normals();
			auto uvs = ob_geo->geometry().uvs();
			std::unordered_map<int, std::unordered_map<int, int>>  indexMapping;
			std::unordered_map<int, int> vertexCount;
			std::unordered_map<int, std::vector<double>> post_vertices, post_normals, post_uvs;
			std::unordered_map<int, std::vector<repo_face_t>> post_faces;

			auto matIndIt = ob_geo->geometry().material_ids().begin();

			for (int i = 0; i < vertices.size(); i += 3)
			{
				for (int j = 0; j < 3; ++j)
				{
					int index = j + i;
					if (offset.size() < j + 1)
					{
						offset.push_back(vertices[index]);
					}
					else
					{
						offset[j] = offset[j] > vertices[index] ? vertices[index] : offset[j];
					}
				}
			}

			for (int iface = 0; iface < faces.size(); iface += 3)
			{
				auto matInd = *matIndIt;
				if (indexMapping.find(matInd) == indexMapping.end())
				{
					//new material
					indexMapping[matInd] = std::unordered_map<int, int>();
					vertexCount[matInd] = 0;

					std::unordered_map<int, std::vector<double>> post_vertices, post_normals, post_uvs;
					std::unordered_map<int, std::vector<repo_face_t>> post_faces;

					post_vertices[matInd] = std::vector<double>();
					post_normals[matInd] = std::vector<double>();
					post_uvs[matInd] = std::vector<double>();
					post_faces[matInd] = std::vector<repo_face_t>();

					auto material = ob_geo->geometry().materials()[matInd];
					std::string matName = useMaterialNames ? material.original_name() : material.name();
					allMaterials.push_back(matName);
					if (materials.find(matName) == materials.end())
					{
						//new material, add it to the vector
						repo_material_t matProp = createMaterial(material);
						materials[matName] = new repo::core::model::MaterialNode(repo::core::model::RepoBSONFactory::makeMaterialNode(matProp, matName));
					}
				}

				repo_face_t face;
				for (int j = 0; j < 3; ++j)
				{
					auto vIndex = faces[iface + j];
					if (indexMapping[matInd].find(vIndex) == indexMapping[matInd].end())
					{
						//new index. create a mapping
						indexMapping[matInd][vIndex] = vertexCount[matInd]++;
						for (int ivert = 0; ivert < 3; ++ivert)
						{
							auto bufferInd = ivert + vIndex * 3;
							post_vertices[matInd].push_back(vertices[bufferInd]);

							if (normals.size())
								post_normals[matInd].push_back(normals[bufferInd]);

							if (uvs.size() && ivert < 2)
							{
								auto uvbufferInd = ivert + vIndex * 2;
								post_uvs[matInd].push_back(uvs[uvbufferInd]);
							}
						}
					}
					face.push_back(indexMapping[matInd][vIndex]);
				}

				post_faces[matInd].push_back(face);

				++matIndIt;
			}

			auto guid = ob_geo->guid();
			auto name = ob_geo->name();
			for (const auto& pair : post_faces)
			{
				auto index = pair.first;
				allVertices.push_back(post_vertices[index]);
				allNormals.push_back(post_normals[index]);
				allFaces.push_back(pair.second);
				allUVs.push_back(post_uvs[index]);

				allIds.push_back(guid);
				allNames.push_back(name);
			}
		}
		if (allIds.size() % 100 == 0)
			repoInfo << allIds.size() << " meshes created";
	} while (contextIterator.next());
}<|endoftext|>


<commit_before>#include <iostream>
#include <algorithm>
#include <SDL2/SDL.h>
#include <IL/il.h>
#include <IL/ilu.h>
#include <cassert>
#include "cluster.h"
#include <cstdio>
#include <cstdlib>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string>
#include <locale>
#include "arduino-serial-lib.h"

using std::cerr;
using std::cout;
using std::endl;
using std::string;

SDL_Window* app_window;
SDL_Renderer* app_renderer;

int setup_SDL(int width, int height)
{
  if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {
    cerr << "SDL_Init Error: " << SDL_GetError() << endl;
    return 1;
  }
  app_window = SDL_CreateWindow("DPAD Image Transformer", 100, 100,
                                width, height,
                                SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);
  if (app_window == NULL) {
    cerr << "SDL_CreateWindow Error: " << SDL_GetError() << endl;
    return 1;
  }

  SDL_EventState(SDL_DROPFILE, SDL_ENABLE);

  app_renderer = SDL_CreateRenderer(
    app_window, -1,
    SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);

  if (app_renderer == NULL) {
    cerr << "SDL_CreateRenderer Error: " << SDL_GetError() << endl;
    return 1;
  }

  return 0;
}

int setup_devil()
{
  if (ilGetInteger(IL_VERSION_NUM) < IL_VERSION) {
    /* wrong DevIL version */
    return -1;
  }

  ilInit();
  iluInit();
  return 0;
}

void write_image_as_header(ILuint image, const ColorClusterer &clusterer)
{
  ilBindImage(image);
  int w = ilGetInteger(IL_IMAGE_WIDTH);
  int h = ilGetInteger(IL_IMAGE_HEIGHT);
  uchar* data = ilGetData();

  int nc = clusterer.clusters();
  printf("#pragma once\n");
  printf("#include <inttypes.h>\n");
  printf("\n");
  printf("#define PALETTE_SIZE %d\n", nc);
  printf("uint32_t palette_data[PALETTE_SIZE] = {");

  const int entries_per_row = 8;
  for (int i = 0, display_row = 0; i < nc; ++i, display_row = (display_row + 1) % entries_per_row)
  {
    if (display_row == 0)
      printf("\n/* %3d-%3d*/ ", i, std::min(i + entries_per_row-1, nc-1));
    ColorKey ck = clusterer[i];
    uchar r, g, b;
    ck.to_rgb(r, g, b);
    printf("0x%02x%02x%02x", r, g, b);
    if (i != nc - 1)
      printf(", ");
  }
  printf("\n};\n\n");

  printf("uint8_t pixel_data[%d][%d] = {", h, w);
  for (int y = h-1; y >= 0; --y)
  {
    printf("\n{");
    for (int x = 0; x < w; ++x)
    {
      int i = y * w + x;
      uchar r = data[3*i], g = data[3*i + 1], b = data[3*i + 2];

      int index = clusterer.get_index(r, g, b);

      printf("%d", index);
      if (x != w - 1)
        printf(", ");
    }
    printf("}");
    if (y != 0)
      printf(",");
  }
  printf("\n};\n");
}

ILuint load_image(const char* filename)
{
  ILuint tex;
  ilGenImages(1, &tex);
  ilBindImage(tex);

  bool success = ilLoadImage(filename);

  if (!success)
  {
    cerr << "Could not load image: " << filename << endl;
    return 0;
  }

  cerr << "Loaded " << filename << endl;

  success = ilConvertImage(IL_RGB, IL_UNSIGNED_BYTE);
  if (!success)
  {
    cerr << "Could not convert image to R8G8B8" << endl;
  }

  cerr << "converted image" << endl;

  return tex;
}

ILuint resize_image(ILuint image, ColorClusterer& clusterer)
{
  ILuint new_image;
  ilGenImages(1, &new_image);
  ilBindImage(new_image);

  ilCopyImage(image);

  iluScale(32, 32, 8);

  uchar* pixels = ilGetData();

  int img_width = 32;
  for (int y = 0; y < 32; ++y) {
    for (int x = 0; x < 32; ++x) {
      uchar* offset = &pixels[3 * img_width * y + 3 * x];
      clusterer.add_pixel(offset[0], offset[1], offset[2]);
    }
  }

  clusterer.update_clusters();

  return new_image;
}

ILuint posterize_image(ILuint image, const ColorClusterer& clusterer)
{
  ILuint new_image;
  ilGenImages(1, &new_image);
  ilBindImage(new_image);

  ilCopyImage(image);

  iluScale(32, 32, 8);

  uchar* pixels = ilGetData();

  int img_width = 32;
  for (int y = 0; y < 32; ++y) {
    for (int x = 0; x < 32; ++x) {
      uchar* offset = &pixels[3 * img_width * y + 3 * x];

      int color_index = clusterer.get_index(offset[0], offset[1], offset[2]);
      clusterer[color_index].to_rgb(offset[0], offset[1], offset[2]);
    }
  }

  return new_image;
}

void write_and_ack(int fd, uint8_t b)
{
  serialport_writebyte(fd, b);
  char buffer[256];
  serialport_read_until(fd, buffer, '\n', 255, 1000);
}

void send_image(ILuint image, const ColorClusterer& clusterer)
{
  int fd;
  if ((fd = serialport_init("/dev/ttyACM0", 9600)) < 0)
    cerr << "Could not open arduino port." << endl;

  cerr << "Opening. Waiting 1 seconds." << endl;
  sleep(1);

  uchar num_clusters = clusterer.clusters();
  write_and_ack(fd, num_clusters);

  for (int i = 0; i < num_clusters; ++i)
  {
    uchar r, g, b;
    clusterer[i].to_rgb(r, g, b);
    write_and_ack(fd, r);
    write_and_ack(fd, g);
    write_and_ack(fd, b);
    usleep(10000);
  }

  const uchar* data = ilGetData();
  for (int i = 0; i < 1024; ++i)
  {
    const uchar* offset = &data[3*i];
    uchar index = clusterer.get_index(offset[0], offset[1], offset[2]);
    write_and_ack(fd, index);
    usleep(1000);
  };

  cerr << "Wrote image." << endl;
  serialport_close(fd);
}

SDL_Texture* make_sdl_texture(ILuint image_tex)
{

  int img_width = ilGetInteger(IL_IMAGE_WIDTH);
  int img_height = ilGetInteger(IL_IMAGE_HEIGHT);

  SDL_Texture* sdl_tex = SDL_CreateTexture(app_renderer, SDL_PIXELFORMAT_RGB24,
                                           SDL_TEXTUREACCESS_STREAMING,
                                           img_width, img_height);

  SDL_UpdateTexture(sdl_tex, NULL, ilGetData(), img_width * 3);

  return sdl_tex;
}

int main(int argc, char **args)
{
  setup_devil();
  string command("");
  if (argc > 1)
  {
    command = args[1];
    transform(command.begin(), command.end(), command.begin(), tolower);
  }

  // non-interactive c++ header generation
  if (command == "source")
  {
    ILuint image = load_image( args[2] );
    ColorClusterer clusterer(255);
    ILuint resized_image = resize_image( image, clusterer );

    write_image_as_header( resized_image, clusterer );

    ilDeleteImage(image);
    ilDeleteImage(resized_image);

    return 0;
  }

  if (command == "send")
  {
    ILuint image = load_image( args[2] );
    ColorClusterer clusterer(255);
    ILuint resized_image = resize_image( image, clusterer );

    send_image( resized_image, clusterer );

    ilDeleteImage(image);
    ilDeleteImage(resized_image);

    return 0;

  }

  if (setup_SDL(512, 512))
  {
    cerr << "could not load SDL" << endl;
    return 1;
  }

  cerr << "Loaded SDL" << endl;

  SDL_RenderClear(app_renderer);
  SDL_SetRenderDrawColor(app_renderer, 63, 63, 63, 0);

  SDL_Texture* tex = NULL;

  bool quit = false;

  ColorClusterer cluster(255);

  SDL_Event e;
  while (!quit) {
    while (SDL_PollEvent(&e)) {
      if (e.type == SDL_DROPFILE)
      {
        const char* filename = e.drop.file;

        ILuint image = load_image( filename );
        cluster.clear();
        ILuint ri = resize_image( image, cluster );
        ILuint posterized_image = posterize_image( ri, cluster );

        SDL_Texture* new_tex = make_sdl_texture(posterized_image);

        ilDeleteImage(image);
        ilDeleteImage(ri);
        ilDeleteImage(posterized_image);

        if (new_tex) {
          SDL_DestroyTexture(tex);
          tex = new_tex;
          cerr << "changed texture" << endl;
        }
        else {
          cerr << "Could not load texture" << endl;
        }
      }

      if (e.type == SDL_KEYDOWN) {
        if (e.key.keysym.sym == SDLK_ESCAPE) {
          quit = true;
        }
      }

      if (e.type == SDL_QUIT)
        quit = true;
    }

    SDL_RenderClear(app_renderer);
    SDL_RenderCopy(app_renderer, tex, NULL, NULL);
    SDL_RenderPresent(app_renderer);
  }

  SDL_DestroyTexture(tex);

  SDL_DestroyRenderer(app_renderer);
  SDL_DestroyWindow(app_window);
  SDL_Quit();
}

<commit_msg>Added 'send_color' command<commit_after>#include <iostream>
#include <algorithm>
#include <SDL2/SDL.h>
#include <IL/il.h>
#include <IL/ilu.h>
#include <cassert>
#include "cluster.h"
#include <cstdio>
#include <cstdlib>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string>
#include <locale>
#include "arduino-serial-lib.h"

using std::cerr;
using std::cout;
using std::endl;
using std::string;

SDL_Window* app_window;
SDL_Renderer* app_renderer;

int setup_SDL(int width, int height)
{
  if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {
    cerr << "SDL_Init Error: " << SDL_GetError() << endl;
    return 1;
  }
  app_window = SDL_CreateWindow("DPAD Image Transformer", 100, 100,
                                width, height,
                                SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);
  if (app_window == NULL) {
    cerr << "SDL_CreateWindow Error: " << SDL_GetError() << endl;
    return 1;
  }

  SDL_EventState(SDL_DROPFILE, SDL_ENABLE);

  app_renderer = SDL_CreateRenderer(
    app_window, -1,
    SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);

  if (app_renderer == NULL) {
    cerr << "SDL_CreateRenderer Error: " << SDL_GetError() << endl;
    return 1;
  }

  return 0;
}

int setup_devil()
{
  if (ilGetInteger(IL_VERSION_NUM) < IL_VERSION) {
    /* wrong DevIL version */
    return -1;
  }

  ilInit();
  iluInit();
  return 0;
}

void write_image_as_header(ILuint image, const ColorClusterer &clusterer)
{
  ilBindImage(image);
  int w = ilGetInteger(IL_IMAGE_WIDTH);
  int h = ilGetInteger(IL_IMAGE_HEIGHT);
  uchar* data = ilGetData();

  int nc = clusterer.clusters();
  printf("#pragma once\n");
  printf("#include <inttypes.h>\n");
  printf("\n");
  printf("#define PALETTE_SIZE %d\n", nc);
  printf("uint32_t palette_data[PALETTE_SIZE] = {");

  const int entries_per_row = 8;
  for (int i = 0, display_row = 0; i < nc; ++i, display_row = (display_row + 1) % entries_per_row)
  {
    if (display_row == 0)
      printf("\n/* %3d-%3d*/ ", i, std::min(i + entries_per_row-1, nc-1));
    ColorKey ck = clusterer[i];
    uchar r, g, b;
    ck.to_rgb(r, g, b);
    printf("0x%02x%02x%02x", r, g, b);
    if (i != nc - 1)
      printf(", ");
  }
  printf("\n};\n\n");

  printf("uint8_t pixel_data[%d][%d] = {", h, w);
  for (int y = h-1; y >= 0; --y)
  {
    printf("\n{");
    for (int x = 0; x < w; ++x)
    {
      int i = y * w + x;
      uchar r = data[3*i], g = data[3*i + 1], b = data[3*i + 2];

      int index = clusterer.get_index(r, g, b);

      printf("%d", index);
      if (x != w - 1)
        printf(", ");
    }
    printf("}");
    if (y != 0)
      printf(",");
  }
  printf("\n};\n");
}

ILuint load_image(const char* filename)
{
  ILuint tex;
  ilGenImages(1, &tex);
  ilBindImage(tex);

  bool success = ilLoadImage(filename);

  if (!success)
  {
    cerr << "Could not load image: " << filename << endl;
    return 0;
  }

  cerr << "Loaded " << filename << endl;

  success = ilConvertImage(IL_RGB, IL_UNSIGNED_BYTE);
  if (!success)
  {
    cerr << "Could not convert image to R8G8B8" << endl;
  }

  cerr << "converted image" << endl;

  return tex;
}

ILuint resize_image(ILuint image, ColorClusterer& clusterer)
{
  ILuint new_image;
  ilGenImages(1, &new_image);
  ilBindImage(new_image);

  ilCopyImage(image);

  iluScale(32, 32, 8);

  uchar* pixels = ilGetData();

  int img_width = 32;
  for (int y = 0; y < 32; ++y) {
    for (int x = 0; x < 32; ++x) {
      uchar* offset = &pixels[3 * img_width * y + 3 * x];
      clusterer.add_pixel(offset[0], offset[1], offset[2]);
    }
  }

  clusterer.update_clusters();

  return new_image;
}

ILuint posterize_image(ILuint image, const ColorClusterer& clusterer)
{
  ILuint new_image;
  ilGenImages(1, &new_image);
  ilBindImage(new_image);

  ilCopyImage(image);

  iluScale(32, 32, 8);

  uchar* pixels = ilGetData();

  int img_width = 32;
  for (int y = 0; y < 32; ++y) {
    for (int x = 0; x < 32; ++x) {
      uchar* offset = &pixels[3 * img_width * y + 3 * x];

      int color_index = clusterer.get_index(offset[0], offset[1], offset[2]);
      clusterer[color_index].to_rgb(offset[0], offset[1], offset[2]);
    }
  }

  return new_image;
}

void write_and_ack(int fd, uint8_t b)
{
  serialport_writebyte(fd, b);
  char buffer[256];
  serialport_read_until(fd, buffer, '\n', 255, 1000);
}

void send_color(uint8_t r, uint8_t g, uint8_t b)
{
  int fd;
  if ((fd = serialport_init("/dev/ttyACM0", 9600)) < 0)
  {
    cerr << "Could not open arduino port." << endl;
    exit(1);
  }

  cerr << "Opening. Waiting 1 seconds." << endl;
  sleep(1);
  write_and_ack(fd, 1);
  write_and_ack(fd, r);
  write_and_ack(fd, g);
  write_and_ack(fd, b);
}

void send_image(ILuint image, const ColorClusterer& clusterer)
{
  int fd;
  if ((fd = serialport_init("/dev/ttyACM0", 9600)) < 0)
    cerr << "Could not open arduino port." << endl;

  cerr << "Opening. Waiting 1 seconds." << endl;
  sleep(1);

  uchar num_clusters = clusterer.clusters();
  write_and_ack(fd, 0);
  write_and_ack(fd, num_clusters);

  for (int i = 0; i < num_clusters; ++i)
  {
    uchar r, g, b;
    clusterer[i].to_rgb(r, g, b);
    write_and_ack(fd, r);
    write_and_ack(fd, g);
    write_and_ack(fd, b);
    usleep(10000);
  }

  const uchar* data = ilGetData();
  for (int i = 0; i < 1024; ++i)
  {
    const uchar* offset = &data[3*i];
    uchar index = clusterer.get_index(offset[0], offset[1], offset[2]);
    write_and_ack(fd, index);
    usleep(1000);
  };

  cerr << "Wrote image." << endl;
  serialport_close(fd);
}

SDL_Texture* make_sdl_texture(ILuint image_tex)
{

  int img_width = ilGetInteger(IL_IMAGE_WIDTH);
  int img_height = ilGetInteger(IL_IMAGE_HEIGHT);

  SDL_Texture* sdl_tex = SDL_CreateTexture(app_renderer, SDL_PIXELFORMAT_RGB24,
                                           SDL_TEXTUREACCESS_STREAMING,
                                           img_width, img_height);

  SDL_UpdateTexture(sdl_tex, NULL, ilGetData(), img_width * 3);

  return sdl_tex;
}

int main(int argc, char **args)
{
  setup_devil();
  string command("");
  if (argc > 1)
  {
    command = args[1];
    transform(command.begin(), command.end(), command.begin(), tolower);
  }

  // non-interactive c++ header generation
  if (command == "source")
  {
    ILuint image = load_image( args[2] );
    ColorClusterer clusterer(255);
    ILuint resized_image = resize_image( image, clusterer );

    write_image_as_header( resized_image, clusterer );

    ilDeleteImage(image);
    ilDeleteImage(resized_image);

    return 0;
  }

  if (command == "send")
  {
    ILuint image = load_image( args[2] );
    ColorClusterer clusterer(255);
    ILuint resized_image = resize_image( image, clusterer );

    send_image( resized_image, clusterer );

    ilDeleteImage(image);
    ilDeleteImage(resized_image);

    return 0;

  }

  if (command == "send_color")
  {
    assert(argc >= 5);
    send_color( atoi(args[2]), atoi(args[3]), atoi(args[4]));
    return 0;
  }

  if (setup_SDL(512, 512))
  {
    cerr << "could not load SDL" << endl;
    return 1;
  }

  cerr << "Loaded SDL" << endl;

  SDL_RenderClear(app_renderer);
  SDL_SetRenderDrawColor(app_renderer, 63, 63, 63, 0);

  SDL_Texture* tex = NULL;

  bool quit = false;

  ColorClusterer cluster(255);

  SDL_Event e;
  while (!quit) {
    while (SDL_PollEvent(&e)) {
      if (e.type == SDL_DROPFILE)
      {
        const char* filename = e.drop.file;

        ILuint image = load_image( filename );
        cluster.clear();
        ILuint ri = resize_image( image, cluster );
        ILuint posterized_image = posterize_image( ri, cluster );

        SDL_Texture* new_tex = make_sdl_texture(posterized_image);

        ilDeleteImage(image);
        ilDeleteImage(ri);
        ilDeleteImage(posterized_image);

        if (new_tex) {
          SDL_DestroyTexture(tex);
          tex = new_tex;
          cerr << "changed texture" << endl;
        }
        else {
          cerr << "Could not load texture" << endl;
        }
      }

      if (e.type == SDL_KEYDOWN) {
        if (e.key.keysym.sym == SDLK_ESCAPE) {
          quit = true;
        }
      }

      if (e.type == SDL_QUIT)
        quit = true;
    }

    SDL_RenderClear(app_renderer);
    SDL_RenderCopy(app_renderer, tex, NULL, NULL);
    SDL_RenderPresent(app_renderer);
  }

  SDL_DestroyTexture(tex);

  SDL_DestroyRenderer(app_renderer);
  SDL_DestroyWindow(app_window);
  SDL_Quit();
}

<|endoftext|>


<commit_before>// Copyright (C) 2018 Elviss Strazdins
// This file is part of the Ouzel engine.

#include "MainMenu.hpp"
#include "SpritesSample.hpp"
#include "GUISample.hpp"
#include "RTSample.hpp"
#include "AnimationsSample.hpp"
#include "InputSample.hpp"
#include "SoundSample.hpp"
#include "PerspectiveSample.hpp"

std::string DEVELOPER_NAME = "org.ouzel";
std::string APPLICATION_NAME = "samples";

using namespace ouzel;

void ouzelMain(const std::vector<std::string>& args)
{
    // disable screen saver
    engine->setScreenSaverEnabled(false);

    std::string sample;

    for (auto arg = args.begin(); arg != args.end(); ++arg)
    {
        if (arg == args.begin())
        {
            // skip the first parameter
            continue;
        }

        if (*arg == "-sample")
        {
            auto nextArg = ++arg;

            if (nextArg != args.end())
            {
                sample = *nextArg;
            }
            else
            {
                ouzel::Log(ouzel::Log::Level::WARN) << "No sample specified";
            }
        }
        else
        {
            ouzel::Log(ouzel::Log::Level::WARN) << "Invalid argument \"" << *arg << "\"";
        }
    }

    engine->getFileSystem()->addResourcePath("Resources");

    engine->getRenderer()->setClearColor(ouzel::Color(64, 0, 0));

    std::unique_ptr<ouzel::scene::Scene> currentScene;

    if (!sample.empty())
    {
        if (sample == "sprites")
        {
            currentScene.reset(new SpritesSample());
        }
        else if (sample == "gui")
        {
            currentScene.reset(new GUISample());
        }
        else if (sample == "render_target")
        {
            currentScene.reset(new RTSample());
        }
        else if (sample == "animations")
        {
            currentScene.reset(new AnimationsSample());
        }
        else if (sample == "input")
        {
            currentScene.reset(new InputSample());
        }
        else if (sample == "sound")
        {
            currentScene.reset(new SoundSample());
        }
        else if (sample == "perspective")
        {
            currentScene.reset(new PerspectiveSample());
        }
    }

    if (!currentScene)
    {
        currentScene.reset(new MainMenu());
    }

    engine->getSceneManager()->setScene(std::move(currentScene));
}
<commit_msg>Remove comments<commit_after>// Copyright (C) 2018 Elviss Strazdins
// This file is part of the Ouzel engine.

#include "MainMenu.hpp"
#include "SpritesSample.hpp"
#include "GUISample.hpp"
#include "RTSample.hpp"
#include "AnimationsSample.hpp"
#include "InputSample.hpp"
#include "SoundSample.hpp"
#include "PerspectiveSample.hpp"

std::string DEVELOPER_NAME = "org.ouzel";
std::string APPLICATION_NAME = "samples";

using namespace ouzel;

Archive archive;

void ouzelMain(const std::vector<std::string>& args)
{
    // disable screen saver
    engine->setScreenSaverEnabled(false);

    std::string sample;

    for (auto arg = args.begin(); arg != args.end(); ++arg)
    {
        if (arg == args.begin())
        {
            // skip the first parameter
            continue;
        }

        if (*arg == "-sample")
        {
            auto nextArg = ++arg;

            if (nextArg != args.end())
            {
                sample = *nextArg;
            }
            else
            {
                ouzel::Log(ouzel::Log::Level::WARN) << "No sample specified";
            }
        }
        else
        {
            ouzel::Log(ouzel::Log::Level::WARN) << "Invalid argument \"" << *arg << "\"";
        }
    }

    archive.open("resources.zip");

    engine->getFileSystem()->addArchive(&archive);
    engine->getFileSystem()->addResourcePath("Resources");

    engine->getRenderer()->setClearColor(ouzel::Color(64, 0, 0));

    std::unique_ptr<ouzel::scene::Scene> currentScene;

    if (!sample.empty())
    {
        if (sample == "sprites")
        {
            currentScene.reset(new SpritesSample());
        }
        else if (sample == "gui")
        {
            currentScene.reset(new GUISample());
        }
        else if (sample == "render_target")
        {
            currentScene.reset(new RTSample());
        }
        else if (sample == "animations")
        {
            currentScene.reset(new AnimationsSample());
        }
        else if (sample == "input")
        {
            currentScene.reset(new InputSample());
        }
        else if (sample == "sound")
        {
            currentScene.reset(new SoundSample());
        }
        else if (sample == "perspective")
        {
            currentScene.reset(new PerspectiveSample());
        }
    }

    if (!currentScene)
    {
        currentScene.reset(new MainMenu());
    }

    engine->getSceneManager()->setScene(std::move(currentScene));
}
<|endoftext|>


<commit_before>#include "El.hpp"
using namespace El;

int main( int argc, char* argv[] )
{
    Initialize( argc, argv );

    const Int m = Input("--m","matrix height",100);
    const Int n = Input("--n","matrix width",100);

    DistMatrix<double> A;
    Uniform( A, m, n );
    Display( A, "A" );

    Finalize();
    return 0;
}
<commit_msg>Updated test file<commit_after>#include "El.hpp"
using namespace El;

int main( int argc, char* argv[] )
{
    Initialize( argc, argv );

    const Int m = Input("--m","matrix height",100);
    const Int n = Input("--n","matrix width",20);

    DistMatrix<double> A;
    Uniform( A, m, n );

    DistMatrix<Int,VR,STAR> p;
    DistMatrix<double,STAR,VR> Z;
    QRCtrl<double> ctrl;
    ctrl.boundRank = true;
    ctrl.maxRank = 20;
    ID( A, p, Z, ctrl );
    if( mpi::WorldRank() == 0 )
        std::cout << Z.Height() << ", " << Z.Width() << std::endl;

    Finalize();
    return 0;
}
<|endoftext|>


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

#include "PEyeLog.h"
#include <cassert>
#include <cerrno>
#include <sstream>
#include <cctype>
#include <iostream>

using namespace std;

/* reading of binary gaze entries */

int readBinaryGaze(ifstream& stream, PEyeLogEntry** out, entrytype et) {
    double time;
    float x, y, pupil;

    assert(et == LGAZE || et == RGAZE);
    assert(*out == nullptr);

    if (!stream.read(reinterpret_cast<char*>(&time), sizeof(time)))
        return errno;
    if (!stream.read(reinterpret_cast<char*>(&x), sizeof(x)))
        return errno;
    if (!stream.read(reinterpret_cast<char*>(&y), sizeof(y)))
        return errno;
    if (!stream.read(reinterpret_cast<char*>(&pupil), sizeof(pupil)))
        return errno;

    *out = new PGazeEntry(et, time, x, y, pupil);
    return 0;
}

int readBinaryFix(ifstream& stream, PEyeLogEntry** out, entrytype et) {
    double time;
    double duration;
    float x, y;

    assert(et == LFIX || et == RFIX);
    assert(*out == NULL);

    if (!stream.read( (char*)&time      , sizeof(time)))
        return errno;
    if (!stream.read( (char*)&duration  , sizeof(duration)))
        return errno;
    if (!stream.read( (char*)&x         , sizeof(x)))
        return errno;
    if (!stream.read( (char*)&y         , sizeof(y)))
        return errno;

    *out = new PFixationEntry(et, time, duration, x, y);

    return 0;
}

int readBinaryMessage(ifstream& stream, PEyeLogEntry** out) {
    double time;
    uint32_t size;
    string msg;

    assert(*out == nullptr);

    if (!stream.read( (char*)&time  , sizeof(time)))
        return errno;
    if (!stream.read( (char*)&size  , sizeof(size)))
        return errno;
    msg.resize(size);
    if (!stream.read( (char*) msg.data(), size))
        return errno;

    *out = new PMessageEntry(time, msg);

    return 0;
}

int readBinarySac(ifstream& stream, PEyeLogEntry** out, entrytype et) {
    double time;
    double duration;
    float x1, y1, x2, y2;

    assert(et == LSAC || et == RSAC);

    if (!stream.read( (char*)&time      , sizeof(time)))
        return errno;
    if (!stream.read( (char*)&duration  , sizeof(duration)))
        return errno;
    if (!stream.read( (char*)&x1        , sizeof(x1)))
        return errno;
    if (!stream.read( (char*)&y1        , sizeof(y1)))
        return errno;
    if (!stream.read( (char*)&x2        , sizeof(x2)))
        return errno;
    if (!stream.read( (char*)&y2        , sizeof(y2)))
        return errno;

    *out = new PSaccadeEntry(et, time, duration, x1, y1, x2, y2);

    return 0;
}

PEyeLog::PEyeLog()
    : m_filename(),
      m_isopen(false)
{
    this->clear();
}

PEyeLog::~PEyeLog()
{
    clear();
}

int PEyeLog::open(const string& fname)
{
    m_filename = fname;
    m_file.open(fname.c_str(), fstream::binary|fstream::out);
    if (!m_file.is_open())
        return errno;
    return 0;
}

void PEyeLog::close()
{
    m_file.close();
    m_filename = "";
}

void PEyeLog::clear()
{
    for (unsigned i = 0; i < m_entries.size(); i++) {
        delete m_entries[i];
    }
    m_entries.clear();
}

void PEyeLog::reserve(unsigned size)
{
    if (size > m_entries.size())
        m_entries.reserve(size);
}

void PEyeLog::addEntry(PEyeLogEntry* p)
{
    m_entries.push_back(p);
}

int PEyeLog::read(const string& file, bool clear_content) {
    if (clear_content)
        clear();

    return readLog(this, file);
}

int PEyeLog::write(eyelog_format f) const
{
    int ret = 0;
    for (const auto& entry : m_entries) {
        ret = entry->writeBinary(m_file);
        if (ret)
            return ret;
    }
    return ret;
}

bool PEyeLog::isOpen() const
{
    return m_file.is_open();
}

const char* PEyeLog::getFilename()const
{
    return m_filename.c_str();
}

const std::vector<PEyeLogEntry*>& PEyeLog::getEntries()const
{
    return m_entries;
}

/* *******
 * Implementation of functions that load a PEyeLog from disk.
 */

/**
 * returns the contents of a file in a string
 */
string readStreamAsString(ifstream& s)
{
    string ret;
    assert(s.tellg() == ifstream::pos_type(0));
    s.seekg(0, s.end);
    streampos size = s.tellg();
    s.seekg(0);
    ret.resize(string::size_type(size));
    s.read(&ret[0], ret.size());
    return ret;
}

/**
 * returns a vector of strings.
 */
vector<string> getLines(ifstream& stream)
{
    vector<string> output;
    string buffer;

    assert(stream.good());

    while (getline(stream, buffer,'\n'))
        output.push_back(buffer);
    return output;
}

bool is_a_digit(const string& token)
{
    for (int c: token) {
        if (c < '0' || c > '9')
            return false;
    }
    return true;
}

int readAscManual(std::ifstream& stream, PEyeLog* plog)
{
    vector<string> lines = getLines(stream);
    bool isleft = false;

    // loops over all lines ignoring those values it doesn't understand
    for (const auto& line : lines) {
        istringstream stream(line);
        string token;

        stream >> token;

        if (is_a_digit(token)) { // either bi or monocular sample
            float x1, y1, p1=0, x2, y2, p2=0;
            double time = atof(token.c_str());
            string leftover;
            std::getline(stream, leftover);
            int matched = sscanf(leftover.c_str(),
                    "%f%f%f%f%f%f",
                    &x1, &y1, &p1, &x2, &y2, &p2
                    );
            if (matched >= 3 && matched < 6) { // monocular sample
                plog->addEntry(

                        new PGazeEntry( isleft ? LGAZE : RGAZE,
                                       time,
                                       x1,
                                       y1,
                                       p1
                                       )
                        );
            }
            else if (matched == 6) { // binocular sample
                plog->addEntry(
                        new PGazeEntry( LGAZE,
                                       time,
                                       x1,
                                       y1,
                                       p1
                                       )
                        );

                plog->addEntry(
                        new PGazeEntry( RGAZE,
                                       time,
                                       x2,
                                       y2,
                                       p2
                                       )
                        );
            }
        }
        else if (token == "EFIX") {
            string c;
			double tstart, tend, dur;
		    float x, y;
            if (stream >> c >> tstart >> tend >> dur >> x >> y) {
                plog->addEntry(
                        new PFixationEntry(c == "L" ? LFIX : RFIX,
                                          tstart,
                                          dur,
                                          x,
                                          y
                                          )
                        );
            }
        }
        else if (token == "MSG") {
            double time;
            string msg;
            string leftover;
            if (! (stream >> time) )
                continue;
            std::getline(stream, leftover);

            // remove leading whitespace
            string::iterator it;
            for (it = leftover.begin(); it < leftover.end(); it++)
                if (! std::isspace(*it))
                    break;
            msg = string(it, leftover.end());

            while(msg.size() > 0 && isspace(msg[msg.size()-1]) )//rm trailing whitespace
                msg.resize(msg.size()-1);

            plog->addEntry(new PMessageEntry(time, msg));
        }
        else if (token == "SAMPLES") {
            string gaze, leftorright;
            if (stream >> gaze >> leftorright) {
                if (gaze != "GAZE")
                    continue;
                isleft = leftorright == "RIGHT" ? true : false;
            }
        }
    }
    return 0;
}

int readCsvFormat(std::ifstream& stream, PEyeLog* plog)
{
    int result = 0;
    bool noerror = true;
    while (stream && noerror) {
        double time, dur;
        float x1, y1, x2, y2, p;
        string msg;
        unsigned type;
        entrytype e;

        if(stream >> type)
            ;
        else if (stream.eof())
            break;
        else {
            return 1;
        }
        switch (e = entrytype(type)) {
            case LGAZE:
            case RGAZE:
                if (stream >> time >> x1 >> y1 >> p)
                    plog->addEntry(new PGazeEntry(e, time, x1, y1, p));
                else {
                    noerror = false;
                    return 1;
                }
                break;
            case LFIX:
            case RFIX:
                if (stream >> time >> dur >> x1 >> y1)
                    plog->addEntry(
                            new PFixationEntry(e, time, dur, x1, y1)
                            );
                else {
                    noerror = false;
                    return 1;
                }
                break;
            case STIMULUS:
                assert(1==0); // not implemented yet.
            case MESSAGE:
                if (stream >> time) {
                    char c;
                    // remove leading whitespace.
                    while (stream >> c) {
                        if (!std::isspace(c)) {
                            stream.unget();
                            break;
                        }
                    }
                    std::getline(stream, msg, '\n');
                    plog->addEntry(
                            new PMessageEntry(time, msg)
                            );
                }
                else {
                    noerror = false;
                    return 1;
                }
                break;
            case LSAC:
            case RSAC:
                if (stream >> time >> dur >> x1 >> y1 >> x2 >> y2)
                    plog->addEntry(
                            new PSaccadeEntry(e, time, dur, x1, y1, x2, y2)
                            );
                else {
                    noerror = false;
                    return 1;
                }
                break;
            default:
                result = 1;
                noerror = false;
        };
    }
    return result;
}

int readBinary(std::ifstream& stream, PEyeLog* plog)
{
    int result = 0;
    assert(stream.is_open());

    while (stream) {
        uint16_t e;
        entrytype et;

        stream.read((char*)&e, sizeof(e));
        if (stream.eof())
            break;

        et = entrytype(e);
        PEyeLogEntry* p = nullptr;
        switch(et) {
            case LGAZE:
            case RGAZE:
                result = readBinaryGaze(stream, &p, et);
                break;
            case LFIX:
            case RFIX:
                 result = readBinaryFix(stream, &p, et);
                break;
            case MESSAGE:
                 result = readBinaryMessage(stream, &p);
                break;
            case LSAC:
            case RSAC:
                 result = readBinarySac(stream, &p, et);
                break;
            default:
                return -1;
        }

        if (result){
            plog->clear();
            return result;
        }

        if (p)
            plog->addEntry(p);
    }
    return result;
}

/**
 * writes a binary logfile.
 */
int writeBinary(std::ofstream& stream, const PEyeLog& l)
{
    int result = 0;

    auto& entries = l.getEntries();
    for (auto& e: entries) {
        e->writeBinary(stream);
        if (!stream.good()) {
            result = errno;
            break;
        }
    }
    return result;
}

int readLog(PEyeLog* out, const string& filename) {
    ifstream stream;
    int result;
    stream.open(filename.c_str(), ios::in | ios::binary);

    if ( !stream.is_open() )
        return errno;

    // First we try to read as binary
    result = ::readBinary(stream, out);

    /*Clear file status try read in our CsvFormat*/
    if (result != 0) {
        stream.seekg(0);
        stream.clear();
        assert(stream.good());
        result = readCsvFormat(stream, out);
    }

    /*Clear file status try read in Eyeling EDF format*/
    if (result != 0) {
        stream.seekg(0);
        stream.clear();
        assert(stream.good());
        result = readAscManual(stream, out);
    }

    return result;
}
<commit_msg>added support to save the file in csv format.<commit_after>/*
 * PEyeLog.cpp
 *
 * This file is part of libeye and responsible for logging experiments
 *
 * Copyright (C) 2016  Maarten Duijndam
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "PEyeLog.h"
#include <cassert>
#include <cerrno>
#include <sstream>
#include <cctype>
#include <iostream>

using namespace std;

/* reading of binary gaze entries */

int readBinaryGaze(ifstream& stream, PEyeLogEntry** out, entrytype et) {
    double time;
    float x, y, pupil;

    assert(et == LGAZE || et == RGAZE);
    assert(*out == nullptr);

    if (!stream.read(reinterpret_cast<char*>(&time), sizeof(time)))
        return errno;
    if (!stream.read(reinterpret_cast<char*>(&x), sizeof(x)))
        return errno;
    if (!stream.read(reinterpret_cast<char*>(&y), sizeof(y)))
        return errno;
    if (!stream.read(reinterpret_cast<char*>(&pupil), sizeof(pupil)))
        return errno;

    *out = new PGazeEntry(et, time, x, y, pupil);
    return 0;
}

int readBinaryFix(ifstream& stream, PEyeLogEntry** out, entrytype et) {
    double time;
    double duration;
    float x, y;

    assert(et == LFIX || et == RFIX);
    assert(*out == NULL);

    if (!stream.read( (char*)&time      , sizeof(time)))
        return errno;
    if (!stream.read( (char*)&duration  , sizeof(duration)))
        return errno;
    if (!stream.read( (char*)&x         , sizeof(x)))
        return errno;
    if (!stream.read( (char*)&y         , sizeof(y)))
        return errno;

    *out = new PFixationEntry(et, time, duration, x, y);

    return 0;
}

int readBinaryMessage(ifstream& stream, PEyeLogEntry** out) {
    double time;
    uint32_t size;
    string msg;

    assert(*out == nullptr);

    if (!stream.read( (char*)&time  , sizeof(time)))
        return errno;
    if (!stream.read( (char*)&size  , sizeof(size)))
        return errno;
    msg.resize(size);
    if (!stream.read( (char*) msg.data(), size))
        return errno;

    *out = new PMessageEntry(time, msg);

    return 0;
}

int readBinarySac(ifstream& stream, PEyeLogEntry** out, entrytype et) {
    double time;
    double duration;
    float x1, y1, x2, y2;

    assert(et == LSAC || et == RSAC);

    if (!stream.read( (char*)&time      , sizeof(time)))
        return errno;
    if (!stream.read( (char*)&duration  , sizeof(duration)))
        return errno;
    if (!stream.read( (char*)&x1        , sizeof(x1)))
        return errno;
    if (!stream.read( (char*)&y1        , sizeof(y1)))
        return errno;
    if (!stream.read( (char*)&x2        , sizeof(x2)))
        return errno;
    if (!stream.read( (char*)&y2        , sizeof(y2)))
        return errno;

    *out = new PSaccadeEntry(et, time, duration, x1, y1, x2, y2);

    return 0;
}

PEyeLog::PEyeLog()
    : m_filename(),
      m_isopen(false)
{
    this->clear();
}

PEyeLog::~PEyeLog()
{
    clear();
}

int PEyeLog::open(const string& fname)
{
    m_filename = fname;
    m_file.open(fname.c_str(), fstream::binary|fstream::out);
    if (!m_file.is_open())
        return errno;
    return 0;
}

void PEyeLog::close()
{
    m_file.close();
    m_filename = "";
}

void PEyeLog::clear()
{
    for (unsigned i = 0; i < m_entries.size(); i++) {
        delete m_entries[i];
    }
    m_entries.clear();
}

void PEyeLog::reserve(unsigned size)
{
    if (size > m_entries.size())
        m_entries.reserve(size);
}

void PEyeLog::addEntry(PEyeLogEntry* p)
{
    m_entries.push_back(p);
}

int PEyeLog::read(const string& file, bool clear_content) {
    if (clear_content)
        clear();

    return readLog(this, file);
}

int PEyeLog::write(eyelog_format f) const
{
    int ret = 0;
    if (f == FORMAT_BINARY) {
        for (const auto& entry : m_entries) {
            ret = entry->writeBinary(m_file);
            if (ret)
                return ret;
        }
    } else {
        for (unsigned i = 0; i < m_entries.size(); ++i) {
            std::string line;
            if (i == m_entries.size() -1)
                line = m_entries[i]->toString() + '\n';
            else
                line = m_entries[i]->toString();

            if (m_file << line) {
                return errno;
            }
        }
    }
    return ret;
}

bool PEyeLog::isOpen() const
{
    return m_file.is_open();
}

const char* PEyeLog::getFilename()const
{
    return m_filename.c_str();
}

const std::vector<PEyeLogEntry*>& PEyeLog::getEntries()const
{
    return m_entries;
}

/* *******
 * Implementation of functions that load a PEyeLog from disk.
 */

/**
 * returns the contents of a file in a string
 */
string readStreamAsString(ifstream& s)
{
    string ret;
    assert(s.tellg() == ifstream::pos_type(0));
    s.seekg(0, s.end);
    streampos size = s.tellg();
    s.seekg(0);
    ret.resize(string::size_type(size));
    s.read(&ret[0], ret.size());
    return ret;
}

/**
 * returns a vector of strings.
 */
vector<string> getLines(ifstream& stream)
{
    vector<string> output;
    string buffer;

    assert(stream.good());

    while (getline(stream, buffer,'\n'))
        output.push_back(buffer);
    return output;
}

bool is_a_digit(const string& token)
{
    for (int c: token) {
        if (c < '0' || c > '9')
            return false;
    }
    return true;
}

int readAscManual(std::ifstream& stream, PEyeLog* plog)
{
    vector<string> lines = getLines(stream);
    bool isleft = false;

    // loops over all lines ignoring those values it doesn't understand
    for (const auto& line : lines) {
        istringstream stream(line);
        string token;

        stream >> token;

        if (is_a_digit(token)) { // either bi or monocular sample
            float x1, y1, p1=0, x2, y2, p2=0;
            double time = atof(token.c_str());
            string leftover;
            std::getline(stream, leftover);
            int matched = sscanf(leftover.c_str(),
                    "%f%f%f%f%f%f",
                    &x1, &y1, &p1, &x2, &y2, &p2
                    );
            if (matched >= 3 && matched < 6) { // monocular sample
                plog->addEntry(

                        new PGazeEntry( isleft ? LGAZE : RGAZE,
                                       time,
                                       x1,
                                       y1,
                                       p1
                                       )
                        );
            }
            else if (matched == 6) { // binocular sample
                plog->addEntry(
                        new PGazeEntry( LGAZE,
                                       time,
                                       x1,
                                       y1,
                                       p1
                                       )
                        );

                plog->addEntry(
                        new PGazeEntry( RGAZE,
                                       time,
                                       x2,
                                       y2,
                                       p2
                                       )
                        );
            }
        }
        else if (token == "EFIX") {
            string c;
			double tstart, tend, dur;
		    float x, y;
            if (stream >> c >> tstart >> tend >> dur >> x >> y) {
                plog->addEntry(
                        new PFixationEntry(c == "L" ? LFIX : RFIX,
                                          tstart,
                                          dur,
                                          x,
                                          y
                                          )
                        );
            }
        }
        else if (token == "MSG") {
            double time;
            string msg;
            string leftover;
            if (! (stream >> time) )
                continue;
            std::getline(stream, leftover);

            // remove leading whitespace
            string::iterator it;
            for (it = leftover.begin(); it < leftover.end(); it++)
                if (! std::isspace(*it))
                    break;
            msg = string(it, leftover.end());

            while(msg.size() > 0 && isspace(msg[msg.size()-1]) )//rm trailing whitespace
                msg.resize(msg.size()-1);

            plog->addEntry(new PMessageEntry(time, msg));
        }
        else if (token == "SAMPLES") {
            string gaze, leftorright;
            if (stream >> gaze >> leftorright) {
                if (gaze != "GAZE")
                    continue;
                isleft = leftorright == "RIGHT" ? true : false;
            }
        }
    }
    return 0;
}

int readCsvFormat(std::ifstream& stream, PEyeLog* plog)
{
    int result = 0;
    bool noerror = true;
    while (stream && noerror) {
        double time, dur;
        float x1, y1, x2, y2, p;
        string msg;
        unsigned type;
        entrytype e;

        if(stream >> type)
            ;
        else if (stream.eof())
            break;
        else {
            return 1;
        }
        switch (e = entrytype(type)) {
            case LGAZE:
            case RGAZE:
                if (stream >> time >> x1 >> y1 >> p)
                    plog->addEntry(new PGazeEntry(e, time, x1, y1, p));
                else {
                    noerror = false;
                    return 1;
                }
                break;
            case LFIX:
            case RFIX:
                if (stream >> time >> dur >> x1 >> y1)
                    plog->addEntry(
                            new PFixationEntry(e, time, dur, x1, y1)
                            );
                else {
                    noerror = false;
                    return 1;
                }
                break;
            case STIMULUS:
                assert(1==0); // not implemented yet.
            case MESSAGE:
                if (stream >> time) {
                    char c;
                    // remove leading whitespace.
                    while (stream >> c) {
                        if (!std::isspace(c)) {
                            stream.unget();
                            break;
                        }
                    }
                    std::getline(stream, msg, '\n');
                    plog->addEntry(
                            new PMessageEntry(time, msg)
                            );
                }
                else {
                    noerror = false;
                    return 1;
                }
                break;
            case LSAC:
            case RSAC:
                if (stream >> time >> dur >> x1 >> y1 >> x2 >> y2)
                    plog->addEntry(
                            new PSaccadeEntry(e, time, dur, x1, y1, x2, y2)
                            );
                else {
                    noerror = false;
                    return 1;
                }
                break;
            default:
                result = 1;
                noerror = false;
        };
    }
    return result;
}

int readBinary(std::ifstream& stream, PEyeLog* plog)
{
    int result = 0;
    assert(stream.is_open());

    while (stream) {
        uint16_t e;
        entrytype et;

        stream.read((char*)&e, sizeof(e));
        if (stream.eof())
            break;

        et = entrytype(e);
        PEyeLogEntry* p = nullptr;
        switch(et) {
            case LGAZE:
            case RGAZE:
                result = readBinaryGaze(stream, &p, et);
                break;
            case LFIX:
            case RFIX:
                 result = readBinaryFix(stream, &p, et);
                break;
            case MESSAGE:
                 result = readBinaryMessage(stream, &p);
                break;
            case LSAC:
            case RSAC:
                 result = readBinarySac(stream, &p, et);
                break;
            default:
                return -1;
        }

        if (result){
            plog->clear();
            return result;
        }

        if (p)
            plog->addEntry(p);
    }
    return result;
}

/**
 * writes a binary logfile.
 */
int writeBinary(std::ofstream& stream, const PEyeLog& l)
{
    int result = 0;

    auto& entries = l.getEntries();
    for (auto& e: entries) {
        e->writeBinary(stream);
        if (!stream.good()) {
            result = errno;
            break;
        }
    }
    return result;
}

int readLog(PEyeLog* out, const string& filename) {
    ifstream stream;
    int result;
    stream.open(filename.c_str(), ios::in | ios::binary);

    if ( !stream.is_open() )
        return errno;

    // First we try to read as binary
    result = ::readBinary(stream, out);

    /*Clear file status try read in our CsvFormat*/
    if (result != 0) {
        stream.seekg(0);
        stream.clear();
        assert(stream.good());
        result = readCsvFormat(stream, out);
    }

    /*Clear file status try read in Eyeling EDF format*/
    if (result != 0) {
        stream.seekg(0);
        stream.clear();
        assert(stream.good());
        result = readAscManual(stream, out);
    }

    return result;
}
<|endoftext|>