<commit_before>/**
 * @file llpanelpeoplemenus.h
 * @brief Menus used by the side tray "People" panel
 *
 * $LicenseInfo:firstyear=2009&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2010, Linden Research, Inc.
 *
 * 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;
 * version 2.1 of the License only.
 *
 * 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
 *
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#include "llviewerprecompiledheaders.h"

// libs
#include "llmenugl.h"
#include "lluictrlfactory.h"

#include "llpanelpeoplemenus.h"

// newview
#include "llagent.h"
#include "llagentdata.h"			// for gAgentID
#include "llavataractions.h"
#include "llcallingcard.h"			// for LLAvatarTracker
#include "llviewermenu.h"			// for gMenuHolder
#include "llfloatersidepanelcontainer.h"
#include "llpanelpeople.h"

namespace LLPanelPeopleMenus
{

NearbyMenu gNearbyMenu;

//== NearbyMenu ===============================================================

LLContextMenu* NearbyMenu::createMenu()
{
	// set up the callbacks for all of the avatar menu items
	LLUICtrl::CommitCallbackRegistry::ScopedRegistrar registrar;
	LLUICtrl::EnableCallbackRegistry::ScopedRegistrar enable_registrar;

	if ( mUUIDs.size() == 1 )
	{
		// Set up for one person selected menu

		const LLUUID& id = mUUIDs.front();
		registrar.add("Avatar.Profile",			boost::bind(&LLAvatarActions::showProfile,				id));
		registrar.add("Avatar.AddFriend",		boost::bind(&LLAvatarActions::requestFriendshipDialog,	id));
		registrar.add("Avatar.RemoveFriend",	boost::bind(&LLAvatarActions::removeFriendDialog, 		id));
		registrar.add("Avatar.IM",				boost::bind(&LLAvatarActions::startIM,					id));
		registrar.add("Avatar.Call",			boost::bind(&LLAvatarActions::startCall,				id));
		registrar.add("Avatar.OfferTeleport",	boost::bind(&NearbyMenu::offerTeleport,					this));
		registrar.add("Avatar.GroupInvite",		boost::bind(&LLAvatarActions::inviteToGroup,			id));
		registrar.add("Avatar.getScriptInfo",	boost::bind(&LLAvatarActions::getScriptInfo,			id));
		registrar.add("Avatar.ShowOnMap",		boost::bind(&LLAvatarActions::showOnMap,				id));
		registrar.add("Avatar.Share",			boost::bind(&LLAvatarActions::share,					id));
		registrar.add("Avatar.Pay",				boost::bind(&LLAvatarActions::pay,						id));
		registrar.add("Avatar.BlockUnblock",	boost::bind(&LLAvatarActions::toggleBlock,				id));
		// [SL:KB] - Patch: UI-SidepanelPeople | Checked: 2010-12-03 (Catznip-2.4.0g) | Modified: Catznip-2.4.0g
		registrar.add("Avatar.ZoomIn",							boost::bind(&LLAvatarActions::zoomIn,						id));
		enable_registrar.add("Avatar.VisibleZoomIn",			boost::bind(&LLAvatarActions::canZoomIn,					id));
		registrar.add("Avatar.Report",							boost::bind(&LLAvatarActions::report,						id));
		registrar.add("Avatar.Eject",							boost::bind(&LLAvatarActions::landEject,					id));
		registrar.add("Avatar.Freeze",							boost::bind(&LLAvatarActions::landFreeze,					id));
		enable_registrar.add("Avatar.VisibleFreezeEject",		boost::bind(&LLAvatarActions::canLandFreezeOrEject,			id));
		registrar.add("Avatar.Kick",							boost::bind(&LLAvatarActions::estateKick,					id));
		registrar.add("Avatar.TeleportHome",					boost::bind(&LLAvatarActions::estateTeleportHome,			id));
		enable_registrar.add("Avatar.VisibleKickTeleportHome",	boost::bind(&LLAvatarActions::canEstateKickOrTeleportHome,	id));
		// [/SL:KB]

		registrar.add("Nearby.People.TeleportToAvatar", boost::bind(&NearbyMenu::teleportToAvatar,	this));
		registrar.add("Nearby.People.TrackAvatar", boost::bind(&NearbyMenu::onTrackAvatarMenuItemClick, this));

		registrar.add("Avatar.ZoomIn",                        boost::bind(&LLAvatarActions::zoomIn,                id));
                enable_registrar.add("Avatar.VisibleZoomIn",        boost::bind(&LLAvatarActions::canZoomIn,            id));
		enable_registrar.add("Avatar.EnableItem", boost::bind(&NearbyMenu::enableContextMenuItem,	this, _2));
		enable_registrar.add("Avatar.CheckItem",  boost::bind(&NearbyMenu::checkContextMenuItem,	this, _2));

		// create the context menu from the XUI
		return createFromFile("menu_people_nearby.xml");
	}
	else
	{
		// Set up for multi-selected People

		// registrar.add("Avatar.AddFriend",	boost::bind(&LLAvatarActions::requestFriendshipDialog,	mUUIDs)); // *TODO: unimplemented
		registrar.add("Avatar.IM",			boost::bind(&LLAvatarActions::startConference,			mUUIDs));
		registrar.add("Avatar.Call",		boost::bind(&LLAvatarActions::startAdhocCall,			mUUIDs));
		registrar.add("Avatar.OfferTeleport",	boost::bind(&NearbyMenu::offerTeleport,					this));
		registrar.add("Avatar.RemoveFriend",boost::bind(&LLAvatarActions::removeFriendsDialog,		mUUIDs));
		// registrar.add("Avatar.Share",		boost::bind(&LLAvatarActions::startIM,					mUUIDs)); // *TODO: unimplemented
		// registrar.add("Avatar.Pay",		boost::bind(&LLAvatarActions::pay,						mUUIDs)); // *TODO: unimplemented
		enable_registrar.add("Avatar.EnableItem",	boost::bind(&NearbyMenu::enableContextMenuItem,	this, _2));
		// [SL:KB] - Patch: UI-SidepanelPeople | Checked: 2010-11-05 (Catznip-2.4.0g) | Added: Catznip-2.4.0g
		registrar.add("Avatar.Eject",							boost::bind(&LLAvatarActions::landEjectMultiple,			mUUIDs));
		registrar.add("Avatar.Freeze",							boost::bind(&LLAvatarActions::landFreezeMultiple,			mUUIDs));
		enable_registrar.add("Avatar.VisibleFreezeEject",		boost::bind(&LLAvatarActions::canLandFreezeOrEjectMultiple,	mUUIDs, false));
		registrar.add("Avatar.Kick",							boost::bind(&LLAvatarActions::estateKickMultiple,			mUUIDs));
		registrar.add("Avatar.TeleportHome",					boost::bind(&LLAvatarActions::estateTeleportHomeMultiple,	mUUIDs));
		enable_registrar.add("Avatar.VisibleKickTeleportHome",	boost::bind(&LLAvatarActions::canEstateKickOrTeleportHomeMultiple, mUUIDs, false));
		// [/SL:KB]

		// create the context menu from the XUI
		return createFromFile("menu_people_nearby_multiselect.xml");
	}
}

bool NearbyMenu::enableContextMenuItem(const LLSD& userdata)
{
	std::string item = userdata.asString();

	// Note: can_block and can_delete is used only for one person selected menu
	// so we don't need to go over all uuids.

	if (item == std::string("can_block"))
	{
		const LLUUID& id = mUUIDs.front();
		return LLAvatarActions::canBlock(id);
	}
	else if (item == std::string("can_add"))
	{
		// We can add friends if:
		// - there are selected people
		// - and there are no friends among selection yet.

		//EXT-7389 - disable for more than 1
		if(mUUIDs.size() > 1)
		{
			return false;
		}

		bool result = (mUUIDs.size() > 0);

		uuid_vec_t::const_iterator
			id = mUUIDs.begin(),
			uuids_end = mUUIDs.end();

		for (;id != uuids_end; ++id)
		{
			if ( LLAvatarActions::isFriend(*id) )
			{
				result = false;
				break;
			}
		}

		return result;
	}
	else if (item == std::string("can_delete"))
	{
		// We can remove friends if:
		// - there are selected people
		// - and there are only friends among selection.

		bool result = (mUUIDs.size() > 0);

		uuid_vec_t::const_iterator
			id = mUUIDs.begin(),
			uuids_end = mUUIDs.end();

		for (;id != uuids_end; ++id)
		{
			if ( !LLAvatarActions::isFriend(*id) )
			{
				result = false;
				break;
			}
		}

		return result;
	}
	else if (item == std::string("can_call"))
	{
		return LLAvatarActions::canCall();
	}
	else if (item == std::string("can_show_on_map"))
	{
		const LLUUID& id = mUUIDs.front();

		return (LLAvatarTracker::instance().isBuddyOnline(id) && is_agent_mappable(id))
					|| gAgent.isGodlike();
	}
//	else if(item == std::string("can_offer_teleport")) ND_MERGE this lines had been missing from FS, intentional?
//	{
//		return LLAvatarActions::canOfferTeleport(mUUIDs);
//	}
	return false;
}

bool NearbyMenu::checkContextMenuItem(const LLSD& userdata)
{
	std::string item = userdata.asString();
	const LLUUID& id = mUUIDs.front();

	if (item == std::string("is_blocked"))
	{
		return LLAvatarActions::isBlocked(id);
	}

	return false;
}

void NearbyMenu::offerTeleport()
{
	// boost::bind cannot recognize overloaded method LLAvatarActions::offerTeleport(),
	// so we have to use a wrapper.
	LLAvatarActions::offerTeleport(mUUIDs);
}

void NearbyMenu::teleportToAvatar()
// AO: wrapper for functionality managed by LLPanelPeople, because it manages the nearby avatar list.
// Will only work for avatars within radar range.
{
	LLPanelPeople* peoplePanel = dynamic_cast<LLPanelPeople*>(LLFloaterSidePanelContainer::getPanel("people", "panel_people"));
	peoplePanel->teleportToAvatar(mUUIDs.front());
}

// Ansariel: Avatar tracking feature
void NearbyMenu::onTrackAvatarMenuItemClick()
{
	LLPanelPeople* peoplePanel = dynamic_cast<LLPanelPeople*>(LLFloaterSidePanelContainer::getPanel("people", "panel_people"));
	peoplePanel->startTracking(mUUIDs.front());
}

} // namespace LLPanelPeopleMenus
<commit_msg>Cleared merge issue in llpanelpeoplemenus.cpp<commit_after>/**
 * @file llpanelpeoplemenus.h
 * @brief Menus used by the side tray "People" panel
 *
 * $LicenseInfo:firstyear=2009&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2010, Linden Research, Inc.
 *
 * 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;
 * version 2.1 of the License only.
 *
 * 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
 *
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#include "llviewerprecompiledheaders.h"

// libs
#include "llmenugl.h"
#include "lluictrlfactory.h"

#include "llpanelpeoplemenus.h"

// newview
#include "llagent.h"
#include "llagentdata.h"			// for gAgentID
#include "llavataractions.h"
#include "llcallingcard.h"			// for LLAvatarTracker
#include "llviewermenu.h"			// for gMenuHolder
#include "llfloatersidepanelcontainer.h"
#include "llpanelpeople.h"

namespace LLPanelPeopleMenus
{

NearbyMenu gNearbyMenu;

//== NearbyMenu ===============================================================

LLContextMenu* NearbyMenu::createMenu()
{
	// set up the callbacks for all of the avatar menu items
	LLUICtrl::CommitCallbackRegistry::ScopedRegistrar registrar;
	LLUICtrl::EnableCallbackRegistry::ScopedRegistrar enable_registrar;

	if ( mUUIDs.size() == 1 )
	{
		// Set up for one person selected menu

		const LLUUID& id = mUUIDs.front();
		registrar.add("Avatar.Profile",			boost::bind(&LLAvatarActions::showProfile,				id));
		registrar.add("Avatar.AddFriend",		boost::bind(&LLAvatarActions::requestFriendshipDialog,	id));
		registrar.add("Avatar.RemoveFriend",	boost::bind(&LLAvatarActions::removeFriendDialog, 		id));
		registrar.add("Avatar.IM",				boost::bind(&LLAvatarActions::startIM,					id));
		registrar.add("Avatar.Call",			boost::bind(&LLAvatarActions::startCall,				id));
		registrar.add("Avatar.OfferTeleport",	boost::bind(&NearbyMenu::offerTeleport,					this));
		registrar.add("Avatar.GroupInvite",		boost::bind(&LLAvatarActions::inviteToGroup,			id));
		registrar.add("Avatar.getScriptInfo",	boost::bind(&LLAvatarActions::getScriptInfo,			id));
		registrar.add("Avatar.ShowOnMap",		boost::bind(&LLAvatarActions::showOnMap,				id));
		registrar.add("Avatar.Share",			boost::bind(&LLAvatarActions::share,					id));
		registrar.add("Avatar.Pay",				boost::bind(&LLAvatarActions::pay,						id));
		registrar.add("Avatar.BlockUnblock",	boost::bind(&LLAvatarActions::toggleBlock,				id));
		// [SL:KB] - Patch: UI-SidepanelPeople | Checked: 2010-12-03 (Catznip-2.4.0g) | Modified: Catznip-2.4.0g
		registrar.add("Avatar.ZoomIn",							boost::bind(&LLAvatarActions::zoomIn,						id));
		enable_registrar.add("Avatar.VisibleZoomIn",			boost::bind(&LLAvatarActions::canZoomIn,					id));
		registrar.add("Avatar.Report",							boost::bind(&LLAvatarActions::report,						id));
		registrar.add("Avatar.Eject",							boost::bind(&LLAvatarActions::landEject,					id));
		registrar.add("Avatar.Freeze",							boost::bind(&LLAvatarActions::landFreeze,					id));
		enable_registrar.add("Avatar.VisibleFreezeEject",		boost::bind(&LLAvatarActions::canLandFreezeOrEject,			id));
		registrar.add("Avatar.Kick",							boost::bind(&LLAvatarActions::estateKick,					id));
		registrar.add("Avatar.TeleportHome",					boost::bind(&LLAvatarActions::estateTeleportHome,			id));
		enable_registrar.add("Avatar.VisibleKickTeleportHome",	boost::bind(&LLAvatarActions::canEstateKickOrTeleportHome,	id));
		// [/SL:KB]

		registrar.add("Nearby.People.TeleportToAvatar", boost::bind(&NearbyMenu::teleportToAvatar,	this));
		registrar.add("Nearby.People.TrackAvatar", boost::bind(&NearbyMenu::onTrackAvatarMenuItemClick, this));

		registrar.add("Avatar.ZoomIn",                        boost::bind(&LLAvatarActions::zoomIn,                id));
                enable_registrar.add("Avatar.VisibleZoomIn",        boost::bind(&LLAvatarActions::canZoomIn,            id));
		enable_registrar.add("Avatar.EnableItem", boost::bind(&NearbyMenu::enableContextMenuItem,	this, _2));
		enable_registrar.add("Avatar.CheckItem",  boost::bind(&NearbyMenu::checkContextMenuItem,	this, _2));

		// create the context menu from the XUI
		return createFromFile("menu_people_nearby.xml");
	}
	else
	{
		// Set up for multi-selected People

		// registrar.add("Avatar.AddFriend",	boost::bind(&LLAvatarActions::requestFriendshipDialog,	mUUIDs)); // *TODO: unimplemented
		registrar.add("Avatar.IM",			boost::bind(&LLAvatarActions::startConference,			mUUIDs));
		registrar.add("Avatar.Call",		boost::bind(&LLAvatarActions::startAdhocCall,			mUUIDs));
		registrar.add("Avatar.OfferTeleport",	boost::bind(&NearbyMenu::offerTeleport,					this));
		registrar.add("Avatar.RemoveFriend",boost::bind(&LLAvatarActions::removeFriendsDialog,		mUUIDs));
		// registrar.add("Avatar.Share",		boost::bind(&LLAvatarActions::startIM,					mUUIDs)); // *TODO: unimplemented
		// registrar.add("Avatar.Pay",		boost::bind(&LLAvatarActions::pay,						mUUIDs)); // *TODO: unimplemented
		enable_registrar.add("Avatar.EnableItem",	boost::bind(&NearbyMenu::enableContextMenuItem,	this, _2));
		// [SL:KB] - Patch: UI-SidepanelPeople | Checked: 2010-11-05 (Catznip-2.4.0g) | Added: Catznip-2.4.0g
		registrar.add("Avatar.Eject",							boost::bind(&LLAvatarActions::landEjectMultiple,			mUUIDs));
		registrar.add("Avatar.Freeze",							boost::bind(&LLAvatarActions::landFreezeMultiple,			mUUIDs));
		enable_registrar.add("Avatar.VisibleFreezeEject",		boost::bind(&LLAvatarActions::canLandFreezeOrEjectMultiple,	mUUIDs, false));
		registrar.add("Avatar.Kick",							boost::bind(&LLAvatarActions::estateKickMultiple,			mUUIDs));
		registrar.add("Avatar.TeleportHome",					boost::bind(&LLAvatarActions::estateTeleportHomeMultiple,	mUUIDs));
		enable_registrar.add("Avatar.VisibleKickTeleportHome",	boost::bind(&LLAvatarActions::canEstateKickOrTeleportHomeMultiple, mUUIDs, false));
		// [/SL:KB]

		// create the context menu from the XUI
		return createFromFile("menu_people_nearby_multiselect.xml");
	}
}

bool NearbyMenu::enableContextMenuItem(const LLSD& userdata)
{
	std::string item = userdata.asString();

	// Note: can_block and can_delete is used only for one person selected menu
	// so we don't need to go over all uuids.

	if (item == std::string("can_block"))
	{
		const LLUUID& id = mUUIDs.front();
		return LLAvatarActions::canBlock(id);
	}
	else if (item == std::string("can_add"))
	{
		// We can add friends if:
		// - there are selected people
		// - and there are no friends among selection yet.

		//EXT-7389 - disable for more than 1
		if(mUUIDs.size() > 1)
		{
			return false;
		}

		bool result = (mUUIDs.size() > 0);

		uuid_vec_t::const_iterator
			id = mUUIDs.begin(),
			uuids_end = mUUIDs.end();

		for (;id != uuids_end; ++id)
		{
			if ( LLAvatarActions::isFriend(*id) )
			{
				result = false;
				break;
			}
		}

		return result;
	}
	else if (item == std::string("can_delete"))
	{
		// We can remove friends if:
		// - there are selected people
		// - and there are only friends among selection.

		bool result = (mUUIDs.size() > 0);

		uuid_vec_t::const_iterator
			id = mUUIDs.begin(),
			uuids_end = mUUIDs.end();

		for (;id != uuids_end; ++id)
		{
			if ( !LLAvatarActions::isFriend(*id) )
			{
				result = false;
				break;
			}
		}

		return result;
	}
	else if (item == std::string("can_call"))
	{
		return LLAvatarActions::canCall();
	}
	else if (item == std::string("can_show_on_map"))
	{
		const LLUUID& id = mUUIDs.front();

		return (LLAvatarTracker::instance().isBuddyOnline(id) && is_agent_mappable(id))
					|| gAgent.isGodlike();
	}
	// <FS> Prevent teleport button from being disabled when someone on your
	//      friends list logs out but is still in the region and you have
	//      multiple people selected.
	//else if(item == std::string("can_offer_teleport"))
	//{
	//	return LLAvatarActions::canOfferTeleport(mUUIDs);
	//}
	// </FS>
	return false;
}

bool NearbyMenu::checkContextMenuItem(const LLSD& userdata)
{
	std::string item = userdata.asString();
	const LLUUID& id = mUUIDs.front();

	if (item == std::string("is_blocked"))
	{
		return LLAvatarActions::isBlocked(id);
	}

	return false;
}

void NearbyMenu::offerTeleport()
{
	// boost::bind cannot recognize overloaded method LLAvatarActions::offerTeleport(),
	// so we have to use a wrapper.
	LLAvatarActions::offerTeleport(mUUIDs);
}

void NearbyMenu::teleportToAvatar()
// AO: wrapper for functionality managed by LLPanelPeople, because it manages the nearby avatar list.
// Will only work for avatars within radar range.
{
	LLPanelPeople* peoplePanel = dynamic_cast<LLPanelPeople*>(LLFloaterSidePanelContainer::getPanel("people", "panel_people"));
	peoplePanel->teleportToAvatar(mUUIDs.front());
}

// Ansariel: Avatar tracking feature
void NearbyMenu::onTrackAvatarMenuItemClick()
{
	LLPanelPeople* peoplePanel = dynamic_cast<LLPanelPeople*>(LLFloaterSidePanelContainer::getPanel("people", "panel_people"));
	peoplePanel->startTracking(mUUIDs.front());
}

} // namespace LLPanelPeopleMenus
<|endoftext|>


<commit_before>#include "RolesProvider.h"
<commit_msg>removed unnecessary file<commit_after><|endoftext|>


<commit_before>//
//  AnimatedMultiSinus.cpp
//  LaserAnimTool
//
//  Created by pach on 07/08/14.
//  Copyright (c) 2014 __MyCompanyName__. All rights reserved.
//

#include "AnimatedMultiSinus.h"

AnimatedMultiSinus::AnimatedMultiSinus(){

}

AnimatedMultiSinus::~AnimatedMultiSinus(){
    AnimatedStuff::~AnimatedStuff();
}

void AnimatedMultiSinus::setup(string name) {
    AnimatedStuff::setup(name);

    type = "AnimatedMultiSinus";

    sin1.freq = 1.;
    sin1.speed = 0.;
    sin1.height = 1.;
    sin2.freq = 1.;
    sin2.speed = 0.;
    sin2.height = 1.;
    sin3.freq = 1.;
    sin3.speed = 0.;
    sin3.height = 1.;
    sinI1.freq = 1.;
    sinI1.speed = 0.;
    sinI1.height = 1.;
    sinI2.freq = 1.;
    sinI2.speed = 0.;
    sinI2.height = 1.;
    sinI3.freq = 1.;
    sinI3.speed = 0.;
    sinI3.height = 1.;

    gui->addSpacer();
    gui->addIntSlider("/nbPoint", 10, 1000, &nbPoint);
    gui->addSlider("/posY", -1., 1., &posY);
    gui->addSpacer();
    gui->addSlider("/1/freq", 0., 50., &sin1.freq);
    gui->addSlider("/1/speed", -10., 10., &sin1.speed);
    gui->addSlider("/1/height", 0., 1., &sin1.height);
    gui->addSpacer();
    gui->addSlider("/2/freq", 0., 50., &sin2.freq);
    gui->addSlider("/2/speed", -10., 10., &sin2.speed);
    gui->addSlider("/2/height", 0., 1., &sin2.height);
    gui->addSpacer();
    gui->addSlider("/3/freq", 0., 50., &sin3.freq);
    gui->addSlider("/3/speed", -10., 10., &sin3.speed);
    gui->addSlider("/3/height", 0., 1., &sin3.height);
    gui->addSpacer();
    gui->addSlider("tan/1/freq", 0., 50., &sinI1.freq);
    gui->addSlider("tan/1/speed", -10., 10., &sinI1.speed);
    gui->addSlider("tan/1/height", 0., 1., &sinI1.height);
    gui->addSpacer();
    gui->addSlider("tan/2/freq", 0., 50., &sinI2.freq);
    gui->addSlider("tan/2/speed", -10., 10., &sinI2.speed);
    gui->addSlider("tan/2/height", 0., 1., &sinI2.height);
    gui->addSpacer();
    gui->addSlider("tan/3/freq", 0., 50., &sinI3.freq);
    gui->addSlider("tan/3/speed", -10., 10., &sinI3.speed);
    gui->addSlider("tan/3/height", 0., 1., &sinI3.height);
    ofPolyline p;
    polylines.push_back(p);

    load();
}

void AnimatedMultiSinus::update() {

    polylines[0].clear();
    float x1, x2, x3, y1, y2, y3;
    for (int i=0 ; i<nbPoint ; i++){
        y1 = sin((float)i*sin1.freq/nbPoint+ofGetElapsedTimef()*sin1.speed)*sin1.height;
        y2 = sin((float)i*sin2.freq/nbPoint+ofGetElapsedTimef()*sin2.speed)*sin2.height;
        y3 = sin((float)i*sin3.freq/nbPoint+ofGetElapsedTimef()*sin3.speed)*sin3.height;
        x1 = sin((float)i*sinI1.freq/nbPoint+ofGetElapsedTimef()*sinI1.speed)*sinI1.height;
        x2 = sin((float)i*sinI2.freq/nbPoint+ofGetElapsedTimef()*sinI2.speed)*sinI2.height;
        x3 = sin((float)i*sinI3.freq/nbPoint+ofGetElapsedTimef()*sinI3.speed)*sinI3.height;
        polylines[0].addVertex((float)i/(float)nbPoint+x1+x2+x3, y1+y2+y3-posY);
    }

}

void AnimatedMultiSinus::parseOSC(ofxOscMessage &m){
//    string msg = m.getAddress();
//    string cmd ;
//
//    int ces = msg.find_first_of("/");
//
//    if (ces != -1) {
//        if (ces == 0){
//            msg = msg.substr(ces+1);
//            cmd = msg;
//            ces = msg.find_first_of("/");
//            if (ces != -1) {
//                cmd = msg.substr(0, ces);
//                msg = msg.substr(ces);
//            }
//        }
//        else{
//            cmd = msg.substr(0, ces);
//            msg = msg.substr(ces);
//        }
//    }

    vector<string> osc = getOSCcmd(m.getAddress());
    string cmd = osc[0];
    string msg = osc[1];

    if (cmd == "nbPoint"){
        nbPoint = m.getArgAsInt32(0);
    }
    else if (cmd == "posY"){
        posY = ofMap(m.getArgAsFloat(0), 0., 1., -1., 1.);
    }
    else if (cmd == "1"){
//        ces = msg.find_first_of("/");
//
//        if (ces != -1) {
//            if (ces == 0){
//                msg = msg.substr(ces+1);
//                cmd = msg;
//                ces = msg.find_first_of("/");
//                if (ces != -1) {
//                    cmd = msg.substr(0, ces);
//                    msg = msg.substr(ces);
//                }
//            }
//            else{
//                cmd = msg.substr(0, ces);
//                msg = msg.substr(ces);
//            }
//        }
        osc = getOSCcmd(msg);
        cmd = osc[0];
        msg = osc[1];

        if (cmd == "freq"){
            sin1.freq = ofMap(m.getArgAsFloat(0), 0., 1., 0., 500.);
        }
        else if (cmd == "speed"){
            sin1.speed = ofMap(m.getArgAsFloat(0), 0., 1., 0., 50.);
        }
        else if (cmd == "height"){
            sin1.height = m.getArgAsFloat(0);
        }
    }
    else if (cmd == "2"){
//        ces = msg.find_first_of("/");
//
//        if (ces != -1) {
//            if (ces == 0){
//                msg = msg.substr(ces+1);
//                cmd = msg;
//                ces = msg.find_first_of("/");
//                if (ces != -1) {
//                    cmd = msg.substr(0, ces);
//                    msg = msg.substr(ces);
//                }
//            }
//            else{
//                cmd = msg.substr(0, ces);
//                msg = msg.substr(ces);
//            }
//        }
        osc = getOSCcmd(msg);
        cmd = osc[0];
        msg = osc[1];

        if (cmd == "freq"){
            sin2.freq = ofMap(m.getArgAsFloat(0), 0., 1., 0., 500.);
        }
        else if (cmd == "speed"){
            sin2.speed = ofMap(m.getArgAsFloat(0), 0., 1., 0., 50.);
        }
        else if (cmd == "height"){
            sin2.height = m.getArgAsFloat(0);
        }
    }
    else if (cmd == "3"){
//        ces = msg.find_first_of("/");
//
//        if (ces != -1) {
//            if (ces == 0){
//                msg = msg.substr(ces+1);
//                cmd = msg;
//                ces = msg.find_first_of("/");
//                if (ces != -1) {
//                    cmd = msg.substr(0, ces);
//                    msg = msg.substr(ces);
//                }
//            }
//            else{
//                cmd = msg.substr(0, ces);
//                msg = msg.substr(ces);
//            }
//        }

        osc = getOSCcmd(msg);
        cmd = osc[0];
        msg = osc[1];

        if (cmd == "freq"){
            sin3.freq = ofMap(m.getArgAsFloat(0), 0., 1., 0., 500.);
        }
        else if (cmd == "speed"){
            sin3.speed = ofMap(m.getArgAsFloat(0), 0., 1., 0., 50.);
        }
        else if (cmd == "height"){
            sin3.height = m.getArgAsFloat(0);
        }
    }
//    else if (cmd == "1/freq"){
//        sin1.freq = ofMap(m.getArgAsFloat(0), 0., 1., 0., 500.);
//    }
//    else if (cmd == "1/speed"){
//        sin1.speed = ofMap(m.getArgAsFloat(0), 0., 1., 0., 50.);
//    }
//    else if (cmd == "1/height"){
//        sin1.height = m.getArgAsFloat(0);
//    }
//    else if (cmd == "2/freq"){
//        sin2.freq = ofMap(m.getArgAsFloat(0), 0., 1., 0., 500.);
//    }
//    else if (cmd == "2/speed"){
//        sin2.speed = ofMap(m.getArgAsFloat(0), 0., 1., 0., 50.);
//    }
//    else if (cmd == "2/height"){
//        sin2.height = m.getArgAsFloat(0);
//    }
//    else if (cmd == "3/freq"){
//        sin3.freq = ofMap(m.getArgAsFloat(0), 0., 1., 0., 500.);
//    }
//    else if (cmd == "3/speed"){
//        sin3.speed = ofMap(m.getArgAsFloat(0), 0., 1., 0., 50.);
//    }
//    else if (cmd == "3/height"){
//        sin3.height = m.getArgAsFloat(0);
//    }
}<commit_msg>small mods<commit_after>//
//  AnimatedMultiSinus.cpp
//  LaserAnimTool
//
//  Created by pach on 07/08/14.
//  Copyright (c) 2014 __MyCompanyName__. All rights reserved.
//

#include "AnimatedMultiSinus.h"

AnimatedMultiSinus::AnimatedMultiSinus(){

}

AnimatedMultiSinus::~AnimatedMultiSinus(){
    AnimatedStuff::~AnimatedStuff();
}

void AnimatedMultiSinus::setup(string name) {
    AnimatedStuff::setup(name);

    type = "AnimatedMultiSinus";

    sin1.freq = 1.;
    sin1.speed = 0.;
    sin1.height = 1.;
    sin2.freq = 1.;
    sin2.speed = 0.;
    sin2.height = 1.;
    sin3.freq = 1.;
    sin3.speed = 0.;
    sin3.height = 1.;
    sinI1.freq = 1.;
    sinI1.speed = 0.;
    sinI1.height = 1.;
    sinI2.freq = 1.;
    sinI2.speed = 0.;
    sinI2.height = 1.;
    sinI3.freq = 1.;
    sinI3.speed = 0.;
    sinI3.height = 1.;

    gui->addSpacer();
    gui->addIntSlider("/nbPoint", 10, 1000, &nbPoint);
    gui->addSlider("/posY", -1., 1., &posY);
    gui->addSpacer();
    gui->addSlider("/1/freq", 0., 200., &sin1.freq);
    gui->addSlider("/1/speed", -10., 10., &sin1.speed);
    gui->addSlider("/1/height", 0., 1., &sin1.height);
    gui->addSpacer();
    gui->addSlider("/2/freq", 0., 200., &sin2.freq);
    gui->addSlider("/2/speed", -10., 10., &sin2.speed);
    gui->addSlider("/2/height", 0., 1., &sin2.height);
    gui->addSpacer();
    gui->addSlider("/3/freq", 0., 200., &sin3.freq);
    gui->addSlider("/3/speed", -10., 10., &sin3.speed);
    gui->addSlider("/3/height", 0., 1., &sin3.height);
    gui->addSpacer();
    gui->addSlider("tan/1/freq", 0., 50., &sinI1.freq);
    gui->addSlider("tan/1/speed", -10., 10., &sinI1.speed);
    gui->addSlider("tan/1/height", 0., 1., &sinI1.height);
    gui->addSpacer();
    gui->addSlider("tan/2/freq", 0., 50., &sinI2.freq);
    gui->addSlider("tan/2/speed", -10., 10., &sinI2.speed);
    gui->addSlider("tan/2/height", 0., 1., &sinI2.height);
    gui->addSpacer();
    gui->addSlider("tan/3/freq", 0., 50., &sinI3.freq);
    gui->addSlider("tan/3/speed", -10., 10., &sinI3.speed);
    gui->addSlider("tan/3/height", 0., 1., &sinI3.height);
    ofPolyline p;
    polylines.push_back(p);

    load();
}

void AnimatedMultiSinus::update() {

    polylines[0].clear();
    float x1, x2, x3, y1, y2, y3;
    for (int i=0 ; i<nbPoint ; i++){
        y1 = sin((float)i*sin1.freq/nbPoint+ofGetElapsedTimef()*sin1.speed)*sin1.height;
        y2 = sin((float)i*sin2.freq/nbPoint+ofGetElapsedTimef()*sin2.speed)*sin2.height;
        y3 = sin((float)i*sin3.freq/nbPoint+ofGetElapsedTimef()*sin3.speed)*sin3.height;
        x1 = sin((float)i*sinI1.freq/nbPoint+ofGetElapsedTimef()*sinI1.speed)*sinI1.height;
        x2 = sin((float)i*sinI2.freq/nbPoint+ofGetElapsedTimef()*sinI2.speed)*sinI2.height;
        x3 = sin((float)i*sinI3.freq/nbPoint+ofGetElapsedTimef()*sinI3.speed)*sinI3.height;
        polylines[0].addVertex((float)i/(float)nbPoint+x1+x2+x3, y1+y2+y3-posY);
    }

}

void AnimatedMultiSinus::parseOSC(ofxOscMessage &m){
//    string msg = m.getAddress();
//    string cmd ;
//
//    int ces = msg.find_first_of("/");
//
//    if (ces != -1) {
//        if (ces == 0){
//            msg = msg.substr(ces+1);
//            cmd = msg;
//            ces = msg.find_first_of("/");
//            if (ces != -1) {
//                cmd = msg.substr(0, ces);
//                msg = msg.substr(ces);
//            }
//        }
//        else{
//            cmd = msg.substr(0, ces);
//            msg = msg.substr(ces);
//        }
//    }

    vector<string> osc = getOSCcmd(m.getAddress());
    string cmd = osc[0];
    string msg = osc[1];

    if (cmd == "nbPoint"){
        nbPoint = m.getArgAsInt32(0);
    }
    else if (cmd == "posY"){
        posY = ofMap(m.getArgAsFloat(0), 0., 1., -1., 1.);
    }
    else if (cmd == "1"){
//        ces = msg.find_first_of("/");
//
//        if (ces != -1) {
//            if (ces == 0){
//                msg = msg.substr(ces+1);
//                cmd = msg;
//                ces = msg.find_first_of("/");
//                if (ces != -1) {
//                    cmd = msg.substr(0, ces);
//                    msg = msg.substr(ces);
//                }
//            }
//            else{
//                cmd = msg.substr(0, ces);
//                msg = msg.substr(ces);
//            }
//        }
        osc = getOSCcmd(msg);
        cmd = osc[0];
        msg = osc[1];

        if (cmd == "freq"){
            sin1.freq = ofMap(m.getArgAsFloat(0), 0., 1., 0., 500.);
        }
        else if (cmd == "speed"){
            sin1.speed = ofMap(m.getArgAsFloat(0), 0., 1., 0., 50.);
        }
        else if (cmd == "height"){
            sin1.height = m.getArgAsFloat(0);
        }
    }
    else if (cmd == "2"){
//        ces = msg.find_first_of("/");
//
//        if (ces != -1) {
//            if (ces == 0){
//                msg = msg.substr(ces+1);
//                cmd = msg;
//                ces = msg.find_first_of("/");
//                if (ces != -1) {
//                    cmd = msg.substr(0, ces);
//                    msg = msg.substr(ces);
//                }
//            }
//            else{
//                cmd = msg.substr(0, ces);
//                msg = msg.substr(ces);
//            }
//        }
        osc = getOSCcmd(msg);
        cmd = osc[0];
        msg = osc[1];

        if (cmd == "freq"){
            sin2.freq = ofMap(m.getArgAsFloat(0), 0., 1., 0., 500.);
        }
        else if (cmd == "speed"){
            sin2.speed = ofMap(m.getArgAsFloat(0), 0., 1., 0., 50.);
        }
        else if (cmd == "height"){
            sin2.height = m.getArgAsFloat(0);
        }
    }
    else if (cmd == "3"){
//        ces = msg.find_first_of("/");
//
//        if (ces != -1) {
//            if (ces == 0){
//                msg = msg.substr(ces+1);
//                cmd = msg;
//                ces = msg.find_first_of("/");
//                if (ces != -1) {
//                    cmd = msg.substr(0, ces);
//                    msg = msg.substr(ces);
//                }
//            }
//            else{
//                cmd = msg.substr(0, ces);
//                msg = msg.substr(ces);
//            }
//        }

        osc = getOSCcmd(msg);
        cmd = osc[0];
        msg = osc[1];

        if (cmd == "freq"){
            sin3.freq = ofMap(m.getArgAsFloat(0), 0., 1., 0., 500.);
        }
        else if (cmd == "speed"){
            sin3.speed = ofMap(m.getArgAsFloat(0), 0., 1., 0., 50.);
        }
        else if (cmd == "height"){
            sin3.height = m.getArgAsFloat(0);
        }
    }
//    else if (cmd == "1/freq"){
//        sin1.freq = ofMap(m.getArgAsFloat(0), 0., 1., 0., 500.);
//    }
//    else if (cmd == "1/speed"){
//        sin1.speed = ofMap(m.getArgAsFloat(0), 0., 1., 0., 50.);
//    }
//    else if (cmd == "1/height"){
//        sin1.height = m.getArgAsFloat(0);
//    }
//    else if (cmd == "2/freq"){
//        sin2.freq = ofMap(m.getArgAsFloat(0), 0., 1., 0., 500.);
//    }
//    else if (cmd == "2/speed"){
//        sin2.speed = ofMap(m.getArgAsFloat(0), 0., 1., 0., 50.);
//    }
//    else if (cmd == "2/height"){
//        sin2.height = m.getArgAsFloat(0);
//    }
//    else if (cmd == "3/freq"){
//        sin3.freq = ofMap(m.getArgAsFloat(0), 0., 1., 0., 500.);
//    }
//    else if (cmd == "3/speed"){
//        sin3.speed = ofMap(m.getArgAsFloat(0), 0., 1., 0., 50.);
//    }
//    else if (cmd == "3/height"){
//        sin3.height = m.getArgAsFloat(0);
//    }
}<|endoftext|>


<commit_before>
/*
 * Copyright 2006 The Android Open Source Project
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "Sk2DPathEffect.h"
#include "SkBlitter.h"
#include "SkPath.h"
#include "SkScan.h"

class Sk2DPathEffectBlitter : public SkBlitter {
public:
    Sk2DPathEffectBlitter(Sk2DPathEffect* pe, SkPath* dst)
        : fPE(pe), fDst(dst)
    {}
    virtual void blitH(int x, int y, int count)
    {
        fPE->nextSpan(x, y, count, fDst);
    }
private:
    Sk2DPathEffect* fPE;
    SkPath*         fDst;
};

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

Sk2DPathEffect::Sk2DPathEffect(const SkMatrix& mat) : fMatrix(mat)
{
    mat.invert(&fInverse);
}

bool Sk2DPathEffect::filterPath(SkPath* dst, const SkPath& src, SkScalar* width)
{
    Sk2DPathEffectBlitter   blitter(this, dst);
    SkPath                  tmp;
    SkIRect                 ir;

    src.transform(fInverse, &tmp);
    tmp.getBounds().round(&ir);
    if (!ir.isEmpty()) {
        // need to pass a clip to fillpath, required for inverse filltypes,
        // even though those do not make sense for this patheffect
        SkRegion clip(ir);

        this->begin(ir, dst);
        SkScan::FillPath(tmp, clip, &blitter);
        this->end(dst);
    }
    return true;
}

void Sk2DPathEffect::nextSpan(int x, int y, int count, SkPath* path)
{
    const SkMatrix& mat = this->getMatrix();
    SkPoint src, dst;

    src.set(SkIntToScalar(x) + SK_ScalarHalf, SkIntToScalar(y) + SK_ScalarHalf);
    do {
        mat.mapPoints(&dst, &src, 1);
        this->next(dst, x++, y, path);
        src.fX += SK_Scalar1;
    } while (--count > 0);
}

void Sk2DPathEffect::begin(const SkIRect& uvBounds, SkPath* dst) {}
void Sk2DPathEffect::next(const SkPoint& loc, int u, int v, SkPath* dst) {}
void Sk2DPathEffect::end(SkPath* dst) {}

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

void Sk2DPathEffect::flatten(SkFlattenableWriteBuffer& buffer)
{
    char storage[SkMatrix::kMaxFlattenSize];
    uint32_t size = fMatrix.flatten(storage);
    buffer.write32(size);
    buffer.write(storage, size);
}

Sk2DPathEffect::Sk2DPathEffect(SkFlattenableReadBuffer& buffer)
{
    char storage[SkMatrix::kMaxFlattenSize];
    uint32_t size = buffer.readS32();
    SkASSERT(size <= sizeof(storage));
    buffer.read(storage, size);
    fMatrix.unflatten(storage);
    fMatrix.invert(&fInverse);
}

SkFlattenable::Factory Sk2DPathEffect::getFactory()
{
    return CreateProc;
}

SkFlattenable* Sk2DPathEffect::CreateProc(SkFlattenableReadBuffer& buffer)
{
    return SkNEW_ARGS(Sk2DPathEffect, (buffer));
}

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

SkPath2DPathEffect::SkPath2DPathEffect(const SkMatrix& m, const SkPath& p)
    : INHERITED(m), fPath(p) {
}

SkPath2DPathEffect::SkPath2DPathEffect(SkFlattenableReadBuffer& buffer)
        : INHERITED(buffer) {
    fPath.unflatten(buffer);
}

SkFlattenable* SkPath2DPathEffect::CreateProc(SkFlattenableReadBuffer& buffer) {
    return SkNEW_ARGS(SkPath2DPathEffect, (buffer));
}

void SkPath2DPathEffect::flatten(SkFlattenableWriteBuffer& buffer) {
    this->INHERITED::flatten(buffer);
    fPath.flatten(buffer);
}

SkFlattenable::Factory SkPath2DPathEffect::getFactory() {
    return CreateProc;
}

void SkPath2DPathEffect::next(const SkPoint& loc, int u, int v, SkPath* dst) {
    dst->addPath(fPath, loc.fX, loc.fY);
}

static SkFlattenable::Registrar gReg("SkPath2DPathEffect",
                                     SkPath2DPathEffect::CreateProc);

<commit_msg>style cleanup<commit_after>
/*
 * Copyright 2006 The Android Open Source Project
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "Sk2DPathEffect.h"
#include "SkBlitter.h"
#include "SkPath.h"
#include "SkScan.h"

class Sk2DPathEffectBlitter : public SkBlitter {
public:
    Sk2DPathEffectBlitter(Sk2DPathEffect* pe, SkPath* dst)
        : fPE(pe), fDst(dst) {}

    virtual void blitH(int x, int y, int count) {
        fPE->nextSpan(x, y, count, fDst);
    }
private:
    Sk2DPathEffect* fPE;
    SkPath*         fDst;
};

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

Sk2DPathEffect::Sk2DPathEffect(const SkMatrix& mat) : fMatrix(mat) {
    mat.invert(&fInverse);
}

bool Sk2DPathEffect::filterPath(SkPath* dst, const SkPath& src, SkScalar* width) {
    Sk2DPathEffectBlitter   blitter(this, dst);
    SkPath                  tmp;
    SkIRect                 ir;

    src.transform(fInverse, &tmp);
    tmp.getBounds().round(&ir);
    if (!ir.isEmpty()) {
        // need to pass a clip to fillpath, required for inverse filltypes,
        // even though those do not make sense for this patheffect
        SkRegion clip(ir);

        this->begin(ir, dst);
        SkScan::FillPath(tmp, clip, &blitter);
        this->end(dst);
    }
    return true;
}

void Sk2DPathEffect::nextSpan(int x, int y, int count, SkPath* path) {
    const SkMatrix& mat = this->getMatrix();
    SkPoint src, dst;

    src.set(SkIntToScalar(x) + SK_ScalarHalf, SkIntToScalar(y) + SK_ScalarHalf);
    do {
        mat.mapPoints(&dst, &src, 1);
        this->next(dst, x++, y, path);
        src.fX += SK_Scalar1;
    } while (--count > 0);
}

void Sk2DPathEffect::begin(const SkIRect& uvBounds, SkPath* dst) {}
void Sk2DPathEffect::next(const SkPoint& loc, int u, int v, SkPath* dst) {}
void Sk2DPathEffect::end(SkPath* dst) {}

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

void Sk2DPathEffect::flatten(SkFlattenableWriteBuffer& buffer) {
    char storage[SkMatrix::kMaxFlattenSize];
    uint32_t size = fMatrix.flatten(storage);
    buffer.write32(size);
    buffer.write(storage, size);
}

Sk2DPathEffect::Sk2DPathEffect(SkFlattenableReadBuffer& buffer) {
    char storage[SkMatrix::kMaxFlattenSize];
    uint32_t size = buffer.readS32();
    SkASSERT(size <= sizeof(storage));
    buffer.read(storage, size);
    fMatrix.unflatten(storage);
    fMatrix.invert(&fInverse);
}

SkFlattenable::Factory Sk2DPathEffect::getFactory() {
    return CreateProc;
}

SkFlattenable* Sk2DPathEffect::CreateProc(SkFlattenableReadBuffer& buffer) {
    return SkNEW_ARGS(Sk2DPathEffect, (buffer));
}

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

SkPath2DPathEffect::SkPath2DPathEffect(const SkMatrix& m, const SkPath& p)
    : INHERITED(m), fPath(p) {
}

SkPath2DPathEffect::SkPath2DPathEffect(SkFlattenableReadBuffer& buffer)
        : INHERITED(buffer) {
    fPath.unflatten(buffer);
}

SkFlattenable* SkPath2DPathEffect::CreateProc(SkFlattenableReadBuffer& buffer) {
    return SkNEW_ARGS(SkPath2DPathEffect, (buffer));
}

void SkPath2DPathEffect::flatten(SkFlattenableWriteBuffer& buffer) {
    this->INHERITED::flatten(buffer);
    fPath.flatten(buffer);
}

SkFlattenable::Factory SkPath2DPathEffect::getFactory() {
    return CreateProc;
}

void SkPath2DPathEffect::next(const SkPoint& loc, int u, int v, SkPath* dst) {
    dst->addPath(fPath, loc.fX, loc.fY);
}

static SkFlattenable::Registrar gReg("SkPath2DPathEffect",
                                     SkPath2DPathEffect::CreateProc);

<|endoftext|>


<commit_before>#pragma once

#include "../utilmacro.hpp"

#include <iosfwd>
#include <string>
#include <vector>

namespace nip::error {
	enum _Error_Type : uint8_t { NOTE, WARNING, ERROR, FATAL_ERROR };

	struct _Error {
		_Error(_Error_Type type_i, const char* msg_i, size_t ll = 0, size_t lc = 0, bool hl = false)
		    : msg(msg_i), loc_line(ll), loc_char(lc), has_location(hl), type(type_i) {}
		std::string msg;
		size_t loc_line;
		size_t loc_char;
		bool has_location;
		_Error_Type type;
	};

	class Error_Handler {
	  public:
		ALWAYS_INLINE void add_error(_Error_Type type, const char* msg, size_t ll = 0,
		                             size_t lc = 0, bool hl = false);
		void print_errors(std::ostream&);

		Error_Handler(){};
		Error_Handler(std::vector<std::string>&& source) : source_file(source){};
		void set_source(std::vector<std::string>&& source) {
			source_file = source;
		};

	  private:
		void sort();

		std::vector<_Error> error_list;
		std::vector<std::string> source_file;

		bool has_note    = false;
		bool has_warning = false;
		bool has_error   = false;
		bool has_fatal   = false;
		bool sorted      = false;
	};
}

ALWAYS_INLINE void nip::error::Error_Handler::add_error(_Error_Type type, const char* msg,
                                                        size_t ll, size_t lc, bool hl) {
	error_list.emplace_back(type, msg, ll, lc, hl);
	switch (type) {
		case NOTE:
			has_note = true;
			break;
		case WARNING:
			has_warning = true;
			break;
		case ERROR:
			has_error = true;
			break;
		case FATAL_ERROR:
			has_fatal = true;
			break;
	}
}<commit_msg>Add wrapper function to add an error with a string<commit_after>#pragma once

#include "../utilmacro.hpp"

#include <iosfwd>
#include <string>
#include <vector>

namespace nip::error {
	enum _Error_Type : uint8_t { NOTE, WARNING, ERROR, FATAL_ERROR };

	struct _Error {
		_Error(_Error_Type type_i, const char* msg_i, size_t ll = 0, size_t lc = 0, bool hl = false)
		    : msg(msg_i), loc_line(ll), loc_char(lc), has_location(hl), type(type_i) {}
		std::string msg;
		size_t loc_line;
		size_t loc_char;
		bool has_location;
		_Error_Type type;
	};

	class Error_Handler {
	  public:
		ALWAYS_INLINE void add_error(_Error_Type type, std::string& msg, size_t ll = 0,
		                             size_t lc = 0, bool hl = false);
		ALWAYS_INLINE void add_error(_Error_Type type, const char* msg, size_t ll = 0,
		                             size_t lc = 0, bool hl = false);
		void print_errors(std::ostream&);

		Error_Handler(){};
		Error_Handler(std::vector<std::string>&& source) : source_file(source){};
		void set_source(std::vector<std::string>&& source) {
			source_file = source;
		};

	  private:
		void sort();

		std::vector<_Error> error_list;
		std::vector<std::string> source_file;

		bool has_note    = false;
		bool has_warning = false;
		bool has_error   = false;
		bool has_fatal   = false;
		bool sorted      = false;
	};
}

ALWAYS_INLINE void nip::error::Error_Handler::add_error(_Error_Type type, std::string& msg,
                                                        size_t ll, size_t lc, bool hl) {
	add_error(type, msg.data(), ll, lc, hl);
}

ALWAYS_INLINE void nip::error::Error_Handler::add_error(_Error_Type type, const char* msg,
                                                        size_t ll, size_t lc, bool hl) {
	error_list.emplace_back(type, msg, ll, lc, hl);
	switch (type) {
		case NOTE:
			has_note = true;
			break;
		case WARNING:
			has_warning = true;
			break;
		case ERROR:
			has_error = true;
			break;
		case FATAL_ERROR:
			has_fatal = true;
			break;
	}
}<|endoftext|>


<commit_before>#ifndef PLATE2D_HPP
#define PLATE2D_HPP
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
    #include <wx/wx.h>
#endif
#include <wx/datetime.h>

#include <vector>
#include <functional>
#include "Plater.hpp"
#include "ColorScheme.hpp"
#include "Settings.hpp"
#include "Plater/PlaterObject.hpp"
#include "misc_ui.hpp"

#include "Log.hpp"

namespace Slic3r { namespace GUI {

// Setup for an Easter Egg with the canvas text.
const wxDateTime today_date {wxDateTime().GetDateOnly()};
const wxDateTime special_date {13, wxDateTime::Month::Sep, 2006, 0, 0, 0, 0};
const bool today_is_special = {today_date.GetDay() == special_date.GetDay() && today_date.GetMonth() == special_date.GetMonth()};

enum class MoveDirection {
    Up, Down, Left, Right
};

/// simple POD to make referencing this pair of identifiers easy
struct InstanceIdx {
    long obj;
    long inst;
};

class Plate2D : public wxPanel {
public:
    Plate2D(wxWindow* parent, const wxSize& size, std::vector<PlaterObject>& _objects, std::shared_ptr<Model> _model, std::shared_ptr<Config> _config, std::shared_ptr<Settings> _settings);

    /// Read print bed size from config and calculate the scaled rendition of the bed given the draw canvas.
    void update_bed_size();

    std::function<void (const unsigned int obj_idx)> on_select_object {};
    std::function<void ()> on_double_click {};

    /// Do something on right-clicks.
    std::function<void (const wxPoint& pos)> on_right_click {};
    std::function<void ()> on_instances_moved {};

    void set_selected (long obj, long inst) { this->selected_instance = {obj, inst}; }

private:
    std::vector<PlaterObject>& objects; //< reference to parent vector
    std::shared_ptr<Slic3r::Model> model;
    std::shared_ptr<Slic3r::Config> config;
    std::shared_ptr<Settings> settings;

    // Different brushes to draw with, initialized from settings->Color during the constructor
    wxBrush objects_brush {};
    wxBrush instance_brush {};
    wxBrush selected_brush {};
    wxBrush bed_brush {};
    wxBrush dragged_brush {};
    wxBrush transparent_brush {};

    wxPen grid_pen {};
    wxPen print_center_pen {};
    wxPen clearance_pen {};
    wxPen skirt_pen {};
    wxPen dark_pen {};

    bool user_drawn_background {(the_os == OS::Mac ? false : true)};

    /// The object id and selected
    InstanceIdx selected_instance {-1, -1};
    InstanceIdx drag_object {-1, -1};

    /// Handle mouse-move events
    void mouse_drag(wxMouseEvent& e);
    void mouse_down(wxMouseEvent& e);
    void mouse_up(wxMouseEvent& e);
    void mouse_dclick(wxMouseEvent& e);

    wxPoint drag_start_pos {wxPoint(-1, -1)};

    /// Handle repaint events
    void repaint(wxPaintEvent& e);

    void nudge_key(wxKeyEvent& e);

    void nudge(MoveDirection dir);

    /// Set/Update all of the colors used by the various brushes in the panel.
    void set_colors();

    /// Convert a scale point array to a pixel polygon suitable for DrawPolygon
    std::vector<wxPoint> scaled_points_to_pixel(const Slic3r::Polygon& poly, bool unscale);
    std::vector<wxPoint> scaled_points_to_pixel(const Slic3r::Polyline& poly, bool unscale);

    /// For a specific point, unscale it relative to the origin
    wxPoint unscaled_point_to_pixel(const wxPoint& in);

    /// Displacement needed to center bed.
    wxPoint bed_origin {};

    /// private class variables to stash bits for drawing the print bed area.
    wxRealPoint print_center {};
    Slic3r::Polygon bed_polygon {};
    std::vector<wxPoint> grid {};

    /// Set up the 2D canvas blank canvas text.
    /// Easter egg: Sept. 13, 2006. The first part ever printed by a RepRap to make another RepRap.
    const wxString CANVAS_TEXT { today_is_special ? _(L"What do you want to print today?™") : _("Drag your objects here") };

    /// How much to scale the points to fit in the draw bounding box area.
    /// Expressed as pixel / mm
    double scaling_factor {1.0};

    const std::string LogChannel {"GUI_2D"};

    Slic3r::Point point_to_model_units(coordf_t x, coordf_t y) {
        const auto& zero {this->bed_origin};
        return Slic3r::Point(
            scale_(x - zero.x) / this->scaling_factor,
            scale_(zero.y - y) / this->scaling_factor
        );
    }
    Slic3r::Point point_to_model_units(const wxPoint& pt) {
        return this->point_to_model_units(pt.x, pt.y);
    }
    Slic3r::Point point_to_model_units(const Pointf& pt) {
        return this->point_to_model_units(pt.x, pt.y);
    }

    /// Remove all instance thumbnails.
    void clean_instance_thumbnails();
};

} } // Namespace Slic3r::GUI
#endif // PLATE2D_HPP
<commit_msg>Use wxDateTime::Now() to initialze current date instead of default constructor (avoid runtime errors)<commit_after>#ifndef PLATE2D_HPP
#define PLATE2D_HPP
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
    #include <wx/wx.h>
#endif
#include <wx/datetime.h>

#include <vector>
#include <functional>
#include "Plater.hpp"
#include "ColorScheme.hpp"
#include "Settings.hpp"
#include "Plater/PlaterObject.hpp"
#include "misc_ui.hpp"

#include "Log.hpp"

namespace Slic3r { namespace GUI {

// Setup for an Easter Egg with the canvas text.
const wxDateTime today_date {wxDateTime::Now()};
const wxDateTime special_date {13, wxDateTime::Month::Sep, 2006, 0, 0, 0, 0};
const bool today_is_special = {today_date.GetDay() == special_date.GetDay() && today_date.GetMonth() == special_date.GetMonth()};

enum class MoveDirection {
    Up, Down, Left, Right
};

/// simple POD to make referencing this pair of identifiers easy
struct InstanceIdx {
    long obj;
    long inst;
};

class Plate2D : public wxPanel {
public:
    Plate2D(wxWindow* parent, const wxSize& size, std::vector<PlaterObject>& _objects, std::shared_ptr<Model> _model, std::shared_ptr<Config> _config, std::shared_ptr<Settings> _settings);

    /// Read print bed size from config and calculate the scaled rendition of the bed given the draw canvas.
    void update_bed_size();

    std::function<void (const unsigned int obj_idx)> on_select_object {};
    std::function<void ()> on_double_click {};

    /// Do something on right-clicks.
    std::function<void (const wxPoint& pos)> on_right_click {};
    std::function<void ()> on_instances_moved {};

    void set_selected (long obj, long inst) { this->selected_instance = {obj, inst}; }

private:
    std::vector<PlaterObject>& objects; //< reference to parent vector
    std::shared_ptr<Slic3r::Model> model;
    std::shared_ptr<Slic3r::Config> config;
    std::shared_ptr<Settings> settings;

    // Different brushes to draw with, initialized from settings->Color during the constructor
    wxBrush objects_brush {};
    wxBrush instance_brush {};
    wxBrush selected_brush {};
    wxBrush bed_brush {};
    wxBrush dragged_brush {};
    wxBrush transparent_brush {};

    wxPen grid_pen {};
    wxPen print_center_pen {};
    wxPen clearance_pen {};
    wxPen skirt_pen {};
    wxPen dark_pen {};

    bool user_drawn_background {(the_os == OS::Mac ? false : true)};

    /// The object id and selected
    InstanceIdx selected_instance {-1, -1};
    InstanceIdx drag_object {-1, -1};

    /// Handle mouse-move events
    void mouse_drag(wxMouseEvent& e);
    void mouse_down(wxMouseEvent& e);
    void mouse_up(wxMouseEvent& e);
    void mouse_dclick(wxMouseEvent& e);

    wxPoint drag_start_pos {wxPoint(-1, -1)};

    /// Handle repaint events
    void repaint(wxPaintEvent& e);

    void nudge_key(wxKeyEvent& e);

    void nudge(MoveDirection dir);

    /// Set/Update all of the colors used by the various brushes in the panel.
    void set_colors();

    /// Convert a scale point array to a pixel polygon suitable for DrawPolygon
    std::vector<wxPoint> scaled_points_to_pixel(const Slic3r::Polygon& poly, bool unscale);
    std::vector<wxPoint> scaled_points_to_pixel(const Slic3r::Polyline& poly, bool unscale);

    /// For a specific point, unscale it relative to the origin
    wxPoint unscaled_point_to_pixel(const wxPoint& in);

    /// Displacement needed to center bed.
    wxPoint bed_origin {};

    /// private class variables to stash bits for drawing the print bed area.
    wxRealPoint print_center {};
    Slic3r::Polygon bed_polygon {};
    std::vector<wxPoint> grid {};

    /// Set up the 2D canvas blank canvas text.
    /// Easter egg: Sept. 13, 2006. The first part ever printed by a RepRap to make another RepRap.
    const wxString CANVAS_TEXT { today_is_special ? _(L"What do you want to print today?™") : _("Drag your objects here") };

    /// How much to scale the points to fit in the draw bounding box area.
    /// Expressed as pixel / mm
    double scaling_factor {1.0};

    const std::string LogChannel {"GUI_2D"};

    Slic3r::Point point_to_model_units(coordf_t x, coordf_t y) {
        const auto& zero {this->bed_origin};
        return Slic3r::Point(
            scale_(x - zero.x) / this->scaling_factor,
            scale_(zero.y - y) / this->scaling_factor
        );
    }
    Slic3r::Point point_to_model_units(const wxPoint& pt) {
        return this->point_to_model_units(pt.x, pt.y);
    }
    Slic3r::Point point_to_model_units(const Pointf& pt) {
        return this->point_to_model_units(pt.x, pt.y);
    }

    /// Remove all instance thumbnails.
    void clean_instance_thumbnails();
};

} } // Namespace Slic3r::GUI
#endif // PLATE2D_HPP
<|endoftext|>


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

    Copyright (c) 2007 Tobias Koenig <tokoe@kde.org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 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 General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/

#include "contacteditordialog.h"

#include "kabc/kabcitemeditor.h"

#include "collectioncombobox.h"
#include <akonadi/item.h>

#include <klocale.h>

#include <QtGui/QGridLayout>
#include <QtGui/QLabel>

ContactEditorDialog::ContactEditorDialog( Mode mode, QAbstractItemModel *collectionModel, QWidget *parent )
  : KDialog( parent )
{
  setCaption( mode == CreateMode ? i18n( "New Contact" ) : i18n( "Edit Contact" ) );
  setButtons( Ok | Cancel );

  QWidget *mainWidget = new QWidget( this );
  setMainWidget( mainWidget );

  QGridLayout *layout = new QGridLayout( mainWidget );

  mEditor = new Akonadi::KABCItemEditor( mode == CreateMode ? Akonadi::KABCItemEditor::CreateMode : Akonadi::KABCItemEditor::EditMode, this );

  if ( mode == CreateMode ) {
     QLabel *label = new QLabel( i18n( "Add to:" ), mainWidget );
     KABC::CollectionComboBox *box = new KABC::CollectionComboBox( mainWidget );
     if ( collectionModel )
       box->setModel( collectionModel );

     layout->addWidget( label, 0, 0 );
     layout->addWidget( box, 0, 1 );

     connect( box, SIGNAL( selectionChanged( const Akonadi::Collection& ) ),
              mEditor, SLOT( setDefaultCollection( const Akonadi::Collection& ) ) );
  }

  layout->addWidget( mEditor, 1, 0, 1, 2 );
  layout->setColumnStretch( 1, 1 );

  connect( mEditor, SIGNAL( contactStored( const Akonadi::Item& ) ),
           this, SIGNAL( contactStored( const Akonadi::Item& ) ) );

  connect( this, SIGNAL( okClicked() ), this, SLOT( slotOkClicked() ) );
  connect( this, SIGNAL( cancelClicked() ), this, SLOT( slotCancelClicked() ) );
}

ContactEditorDialog::~ContactEditorDialog()
{
}

void ContactEditorDialog::setContact( const Akonadi::Item &contact )
{
  mEditor->loadContact( contact );
}

void ContactEditorDialog::slotOkClicked()
{
  mEditor->saveContact();

  accept();
}

void ContactEditorDialog::slotCancelClicked()
{
  reject();
}

#include "contacteditordialog.moc"
<commit_msg>Sets the initial collection<commit_after>/*
    This file is part of KContactManager.

    Copyright (c) 2007 Tobias Koenig <tokoe@kde.org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 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 General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/

#include "contacteditordialog.h"

#include "kabc/kabcitemeditor.h"

#include "collectioncombobox.h"
#include <akonadi/item.h>

#include <klocale.h>

#include <QtGui/QGridLayout>
#include <QtGui/QLabel>

ContactEditorDialog::ContactEditorDialog( Mode mode, QAbstractItemModel *collectionModel, QWidget *parent )
  : KDialog( parent )
{
  setCaption( mode == CreateMode ? i18n( "New Contact" ) : i18n( "Edit Contact" ) );
  setButtons( Ok | Cancel );

  QWidget *mainWidget = new QWidget( this );
  setMainWidget( mainWidget );

  QGridLayout *layout = new QGridLayout( mainWidget );

  mEditor = new Akonadi::KABCItemEditor( mode == CreateMode ? Akonadi::KABCItemEditor::CreateMode : Akonadi::KABCItemEditor::EditMode, this );

  if ( mode == CreateMode ) {
     QLabel *label = new QLabel( i18n( "Add to:" ), mainWidget );
     KABC::CollectionComboBox *box = new KABC::CollectionComboBox( mainWidget );
     if ( collectionModel )
       box->setModel( collectionModel );

     layout->addWidget( label, 0, 0 );
     layout->addWidget( box, 0, 1 );

     connect( box, SIGNAL( selectionChanged( const Akonadi::Collection& ) ),
              mEditor, SLOT( setDefaultCollection( const Akonadi::Collection& ) ) );

     mEditor->setDefaultCollection( box->selectedCollection() );
  }

  layout->addWidget( mEditor, 1, 0, 1, 2 );
  layout->setColumnStretch( 1, 1 );

  connect( mEditor, SIGNAL( contactStored( const Akonadi::Item& ) ),
           this, SIGNAL( contactStored( const Akonadi::Item& ) ) );

  connect( this, SIGNAL( okClicked() ), this, SLOT( slotOkClicked() ) );
  connect( this, SIGNAL( cancelClicked() ), this, SLOT( slotCancelClicked() ) );
}

ContactEditorDialog::~ContactEditorDialog()
{
}

void ContactEditorDialog::setContact( const Akonadi::Item &contact )
{
  mEditor->loadContact( contact );
}

void ContactEditorDialog::slotOkClicked()
{
  mEditor->saveContact();

  accept();
}

void ContactEditorDialog::slotCancelClicked()
{
  reject();
}

#include "contacteditordialog.moc"
<|endoftext|>


<commit_before>#include "Input/InputHandler.hpp"
#include <SFML/Graphics.hpp>
#include <cmath>
#include <iostream>

InputHandler::InputHandler(sf::RenderWindow *window)
: m_window{window}
, m_lastMousePos{ 0, 0 }
, m_rightMouseClickState{ 0 }
{

}

void InputHandler::handleInput(QueueHelper<Input> &inputQueue)
{
    handleEvents(inputQueue);
    handleRealTimeInput(inputQueue);
}

void InputHandler::handleEvents(QueueHelper<Input> &inputQueue)
{
    sf::Event event;
    while (m_window->pollEvent(event))
    {
        if (event.type == sf::Event::Closed)
        {
            m_window->close();
        }
        else if (event.type == sf::Event::Resized)
        {
            // update the view to the new size of the window
            sf::FloatRect visibleArea(0, 0, event.size.width, event.size.height);
            m_window->setView(sf::View(visibleArea));
        }
        else if (event.type == sf::Event::LostFocus)
        {
            // Do nothing at the moment
        }
        else if (event.type == sf::Event::GainedFocus)
        {
            // Do nothing at the moment
        }
        else if (event.type == sf::Event::KeyPressed)
        {
            if (event.key.code == sf::Keyboard::F1)
            {
                inputQueue.push({ InputTypes::D1 });
            }
            else if (event.key.code == sf::Keyboard::F2)
            {
                inputQueue.push({ InputTypes::D2 });
            }
            else if (event.key.code == sf::Keyboard::F3)
            {
                inputQueue.push({ InputTypes::D3 });
            }
            else if (event.key.code == sf::Keyboard::F4)
            {
                inputQueue.push({ InputTypes::D4 });
            }

        }
        else if (event.type == sf::Event::MouseButtonPressed)
        {
            if (event.mouseButton.button == sf::Mouse::Left)
            {
                inputQueue.push({ InputTypes::LEFT_CLICK });
            }
        }

    }
}

void InputHandler::handleRealTimeInput(QueueHelper<Input> &inputQueue)
{
    const sf::Vector2i CurrentMousePos = { sf::Mouse::getPosition(*m_window) };

    inputQueue.push({ InputTypes::CURSOR_POS, static_cast<sf::Vector2f>(CurrentMousePos) });
    /*
    if (CurrentMousePos != m_lastMousePos)
    {
        const sf::Vector2i WindowCenter(static_cast<int>(m_window->getSize().x / 2), static_cast<int>(m_window->getSize().y / 2));
        const sf::Vector2i TranslatedMousePos = { CurrentMousePos - WindowCenter };
        const sf::Vector2f TranslatedMousePosF(static_cast<sf::Vector2f>(TranslatedMousePos));
        inputQueue.push({ InputTypes::TRANSLATED_CURSOR_POS, TranslatedMousePosF });

    }
    */

    if (sf::Keyboard::isKeyPressed(sf::Keyboard::W) && sf::Keyboard::isKeyPressed(sf::Keyboard::A))
    {
        inputQueue.push({ InputTypes::UP_LEFT });
    }
    else if(sf::Keyboard::isKeyPressed(sf::Keyboard::W) && sf::Keyboard::isKeyPressed(sf::Keyboard::D))
    {
        inputQueue.push({ InputTypes::UP_RIGHT });
    }
    else if(sf::Keyboard::isKeyPressed(sf::Keyboard::S) && sf::Keyboard::isKeyPressed(sf::Keyboard::A))
    {
        inputQueue.push({ InputTypes::DOWN_LEFT });
    }
    else if(sf::Keyboard::isKeyPressed(sf::Keyboard::S) && sf::Keyboard::isKeyPressed(sf::Keyboard::D))
    {
        inputQueue.push({ InputTypes::DOWN_RIGHT });
    }
    // Dont handle W A S D separately, when there are pairs like W+A or W+D or S+A or S+D
    else
    {
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
        {
            inputQueue.push({ InputTypes::UP });
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::S))
        {
            inputQueue.push({ InputTypes::DOWN });
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
        {
            inputQueue.push({ InputTypes::LEFT });
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
        {
            inputQueue.push({ InputTypes::RIGHT });
        }
    }

    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
    {
        inputQueue.push({ InputTypes::UP_A });
    }
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
    {
        inputQueue.push({ InputTypes::DOWN_A });
    }
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
    {
        inputQueue.push({ InputTypes::LEFT_A });
    }
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
    {
        inputQueue.push({ InputTypes::RIGHT_A });
    }
    handleRealTimeRightClick(inputQueue);

    m_lastMousePos.x = CurrentMousePos.x;
    m_lastMousePos.y = CurrentMousePos.y;
}

void InputHandler::handleRealTimeRightClick(QueueHelper<Input> &inputQueue)
{
    bool isPressed = { sf::Mouse::isButtonPressed(sf::Mouse::Right) };
    // Left mouse key was not pressed and is not pressed (start pressing)
    if (isPressed && m_rightMouseClickState == 0)
    {
        m_rightMouseClickState = 1;
        inputQueue.push({ InputTypes::RIGHT_CLICK_START });
    }
    // Left mouse key was pressed and is still pressed (still pressing)
    else if (isPressed && m_rightMouseClickState == 1)
    {
        m_rightMouseClickState = 2;
        inputQueue.push({ InputTypes::RIGHT_CLICK_STILL });
    }
    // Left mouse key was pressed and is not pressed anymore(stop pressing)
    else if (!isPressed && m_rightMouseClickState == 2)
    {
        m_rightMouseClickState = 3;
        inputQueue.push({ InputTypes::RIGHT_CLICK_STOPED });
    }
    // Left mouse key was not pressed and is not pressed at the moment
    else if (!isPressed && m_rightMouseClickState == 3)
    {
        m_rightMouseClickState = 0;
    }
}
<commit_msg>Add window resize functionality<commit_after>#include "Input/InputHandler.hpp"
#include <SFML/Graphics.hpp>
#include <cmath>
#include <iostream>

InputHandler::InputHandler(sf::RenderWindow *window)
: m_window{window}
, m_lastMousePos{ 0, 0 }
, m_rightMouseClickState{ 0 }
{

}

void InputHandler::handleInput(QueueHelper<Input> &inputQueue)
{
    handleEvents(inputQueue);
    handleRealTimeInput(inputQueue);
}

void InputHandler::handleEvents(QueueHelper<Input> &inputQueue)
{
    sf::Event event;
    while (m_window->pollEvent(event))
    {
        if (event.type == sf::Event::Closed)
        {
            m_window->close();
        }
        else if (event.type == sf::Event::Resized)
        {
            // update the view to the new size of the window
            sf::FloatRect visibleArea(0, 0, event.size.width, event.size.height);
            sf::View view(visibleArea);
            //view.zoom(0.5f);
            m_window->setView(view);

        }
        else if (event.type == sf::Event::LostFocus)
        {
            // Do nothing at the moment
        }
        else if (event.type == sf::Event::GainedFocus)
        {
            // Do nothing at the moment
        }
        else if (event.type == sf::Event::KeyPressed)
        {
            if (event.key.code == sf::Keyboard::F1)
            {
                inputQueue.push({ InputTypes::D1 });
            }
            else if (event.key.code == sf::Keyboard::F2)
            {
                inputQueue.push({ InputTypes::D2 });
            }
            else if (event.key.code == sf::Keyboard::F3)
            {
                inputQueue.push({ InputTypes::D3 });
            }
            else if (event.key.code == sf::Keyboard::F4)
            {
                inputQueue.push({ InputTypes::D4 });
            }

        }
        else if (event.type == sf::Event::MouseButtonPressed)
        {
            if (event.mouseButton.button == sf::Mouse::Left)
            {
                inputQueue.push({ InputTypes::LEFT_CLICK });
            }
        }

    }
}

void InputHandler::handleRealTimeInput(QueueHelper<Input> &inputQueue)
{
    const sf::Vector2i CurrentMousePos = { sf::Mouse::getPosition(*m_window) };

    inputQueue.push({ InputTypes::CURSOR_POS, static_cast<sf::Vector2f>(CurrentMousePos) });
    /*
    if (CurrentMousePos != m_lastMousePos)
    {
        const sf::Vector2i WindowCenter(static_cast<int>(m_window->getSize().x / 2), static_cast<int>(m_window->getSize().y / 2));
        const sf::Vector2i TranslatedMousePos = { CurrentMousePos - WindowCenter };
        const sf::Vector2f TranslatedMousePosF(static_cast<sf::Vector2f>(TranslatedMousePos));
        inputQueue.push({ InputTypes::TRANSLATED_CURSOR_POS, TranslatedMousePosF });

    }
    */

    if (sf::Keyboard::isKeyPressed(sf::Keyboard::W) && sf::Keyboard::isKeyPressed(sf::Keyboard::A))
    {
        inputQueue.push({ InputTypes::UP_LEFT });
    }
    else if(sf::Keyboard::isKeyPressed(sf::Keyboard::W) && sf::Keyboard::isKeyPressed(sf::Keyboard::D))
    {
        inputQueue.push({ InputTypes::UP_RIGHT });
    }
    else if(sf::Keyboard::isKeyPressed(sf::Keyboard::S) && sf::Keyboard::isKeyPressed(sf::Keyboard::A))
    {
        inputQueue.push({ InputTypes::DOWN_LEFT });
    }
    else if(sf::Keyboard::isKeyPressed(sf::Keyboard::S) && sf::Keyboard::isKeyPressed(sf::Keyboard::D))
    {
        inputQueue.push({ InputTypes::DOWN_RIGHT });
    }
    // Dont handle W A S D separately, when there are pairs like W+A or W+D or S+A or S+D
    else
    {
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
        {
            inputQueue.push({ InputTypes::UP });
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::S))
        {
            inputQueue.push({ InputTypes::DOWN });
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
        {
            inputQueue.push({ InputTypes::LEFT });
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
        {
            inputQueue.push({ InputTypes::RIGHT });
        }
    }

    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
    {
        inputQueue.push({ InputTypes::UP_A });
    }
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
    {
        inputQueue.push({ InputTypes::DOWN_A });
    }
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
    {
        inputQueue.push({ InputTypes::LEFT_A });
    }
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
    {
        inputQueue.push({ InputTypes::RIGHT_A });
    }
    handleRealTimeRightClick(inputQueue);

    m_lastMousePos.x = CurrentMousePos.x;
    m_lastMousePos.y = CurrentMousePos.y;
}

void InputHandler::handleRealTimeRightClick(QueueHelper<Input> &inputQueue)
{
    bool isPressed = { sf::Mouse::isButtonPressed(sf::Mouse::Right) };
    // Left mouse key was not pressed and is not pressed (start pressing)
    if (isPressed && m_rightMouseClickState == 0)
    {
        m_rightMouseClickState = 1;
        inputQueue.push({ InputTypes::RIGHT_CLICK_START });
    }
    // Left mouse key was pressed and is still pressed (still pressing)
    else if (isPressed && m_rightMouseClickState == 1)
    {
        m_rightMouseClickState = 2;
        inputQueue.push({ InputTypes::RIGHT_CLICK_STILL });
    }
    // Left mouse key was pressed and is not pressed anymore(stop pressing)
    else if (!isPressed && m_rightMouseClickState == 2)
    {
        m_rightMouseClickState = 3;
        inputQueue.push({ InputTypes::RIGHT_CLICK_STOPED });
    }
    // Left mouse key was not pressed and is not pressed at the moment
    else if (!isPressed && m_rightMouseClickState == 3)
    {
        m_rightMouseClickState = 0;
    }
}
<|endoftext|>


<commit_before>// GradMinimizer: test RooGradMinimizer class
//
// call from command line like, for instance:
// root -l 'GradMinimizer.cpp()'

// R__LOAD_LIBRARY(libRooFit)

#include <iostream>
// #include <exception>

using namespace RooFit;

void GradMinimizer() {
  // produce the same random stuff every time
  gRandom->SetSeed(1);

  RooWorkspace w = RooWorkspace();

  w.factory("Gaussian::g(x[-5,5],mu[-3,3],sigma[1])");

  auto x = w.var("x");
  RooAbsPdf * pdf = w.pdf("g");
  RooRealVar * mu = w.var("mu");

  RooDataSet * data = pdf->generate(RooArgSet(*x), 10000);
  mu->setVal(-2.9);

  auto nll = pdf->createNLL(*data);

  // save initial values for the start of all minimizations
  RooArgSet values = RooArgSet(*mu, *pdf, *nll);

  RooArgSet* savedValues = dynamic_cast<RooArgSet*>(values.snapshot());
  if (savedValues == nullptr) {
    throw std::runtime_error("params->snapshot() cannot be casted to RooArgSet!");
  }

  // --------

  RooWallTimer wtimer;
  // RooCPUTimer ctimer

  // --------

  std::cout << "trying nominal calculation" << std::endl;

  RooMinimizer m0(*nll);
  m0.setMinimizerType("Minuit2");

  m0.setStrategy(0);
  // m0.setVerbose();
  m0.setPrintLevel(0);

  wtimer.start();
  m0.migrad();
  wtimer.stop();

  std::cout << "  -- nominal calculation wall clock time:        " << wtimer.timing_s() << "s" << std::endl;

  // m0.hesse();

  // m0.minos();

  // --------

  std::cout << "\n === reset initial values === \n" << std::endl;
  values = *savedValues;

  // --------

  std::cout << "trying GradMinimizer" << std::endl;

  RooGradMinimizer m1(*nll);

  m1.setStrategy(0);
  // m1.setVerbose();
  m1.setPrintLevel(0);

  wtimer.start();
  m1.migrad();
  wtimer.stop();

  std::cout << "  -- GradMinimizer calculation wall clock time:  " << wtimer.timing_s() << "s" << std::endl;

  // std::cout << "run hesse" << std::endl;
  // m1.hesse();
  // std::cout << "hesse done" << std::endl;

  // m1.minos();
  // std::cout << "minos done" << std::endl;

  // std::cout << std::endl << std::endl;
  // values.Print("v");
  // mu->Print("v");
  // std::cout << std::endl << std::endl;

  // --------

  std::cout << "\n === reset initial values === \n" << std::endl;
  values = *savedValues;

  // --------

  std::cout << "trying nominal calculation AGAIN" << std::endl;

  RooMinimizer m2(*nll);
  m2.setMinimizerType("Minuit2");

  m2.setStrategy(0);
  // m2.setVerbose();
  m2.setPrintLevel(0);

  wtimer.start();
  m2.migrad();
  wtimer.stop();

  std::cout << "  -- second nominal calculation wall clock time: " << wtimer.timing_s() << "s" << std::endl;

  // m2.hesse();

  // m2.minos();

}
<commit_msg>Small modifications<commit_after>// GradMinimizer: test RooGradMinimizer class
//
// call from command line like, for instance:
// root -l 'GradMinimizer.cpp()'

// R__LOAD_LIBRARY(libRooFit)
#pragma cling load("libRooFit")

#include <iostream>
// #include <exception>

using namespace RooFit;

void GradMinimizer() {
  // produce the same random stuff every time
  gRandom->SetSeed(1);

  RooWorkspace w = RooWorkspace();

  w.factory("Gaussian::g(x[-5,5],mu[0,-3,3],sigma[1])");

  auto x = w.var("x");
  RooAbsPdf * pdf = w.pdf("g");
  RooRealVar * mu = w.var("mu");

  RooDataSet * data = pdf->generate(RooArgSet(*x), 10000);
  mu->setVal(-2.9);
  // mu->setError(0.1);

  auto nll = pdf->createNLL(*data);

  // save initial values for the start of all minimizations
  RooArgSet values = RooArgSet(*mu, *pdf, *nll);

  RooArgSet* savedValues = dynamic_cast<RooArgSet*>(values.snapshot());
  if (savedValues == nullptr) {
    throw std::runtime_error("params->snapshot() cannot be casted to RooArgSet!");
  }

  // --------

  RooWallTimer wtimer;
  // RooCPUTimer ctimer

  // --------

  std::cout << "trying nominal calculation" << std::endl;

  RooMinimizer m0(*nll);
  m0.setMinimizerType("Minuit2");

  m0.setStrategy(0);
  // m0.setVerbose();
  m0.setPrintLevel(0);

  wtimer.start();
  m0.migrad();
  wtimer.stop();

  std::cout << "  -- nominal calculation wall clock time:        " << wtimer.timing_s() << "s" << std::endl;

  // m0.hesse();

  // m0.minos();

  std::cout << " ====================================== " << std::endl;
  // --------

  std::cout << " ======== reset initial values ======== " << std::endl;
  values = *savedValues;

  // --------
  std::cout << " ====================================== " << std::endl;

  std::cout << "trying GradMinimizer" << std::endl;

  RooGradMinimizer m1(*nll);

  m1.setStrategy(0);
  // m1.setVerbose();
  m1.setPrintLevel(0);

  wtimer.start();
  m1.migrad();
  wtimer.stop();

  std::cout << "  -- GradMinimizer calculation wall clock time:  " << wtimer.timing_s() << "s" << std::endl;

  // std::cout << "run hesse" << std::endl;
  // m1.hesse();
  // std::cout << "hesse done" << std::endl;

  // m1.minos();
  // std::cout << "minos done" << std::endl;

  // std::cout << std::endl << std::endl;
  // values.Print("v");
  // mu->Print("v");
  // std::cout << std::endl << std::endl;

  // --------

  // std::cout << "\n === reset initial values === \n" << std::endl;
  // values = *savedValues;

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

  // std::cout << "trying nominal calculation AGAIN" << std::endl;

  // RooMinimizer m2(*nll);
  // m2.setMinimizerType("Minuit2");

  // m2.setStrategy(0);
  // // m2.setVerbose();
  // m2.setPrintLevel(0);

  // wtimer.start();
  // m2.migrad();
  // wtimer.stop();

  // std::cout << "  -- second nominal calculation wall clock time: " << wtimer.timing_s() << "s" << std::endl;

  // m2.hesse();

  // m2.minos();

}
<|endoftext|>