<commit_before>#include <algorithm>

#include "EntityAnimationData.h"

#include "components/debug/Debug.h"

EntityAnimationData::Keyframe::Keyframe(double width, double height, int textureID)
{
	DebugAssert(width >= 0.0);
	DebugAssert(height >= 0.0);
	DebugAssert(textureID >= 0);

	this->width = width;
	this->height = height;
	this->textureID = textureID;
}

double EntityAnimationData::Keyframe::getWidth() const
{
	return this->width;
}

double EntityAnimationData::Keyframe::getHeight() const
{
	return this->height;
}

int EntityAnimationData::Keyframe::getTextureID() const
{
	return this->textureID;
}

EntityAnimationData::State::State(StateType type, double secondsPerFrame, bool loop)
{
	DebugAssert(secondsPerFrame > 0.0);

	this->type = type;
	this->secondsPerFrame = secondsPerFrame;
	this->loop = loop;
}

EntityAnimationData::StateType EntityAnimationData::State::getType() const
{
	return this->type;
}

bool EntityAnimationData::State::getLoop() const
{
	return this->loop;
}

double EntityAnimationData::State::getSecondsPerFrame() const
{
	return this->secondsPerFrame;
}

BufferView<const EntityAnimationData::Keyframe> EntityAnimationData::State::getKeyframes() const
{
	return BufferView(this->keyframes.data(), static_cast<int>(this->keyframes.size()));
}

void EntityAnimationData::State::addKeyframe(Keyframe &&keyframe)
{
	this->keyframes.push_back(std::move(keyframe));
}

void EntityAnimationData::State::clearKeyframes()
{
	this->keyframes.clear();
}

EntityAnimationData::Instance::Instance(const EntityAnimationData *animationData)
{
	this->animationData = animationData;
	this->stateType = static_cast<StateType>(-1);
	this->percentDone = 0.0;
}

const EntityAnimationData::State &EntityAnimationData::Instance::getState() const
{
	const State *state = this->animationData->findState(this->stateType);
	DebugAssertMsg(state != nullptr, "Couldn't find state \"" +
		std::to_string(static_cast<int>(this->stateType)) + "\".");
	return *state;
}

int EntityAnimationData::Instance::getKeyframeIndex() const
{
	const State &state = this->getState();
	const BufferView<const Keyframe> keyframes = state.getKeyframes();
	const int keyframeCount = keyframes.getCount();

	// Can't have an animation state with no keyframes.
	DebugAssert(keyframeCount > 0);

	const double realIndex = this->percentDone * static_cast<double>(keyframeCount);
	const int index = std::clamp(static_cast<int>(realIndex), 0, keyframeCount - 1);
	return index;
}

void EntityAnimationData::Instance::setStateType(StateType stateType)
{
	this->stateType = stateType;
}

void EntityAnimationData::Instance::resetTime()
{
	this->percentDone = 0.0;
}

void EntityAnimationData::Instance::tick(double dt)
{
	const State &state = this->getState();
	const BufferView<const Keyframe> keyframes = state.getKeyframes();
	const int keyframeCount = keyframes.getCount();
	const double secondsPerFrame = state.getSecondsPerFrame();

	const double targetSeconds = keyframeCount * secondsPerFrame;
	const double currentSeconds = (this->percentDone * targetSeconds) + dt;
	this->percentDone = std::clamp(currentSeconds / targetSeconds, 0.0, 1.0);
}

const EntityAnimationData::State *EntityAnimationData::findState(StateType stateType) const
{
	const auto iter = std::find_if(this->states.begin(), this->states.end(),
		[stateType](const EntityAnimationData::State &state)
	{
		return state.getType() == stateType;
	});

	return (iter != this->states.end()) ? &(*iter) : nullptr;
}

void EntityAnimationData::addState(State &&state)
{
	// Can't have two states of the same type.
	DebugAssert(this->findState(state.getType()) == nullptr);

	this->states.push_back(std::move(state));
}

void EntityAnimationData::removeState(StateType stateType)
{
	const State *state = this->findState(stateType);

	if (state != nullptr)
	{
		const State *firstState = this->states.data();
		const int index = static_cast<int>(std::distance(firstState, state));
		this->states.erase(this->states.begin() + index);
	}
}

void EntityAnimationData::clear()
{
	this->states.clear();
}
<commit_msg>Reset entity animation time when changing states.<commit_after>#include <algorithm>

#include "EntityAnimationData.h"

#include "components/debug/Debug.h"

EntityAnimationData::Keyframe::Keyframe(double width, double height, int textureID)
{
	DebugAssert(width >= 0.0);
	DebugAssert(height >= 0.0);
	DebugAssert(textureID >= 0);

	this->width = width;
	this->height = height;
	this->textureID = textureID;
}

double EntityAnimationData::Keyframe::getWidth() const
{
	return this->width;
}

double EntityAnimationData::Keyframe::getHeight() const
{
	return this->height;
}

int EntityAnimationData::Keyframe::getTextureID() const
{
	return this->textureID;
}

EntityAnimationData::State::State(StateType type, double secondsPerFrame, bool loop)
{
	DebugAssert(secondsPerFrame > 0.0);

	this->type = type;
	this->secondsPerFrame = secondsPerFrame;
	this->loop = loop;
}

EntityAnimationData::StateType EntityAnimationData::State::getType() const
{
	return this->type;
}

bool EntityAnimationData::State::getLoop() const
{
	return this->loop;
}

double EntityAnimationData::State::getSecondsPerFrame() const
{
	return this->secondsPerFrame;
}

BufferView<const EntityAnimationData::Keyframe> EntityAnimationData::State::getKeyframes() const
{
	return BufferView(this->keyframes.data(), static_cast<int>(this->keyframes.size()));
}

void EntityAnimationData::State::addKeyframe(Keyframe &&keyframe)
{
	this->keyframes.push_back(std::move(keyframe));
}

void EntityAnimationData::State::clearKeyframes()
{
	this->keyframes.clear();
}

EntityAnimationData::Instance::Instance(const EntityAnimationData *animationData)
{
	this->animationData = animationData;
	this->stateType = static_cast<StateType>(-1);
	this->percentDone = 0.0;
}

const EntityAnimationData::State &EntityAnimationData::Instance::getState() const
{
	const State *state = this->animationData->findState(this->stateType);
	DebugAssertMsg(state != nullptr, "Couldn't find state \"" +
		std::to_string(static_cast<int>(this->stateType)) + "\".");
	return *state;
}

int EntityAnimationData::Instance::getKeyframeIndex() const
{
	const State &state = this->getState();
	const BufferView<const Keyframe> keyframes = state.getKeyframes();
	const int keyframeCount = keyframes.getCount();

	// Can't have an animation state with no keyframes.
	DebugAssert(keyframeCount > 0);

	const double realIndex = this->percentDone * static_cast<double>(keyframeCount);
	const int index = std::clamp(static_cast<int>(realIndex), 0, keyframeCount - 1);
	return index;
}

void EntityAnimationData::Instance::setStateType(StateType stateType)
{
	this->stateType = stateType;
	this->resetTime();
}

void EntityAnimationData::Instance::resetTime()
{
	this->percentDone = 0.0;
}

void EntityAnimationData::Instance::tick(double dt)
{
	const State &state = this->getState();
	const BufferView<const Keyframe> keyframes = state.getKeyframes();
	const int keyframeCount = keyframes.getCount();
	const double secondsPerFrame = state.getSecondsPerFrame();

	const double targetSeconds = keyframeCount * secondsPerFrame;
	const double currentSeconds = (this->percentDone * targetSeconds) + dt;
	this->percentDone = std::clamp(currentSeconds / targetSeconds, 0.0, 1.0);
}

const EntityAnimationData::State *EntityAnimationData::findState(StateType stateType) const
{
	const auto iter = std::find_if(this->states.begin(), this->states.end(),
		[stateType](const EntityAnimationData::State &state)
	{
		return state.getType() == stateType;
	});

	return (iter != this->states.end()) ? &(*iter) : nullptr;
}

void EntityAnimationData::addState(State &&state)
{
	// Can't have two states of the same type.
	DebugAssert(this->findState(state.getType()) == nullptr);

	this->states.push_back(std::move(state));
}

void EntityAnimationData::removeState(StateType stateType)
{
	const State *state = this->findState(stateType);

	if (state != nullptr)
	{
		const State *firstState = this->states.data();
		const int index = static_cast<int>(std::distance(firstState, state));
		this->states.erase(this->states.begin() + index);
	}
}

void EntityAnimationData::clear()
{
	this->states.clear();
}
<|endoftext|>


<commit_before>/*************************************************************************/
/* spdlog - an extremely fast and easy to use c++11 logging library.     */
/* Copyright (c) 2014 Gabi Melman.                                       */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

//
// spdlog usage example
//
#include <iostream>
#include "spdlog/spdlog.h"

int main(int, char* [])
{
    namespace spd = spdlog;
    try
    {
        // Set log level to all loggers to debug and above
        spd::set_level(spd::level::debug);

        // Create console, multithreaded logger
        auto console = spd::stdout_logger_mt("console");
        console->info("Welcome to spdlog!") ;
        console->info("An info message example {}..", 1);
        console->info() << "Streams are supported too  " << 1;

        console->info("Easy padding in numbers like {:08d}", 12);
        console->info("Support for int: {0:d};  hex: {0:x};  oct: {0:o}; bin: {0:b}", 42);
        console->info("Support for floats {:03.2f}", 1.23456);
        console->info("Positional args are {1} {0}..", "too", "supported");

        console->info("{:<30}", "left aligned");
        console->info("{:>30}", "right aligned");
        console->info("{:^30}", "centered");

        // Create a file rotating logger with 5mb size max and 3 rotated files
        auto file_logger = spd::rotating_logger_mt("file_logger", "logs/mylogfile", 1048576 * 5, 3);
        file_logger->set_level(spd::level::info);
        for(int i = 0; i < 10; ++i)
            file_logger->info("{} * {} equals {:>10}", i, i, i*i);

        // Customize msg format for all messages
        spd::set_pattern("*** [%H:%M:%S %z] [thread %t] %v ***");
        file_logger->info("This is another message with custom format");

        spd::get("console")->info("loggers can be retrieved from a global registry using the spdlog::get(logger_name) function");

        SPDLOG_TRACE(console, "Enabled only #ifdef SPDLOG_TRACE_ON..{} ,{}", 1, 3.23);
        SPDLOG_DEBUG(console, "Enabled only #ifdef SPDLOG_DEBUG_ON.. {} ,{}", 1, 3.23);

        //
        // Asynchronous logging is very fast..
        // Just call spdlog::set_async_mode(q_size) and all created loggers from now on will be asynchronous..
        //
        size_t q_size = 1048576; //queue size must be power of 2
        spdlog::set_async_mode(q_size);
        auto async_file= spd::daily_logger_st("async_file_logger", "logs/async_log.txt");
        async_file->info() << "This is async log.." << "Should be very fast!";

        // syslog example. linux only..
#ifdef __linux__
        std::string ident = "spdlog-example";
        auto syslog_logger = spd::syslog_logger("syslog", ident, LOG_PID);
        syslog_logger->warn("This is warning that will end up in syslog. This is Linux only!");
#endif

    }
    catch (const spd::spdlog_ex& ex)
    {
        std::cout << "Log failed: " << ex.what() << std::endl;
    }
}
<commit_msg>Update example.cpp<commit_after>/*************************************************************************/
/* spdlog - an extremely fast and easy to use c++11 logging library.     */
/* Copyright (c) 2014 Gabi Melman.                                       */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

//
// spdlog usage example
//
#include <iostream>
#include "spdlog/spdlog.h"

int main(int, char* [])
{
    namespace spd = spdlog;
    try
    {
        // Set log level to all loggers to debug and above
        spd::set_level(spd::level::debug);

        // Create console, multithreaded logger
        auto console = spd::stdout_logger_mt("console");
        console->info("Welcome to spdlog!") ;
        console->info("An info message example {}..", 1);
        console->info() << "Streams are supported too  " << 1;

        console->info("Easy padding in numbers like {:08d}", 12);
        console->info("Support for int: {0:d};  hex: {0:x};  oct: {0:o}; bin: {0:b}", 42);
        console->info("Support for floats {:03.2f}", 1.23456);
        console->info("Positional args are {1} {0}..", "too", "supported");

        console->info("{:<30}", "left aligned");
        console->info("{:>30}", "right aligned");
        console->info("{:^30}", "centered");

        // Create a file rotating logger with 5mb size max and 3 rotated files
        auto file_logger = spd::rotating_logger_mt("file_logger", "logs/mylogfile", 1048576 * 5, 3);
        file_logger->set_level(spd::level::info);
        for(int i = 0; i < 10; ++i)
            file_logger->info("{} * {} equals {:>10}", i, i, i*i);

        // Customize msg format for all messages
        spd::set_pattern("*** [%H:%M:%S %z] [thread %t] %v ***");
        file_logger->info("This is another message with custom format");

        spd::get("console")->info("loggers can be retrieved from a global registry using the spdlog::get(logger_name) function");

        SPDLOG_TRACE(console, "Enabled only #ifdef SPDLOG_TRACE_ON..{} ,{}", 1, 3.23);
        SPDLOG_DEBUG(console, "Enabled only #ifdef SPDLOG_DEBUG_ON.. {} ,{}", 1, 3.23);

        // Asynchronous logging is very fast..
        // Just call spdlog::set_async_mode(q_size) and all created loggers from now on will be asynchronous..
        size_t q_size = 1048576; //queue size must be power of 2
        spdlog::set_async_mode(q_size);
        auto async_file= spd::daily_logger_st("async_file_logger", "logs/async_log.txt");
        async_file->info() << "This is async log.." << "Should be very fast!";

        // syslog example. linux only..
#ifdef __linux__
        std::string ident = "spdlog-example";
        auto syslog_logger = spd::syslog_logger("syslog", ident, LOG_PID);
        syslog_logger->warn("This is warning that will end up in syslog. This is Linux only!");
#endif

    }
    catch (const spd::spdlog_ex& ex)
    {
        std::cout << "Log failed: " << ex.what() << std::endl;
    }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: accfrmobjslist.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 02:50:01 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/
#ifndef _ACCFRMOBJSLIST_HXX
#define _ACCFRMOBJSLIST_HXX

#ifndef _ACCFRMOBJ_HXX
#include <accfrmobj.hxx>
#endif

class SwFrmOrObjSList;

class SwFrmOrObjSList_const_iterator
{
    friend class SwFrmOrObjSList;
    const SwFrmOrObjSList& rList;   // The frame we are iterating over
    SwFrmOrObj aCurr;               // The current object
    sal_uInt16 nNextObj;            // The index of the current sdr object

    inline SwFrmOrObjSList_const_iterator( const SwFrmOrObjSList& rLst );
    SwFrmOrObjSList_const_iterator( const SwFrmOrObjSList& rLst, sal_Bool );

//  SwFrmOrObjSList_const_iterator& begin();
    SwFrmOrObjSList_const_iterator& next();
    SwFrmOrObjSList_const_iterator& next_visible();

public:

    inline SwFrmOrObjSList_const_iterator(
            const SwFrmOrObjSList_const_iterator& rIter );
    inline sal_Bool operator==(
            const SwFrmOrObjSList_const_iterator& r ) const;
    inline sal_Bool operator!=(
            const SwFrmOrObjSList_const_iterator& r ) const;
    inline SwFrmOrObjSList_const_iterator& operator++();
    inline const SwFrmOrObj& operator*() const;
};

// An iterator to iterate over a frame's child in any order
class SwFrmOrObjSList
{
    friend class SwFrmOrObjSList_const_iterator;

    SwRect aVisArea;
    const SwFrm *pFrm;  // The frame we are iterating over
    sal_Bool bVisibleOnly;

public:

    typedef SwFrmOrObjSList_const_iterator const_iterator;

    inline SwFrmOrObjSList( const SwFrm *pF );
    inline SwFrmOrObjSList( const SwRect& rVisArea, const SwFrm *pF );

    inline const_iterator begin() const;
    inline const_iterator end() const;
};

inline SwFrmOrObjSList_const_iterator::SwFrmOrObjSList_const_iterator(
        const SwFrmOrObjSList& rLst ) :
    rList( rLst ), nNextObj( 0 )
{
}

inline SwFrmOrObjSList_const_iterator::SwFrmOrObjSList_const_iterator(
        const SwFrmOrObjSList_const_iterator& rIter ) :
    rList( rIter.rList ),
    aCurr( rIter.aCurr ),
    nNextObj( rIter.nNextObj )
{
}

inline sal_Bool SwFrmOrObjSList_const_iterator::operator==(
    const SwFrmOrObjSList_const_iterator& r ) const
{
    return aCurr == r.aCurr;
}

inline sal_Bool SwFrmOrObjSList_const_iterator::operator!=(
    const SwFrmOrObjSList_const_iterator& r ) const
{
    return !(aCurr == r.aCurr);
}

inline SwFrmOrObjSList_const_iterator& SwFrmOrObjSList_const_iterator::operator++()
{
    return rList.bVisibleOnly ? next_visible() : next();
}

inline const SwFrmOrObj& SwFrmOrObjSList_const_iterator::operator*() const
{
    return aCurr;
}

inline SwFrmOrObjSList::SwFrmOrObjSList( const SwFrm *pF ) :
    pFrm( pF ),
    bVisibleOnly( sal_False )
{
}

inline SwFrmOrObjSList::SwFrmOrObjSList( const SwRect& rVisArea,
                                             const SwFrm *pF ) :
    aVisArea( rVisArea ),
    pFrm( pF )
{
    SwFrmOrObj aFrm( pFrm );
    bVisibleOnly = aFrm.IsVisibleChildrenOnly();
}

inline SwFrmOrObjSList_const_iterator SwFrmOrObjSList::begin() const
{
//  SwFrmOrObjSList_const_iterator aIter2( *this );
//  aIter2.begin();
//  return aIter2;
    return SwFrmOrObjSList_const_iterator( *this, sal_True );
}

inline SwFrmOrObjSList_const_iterator SwFrmOrObjSList::end() const
{
    return SwFrmOrObjSList_const_iterator( *this );
}

#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.4.1202); FILE MERGED 2008/04/01 12:53:45 thb 1.4.1202.2: #i85898# Stripping all external header guards 2008/03/31 16:53:38 rt 1.4.1202.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: accfrmobjslist.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _ACCFRMOBJSLIST_HXX
#define _ACCFRMOBJSLIST_HXX

#include <accfrmobj.hxx>

class SwFrmOrObjSList;

class SwFrmOrObjSList_const_iterator
{
    friend class SwFrmOrObjSList;
    const SwFrmOrObjSList& rList;   // The frame we are iterating over
    SwFrmOrObj aCurr;               // The current object
    sal_uInt16 nNextObj;            // The index of the current sdr object

    inline SwFrmOrObjSList_const_iterator( const SwFrmOrObjSList& rLst );
    SwFrmOrObjSList_const_iterator( const SwFrmOrObjSList& rLst, sal_Bool );

//  SwFrmOrObjSList_const_iterator& begin();
    SwFrmOrObjSList_const_iterator& next();
    SwFrmOrObjSList_const_iterator& next_visible();

public:

    inline SwFrmOrObjSList_const_iterator(
            const SwFrmOrObjSList_const_iterator& rIter );
    inline sal_Bool operator==(
            const SwFrmOrObjSList_const_iterator& r ) const;
    inline sal_Bool operator!=(
            const SwFrmOrObjSList_const_iterator& r ) const;
    inline SwFrmOrObjSList_const_iterator& operator++();
    inline const SwFrmOrObj& operator*() const;
};

// An iterator to iterate over a frame's child in any order
class SwFrmOrObjSList
{
    friend class SwFrmOrObjSList_const_iterator;

    SwRect aVisArea;
    const SwFrm *pFrm;  // The frame we are iterating over
    sal_Bool bVisibleOnly;

public:

    typedef SwFrmOrObjSList_const_iterator const_iterator;

    inline SwFrmOrObjSList( const SwFrm *pF );
    inline SwFrmOrObjSList( const SwRect& rVisArea, const SwFrm *pF );

    inline const_iterator begin() const;
    inline const_iterator end() const;
};

inline SwFrmOrObjSList_const_iterator::SwFrmOrObjSList_const_iterator(
        const SwFrmOrObjSList& rLst ) :
    rList( rLst ), nNextObj( 0 )
{
}

inline SwFrmOrObjSList_const_iterator::SwFrmOrObjSList_const_iterator(
        const SwFrmOrObjSList_const_iterator& rIter ) :
    rList( rIter.rList ),
    aCurr( rIter.aCurr ),
    nNextObj( rIter.nNextObj )
{
}

inline sal_Bool SwFrmOrObjSList_const_iterator::operator==(
    const SwFrmOrObjSList_const_iterator& r ) const
{
    return aCurr == r.aCurr;
}

inline sal_Bool SwFrmOrObjSList_const_iterator::operator!=(
    const SwFrmOrObjSList_const_iterator& r ) const
{
    return !(aCurr == r.aCurr);
}

inline SwFrmOrObjSList_const_iterator& SwFrmOrObjSList_const_iterator::operator++()
{
    return rList.bVisibleOnly ? next_visible() : next();
}

inline const SwFrmOrObj& SwFrmOrObjSList_const_iterator::operator*() const
{
    return aCurr;
}

inline SwFrmOrObjSList::SwFrmOrObjSList( const SwFrm *pF ) :
    pFrm( pF ),
    bVisibleOnly( sal_False )
{
}

inline SwFrmOrObjSList::SwFrmOrObjSList( const SwRect& rVisArea,
                                             const SwFrm *pF ) :
    aVisArea( rVisArea ),
    pFrm( pF )
{
    SwFrmOrObj aFrm( pFrm );
    bVisibleOnly = aFrm.IsVisibleChildrenOnly();
}

inline SwFrmOrObjSList_const_iterator SwFrmOrObjSList::begin() const
{
//  SwFrmOrObjSList_const_iterator aIter2( *this );
//  aIter2.begin();
//  return aIter2;
    return SwFrmOrObjSList_const_iterator( *this, sal_True );
}

inline SwFrmOrObjSList_const_iterator SwFrmOrObjSList::end() const
{
    return SwFrmOrObjSList_const_iterator( *this );
}

#endif
<|endoftext|>


<commit_before>#include <stdio.h>
#include <string>
#include "zmq.hpp"
#include "canna_core.h"
#include "canna_random.h"

int main(int argc, char** argv)
{
    if (argc < 2) {
        printf("usage: peering me {you} ...\n");
        return 0;
    }

    char *self = argv[1];
    printf("I: preparing broker at %s ... \n", self);
    CaRandom random;
    random.SetSeed(canna_gettime());

    zmq::context_t context(1);

    zmq::socket_t statebe(context, ZMQ_PUB);
    char statebe_ipc[64];
    memset(statebe_ipc, 0, sizeof(statebe_ipc));
    sprintf(statebe_ipc, "ipc://%s-state.ipc", self);
    statebe.bind(statebe_ipc);

    zmq::socket_t statefe(context, ZMQ_SUB);
    const char *filter = "";
    statefe.setsockopt(ZMQ_SUBSCRIBE, filter, strlen(filter));
    for (int index = 2; index < argc; index++) {
        char *peer = argv[index];
        char statefe_ipc[64];
        memset(statefe_ipc, 0, sizeof(statefe_ipc));
        sprintf(statebe_ipc, "ipc://%s-state.ipc", peer);
        printf("I: connecting to state backend at '%s'\n", statefe_ipc);
        statefe.connect(statefe_ipc);
    }

    while (true) {
        zmq::pollitem_t items[] = {(void *)statefe, 0, ZMQ_POLLIN, 0};
        zmq::poll(items, 1, 1000);

        if (items[0].revents & ZMQ_POLLIN) {
            std::string peer_name = canna_recv(statefe);
            std::string available = canna_recv(statefe);
            printf("%s - %s work free \n", peer_name.c_str(), available.c_str());
        } else {
            canna_send(statebe, self);
            canna_send(statebe, "ping");
        }
    }

    return 0;
}
<commit_msg>bug fixed<commit_after>#include <stdio.h>
#include <string>
#include "zmq.hpp"
#include "canna_core.h"
#include "canna_random.h"

int main(int argc, char** argv)
{
    if (argc < 2) {
        printf("usage: peering me {you} ...\n");
        return 0;
    }

    char *self = argv[1];
    printf("I: preparing broker at %s ... \n", self);
    CaRandom random;
    random.SetSeed(canna_gettime());

    zmq::context_t context(1);

    zmq::socket_t statebe(context, ZMQ_PUB);
    char statebe_ipc[64];
    memset(statebe_ipc, 0, sizeof(statebe_ipc));
    sprintf(statebe_ipc, "ipc://%s-state.ipc", self);
    statebe.bind(statebe_ipc);

    zmq::socket_t statefe(context, ZMQ_SUB);
    const char *filter = "";
    statefe.setsockopt(ZMQ_SUBSCRIBE, filter, strlen(filter));
    for (int index = 2; index < argc; index++) {
        char *peer = argv[index];
        char statefe_ipc[64];
        memset(statefe_ipc, 0, sizeof(statefe_ipc));
        sprintf(statefe_ipc, "ipc://%s-state.ipc", peer);
        printf("I: connecting to state backend at '%s'\n", statefe_ipc);
        statefe.connect(statefe_ipc);
    }

    while (true) {
        zmq::pollitem_t items[] = {(void *)statefe, 0, ZMQ_POLLIN, 0};
        zmq::poll(items, 1, 1000);

        if (items[0].revents & ZMQ_POLLIN) {
            std::string peer_name = canna_recv(statefe);
            std::string available = canna_recv(statefe);
            printf("%s - %s work free \n", peer_name.c_str(), available.c_str());
        } else {
            canna_send(statebe, self);
            canna_send(statebe, "ping");
        }
    }

    return 0;
}
<|endoftext|>


<commit_before>//--------------------------------------------------------------------------
// $Id$
//--------------------------------------------------------------------------
//
//--------------------------------------------------------------------------
// Copyright (C) 2004  Andrew Ross <andrewr@coriolis.greenend.org.uk>
// Copyright (C) 2004  Alan W. Irwin
//
// This file is part of PLplot.
//
// PLplot is free software; you can redistribute it and/or modify
// it under the terms of the GNU Library General Public License as published by
// the Free Software Foundation; version 2 of the License.
//
// PLplot 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 Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public License
// along with PLplot; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
//--------------------------------------------------------------------------
//
//--------------------------------------------------------------------------
// Implementation of PLplot example 15 in C++.
//--------------------------------------------------------------------------

#include "plc++demos.h"

#ifdef PL_USE_NAMESPACE
using namespace std;
#endif

class x15 {
public:
    x15( int, const char ** );
    void plot1( PLFLT * *, PLFLT, PLFLT );
    void plot2( PLFLT * *, PLFLT, PLFLT );
    void plot3();

private:
    // Class data
    plstream           *pls;

    const static int   XPTS;
    const static int   YPTS;
    // calculated constants and array that depends on them
    const static PLFLT XSPA;
    const static PLFLT YSPA;
    const static PLFLT tr[];
};

const int   x15::  XPTS = 35;
const int   x15::  YPTS = 46;
// calculated constants and array that depends on them
const PLFLT x15::XSPA = 2. / ( XPTS - 1 );
const PLFLT x15::YSPA = 2. / ( YPTS - 1 );
const PLFLT x15::tr[] = { XSPA, 0.0, -1.0, 0.0, YSPA, -1.0 };

x15::x15( int argc, const char ** argv )
{
    int   i, j;

    PLFLT xx;
    PLFLT yy;
    PLFLT x;
    PLFLT y;
    PLFLT **z;
    PLFLT zmin, zmax;

    // plplot initialization

    pls = new plstream();

    // Parse and process command line arguments.
    pls->parseopts( &argc, argv, PL_PARSE_FULL );

    // Initialize PLplot.
    pls->init();
    // no need to fiddle with color maps since example uses default cmap0
    // and the cmap1 fiddling that x15c.c does is completely irrelevant
    // (although interesting).

    pls->Alloc2dGrid( &z, XPTS, YPTS );

    for ( i = 0; i < XPTS; i++ )
    {
        xx = (PLFLT) ( i - ( XPTS / 2 ) ) / (PLFLT) ( XPTS / 2 );
        for ( j = 0; j < YPTS; j++ )
        {
            yy      = ( (PLFLT) ( j - ( YPTS / 2 ) ) / (PLFLT) ( YPTS / 2 ) ) - 1.;
            z[i][j] = xx * xx - yy * yy + ( xx - yy ) / ( xx * xx + yy * yy + 0.1 );
            x       = tr[0] * i + tr[1] * j + tr[2];
            y       = tr[3] * i + tr[4] * j + tr[5];
        }
    }

    pls->MinMax2dGrid( z, XPTS, YPTS, &zmax, &zmin );

    plot1( z, zmin, zmax );
    plot2( z, zmin, zmax );
    plot3();

    //pls->end();

    // Tidy up allocated grids
    pls->Free2dGrid( z, XPTS, YPTS );

    delete pls;
}

// Illustrates a single shaded region.

void x15::plot1( PLFLT **z, PLFLT zmin, PLFLT zmax )
{
    PLFLT shade_min, shade_max, sh_color;
    int   sh_cmap   = 0, sh_width;
    int   min_color = 0, min_width = 0, max_color = 0, max_width = 0;

    pls->adv( 0 );
    pls->vpor( 0.1, 0.9, 0.1, 0.9 );
    pls->wind( -1.0, 1.0, -1.0, 1.0 );

    // Plot using identity transform

    shade_min = zmin + ( zmax - zmin ) * 0.4;
    shade_max = zmin + ( zmax - zmin ) * 0.6;
    sh_color  = 7;
    sh_width  = 2;
    min_color = 9;
    max_color = 2;
    min_width = 2;
    max_width = 2;

    pls->psty( 8 );

    pls->shade( z, XPTS, YPTS, NULL, -1., 1., -1., 1.,
        shade_min, shade_max,
        sh_cmap, sh_color, sh_width,
        min_color, min_width, max_color, max_width,
        plstream::fill, true, NULL, NULL );

    pls->col0( 1 );
    pls->box( "bcnst", 0.0, 0, "bcnstv", 0.0, 0 );
    pls->col0( 2 );
    pls->lab( "distance", "altitude", "Bogon flux" );
}

// Illustrates multiple adjacent shaded regions, using different fill
// patterns for each region.

void x15::plot2( PLFLT **z, PLFLT zmin, PLFLT zmax )
{
    PLFLT        shade_min, shade_max, sh_color;
    int          sh_cmap   = 0, sh_width;
    int          min_color = 0, min_width = 0, max_color = 0, max_width = 0;
    int          i;
    static PLINT nlin[10]   = { 1, 1, 1, 1, 1, 2, 2, 2, 2, 2 };
    static PLINT inc[10][2] = { { 450,    0 }, { -450,    0 }, { 0,   0 }, { 900,   0 },
                                { 300,    0 }, {  450, -450 }, { 0, 900 }, {   0, 450 },
                                { 450, -450 }, {    0,  900 } };
    static PLINT del[10][2] = { { 2000, 2000 }, { 2000, 2000 }, { 2000, 2000 },
                                { 2000, 2000 }, { 2000, 2000 }, { 2000, 2000 },
                                { 2000, 2000 }, { 2000, 2000 }, { 4000, 4000 },
                                { 4000, 2000 } };
    sh_width = 2;

    pls->adv( 0 );
    pls->vpor( 0.1, 0.9, 0.1, 0.9 );
    pls->wind( -1.0, 1.0, -1.0, 1.0 );

    // Plot using identity transform

    for ( i = 0; i < 10; i++ )
    {
        shade_min = zmin + ( zmax - zmin ) * i / 10.0;
        shade_max = zmin + ( zmax - zmin ) * ( i + 1 ) / 10.0;
        sh_color  = i + 6;
        pls->pat( nlin[i], inc[i], del[i] );

        pls->shade( z, XPTS, YPTS, NULL, -1., 1., -1., 1.,
            shade_min, shade_max,
            sh_cmap, sh_color, sh_width,
            min_color, min_width, max_color, max_width,
            plstream::fill, true, NULL, NULL );
    }

    pls->col0( 1 );
    pls->box( "bcnst", 0.0, 0, "bcnstv", 0.0, 0 );
    pls->col0( 2 );
    pls->lab( "distance", "altitude", "Bogon flux" );
}

// Illustrates shaded regions in 3d, using a different fill pattern for
// each region.

void x15::plot3()
{
    static PLFLT xx[2][5] = { { -1.0, 1.0, 1.0, -1.0, -1.0 },
                              { -1.0, 1.0, 1.0, -1.0, -1.0 } };
    static PLFLT yy[2][5] = { {  1.0,  1.0, 0.0, 0.0,  1.0 },
                              { -1.0, -1.0, 0.0, 0.0, -1.0 } };
    static PLFLT zz[2][5] = { { 0.0, 0.0, 1.0, 1.0, 0.0 },
                              { 0.0, 0.0, 1.0, 1.0, 0.0 } };

    pls->adv( 0 );
    pls->vpor( 0.1, 0.9, 0.1, 0.9 );
    pls->wind( -1.0, 1.0, -1.0, 1.0 );
    pls->w3d( 1., 1., 1., -1.0, 1.0, -1.0, 1.0, 0.0, 1.5, 30, -40 );

// Plot using identity transform

    pls->col0( 1 );
    pls->box3( "bntu", "X", 0.0, 0, "bntu", "Y", 0.0, 0, "bcdfntu", "Z", 0.5, 0 );
    pls->col0( 2 );
    pls->lab( "", "", "3-d polygon filling" );

    pls->col0( 3 );
    pls->psty( 1 );
    pls->line3( 5, xx[0], yy[0], zz[0] );
    pls->fill3( 4, xx[0], yy[0], zz[0] );
    pls->psty( 2 );
    pls->line3( 5, xx[1], yy[1], zz[1] );
    pls->fill3( 4, xx[1], yy[1], zz[1] );
}

int main( int argc, const char ** argv )
{
    x15 *x = new x15( argc, argv );

    delete x;
}

//--------------------------------------------------------------------------
//                              End of x15.cc
//--------------------------------------------------------------------------
<commit_msg>Remove some excess crud from C++ example 15. This code was unused and I assume a result of cutting and pasting when the example was originally written.<commit_after>//--------------------------------------------------------------------------
// $Id$
//--------------------------------------------------------------------------
//
//--------------------------------------------------------------------------
// Copyright (C) 2004  Andrew Ross <andrewr@coriolis.greenend.org.uk>
// Copyright (C) 2004  Alan W. Irwin
//
// This file is part of PLplot.
//
// PLplot is free software; you can redistribute it and/or modify
// it under the terms of the GNU Library General Public License as published by
// the Free Software Foundation; version 2 of the License.
//
// PLplot 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 Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public License
// along with PLplot; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
//--------------------------------------------------------------------------
//
//--------------------------------------------------------------------------
// Implementation of PLplot example 15 in C++.
//--------------------------------------------------------------------------

#include "plc++demos.h"

#ifdef PL_USE_NAMESPACE
using namespace std;
#endif

class x15 {
public:
    x15( int, const char ** );
    void plot1( PLFLT * *, PLFLT, PLFLT );
    void plot2( PLFLT * *, PLFLT, PLFLT );
    void plot3();

private:
    // Class data
    plstream           *pls;

    const static int   XPTS;
    const static int   YPTS;
};

const int   x15::  XPTS = 35;
const int   x15::  YPTS = 46;

x15::x15( int argc, const char ** argv )
{
    int   i, j;

    PLFLT xx;
    PLFLT yy;
    PLFLT **z;
    PLFLT zmin, zmax;

    // plplot initialization

    pls = new plstream();

    // Parse and process command line arguments.
    pls->parseopts( &argc, argv, PL_PARSE_FULL );

    // Initialize PLplot.
    pls->init();
    // no need to fiddle with color maps since example uses default cmap0
    // and the cmap1 fiddling that x15c.c does is completely irrelevant
    // (although interesting).

    pls->Alloc2dGrid( &z, XPTS, YPTS );

    for ( i = 0; i < XPTS; i++ )
    {
        xx = (PLFLT) ( i - ( XPTS / 2 ) ) / (PLFLT) ( XPTS / 2 );
        for ( j = 0; j < YPTS; j++ )
        {
            yy      = ( (PLFLT) ( j - ( YPTS / 2 ) ) / (PLFLT) ( YPTS / 2 ) ) - 1.;
            z[i][j] = xx * xx - yy * yy + ( xx - yy ) / ( xx * xx + yy * yy + 0.1 );
        }
    }

    pls->MinMax2dGrid( z, XPTS, YPTS, &zmax, &zmin );

    plot1( z, zmin, zmax );
    plot2( z, zmin, zmax );
    plot3();

    //pls->end();

    // Tidy up allocated grids
    pls->Free2dGrid( z, XPTS, YPTS );

    delete pls;
}

// Illustrates a single shaded region.

void x15::plot1( PLFLT **z, PLFLT zmin, PLFLT zmax )
{
    PLFLT shade_min, shade_max, sh_color;
    int   sh_cmap   = 0, sh_width;
    int   min_color = 0, min_width = 0, max_color = 0, max_width = 0;

    pls->adv( 0 );
    pls->vpor( 0.1, 0.9, 0.1, 0.9 );
    pls->wind( -1.0, 1.0, -1.0, 1.0 );

    // Plot using identity transform

    shade_min = zmin + ( zmax - zmin ) * 0.4;
    shade_max = zmin + ( zmax - zmin ) * 0.6;
    sh_color  = 7;
    sh_width  = 2;
    min_color = 9;
    max_color = 2;
    min_width = 2;
    max_width = 2;

    pls->psty( 8 );

    pls->shade( z, XPTS, YPTS, NULL, -1., 1., -1., 1.,
        shade_min, shade_max,
        sh_cmap, sh_color, sh_width,
        min_color, min_width, max_color, max_width,
        plstream::fill, true, NULL, NULL );

    pls->col0( 1 );
    pls->box( "bcnst", 0.0, 0, "bcnstv", 0.0, 0 );
    pls->col0( 2 );
    pls->lab( "distance", "altitude", "Bogon flux" );
}

// Illustrates multiple adjacent shaded regions, using different fill
// patterns for each region.

void x15::plot2( PLFLT **z, PLFLT zmin, PLFLT zmax )
{
    PLFLT        shade_min, shade_max, sh_color;
    int          sh_cmap   = 0, sh_width;
    int          min_color = 0, min_width = 0, max_color = 0, max_width = 0;
    int          i;
    static PLINT nlin[10]   = { 1, 1, 1, 1, 1, 2, 2, 2, 2, 2 };
    static PLINT inc[10][2] = { { 450,    0 }, { -450,    0 }, { 0,   0 }, { 900,   0 },
                                { 300,    0 }, {  450, -450 }, { 0, 900 }, {   0, 450 },
                                { 450, -450 }, {    0,  900 } };
    static PLINT del[10][2] = { { 2000, 2000 }, { 2000, 2000 }, { 2000, 2000 },
                                { 2000, 2000 }, { 2000, 2000 }, { 2000, 2000 },
                                { 2000, 2000 }, { 2000, 2000 }, { 4000, 4000 },
                                { 4000, 2000 } };
    sh_width = 2;

    pls->adv( 0 );
    pls->vpor( 0.1, 0.9, 0.1, 0.9 );
    pls->wind( -1.0, 1.0, -1.0, 1.0 );

    // Plot using identity transform

    for ( i = 0; i < 10; i++ )
    {
        shade_min = zmin + ( zmax - zmin ) * i / 10.0;
        shade_max = zmin + ( zmax - zmin ) * ( i + 1 ) / 10.0;
        sh_color  = i + 6;
        pls->pat( nlin[i], inc[i], del[i] );

        pls->shade( z, XPTS, YPTS, NULL, -1., 1., -1., 1.,
            shade_min, shade_max,
            sh_cmap, sh_color, sh_width,
            min_color, min_width, max_color, max_width,
            plstream::fill, true, NULL, NULL );
    }

    pls->col0( 1 );
    pls->box( "bcnst", 0.0, 0, "bcnstv", 0.0, 0 );
    pls->col0( 2 );
    pls->lab( "distance", "altitude", "Bogon flux" );
}

// Illustrates shaded regions in 3d, using a different fill pattern for
// each region.

void x15::plot3()
{
    static PLFLT xx[2][5] = { { -1.0, 1.0, 1.0, -1.0, -1.0 },
                              { -1.0, 1.0, 1.0, -1.0, -1.0 } };
    static PLFLT yy[2][5] = { {  1.0,  1.0, 0.0, 0.0,  1.0 },
                              { -1.0, -1.0, 0.0, 0.0, -1.0 } };
    static PLFLT zz[2][5] = { { 0.0, 0.0, 1.0, 1.0, 0.0 },
                              { 0.0, 0.0, 1.0, 1.0, 0.0 } };

    pls->adv( 0 );
    pls->vpor( 0.1, 0.9, 0.1, 0.9 );
    pls->wind( -1.0, 1.0, -1.0, 1.0 );
    pls->w3d( 1., 1., 1., -1.0, 1.0, -1.0, 1.0, 0.0, 1.5, 30, -40 );

// Plot using identity transform

    pls->col0( 1 );
    pls->box3( "bntu", "X", 0.0, 0, "bntu", "Y", 0.0, 0, "bcdfntu", "Z", 0.5, 0 );
    pls->col0( 2 );
    pls->lab( "", "", "3-d polygon filling" );

    pls->col0( 3 );
    pls->psty( 1 );
    pls->line3( 5, xx[0], yy[0], zz[0] );
    pls->fill3( 4, xx[0], yy[0], zz[0] );
    pls->psty( 2 );
    pls->line3( 5, xx[1], yy[1], zz[1] );
    pls->fill3( 4, xx[1], yy[1], zz[1] );
}

int main( int argc, const char ** argv )
{
    x15 *x = new x15( argc, argv );

    delete x;
}

//--------------------------------------------------------------------------
//                              End of x15.cc
//--------------------------------------------------------------------------
<|endoftext|>


<commit_before>/// \file AddTaskEmcalJetCDFUE.C
/// \brief Adds a AliAnalysisTaskEmcalJetCDFUE analysis task and coresponding containers
///
/// Analysis of UE
///
/// \author Adrian SEVCENCO <Adrian.Sevcenco@cern.ch>, Institute of Space Science, Romania
/// \date Mar 19, 2015

/// Add a AliAnalysisTaskEmcalJetCDFUE task - detailed signature
/// \param const char *ntracks
/// \param const char *nclusters
/// \param const char *njets
/// \param const char *nrho
/// \param Double_t jetradius
/// \param Double_t jetptcut
/// \param Double_t jetareacut
/// \param const char *type ; either TPC, EMCAL or USER
/// \param Int_t leadhadtype ; 0 = charged, 1 = neutral, 2 = both
/// \param const char *taskname
/// \return AliAnalysisTaskEmcalJetCDFUE* task
AliAnalysisTaskEmcalJetCDFUE *AddTaskEmcalJetCDFUE (
  const char *ntracks            = "Tracks",
  const char *nclusters          = "CaloClusters",
  const char *njets              = "Jets",
  const char *nrho               = "",
  Double_t    jetradius          = 0.2,
  Double_t    jetptcut           = 1.,
  Double_t    jetareacut         = 0.001,
  const char *type               = "TPC",      // EMCAL, TPC
  Int_t       leadhadtype        = 0,          // AliJetContainer :: Int_t fLeadingHadronType;  0 = charged, 1 = neutral, 2 = both
  const char *taskname           = "JetCDF"
//   Int_t       nCentBins          = 1,
)
  {
  // Get the pointer to the existing analysis manager via the static access method.
  //==============================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();

  if ( !mgr ) { ::Error ( "AddTaskEmcalJetCDF", "No analysis manager to connect to." );  return NULL; }

  // Check the analysis type using the event handlers connected to the analysis manager.
  //==============================================================================
  if ( !mgr->GetInputEventHandler() ) { ::Error ( "AddTaskEmcalJetCDF", "This task requires an input event handler" ); return NULL; }

  //-------------------------------------------------------
  // Init the task and do settings
  //-------------------------------------------------------

  TString name ( taskname ); TString tracks ( ntracks );
  TString clusters ( nclusters ); TString jets ( njets );  TString rho ( nrho );
  TString acctype = type;
  acctype.ToUpper();

  if ( jetptcut < 1. ) { jetptcut = 1.; }

  TString jetstr = "jpt";
  jetstr += ( ULong_t ) ( jetptcut * 1000 );

  if ( !jets.IsNull() )  { name += "_" + jets; }

  name += "_" + jetstr;

  if ( !rho.IsNull() )  { name += "_" + rho; }

  if ( acctype.CompareTo ( "TPC" )   ) { acctype = "TPC"; }
  if ( acctype.CompareTo ( "EMCAL" ) ) { acctype = "EMCAL"; }
  if ( acctype.CompareTo ( "KUSER" ) ) { acctype = "kUser"; }

  if ( !acctype.IsNull() ) { name += "_" + acctype; }

  AliAnalysisTaskEmcalJetCDFUE *jetTask = new AliAnalysisTaskEmcalJetCDFUE ( name );
  jetTask->SetCentRange ( 0., 100. );
  jetTask->SetNCentBins ( 1 );

  AliParticleContainer *trackCont  = jetTask->AddParticleContainer ( ntracks );
  trackCont->SetClassName ( "AliVTrack" );

  AliClusterContainer *clusterCont = jetTask->AddClusterContainer ( nclusters );
//     clusterCont->SetClassName("AliVCluster");

  AliJetContainer *jetCont = jetTask->AddJetContainer ( njets, acctype.Data(), jetradius );

  if ( jetCont )
      {
      jetCont->SetRhoName ( nrho );
      jetCont->ConnectParticleContainer ( trackCont );
      jetCont->ConnectClusterContainer ( clusterCont );
      jetCont->SetPercAreaCut ( jetareacut );
      jetCont->SetJetPtCut ( jetptcut );
      jetCont->SetLeadingHadronType ( leadhadtype ); // Int_t fLeadingHadronType;  0 = charged, 1 = neutral, 2 = both
      jetCont->SetZLeadingCut ( 0., 1. );
      }

  //-------------------------------------------------------
  // Final settings, pass to manager and set the containers
  //-------------------------------------------------------
  mgr->AddTask ( jetTask );

  TString contname = name + "_histos";
  TString outfile = AliAnalysisManager::GetCommonFileName();

  // Create containers for input/output
  AliAnalysisDataContainer *cinput1  = mgr->GetCommonInputContainer()  ;
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer ( contname.Data(), TList::Class(), AliAnalysisManager::kOutputContainer, outfile.Data() );

  mgr->ConnectInput ( jetTask, 0,  cinput1 );
  mgr->ConnectOutput ( jetTask, 1, coutput1 );

  return jetTask;
  }

/// Add a AliAnalysisTaskEmcalJetCDFUE task - info from AliEmcalJetTask*
/// \param AliEmcalJetTask *jetFinderTask
/// \param Double_t jetptcut
/// \param Double_t jetareacut
/// \param const char *type ; either TPC, EMCAL or USER
/// \param Int_t leadhadtype ; 0 = charged, 1 = neutral, 2 = both
/// \param const char *nrho
/// \param const char *taskname
/// \return AliAnalysisTaskEmcalJetCDFUE* task
AliAnalysisTaskEmcalJetCDFUE *AddTaskEmcalJetCDFUE ( AliEmcalJetTask *jetFinderTask,
    Double_t     jetptcut     = 1.,
    Double_t     jetareacut   = 0.001,
    const char  *type         = "TPC",     // EMCAL, TPC
    Int_t        leadhadtype  = 0,         // AliJetContainer :: Int_t fLeadingHadronType;  0 = charged, 1 = neutral, 2 = both
    const char  *nrho         = "",
    const char  *taskname     = "JetCDF" )
  {
  if ( !jetFinderTask->InheritsFrom ( AliEmcalJetTask::Class() ) )
    { AliError("AddTaskEmcalJetSample :: task is not/ does not inherits from AliEmcalJetTask"); }

  const char *ntracks            = jetFinderTask->GetTracksName();
  const char *nclusters          = jetFinderTask->GetClusName();
  const char *njets              = jetFinderTask->GetJetsName();
  Double_t    jetradius          = jetFinderTask->GetRadius();

  return AddTaskEmcalJetCDFUE ( ntracks , nclusters, njets, nrho, jetradius, jetptcut, jetareacut, type, leadhadtype, taskname );
  }

/// Add a AliAnalysisTaskEmcalJetCDFUE task - info from char* taskname
/// \param const char* taskname ; to be retrieved from list of tasks
/// \param Double_t jetptcut
/// \param Double_t jetareacut
/// \param const char *type ; either TPC, EMCAL or USER
/// \param Int_t leadhadtype ; 0 = charged, 1 = neutral, 2 = both
/// \param const char *nrho
/// \param const char *taskname
/// \return AliAnalysisTaskEmcalJetCDFUE* task
AliAnalysisTaskEmcalJetCDFUE *AddTaskEmcalJetCDFUE ( const char* taskname,
    Double_t     jetptcut     = 1.,
    Double_t     jetareacut   = 0.001,
    const char  *type         = "TPC",     // EMCAL, TPC
    Int_t        leadhadtype  = 0,         // AliJetContainer :: Int_t fLeadingHadronType;  0 = charged, 1 = neutral, 2 = both
    const char  *nrho         = "",
    const char  *taskname     = "JetCDF" )
  {
  AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) { ::Error("AddTaskEmcalJetCDF", "No analysis manager to connect to."); }

  AliEmcalJetTask* jf = dynamic_cast<AliEmcalJetTask*>(mgr->GetTask(taskname));
  if (!jf) { AliError("AddTaskEmcalJetCDF :: task is not EmcalJetTask");}

  const char *ntracks            = jf->GetTracksName();
  const char *nclusters          = jf->GetClusName();
  const char *njets              = jf->GetJetsName();
  Double_t    jetradius          = jf->GetRadius();

  return AddTaskEmcalJetCDFUE ( ntracks , nclusters, njets, nrho, jetradius, jetptcut, jetareacut, type, leadhadtype, taskname );
  }

// kate: indent-mode none; indent-width 2; replace-tabs on;
<commit_msg>AddTaskEmcalJetCDFUE.C :: correction for acceptance selection<commit_after>/// \file AddTaskEmcalJetCDFUE.C
/// \brief Adds a AliAnalysisTaskEmcalJetCDFUE analysis task and coresponding containers
///
/// Analysis of UE
///
/// \author Adrian SEVCENCO <Adrian.Sevcenco@cern.ch>, Institute of Space Science, Romania
/// \date Mar 19, 2015

/// Add a AliAnalysisTaskEmcalJetCDFUE task - detailed signature
/// \param const char *ntracks
/// \param const char *nclusters
/// \param const char *njets
/// \param const char *nrho
/// \param Double_t jetradius
/// \param Double_t jetptcut
/// \param Double_t jetareacut
/// \param const char *type ; either TPC, EMCAL or USER
/// \param Int_t leadhadtype ; 0 = charged, 1 = neutral, 2 = both
/// \param const char *taskname
/// \return AliAnalysisTaskEmcalJetCDFUE* task
AliAnalysisTaskEmcalJetCDFUE *AddTaskEmcalJetCDFUE (
  const char *ntracks            = "Tracks",
  const char *nclusters          = "CaloClusters",
  const char *njets              = "Jets",
  const char *nrho               = "",
  Double_t    jetradius          = 0.2,
  Double_t    jetptcut           = 1.,
  Double_t    jetareacut         = 0.001,
  const char *type               = "TPC",      // EMCAL, TPC
  Int_t       leadhadtype        = 0,          // AliJetContainer :: Int_t fLeadingHadronType;  0 = charged, 1 = neutral, 2 = both
  const char *taskname           = "JetCDF"
//   Int_t       nCentBins          = 1,
)
  {
  // Get the pointer to the existing analysis manager via the static access method.
  //==============================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();

  if ( !mgr ) { ::Error ( "AddTaskEmcalJetCDF", "No analysis manager to connect to." );  return NULL; }

  // Check the analysis type using the event handlers connected to the analysis manager.
  //==============================================================================
  if ( !mgr->GetInputEventHandler() ) { ::Error ( "AddTaskEmcalJetCDF", "This task requires an input event handler" ); return NULL; }

  //-------------------------------------------------------
  // Init the task and do settings
  //-------------------------------------------------------

  TString name ( taskname ); TString tracks ( ntracks );
  TString clusters ( nclusters ); TString jets ( njets );  TString rho ( nrho );

  TString acctype = type; acctype.ToUpper();
  if ( acctype.Contains ("TPC") )   { acctype = "TPC"; }
  if ( acctype.Contains ("EMCAL") ) { acctype = "EMCAL"; }
  if ( acctype.Contains ("USER") )  { acctype = "USER"; }

  if ( jetptcut < 1. ) { jetptcut = 1.; }

  TString jetstr = "jpt";
  jetstr += ( ULong_t ) ( jetptcut * 1000 );

  if ( !jets.IsNull() )    { name += "_" + jets + "_" + jetstr; }
  if ( !rho.IsNull() )     { name += "_" + rho; }
  if ( !acctype.IsNull() ) { name += "_" + acctype; }

  AliAnalysisTaskEmcalJetCDFUE *jetTask = new AliAnalysisTaskEmcalJetCDFUE ( name );
  jetTask->SetCentRange ( 0., 100. );
  jetTask->SetNCentBins ( 1 );

  AliParticleContainer *trackCont  = jetTask->AddParticleContainer ( ntracks );
  trackCont->SetClassName ( "AliVTrack" );

  AliClusterContainer *clusterCont = jetTask->AddClusterContainer ( nclusters );
//     clusterCont->SetClassName("AliVCluster");

  AliJetContainer *jetCont = jetTask->AddJetContainer ( njets, acctype, jetradius );

  if ( jetCont )
      {
      if ( !rho.IsNull() ) { jetCont->SetRhoName ( nrho ); }
      jetCont->ConnectParticleContainer ( trackCont );
      jetCont->ConnectClusterContainer ( clusterCont );
      jetCont->SetPercAreaCut ( jetareacut );
      jetCont->SetJetPtCut ( jetptcut );
      jetCont->SetLeadingHadronType ( leadhadtype ); // Int_t fLeadingHadronType;  0 = charged, 1 = neutral, 2 = both
      jetCont->SetZLeadingCut ( 0., 1. );
      }

  //-------------------------------------------------------
  // Final settings, pass to manager and set the containers
  //-------------------------------------------------------
  mgr->AddTask ( jetTask );

  TString contname = name + "_histos";
  TString outfile = AliAnalysisManager::GetCommonFileName();

  // Create containers for input/output
  AliAnalysisDataContainer *cinput1  = mgr->GetCommonInputContainer()  ;
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer ( contname.Data(), TList::Class(), AliAnalysisManager::kOutputContainer, outfile.Data() );

  mgr->ConnectInput ( jetTask, 0,  cinput1 );
  mgr->ConnectOutput ( jetTask, 1, coutput1 );

  return jetTask;
  }

/// Add a AliAnalysisTaskEmcalJetCDFUE task - info from AliEmcalJetTask*
/// \param AliEmcalJetTask *jetFinderTask
/// \param Double_t jetptcut
/// \param Double_t jetareacut
/// \param const char *type ; either TPC, EMCAL or USER
/// \param Int_t leadhadtype ; 0 = charged, 1 = neutral, 2 = both
/// \param const char *nrho
/// \param const char *taskname
/// \return AliAnalysisTaskEmcalJetCDFUE* task
AliAnalysisTaskEmcalJetCDFUE *AddTaskEmcalJetCDFUE ( AliEmcalJetTask *jetFinderTask,
    Double_t     jetptcut     = 1.,
    Double_t     jetareacut   = 0.001,
    const char  *type         = "TPC",     // EMCAL, TPC
    Int_t        leadhadtype  = 0,         // AliJetContainer :: Int_t fLeadingHadronType;  0 = charged, 1 = neutral, 2 = both
    const char  *nrho         = "",
    const char  *taskname     = "JetCDF" )
  {
  if ( !jetFinderTask->InheritsFrom ( AliEmcalJetTask::Class() ) )
    { AliError("AddTaskEmcalJetSample :: task is not/ does not inherits from AliEmcalJetTask"); }

  const char *ntracks            = jetFinderTask->GetTracksName();
  const char *nclusters          = jetFinderTask->GetClusName();
  const char *njets              = jetFinderTask->GetJetsName();
  Double_t    jetradius          = jetFinderTask->GetRadius();

  return AddTaskEmcalJetCDFUE ( ntracks , nclusters, njets, nrho, jetradius, jetptcut, jetareacut, type, leadhadtype, taskname );
  }

/// Add a AliAnalysisTaskEmcalJetCDFUE task - info from char* taskname
/// \param const char* taskname ; to be retrieved from list of tasks
/// \param Double_t jetptcut
/// \param Double_t jetareacut
/// \param const char *type ; either TPC, EMCAL or USER
/// \param Int_t leadhadtype ; 0 = charged, 1 = neutral, 2 = both
/// \param const char *nrho
/// \param const char *taskname
/// \return AliAnalysisTaskEmcalJetCDFUE* task
AliAnalysisTaskEmcalJetCDFUE *AddTaskEmcalJetCDFUE ( const char* taskname,
    Double_t     jetptcut     = 1.,
    Double_t     jetareacut   = 0.001,
    const char  *type         = "TPC",     // EMCAL, TPC
    Int_t        leadhadtype  = 0,         // AliJetContainer :: Int_t fLeadingHadronType;  0 = charged, 1 = neutral, 2 = both
    const char  *nrho         = "",
    const char  *taskname     = "JetCDF" )
  {
  AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) { ::Error("AddTaskEmcalJetCDF", "No analysis manager to connect to."); }

  AliEmcalJetTask* jf = dynamic_cast<AliEmcalJetTask*>(mgr->GetTask(taskname));
  if (!jf) { AliError("AddTaskEmcalJetCDF :: task is not EmcalJetTask");}

  const char *ntracks            = jf->GetTracksName();
  const char *nclusters          = jf->GetClusName();
  const char *njets              = jf->GetJetsName();
  Double_t    jetradius          = jf->GetRadius();

  return AddTaskEmcalJetCDFUE ( ntracks , nclusters, njets, nrho, jetradius, jetptcut, jetareacut, type, leadhadtype, taskname );
  }

// kate: indent-mode none; indent-width 2; replace-tabs on;
<|endoftext|>


<commit_before>#include <cilantro/point_cloud.hpp>
#include <cilantro/image_viewer.hpp>
#include <cilantro/visualizer.hpp>
#include <cilantro/common_renderables.hpp>
#include <cilantro/icp_common_instances.hpp>

void color_toggle_callback(cilantro::Visualizer &viz, cilantro::RenderingProperties &rp) {
    if (rp.pointColor == cilantro::RenderingProperties::noColor) {
        rp.setPointColor(0.8f, 0.8f, 0.8f);
    } else {
        rp.setPointColor(cilantro::RenderingProperties::noColor);
    }
    viz.setRenderingProperties("model", rp);
}

void capture_callback(bool &capture) {
    capture = true;
}

void clear_callback(cilantro::PointCloud3f &cloud) {
    cloud.clear();
}

int main(int argc, char ** argv) {
    // Intrinsics
    Eigen::Matrix3f K;
    K << 525, 0, 319.5, 0, 525, 239.5, 0, 0, 1;

//    std::string uri = "files://[/home/kzampog/Desktop/rgbd_sequences/dok_demo/rgb_*.png,/home/kzampog/Desktop/rgbd_sequences/dok_demo/depth_*.png]";
    std::string uri = "openni2:[img1=rgb,img2=depth_reg,coloursync=true,closerange=true,holefilter=true]//";

    std::unique_ptr<pangolin::VideoInterface> dok = pangolin::OpenVideo(uri);
    size_t w = 640, h = 480;
    unsigned char* img = new unsigned char[dok->SizeBytes()];

    pangolin::Image<unsigned char> rgb_img(img, w, h, 3*w*sizeof(unsigned char));
    pangolin::Image<unsigned short> depth_img((unsigned short *)(img+3*w*h), w, h, w*sizeof(unsigned short));

    cilantro::DepthValueConverter<unsigned short,float> dc(1000.0f);

    std::string win_name = "Fusion demo";
    pangolin::CreateWindowAndBind(win_name, 2*w, h);
    pangolin::Display("multi").SetBounds(0.0, 1.0, 0.0, 1.0).SetLayout(pangolin::LayoutEqual)
            .AddDisplay(pangolin::Display("disp1")).AddDisplay(pangolin::Display("disp2"));

    cilantro::Visualizer pcdv(win_name, "disp1");
    cilantro::ImageViewer rgbv(win_name, "disp2");

    cilantro::PointCloud3f model, frame;
    bool capture = false;
    pcdv.registerKeyboardCallback('a', std::bind(capture_callback, std::ref(capture)));
    pcdv.registerKeyboardCallback('d', std::bind(clear_callback, std::ref(model)));

    cilantro::RenderingProperties rp;
    pcdv.registerKeyboardCallback('c', std::bind(color_toggle_callback, std::ref(pcdv), std::ref(rp)));
    rp.setUseLighting(false);

    cilantro::RigidTransformation3f cam_pose(cilantro::RigidTransformation3f::Identity());

    float fusion_weight = 0.1f;
    float fusion_weight_compl = 1.0f - fusion_weight;
    float fusion_dist_thresh = 0.02f;

    std::cout << "Press 'a' to initialize model/fuse new view" << std::endl;
    std::cout << "Press 'd' to reinitialize process" << std::endl;
    std::cout << "Press 'c' to toggle model color" << std::endl;

    // Main loop
    while (!pangolin::ShouldQuit()) {
        dok->GrabNext(img, true);
        frame.fromRGBDImages(rgb_img.ptr, depth_img.ptr, dc, w, h, K, false, true);

        // Localize
        if (!model.isEmpty()) {
            cilantro::SimpleCombinedMetricRigidProjectiveICP3f icp(frame.points, frame.normals, model.points);
            icp.correspondenceSearchEngine().setMaxDistance(0.1f*0.1f);
            icp.setInitialTransformation(cam_pose.inverse()).setConvergenceTolerance(5e-4f);
            icp.setMaxNumberOfIterations(6).setMaxNumberOfOptimizationStepIterations(1);
            cam_pose = icp.estimateTransformation().getTransformation().inverse();
        }

        // Map
        if (capture) {
            capture = false;

            if (model.isEmpty()) {
                model.fromRGBDImages(rgb_img.ptr, depth_img.ptr, dc, w, h, K, false, true);
                cam_pose.setIdentity();
            } else {
                cilantro::PointCloud3f frame_t(frame.transformed(cam_pose));
                cilantro::PointCloud3f model_t(model.transformed(cam_pose.inverse()));

                pangolin::ManagedImage<size_t> model_index_map(w, h);
                cilantro::pointsToIndexMap<float>(model_t.points, K, model_index_map.ptr, w, h);
                pangolin::ManagedImage<size_t> frame_index_map(w, h);
                cilantro::pointsToIndexMap<float>(frame.points, K, frame_index_map.ptr, w, h);

                cilantro::PointCloud3f to_append;
                to_append.points.resize(Eigen::NoChange, w*h);
                to_append.normals.resize(Eigen::NoChange, w*h);
                to_append.colors.resize(Eigen::NoChange, w*h);

                size_t app_ind = 0;
                size_t empty = std::numeric_limits<std::size_t>::max();
#pragma omp parallel for
                for (size_t y = 0; y < frame_index_map.h; y++) {
                    for (size_t x = 0; x < frame_index_map.w; x++) {
                        if (frame_index_map(x,y) == empty) continue;
                        if (model_index_map(x,y) != empty) {
                            float view_depth = frame_t.points(2,frame_index_map(x,y));
                            float model_depth = model_t.points(2,model_index_map(x,y));
                            if (std::abs(model_depth - view_depth) < fusion_dist_thresh) {
#pragma omp critical
                                {
                                    model.points.col(model_index_map(x,y)) = fusion_weight_compl*model.points.col(model_index_map(x,y)) + fusion_weight*frame_t.points.col(frame_index_map(x,y));
                                    model.normals.col(model_index_map(x,y)) = (fusion_weight_compl*model.normals.col(model_index_map(x,y)) + fusion_weight*frame_t.normals.col(frame_index_map(x,y))).normalized();
                                    model.colors.col(model_index_map(x,y)) = fusion_weight_compl*model.colors.col(model_index_map(x,y)) + fusion_weight*frame_t.colors.col(frame_index_map(x,y));
                                };
                            }
                        } else {
#pragma omp critical
                            {
                                to_append.points.col(app_ind) = frame_t.points.col(frame_index_map(x,y));
                                to_append.normals.col(app_ind) = frame_t.normals.col(frame_index_map(x,y));
                                to_append.colors.col(app_ind) = frame_t.colors.col(frame_index_map(x,y));
                                app_ind++;
                            };
                        }
                    }
                }
                to_append.points.conservativeResize(Eigen::NoChange, app_ind);
                to_append.normals.conservativeResize(Eigen::NoChange, app_ind);
                to_append.colors.conservativeResize(Eigen::NoChange, app_ind);
                model.append(to_append);
            }
        }

        // Visualization
        rgbv.setImage(rgb_img.ptr, w, h, "RGB24");
        pcdv.addObject<cilantro::PointCloudRenderable>("model", model, rp);
        pcdv.addObject<cilantro::PointCloudRenderable>("frame", frame.transformed(cam_pose), cilantro::RenderingProperties().setOpacity(0.2f));
        pcdv.addObject<cilantro::CameraFrustumRenderable>("cam", w, h, K, cam_pose.matrix(), 0.2f, cilantro::RenderingProperties().setLineWidth(2.0f).setLineColor(1.0f,1.0f,0.0f));

        pcdv.clearRenderArea();
        rgbv.render();
        pcdv.render();
        pangolin::FinishFrame();

        // Keep model rendering properties on update
        rp = pcdv.getRenderingProperties("model");
    }

    if (argc > 1) model.toPLYFile(argv[1], true);

    delete[] img;

    return 0;
}
<commit_msg>Fusion example improvements<commit_after>#include <cilantro/point_cloud.hpp>
#include <cilantro/image_viewer.hpp>
#include <cilantro/visualizer.hpp>
#include <cilantro/common_renderables.hpp>
#include <cilantro/icp_common_instances.hpp>

void color_toggle_callback(cilantro::Visualizer &viz, cilantro::RenderingProperties &rp) {
    if (rp.pointColor == cilantro::RenderingProperties::noColor) {
        rp.setPointColor(0.8f, 0.8f, 0.8f);
    } else {
        rp.setPointColor(cilantro::RenderingProperties::noColor);
    }
    viz.setRenderingProperties("model", rp);
}

void capture_callback(bool &capture) {
    capture = true;
}

void clear_callback(cilantro::PointCloud3f &cloud) {
    cloud.clear();
}

int main(int argc, char ** argv) {
    // Intrinsics
    Eigen::Matrix3f K;
    K << 525, 0, 319.5, 0, 525, 239.5, 0, 0, 1;

//    std::string uri = "files://[/home/kzampog/Desktop/rgbd_sequences/dok_demo/rgb_*.png,/home/kzampog/Desktop/rgbd_sequences/dok_demo/depth_*.png]";
    std::string uri = "openni2:[img1=rgb,img2=depth_reg,coloursync=true,closerange=true,holefilter=true]//";

    std::unique_ptr<pangolin::VideoInterface> dok = pangolin::OpenVideo(uri);
    size_t w = 640, h = 480;
    unsigned char* img = new unsigned char[dok->SizeBytes()];

    pangolin::Image<unsigned char> rgb_img(img, w, h, 3*w*sizeof(unsigned char));
    pangolin::Image<unsigned short> depth_img((unsigned short *)(img+3*w*h), w, h, w*sizeof(unsigned short));

    cilantro::DepthValueConverter<unsigned short,float> dc(1000.0f);

    std::string win_name = "Fusion demo";
    pangolin::CreateWindowAndBind(win_name, 2*w, h);
    pangolin::Display("multi").SetBounds(0.0, 1.0, 0.0, 1.0).SetLayout(pangolin::LayoutEqual)
            .AddDisplay(pangolin::Display("disp1")).AddDisplay(pangolin::Display("disp2"));

    cilantro::Visualizer pcdv(win_name, "disp1");
    cilantro::ImageViewer rgbv(win_name, "disp2");

    cilantro::PointCloud3f model, frame;
    bool capture = false;
    pcdv.registerKeyboardCallback('a', std::bind(capture_callback, std::ref(capture)));
    pcdv.registerKeyboardCallback('d', std::bind(clear_callback, std::ref(model)));

    cilantro::RenderingProperties rp;
    pcdv.registerKeyboardCallback('c', std::bind(color_toggle_callback, std::ref(pcdv), std::ref(rp)));
    rp.setUseLighting(false);

    cilantro::RigidTransformation3f cam_pose(cilantro::RigidTransformation3f::Identity());

    float max_depth = 1.1f;
    float fusion_weight = 0.3f;
    float fusion_dist_thresh = 0.025f;
    float occlusion_thresh = 2.0f*fusion_dist_thresh;
    float factor = -0.5f/(100*100);

    std::cout << "Press 'a' to initialize model/fuse new view" << std::endl;
    std::cout << "Press 'd' to reinitialize process" << std::endl;
    std::cout << "Press 'c' to toggle model color" << std::endl;

    // Main loop
    while (!pangolin::ShouldQuit()) {
        dok->GrabNext(img, true);
        frame.fromRGBDImages(rgb_img.ptr, depth_img.ptr, dc, w, h, K, false, true);

        // Localize
        if (!model.isEmpty()) {
            cilantro::SimpleCombinedMetricRigidProjectiveICP3f icp(frame.points, frame.normals, model.points);
            icp.correspondenceSearchEngine().setMaxDistance(0.1f*0.1f);
            icp.setInitialTransformation(cam_pose.inverse()).setConvergenceTolerance(5e-4f);
            icp.setMaxNumberOfIterations(6).setMaxNumberOfOptimizationStepIterations(1);
            cam_pose = icp.estimateTransformation().getTransformation().inverse();
        }

        // Map
        if (capture) {
            capture = false;

            if (model.isEmpty()) {
                model.fromRGBDImages(rgb_img.ptr, depth_img.ptr, dc, w, h, K, false, true);
                std::vector<size_t> remove_ind;
                remove_ind.reserve(model.size());
                for (size_t i = 0; i < model.size(); i++) {
                    if (model.points(2,i) > max_depth) remove_ind.emplace_back(i);
                }
                model.remove(remove_ind);
                cam_pose.setIdentity();
            } else {
                cilantro::PointCloud3f frame_t(frame.transformed(cam_pose));
                cilantro::PointCloud3f model_t(model.transformed(cam_pose.inverse()));

                // Project cloud to index image maps
                pangolin::ManagedImage<size_t> model_index_map(w, h);
                cilantro::pointsToIndexMap<float>(model_t.points, K, model_index_map.ptr, w, h);
                pangolin::ManagedImage<size_t> frame_index_map(w, h);
                cilantro::pointsToIndexMap<float>(frame.points, K, frame_index_map.ptr, w, h);

                cilantro::PointCloud3f to_append;
                to_append.points.resize(Eigen::NoChange, w*h);
                to_append.normals.resize(Eigen::NoChange, w*h);
                to_append.colors.resize(Eigen::NoChange, w*h);

                size_t append_count = 0;
                std::vector<size_t> remove_ind;
                remove_ind.reserve(w*h);
                const size_t empty = std::numeric_limits<std::size_t>::max();
#pragma omp parallel for
                for (size_t y = 0; y < frame_index_map.h; y++) {
                    for (size_t x = 0; x < frame_index_map.w; x++) {
                        const size_t frame_pt_ind = frame_index_map(x,y);
                        const size_t model_pt_ind = model_index_map(x,y);

                        if (frame_pt_ind == empty) {
                            // Nothing to do
                            continue;
                        }

                        const float frame_depth = frame_t.points(2,frame_pt_ind);
                        const float model_depth = (model_pt_ind != empty) ? model_t.points(2,model_pt_ind) : 0.0f;

                        if ((model_pt_ind == empty || frame_depth < model_depth - occlusion_thresh) && frame.points(2,frame_pt_ind) < max_depth) {
                            // Augment model
#pragma omp critical
                            {
                                to_append.points.col(append_count) = frame_t.points.col(frame_pt_ind);
                                to_append.normals.col(append_count) = frame_t.normals.col(frame_pt_ind);
                                to_append.colors.col(append_count) = frame_t.colors.col(frame_pt_ind);
                                append_count++;
                            }
                        }

                        if (model_pt_ind != empty && std::abs(model_depth - frame_depth) < fusion_dist_thresh) {
                            const float weight = fusion_weight*std::exp(factor*((x - K(0,2))*(x - K(0,2)) + (y - K(1,2))*(y - K(1,2))));
                            const float weight_compl = 1.0f - weight;
                            // Fuse
#pragma omp critical
                            {
                                model.points.col(model_pt_ind) = weight_compl*model.points.col(model_pt_ind) + weight*frame_t.points.col(frame_pt_ind);
                                model.normals.col(model_pt_ind) = (weight_compl*model.normals.col(model_pt_ind) + weight*frame_t.normals.col(frame_pt_ind)).normalized();
                                model.colors.col(model_pt_ind) = weight_compl*model.colors.col(model_pt_ind) + weight*frame_t.colors.col(frame_pt_ind);
                            }
                        }

                        if (model_pt_ind != empty && frame_depth > model_depth + occlusion_thresh) {
                            // Remove occluded
#pragma omp critical
                            remove_ind.emplace_back(model_pt_ind);
                        }
                    }
                }
                model.remove(remove_ind);
                to_append.points.conservativeResize(Eigen::NoChange, append_count);
                to_append.normals.conservativeResize(Eigen::NoChange, append_count);
                to_append.colors.conservativeResize(Eigen::NoChange, append_count);
                model.append(to_append);
            }
        }

        // Visualization
        rgbv.setImage(rgb_img.ptr, w, h, "RGB24");
        pcdv.addObject<cilantro::PointCloudRenderable>("model", model, rp);
        pcdv.addObject<cilantro::PointCloudRenderable>("frame", frame.transformed(cam_pose), cilantro::RenderingProperties().setOpacity(0.2f).setUseLighting(false));
        pcdv.addObject<cilantro::CameraFrustumRenderable>("cam", w, h, K, cam_pose.matrix(), 0.2f, cilantro::RenderingProperties().setLineWidth(2.0f).setLineColor(1.0f,1.0f,0.0f));

        pcdv.clearRenderArea();
        rgbv.render();
        pcdv.render();
        pangolin::FinishFrame();

        // Keep model rendering properties on update
        rp = pcdv.getRenderingProperties("model");
    }

    if (argc > 1) model.toPLYFile(argv[1], true);

    delete[] img;

    return 0;
}
<|endoftext|>