<commit_before>// Copyright (c) 2017 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/

#include <iostream>
#include <string>
#include <type_traits>
#include <typeinfo>
#include <vector>

#include <tao/pegtl.hpp>

using namespace tao::TAOCPP_PEGTL_NAMESPACE;

namespace parse_tree
{
   template< typename >
   struct store_simple : std::false_type
   {
   };

   template< typename >
   struct store_content : std::false_type
   {
   };

   struct node
   {
      std::vector< std::unique_ptr< node > > children;
      const std::type_info* id = nullptr;
      const char* begin = nullptr;
      const char* end = nullptr;
   };

   struct state
   {
      std::vector< std::unique_ptr< node > > stack;

      state()
      {
         emplace_back();
      }

      const node& root() const
      {
         return *stack.front();
      }

      void emplace_back()
      {
         std::unique_ptr< node > r( new node );
         stack.emplace_back( std::move( r ) );
      }
   };

   template< typename Rule, bool = store_simple< Rule >::value, bool = store_content< Rule >::value >
   struct builder_impl;

   template< typename Rule >
   struct builder : builder_impl< Rule >
   {
   };

   template< typename Rule >
   struct builder_impl< Rule, false, false >
      : normal< Rule >
   {
   };

   template< typename Rule >
   struct builder_impl< Rule, true, true >
      : normal< Rule >
   {
      static_assert( sizeof( Rule ) == 0, "error: both store_simple and store_content are set" );
   };

   template< typename Rule >
   struct builder_impl< Rule, true, false >
      : normal< Rule >
   {
      template< typename Input >
      static void start( const Input&, state& s )
      {
         s.emplace_back();
      }

      template< typename Input >
      static void success( const Input&, state& s )
      {
         auto n = std::move( s.stack.back() );
         n->id = &typeid( Rule );
         s.stack.pop_back();
         s.stack.back()->children.emplace_back( std::move( n ) );
      }

      template< typename Input >
      static void failure( const Input&, state& s )
      {
         s.stack.pop_back();
      }
   };

   template< typename Rule >
   struct builder_impl< Rule, false, true >
      : normal< Rule >
   {
      template< typename Input >
      static void start( const Input& in, state& s )
      {
         s.emplace_back();
         s.stack.back()->begin = in.current();
      }

      template< typename Input >
      static void success( const Input& in, state& s )
      {
         auto n = std::move( s.stack.back() );
         n->id = &typeid( Rule );
         n->end = in.current();
         s.stack.pop_back();
         s.stack.back()->children.emplace_back( std::move( n ) );
      }

      template< typename Input >
      static void failure( const Input&, state& s )
      {
         s.stack.pop_back();
      }
   };

   void print_node( const node& n, const std::string& s = "" )
   {
      if( n.id ) {
         if( n.begin ) {
            std::cout << s << internal::demangle( n.id->name() ) << " \"" << std::string( n.begin, n.end ) << '"' << std::endl;
         }
         else {
            std::cout << s << internal::demangle( n.id->name() ) << std::endl;
         }
      }
      else {
         std::cout << "ROOT" << std::endl;
      }
      if( !n.children.empty() ) {
         const auto s2 = s + "  ";
         for( auto& up : n.children ) {
            print_node( *up, s2 );
         }
      }
   }

   // clang-format off
   struct integer : plus< digit > {};
   struct variable : identifier {};

   struct plus : pad< one< '+' >, space > {};
   struct minus : pad< one< '-' >, space > {};
   struct multiply : pad< one< '*' >, space > {};
   struct divide : pad< one< '/' >, space > {};

   struct open_bracket : seq< one< '(' >, star< space > > {};
   struct close_bracket : seq< star< space >, one< ')' > > {};

   struct expression;
   struct bracketed : seq< open_bracket, expression, close_bracket > {};
   struct value : sor< integer, variable, bracketed > {};
   struct product : list< value, sor< multiply, divide > > {};
   struct expression : list< product, sor< plus, minus > > {};

   struct grammar : must< expression, eof > {};

   template<> struct store_content< integer > : std::true_type {};
   template<> struct store_content< variable > : std::true_type {};
   template<> struct store_simple< plus > : std::true_type {};
   template<> struct store_simple< minus > : std::true_type {};
   template<> struct store_simple< multiply > : std::true_type {};
   template<> struct store_simple< divide > : std::true_type {};
   template<> struct store_simple< bracketed > : std::true_type {};
   template<> struct store_simple< product > : std::true_type {};
   template<> struct store_simple< expression > : std::true_type {};
   // clang-format on

}  // namespace parse_tree

int main( int argc, char** argv )
{
   for( int i = 1; i < argc; ++i ) {
      argv_input<> in( argv, i );

      parse_tree::state s;
      parse< parse_tree::grammar, nothing, parse_tree::builder >( in, s );
      print_node( s.root() );
   }
   return 0;
}
<commit_msg>Use actions to simplify/transform the parse tree<commit_after>// Copyright (c) 2017 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/

#include <iostream>
#include <string>
#include <type_traits>
#include <typeinfo>
#include <vector>

#include <tao/pegtl.hpp>

using namespace tao::TAOCPP_PEGTL_NAMESPACE;

namespace parse_tree
{
   template< typename >
   struct store_simple : std::false_type
   {
   };

   template< typename >
   struct store_content : std::false_type
   {
   };

   struct node
   {
      std::vector< std::unique_ptr< node > > children;
      const std::type_info* id = nullptr;
      const char* begin = nullptr;
      const char* end = nullptr;
   };

   struct state
   {
      std::vector< std::unique_ptr< node > > stack;

      state()
      {
         emplace_back();
      }

      const node& root() const
      {
         return *stack.front();
      }

      void emplace_back()
      {
         std::unique_ptr< node > r( new node );
         stack.emplace_back( std::move( r ) );
      }
   };

   template< typename Rule, bool = store_simple< Rule >::value, bool = store_content< Rule >::value >
   struct builder_impl;

   template< typename Rule >
   struct builder : builder_impl< Rule >
   {
   };

   template< typename Rule >
   struct builder_impl< Rule, false, false >
      : normal< Rule >
   {
   };

   template< typename Rule >
   struct builder_impl< Rule, true, true >
      : normal< Rule >
   {
      static_assert( sizeof( Rule ) == 0, "error: both store_simple and store_content are set" );
   };

   template< typename Rule >
   struct builder_impl< Rule, true, false >
      : normal< Rule >
   {
      template< typename Input >
      static void start( const Input&, state& s )
      {
         s.emplace_back();
      }

      template< typename Input >
      static void success( const Input&, state& s )
      {
         auto n = std::move( s.stack.back() );
         n->id = &typeid( Rule );
         s.stack.pop_back();
         s.stack.back()->children.emplace_back( std::move( n ) );
      }

      template< typename Input >
      static void failure( const Input&, state& s )
      {
         s.stack.pop_back();
      }
   };

   template< typename Rule >
   struct action
      : nothing< Rule >
   {
   };

   template< typename Rule >
   struct builder_impl< Rule, false, true >
      : normal< Rule >
   {
      template< typename Input >
      static void start( const Input& in, state& s )
      {
         s.emplace_back();
         s.stack.back()->begin = in.current();
      }

      template< typename Input >
      static void success( const Input& in, state& s )
      {
         auto n = std::move( s.stack.back() );
         n->id = &typeid( Rule );
         n->end = in.current();
         s.stack.pop_back();
         s.stack.back()->children.emplace_back( std::move( n ) );
      }

      template< typename Input >
      static void failure( const Input&, state& s )
      {
         s.stack.pop_back();
      }
   };

   void print_node( const node& n, const std::string& s = "" )
   {
      if( n.id ) {
         if( n.begin ) {
            std::cout << s << internal::demangle( n.id->name() ) << " \"" << std::string( n.begin, n.end ) << '"' << std::endl;
         }
         else {
            std::cout << s << internal::demangle( n.id->name() ) << std::endl;
         }
      }
      else {
         std::cout << "ROOT" << std::endl;
      }
      if( !n.children.empty() ) {
         const auto s2 = s + "  ";
         for( auto& up : n.children ) {
            print_node( *up, s2 );
         }
      }
   }

   // clang-format off
   struct integer : plus< digit > {};
   struct variable : identifier {};

   struct plus : pad< one< '+' >, space > {};
   struct minus : pad< one< '-' >, space > {};
   struct multiply : pad< one< '*' >, space > {};
   struct divide : pad< one< '/' >, space > {};

   struct open_bracket : seq< one< '(' >, star< space > > {};
   struct close_bracket : seq< star< space >, one< ')' > > {};

   struct expression;
   struct bracketed : seq< open_bracket, expression, close_bracket > {};
   struct value : sor< integer, variable, bracketed > {};
   struct product : list< value, sor< multiply, divide > > {};
   struct expression : list< product, sor< plus, minus > > {};

   struct grammar : must< expression, eof > {};

   // select which rules in the grammar will produce parse tree nodes
   template<> struct store_content< integer > : std::true_type {};
   template<> struct store_content< variable > : std::true_type {};
   template<> struct store_simple< plus > : std::true_type {};
   template<> struct store_simple< minus > : std::true_type {};
   template<> struct store_simple< multiply > : std::true_type {};
   template<> struct store_simple< divide > : std::true_type {};
   template<> struct store_simple< product > : std::true_type {};
   template<> struct store_simple< expression > : std::true_type {};
   // clang-format on

   // use actions to transform the parse tree in order to simplify it
   template<>
   struct action< product >
   {
      template< typename Input >
      static void apply( const Input&, state& s )
      {
         auto& n = s.stack.back()->children.back();
         if( n->children.size() == 1 ) {
            n = std::move( n->children.back() );
         }
      }
   };

}  // namespace parse_tree

int main( int argc, char** argv )
{
   for( int i = 1; i < argc; ++i ) {
      argv_input<> in( argv, i );

      parse_tree::state s;
      parse< parse_tree::grammar, parse_tree::action, parse_tree::builder >( in, s );
      print_node( s.root() );
   }
   return 0;
}
<|endoftext|>


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

//
// MapCell.cpp
//
#include "StdAfx.h"

MapCell::~MapCell()
{
	RemoveObjects();
}

void MapCell::Init(uint32 x, uint32 y, uint32 mapid, MapMgr *mapmgr)
{
	_mapmgr = mapmgr;
	_active = false;
	_loaded = false;
	_playerCount = 0;
	_x=x;
	_y=y;
	_unloadpending=false;
	_objects.clear();
}

void MapCell::AddObject(Object *obj)
{
	if(obj->IsPlayer())
		++_playerCount;

	_objects.insert(obj);
}

void MapCell::RemoveObject(Object *obj)
{
	if(obj->IsPlayer())
		--_playerCount;

	_objects.erase(obj);
}

void MapCell::SetActivity(bool state)
{
	if(!_active && state)
	{
		// Move all objects to active set.
		for(ObjectSet::iterator itr = _objects.begin(); itr != _objects.end(); ++itr)
		{
			if(!(*itr)->Active && (*itr)->CanActivate())
				(*itr)->Activate(_mapmgr);
		}

		if(_unloadpending)
			CancelPendingUnload();

		if (sWorld.Collision) {
			CollideInterface.ActivateTile(_mapmgr->GetMapId(), _x/8, _y/8);
		}
	} else if(_active && !state)
	{
		// Move all objects from active set.
		for(ObjectSet::iterator itr = _objects.begin(); itr != _objects.end(); ++itr)
		{
			if((*itr)->Active)
				(*itr)->Deactivate(_mapmgr);
		}

		if(sWorld.map_unload_time && !_unloadpending)
			QueueUnloadPending();

		if (sWorld.Collision) {
			CollideInterface.DeactivateTile(_mapmgr->GetMapId(), _x/8, _y/8);
		}
	}

	_active = state;

}
void MapCell::RemoveObjects()
{
	ObjectSet::iterator itr;
	uint32 count = 0;
	//uint32 ltime = getMSTime();

	/* delete objects in pending respawn state */
	for(itr = _respawnObjects.begin(); itr != _respawnObjects.end(); ++itr)
	{
		switch((*itr)->GetTypeId())
		{
		case TYPEID_UNIT: {
				if( !(*itr)->IsPet() )
				{
					_mapmgr->_reusable_guids_creature.push_back( (*itr)->GetUIdFromGUID() );
					static_cast< Creature* >( *itr )->m_respawnCell=NULL;
					delete static_cast< Creature* >( *itr );
				}
			}break;

		case TYPEID_GAMEOBJECT: {
			_mapmgr->_reusable_guids_gameobject.push_back( (*itr)->GetUIdFromGUID() );
			static_cast< GameObject* >( *itr )->m_respawnCell=NULL;
			delete static_cast< GameObject* >( *itr );
			}break;
		}
	}
	_respawnObjects.clear();

	//This time it's simpler! We just remove everything :)
	for(itr = _objects.begin(); itr != _objects.end(); )
	{
		count++;

		Object *obj = (*itr);

		itr++;

		if(!obj)
			continue;

		if( _unloadpending )
		{
			if(obj->GetTypeFromGUID() == HIGHGUID_TYPE_TRANSPORTER)
				continue;

			if(obj->GetTypeId()==TYPEID_CORPSE && obj->GetUInt32Value(CORPSE_FIELD_OWNER) != 0)
				continue;

			if(!obj->m_loadedFromDB)
				continue;
		}

		if( obj->Active )
			obj->Deactivate( _mapmgr );

		if( obj->IsInWorld() )
			obj->RemoveFromWorld( true );

		delete obj;
	}
	_objects.clear();

	_playerCount = 0;
	_loaded = false;
}

void MapCell::LoadObjects(CellSpawns * sp)
{
	_loaded = true;
	Instance * pInstance = _mapmgr->pInstance;
	InstanceBossInfoMap *bossInfoMap = objmgr.m_InstanceBossInfoMap[_mapmgr->GetMapId()];

	if(sp->CreatureSpawns.size())//got creatures
	{
		for(CreatureSpawnList::iterator i=sp->CreatureSpawns.begin();i!=sp->CreatureSpawns.end();i++)
		{
			uint32 respawnTimeOverride = 0;
			if(pInstance)
			{
				if(bossInfoMap != NULL && IS_PERSISTENT_INSTANCE(pInstance))
				{
					bool skip = false;
					for(std::set<uint32>::iterator killedNpc = pInstance->m_killedNpcs.begin(); killedNpc != pInstance->m_killedNpcs.end(); ++killedNpc)
					{
						// Do not spawn the killed boss.
						if((*killedNpc) == (*i)->entry)
						{
							skip = true;
							break;
						}
						// Do not spawn the killed boss' trash.
						InstanceBossInfoMap::const_iterator bossInfo = bossInfoMap->find((*killedNpc));
						if (bossInfo != bossInfoMap->end() && bossInfo->second->trash.find((*i)->id) != bossInfo->second->trash.end())
						{
							skip = true;
							break;
						}
					}
					if(skip)
						continue;

					for(InstanceBossInfoMap::iterator bossInfo = bossInfoMap->begin(); bossInfo != bossInfoMap->end(); ++bossInfo)
					{
						if(pInstance->m_killedNpcs.find(bossInfo->second->creatureid) == pInstance->m_killedNpcs.end() && bossInfo->second->trash.find((*i)->id) != bossInfo->second->trash.end())
						{
							respawnTimeOverride = bossInfo->second->trashRespawnOverride;
						}
					}
				}
				else
				{
					// No boss information available ... fallback ...
					if(pInstance->m_killedNpcs.find((*i)->id) != pInstance->m_killedNpcs.end())
						continue;
				}
			}

			Creature * c=_mapmgr->CreateCreature((*i)->entry);

			c->SetMapId(_mapmgr->GetMapId());
			c->SetInstanceID(_mapmgr->GetInstanceID());
			c->m_loadedFromDB = true;
			if(respawnTimeOverride > 0)
				c->m_respawnTimeOverride = respawnTimeOverride;

            if(c->Load(*i, _mapmgr->iInstanceMode, _mapmgr->GetMapInfo()))
			{
				if(!c->CanAddToWorld())
					delete c;

				c->PushToWorld(_mapmgr);
			}
			else
				delete c;//missing proto or smth of that kind
		}
	}

	if(sp->GOSpawns.size())//got GOs
	{
		for(GOSpawnList::iterator i=sp->GOSpawns.begin();i!=sp->GOSpawns.end();i++)
		{
			GameObject * go=_mapmgr->CreateGameObject((*i)->entry);
			go->SetInstanceID(_mapmgr->GetInstanceID());
			if(go->Load(*i))
			{
				//uint32 state = go->GetUInt32Value(GAMEOBJECT_STATE);

				// FIXME - burlex
				/*
				if(pInstance && pInstance->FindObject((*i)->stateNpcLink))
				{
					go->SetUInt32Value(GAMEOBJECT_STATE, (state ? 0 : 1));
				}*/

				go->m_loadedFromDB = true;
				go->PushToWorld(_mapmgr);
			}
			else
				delete go;//missing proto or smth of that kind
		}
	}
}

void MapCell::QueueUnloadPending()
{
	if(_unloadpending)
		return;

	_unloadpending = true;
	//Log.Debug("MapCell", "Queueing pending unload of cell %u %u", _x, _y);
	sEventMgr.AddEvent(_mapmgr, &MapMgr::UnloadCell,(uint32)_x,(uint32)_y,MAKE_CELL_EVENT(_x,_y),sWorld.map_unload_time * 1000,1,0);
}

void MapCell::CancelPendingUnload()
{
	//Log.Debug("MapCell", "Cancelling pending unload of cell %u %u", _x, _y);
	if(!_unloadpending)
		return;

	sEventMgr.RemoveEvents(_mapmgr,MAKE_CELL_EVENT(_x,_y));
}

void MapCell::Unload()
{
	//Log.Debug("MapCell", "Unloading cell %u %u", _x, _y);
	ASSERT(_unloadpending);
	if(_active)
		return;

	RemoveObjects();
	_unloadpending=false;
}
<commit_msg>Crashfix by 0x0f7afc68<commit_after>/*
 * ArcEmu MMORPG Server
 * Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/>
 * Copyright (C) 2008 <http://www.ArcEmu.org/>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

//
// MapCell.cpp
//
#include "StdAfx.h"

MapCell::~MapCell()
{
	RemoveObjects();
}

void MapCell::Init(uint32 x, uint32 y, uint32 mapid, MapMgr *mapmgr)
{
	_mapmgr = mapmgr;
	_active = false;
	_loaded = false;
	_playerCount = 0;
	_x=x;
	_y=y;
	_unloadpending=false;
	_objects.clear();
}

void MapCell::AddObject(Object *obj)
{
	if(obj->IsPlayer())
		++_playerCount;

	_objects.insert(obj);
}

void MapCell::RemoveObject(Object *obj)
{
	if(obj->IsPlayer())
		--_playerCount;

	_objects.erase(obj);
}

void MapCell::SetActivity(bool state)
{
	if(!_active && state)
	{
		// Move all objects to active set.
		for(ObjectSet::iterator itr = _objects.begin(); itr != _objects.end(); ++itr)
		{
			if(!(*itr)->Active && (*itr)->CanActivate())
				(*itr)->Activate(_mapmgr);
		}

		if(_unloadpending)
			CancelPendingUnload();

		if (sWorld.Collision) {
			CollideInterface.ActivateTile(_mapmgr->GetMapId(), _x/8, _y/8);
		}
	} else if(_active && !state)
	{
		// Move all objects from active set.
		for(ObjectSet::iterator itr = _objects.begin(); itr != _objects.end(); ++itr)
		{
			if((*itr)->Active)
				(*itr)->Deactivate(_mapmgr);
		}

		if(sWorld.map_unload_time && !_unloadpending)
			QueueUnloadPending();

		if (sWorld.Collision) {
			CollideInterface.DeactivateTile(_mapmgr->GetMapId(), _x/8, _y/8);
		}
	}

	_active = state;

}
void MapCell::RemoveObjects()
{
	ObjectSet::iterator itr;
	uint32 count = 0;
	//uint32 ltime = getMSTime();

	/* delete objects in pending respawn state */
	for(itr = _respawnObjects.begin(); itr != _respawnObjects.end(); ++itr)
	{
		switch((*itr)->GetTypeId())
		{
		case TYPEID_UNIT: {
				if( !(*itr)->IsPet() )
				{
					_mapmgr->_reusable_guids_creature.push_back( (*itr)->GetUIdFromGUID() );
					static_cast< Creature* >( *itr )->m_respawnCell=NULL;
					delete static_cast< Creature* >( *itr );
				}
			}break;

		case TYPEID_GAMEOBJECT: {
			_mapmgr->_reusable_guids_gameobject.push_back( (*itr)->GetUIdFromGUID() );
			static_cast< GameObject* >( *itr )->m_respawnCell=NULL;
			delete static_cast< GameObject* >( *itr );
			}break;
		}
	}
	_respawnObjects.clear();

	//This time it's simpler! We just remove everything :)
	for(itr = _objects.begin(); itr != _objects.end(); )
	{
		count++;

		Object *obj = (*itr);

		itr++;

		if(!obj || _unloadpending)
			continue;

		if( obj->Active )
			obj->Deactivate( _mapmgr );

		if( obj->IsInWorld() )
			obj->RemoveFromWorld( true );

		delete obj;
	}
	_objects.clear();

	_playerCount = 0;
	_loaded = false;
}

void MapCell::LoadObjects(CellSpawns * sp)
{
	_loaded = true;
	Instance * pInstance = _mapmgr->pInstance;
	InstanceBossInfoMap *bossInfoMap = objmgr.m_InstanceBossInfoMap[_mapmgr->GetMapId()];

	if(sp->CreatureSpawns.size())//got creatures
	{
		for(CreatureSpawnList::iterator i=sp->CreatureSpawns.begin();i!=sp->CreatureSpawns.end();i++)
		{
			uint32 respawnTimeOverride = 0;
			if(pInstance)
			{
				if(bossInfoMap != NULL && IS_PERSISTENT_INSTANCE(pInstance))
				{
					bool skip = false;
					for(std::set<uint32>::iterator killedNpc = pInstance->m_killedNpcs.begin(); killedNpc != pInstance->m_killedNpcs.end(); ++killedNpc)
					{
						// Do not spawn the killed boss.
						if((*killedNpc) == (*i)->entry)
						{
							skip = true;
							break;
						}
						// Do not spawn the killed boss' trash.
						InstanceBossInfoMap::const_iterator bossInfo = bossInfoMap->find((*killedNpc));
						if (bossInfo != bossInfoMap->end() && bossInfo->second->trash.find((*i)->id) != bossInfo->second->trash.end())
						{
							skip = true;
							break;
						}
					}
					if(skip)
						continue;

					for(InstanceBossInfoMap::iterator bossInfo = bossInfoMap->begin(); bossInfo != bossInfoMap->end(); ++bossInfo)
					{
						if(pInstance->m_killedNpcs.find(bossInfo->second->creatureid) == pInstance->m_killedNpcs.end() && bossInfo->second->trash.find((*i)->id) != bossInfo->second->trash.end())
						{
							respawnTimeOverride = bossInfo->second->trashRespawnOverride;
						}
					}
				}
				else
				{
					// No boss information available ... fallback ...
					if(pInstance->m_killedNpcs.find((*i)->id) != pInstance->m_killedNpcs.end())
						continue;
				}
			}

			Creature * c=_mapmgr->CreateCreature((*i)->entry);

			c->SetMapId(_mapmgr->GetMapId());
			c->SetInstanceID(_mapmgr->GetInstanceID());
			c->m_loadedFromDB = true;
			if(respawnTimeOverride > 0)
				c->m_respawnTimeOverride = respawnTimeOverride;

            if(c->Load(*i, _mapmgr->iInstanceMode, _mapmgr->GetMapInfo()))
			{
				if(!c->CanAddToWorld())
					delete c;

				c->PushToWorld(_mapmgr);
			}
			else
				delete c;//missing proto or smth of that kind
		}
	}

	if(sp->GOSpawns.size())//got GOs
	{
		for(GOSpawnList::iterator i=sp->GOSpawns.begin();i!=sp->GOSpawns.end();i++)
		{
			GameObject * go=_mapmgr->CreateGameObject((*i)->entry);
			go->SetInstanceID(_mapmgr->GetInstanceID());
			if(go->Load(*i))
			{
				//uint32 state = go->GetUInt32Value(GAMEOBJECT_STATE);

				// FIXME - burlex
				/*
				if(pInstance && pInstance->FindObject((*i)->stateNpcLink))
				{
					go->SetUInt32Value(GAMEOBJECT_STATE, (state ? 0 : 1));
				}*/

				go->m_loadedFromDB = true;
				go->PushToWorld(_mapmgr);
			}
			else
				delete go;//missing proto or smth of that kind
		}
	}
}

void MapCell::QueueUnloadPending()
{
	if(_unloadpending)
		return;

	_unloadpending = true;
	//Log.Debug("MapCell", "Queueing pending unload of cell %u %u", _x, _y);
	sEventMgr.AddEvent(_mapmgr, &MapMgr::UnloadCell,(uint32)_x,(uint32)_y,MAKE_CELL_EVENT(_x,_y),sWorld.map_unload_time * 1000,1,0);
}

void MapCell::CancelPendingUnload()
{
	//Log.Debug("MapCell", "Cancelling pending unload of cell %u %u", _x, _y);
	if(!_unloadpending)
		return;

	sEventMgr.RemoveEvents(_mapmgr,MAKE_CELL_EVENT(_x,_y));
}

void MapCell::Unload()
{
	//Log.Debug("MapCell", "Unloading cell %u %u", _x, _y);
	ASSERT(_unloadpending);
	if(_active)
		return;

	RemoveObjects();
	_unloadpending=false;
}
<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// insert_executor.cpp
//
// Identification: src/executor/insert_executor.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "executor/insert_executor.h"

#include "catalog/manager.h"
#include "common/logger.h"
#include "common/pool.h"
#include "concurrency/transaction_manager_factory.h"
#include "executor/logical_tile.h"
#include "executor/executor_context.h"
#include "expression/container_tuple.h"
#include "planner/insert_plan.h"
#include "storage/data_table.h"
#include "storage/tuple_iterator.h"

namespace peloton {
namespace executor {

/**
 * @brief Constructor for insert executor.
 * @param node Insert node corresponding to this executor.
 */
InsertExecutor::InsertExecutor(const planner::AbstractPlan *node,
                               ExecutorContext *executor_context)
: AbstractExecutor(node, executor_context) {}

/**
 * @brief Nothing to init at the moment.
 * @return true on success, false otherwise.
 */
bool InsertExecutor::DInit() {
  PL_ASSERT(children_.size() == 0 || children_.size() == 1);
  PL_ASSERT(executor_context_);

  done_ = false;
  return true;
}

/**
 * @brief Adds a column to the logical tile, using the position lists.
 * @return true on success, false otherwise.
 */
bool InsertExecutor::DExecute() {
  if (done_) return false;

  PL_ASSERT(!done_);
  PL_ASSERT(executor_context_ != nullptr);

  const planner::InsertPlan &node = GetPlanNode<planner::InsertPlan>();
  storage::DataTable *target_table = node.GetTable();
  oid_t bulk_insert_count = node.GetBulkInsertCount();

  auto &transaction_manager =
      concurrency::TransactionManagerFactory::GetInstance();

  if(!target_table) {
	  transaction_manager.SetTransactionResult(
	             peloton::Result::RESULT_FAILURE);
	         return false;
  }

  LOG_TRACE("Number of tuples in table before insert: %lu",
              target_table->GetTupleCount());
  auto executor_pool = executor_context_->GetExecutorContextPool();

  // Inserting a logical tile.
  if (children_.size() == 1) {
    LOG_TRACE("Insert executor :: 1 child ");

    if (!children_[0]->Execute()) {
      return false;
    }

    std::unique_ptr<LogicalTile> logical_tile(children_[0]->GetOutput());
    PL_ASSERT(logical_tile.get() != nullptr);
    auto target_table_schema = target_table->GetSchema();
    auto column_count = target_table_schema->GetColumnCount();

    std::unique_ptr<storage::Tuple> tuple(
        new storage::Tuple(target_table_schema, true));

    // Go over the logical tile
    for (oid_t tuple_id : *logical_tile) {
      expression::ContainerTuple<LogicalTile> cur_tuple(logical_tile.get(),
                                                        tuple_id);

      // Materialize the logical tile tuple
      for (oid_t column_itr = 0; column_itr < column_count; column_itr++) {
        tuple->SetValue(column_itr, cur_tuple.GetValue(column_itr),
                        executor_pool);
      }

      ItemPointer *index_entry_ptr = nullptr;
      peloton::ItemPointer location = target_table->InsertTuple(tuple.get(), &index_entry_ptr);

      if (location.block == INVALID_OID) {
        transaction_manager.SetTransactionResult(
            peloton::Result::RESULT_FAILURE);
        return false;
      }

      transaction_manager.PerformInsert(location, index_entry_ptr);

      executor_context_->num_processed += 1;  // insert one
    }

    return true;
  }
  // Inserting a collection of tuples from plan node
  else if (children_.size() == 0) {
    LOG_TRACE("Insert executor :: 0 child ");

    // Extract expressions from plan node and construct the tuple.
    // For now we just handle a single tuple
    auto schema = target_table->GetSchema();
    auto project_info = node.GetProjectInfo();
    auto tuple = node.GetTuple();
    std::unique_ptr<storage::Tuple> project_tuple;

    // Check if this is not a raw tuple
    if (tuple == nullptr) {
      // Otherwise, there must exist a project info
      PL_ASSERT(project_info);
      // There should be no direct maps
      PL_ASSERT(project_info->GetDirectMapList().size() == 0);

      project_tuple.reset(new storage::Tuple(schema, true));

      for (auto target : project_info->GetTargetList()) {
        peloton::Value value =
            target.second->Evaluate(nullptr, nullptr, executor_context_);
        project_tuple->SetValue(target.first, value, executor_pool);
      }

      // Set tuple to point to temporary project tuple
      tuple = project_tuple.get();
    }

    // Bulk Insert Mode
    for (oid_t insert_itr = 0; insert_itr < bulk_insert_count; insert_itr++) {

      // Carry out insertion
      ItemPointer *index_entry_ptr = nullptr;
      ItemPointer location = target_table->InsertTuple(tuple, &index_entry_ptr);
      LOG_TRACE("Inserted into location: %u, %u", location.block,
                location.offset);

      if (location.block == INVALID_OID) {
        LOG_TRACE("Failed to Insert. Set txn failure.");
        transaction_manager.SetTransactionResult(Result::RESULT_FAILURE);
        return false;
      }

      transaction_manager.PerformInsert(location, index_entry_ptr);

      LOG_TRACE("Number of tuples in table after insert: %lu",
                target_table->GetTupleCount());

      executor_context_->num_processed += 1;  // insert one
    }

    done_ = true;
    return true;
  }

  return true;
}

}  // namespace executor
}  // namespace peloton
<commit_msg>clean up insert_executor<commit_after>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// insert_executor.cpp
//
// Identification: src/executor/insert_executor.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "executor/insert_executor.h"

#include "catalog/manager.h"
#include "common/logger.h"
#include "common/pool.h"
#include "concurrency/transaction_manager_factory.h"
#include "executor/logical_tile.h"
#include "executor/executor_context.h"
#include "expression/container_tuple.h"
#include "planner/insert_plan.h"
#include "storage/data_table.h"
#include "storage/tuple_iterator.h"

namespace peloton {
namespace executor {

/**
 * @brief Constructor for insert executor.
 * @param node Insert node corresponding to this executor.
 */
InsertExecutor::InsertExecutor(const planner::AbstractPlan *node,
                               ExecutorContext *executor_context)
: AbstractExecutor(node, executor_context) {}

/**
 * @brief Nothing to init at the moment.
 * @return true on success, false otherwise.
 */
bool InsertExecutor::DInit() {
  PL_ASSERT(children_.size() == 0 || children_.size() == 1);
  PL_ASSERT(executor_context_);

  done_ = false;
  return true;
}

/**
 * @brief Adds a column to the logical tile, using the position lists.
 * @return true on success, false otherwise.
 */
bool InsertExecutor::DExecute() {
  if (done_) return false;

  PL_ASSERT(!done_);
  PL_ASSERT(executor_context_ != nullptr);

  const planner::InsertPlan &node = GetPlanNode<planner::InsertPlan>();
  storage::DataTable *target_table = node.GetTable();
  oid_t bulk_insert_count = node.GetBulkInsertCount();

  auto &transaction_manager =
      concurrency::TransactionManagerFactory::GetInstance();

  if(!target_table) {
	  transaction_manager.SetTransactionResult(
	             peloton::Result::RESULT_FAILURE);
	         return false;
  }

  LOG_TRACE("Number of tuples in table before insert: %lu",
              target_table->GetTupleCount());
  auto executor_pool = executor_context_->GetExecutorContextPool();

  // Inserting a logical tile.
  if (children_.size() == 1) {
    LOG_TRACE("Insert executor :: 1 child ");

    if (!children_[0]->Execute()) {
      return false;
    }

    std::unique_ptr<LogicalTile> logical_tile(children_[0]->GetOutput());
    PL_ASSERT(logical_tile.get() != nullptr);
    auto target_table_schema = target_table->GetSchema();
    auto column_count = target_table_schema->GetColumnCount();

    std::unique_ptr<storage::Tuple> tuple(
        new storage::Tuple(target_table_schema, true));

    // Go over the logical tile
    for (oid_t tuple_id : *logical_tile) {
      expression::ContainerTuple<LogicalTile> cur_tuple(logical_tile.get(),
                                                        tuple_id);

      // Materialize the logical tile tuple
      for (oid_t column_itr = 0; column_itr < column_count; column_itr++) {
        tuple->SetValue(column_itr, cur_tuple.GetValue(column_itr),
                        executor_pool);
      }

      // insert tuple into the table.
      ItemPointer *index_entry_ptr = nullptr;
      peloton::ItemPointer location = target_table->InsertTuple(tuple.get(), &index_entry_ptr);

      // it is possible that some concurrent transactions have inserted the same tuple.
      // in this case, abort the transaction.
      if (location.block == INVALID_OID) {
        transaction_manager.SetTransactionResult(
            peloton::Result::RESULT_FAILURE);
        return false;
      }

      transaction_manager.PerformInsert(location, index_entry_ptr);

      executor_context_->num_processed += 1;  // insert one
    }

    return true;
  }
  // Inserting a collection of tuples from plan node
  else if (children_.size() == 0) {
    LOG_TRACE("Insert executor :: 0 child ");

    // Extract expressions from plan node and construct the tuple.
    // For now we just handle a single tuple
    auto schema = target_table->GetSchema();
    auto project_info = node.GetProjectInfo();
    auto tuple = node.GetTuple();
    std::unique_ptr<storage::Tuple> project_tuple;

    // Check if this is not a raw tuple
    if (tuple == nullptr) {
      // Otherwise, there must exist a project info
      PL_ASSERT(project_info);
      // There should be no direct maps
      PL_ASSERT(project_info->GetDirectMapList().size() == 0);

      project_tuple.reset(new storage::Tuple(schema, true));

      for (auto target : project_info->GetTargetList()) {
        peloton::Value value =
            target.second->Evaluate(nullptr, nullptr, executor_context_);
        project_tuple->SetValue(target.first, value, executor_pool);
      }

      // Set tuple to point to temporary project tuple
      tuple = project_tuple.get();
    }

    // Bulk Insert Mode
    for (oid_t insert_itr = 0; insert_itr < bulk_insert_count; insert_itr++) {

      // Carry out insertion
      ItemPointer *index_entry_ptr = nullptr;
      ItemPointer location = target_table->InsertTuple(tuple, &index_entry_ptr);
      LOG_TRACE("Inserted into location: %u, %u", location.block,
                location.offset);

      if (location.block == INVALID_OID) {
        LOG_TRACE("Failed to Insert. Set txn failure.");
        transaction_manager.SetTransactionResult(Result::RESULT_FAILURE);
        return false;
      }

      transaction_manager.PerformInsert(location, index_entry_ptr);

      LOG_TRACE("Number of tuples in table after insert: %lu",
                target_table->GetTupleCount());

      executor_context_->num_processed += 1;  // insert one
    }

    done_ = true;
    return true;
  }

  return true;
}

}  // namespace executor
}  // namespace peloton
<|endoftext|>


<commit_before>// ======================================================================== //
// Copyright 2009-2015 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

#include "tessellation_cache.h"

#include <tbb/scalable_allocator.h>
using namespace tbb;

namespace embree
{

#if defined (__MIC__)
#define USE_TBB_ALLOCATOR 1
#else
#define USE_TBB_ALLOCATOR 0
#endif

  //void*scalable_aligned_malloc(size_t size, size_t align);
  //void scalable_aligned_free(void* ptr );
  //void*scalable_aligned_realloc(void* ptr,size_t size,size_t align);

  /* alloc cache memory */
  float *alloc_tessellation_cache_mem(const size_t blocks)
  {
    //DBG_PRINT(blocks);

#if USE_TBB_ALLOCATOR == 1
    return (float*)scalable_aligned_malloc(64 * blocks,64);
#else
    return (float*)_mm_malloc(64 * blocks,64);
#endif
  }

  /* free cache memory */
  void free_tessellation_cache_mem(void *mem, const size_t blocks)
  {
    assert(mem);
#if USE_TBB_ALLOCATOR == 1
    scalable_aligned_free(mem);
#else
    _mm_free(mem);
#endif
  }

  AtomicCounter SharedTessellationCacheStats::cache_accesses  = 0;
  AtomicCounter SharedTessellationCacheStats::cache_hits      = 0;
  AtomicCounter SharedTessellationCacheStats::cache_misses    = 0;
  AtomicCounter SharedTessellationCacheStats::cache_evictions = 0;

  void SharedTessellationCacheStats::printStats()
  {
    DBG_PRINT(cache_accesses);
    DBG_PRINT(cache_misses);
    DBG_PRINT(cache_hits);
    DBG_PRINT(cache_evictions);
    DBG_PRINT(100.0f * cache_hits / cache_accesses);
    assert(cache_hits + cache_misses == cache_accesses);
  }

  void SharedTessellationCacheStats::clearStats()
  {
    SharedTessellationCacheStats::cache_accesses  = 0;
    SharedTessellationCacheStats::cache_hits      = 0;
    SharedTessellationCacheStats::cache_misses    = 0;
    SharedTessellationCacheStats::cache_evictions = 0;
  }

  AtomicCounter DistributedTessellationCacheStats::cache_accesses  = 0;
  AtomicCounter DistributedTessellationCacheStats::cache_hits      = 0;
  AtomicCounter DistributedTessellationCacheStats::cache_misses    = 0;
  AtomicCounter DistributedTessellationCacheStats::cache_evictions = 0;

  void DistributedTessellationCacheStats::printStats()
  {
    DBG_PRINT(cache_accesses);
    DBG_PRINT(cache_misses);
    DBG_PRINT(cache_hits);
    DBG_PRINT(cache_evictions);
    DBG_PRINT(100.0f * cache_hits / cache_accesses);
    assert(cache_hits + cache_misses == cache_accesses);
  }

  void DistributedTessellationCacheStats::clearStats()
  {
    DistributedTessellationCacheStats::cache_accesses  = 0;
    DistributedTessellationCacheStats::cache_hits      = 0;
    DistributedTessellationCacheStats::cache_misses    = 0;
    DistributedTessellationCacheStats::cache_evictions = 0;
  }

  // AtomicCounter TessellationCache::cache_accesses  = 0;
  // AtomicCounter TessellationCache::cache_hits      = 0;
  // AtomicCounter TessellationCache::cache_misses    = 0;
  // AtomicCounter TessellationCache::cache_clears    = 0;
  // AtomicCounter TessellationCache::cache_evictions = 0;

};

extern "C" void printTessCacheStats()
{
  DBG_PRINT("SHARED TESSELLATION CACHE");
  embree::SharedTessellationCacheStats::printStats();
  embree::SharedTessellationCacheStats::clearStats();
#if 1
  DBG_PRINT("PER THREAD TESSELLATION CACHE");
  embree::DistributedTessellationCacheStats::printStats();
  embree::DistributedTessellationCacheStats::clearStats();
#else
  DBG_PRINT("PER THREAD TESSELLATION CACHE");
  embree::TessellationCache::printStats();
  embree::TessellationCache::clearStats();
#endif
}
<commit_msg>complie fix<commit_after>// ======================================================================== //
// Copyright 2009-2015 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

#if defined (__MIC__)
#define USE_TBB_ALLOCATOR 1
#else
#define USE_TBB_ALLOCATOR 0
#endif

#include "tessellation_cache.h"

#if USE_TBB_ALLOCATOR == 1
#include <tbb/scalable_allocator.h>
using namespace tbb;
#endif

namespace embree
{

  //void*scalable_aligned_malloc(size_t size, size_t align);
  //void scalable_aligned_free(void* ptr );
  //void*scalable_aligned_realloc(void* ptr,size_t size,size_t align);

  /* alloc cache memory */
  float *alloc_tessellation_cache_mem(const size_t blocks)
  {
    //DBG_PRINT(blocks);

#if USE_TBB_ALLOCATOR == 1
    return (float*)scalable_aligned_malloc(64 * blocks,64);
#else
    return (float*)_mm_malloc(64 * blocks,64);
#endif
  }

  /* free cache memory */
  void free_tessellation_cache_mem(void *mem, const size_t blocks)
  {
    assert(mem);
#if USE_TBB_ALLOCATOR == 1
    scalable_aligned_free(mem);
#else
    _mm_free(mem);
#endif
  }

  AtomicCounter SharedTessellationCacheStats::cache_accesses  = 0;
  AtomicCounter SharedTessellationCacheStats::cache_hits      = 0;
  AtomicCounter SharedTessellationCacheStats::cache_misses    = 0;
  AtomicCounter SharedTessellationCacheStats::cache_evictions = 0;

  void SharedTessellationCacheStats::printStats()
  {
    DBG_PRINT(cache_accesses);
    DBG_PRINT(cache_misses);
    DBG_PRINT(cache_hits);
    DBG_PRINT(cache_evictions);
    DBG_PRINT(100.0f * cache_hits / cache_accesses);
    assert(cache_hits + cache_misses == cache_accesses);
  }

  void SharedTessellationCacheStats::clearStats()
  {
    SharedTessellationCacheStats::cache_accesses  = 0;
    SharedTessellationCacheStats::cache_hits      = 0;
    SharedTessellationCacheStats::cache_misses    = 0;
    SharedTessellationCacheStats::cache_evictions = 0;
  }

  AtomicCounter DistributedTessellationCacheStats::cache_accesses  = 0;
  AtomicCounter DistributedTessellationCacheStats::cache_hits      = 0;
  AtomicCounter DistributedTessellationCacheStats::cache_misses    = 0;
  AtomicCounter DistributedTessellationCacheStats::cache_evictions = 0;

  void DistributedTessellationCacheStats::printStats()
  {
    DBG_PRINT(cache_accesses);
    DBG_PRINT(cache_misses);
    DBG_PRINT(cache_hits);
    DBG_PRINT(cache_evictions);
    DBG_PRINT(100.0f * cache_hits / cache_accesses);
    assert(cache_hits + cache_misses == cache_accesses);
  }

  void DistributedTessellationCacheStats::clearStats()
  {
    DistributedTessellationCacheStats::cache_accesses  = 0;
    DistributedTessellationCacheStats::cache_hits      = 0;
    DistributedTessellationCacheStats::cache_misses    = 0;
    DistributedTessellationCacheStats::cache_evictions = 0;
  }

  // AtomicCounter TessellationCache::cache_accesses  = 0;
  // AtomicCounter TessellationCache::cache_hits      = 0;
  // AtomicCounter TessellationCache::cache_misses    = 0;
  // AtomicCounter TessellationCache::cache_clears    = 0;
  // AtomicCounter TessellationCache::cache_evictions = 0;

};

extern "C" void printTessCacheStats()
{
  DBG_PRINT("SHARED TESSELLATION CACHE");
  embree::SharedTessellationCacheStats::printStats();
  embree::SharedTessellationCacheStats::clearStats();
#if 1
  DBG_PRINT("PER THREAD TESSELLATION CACHE");
  embree::DistributedTessellationCacheStats::printStats();
  embree::DistributedTessellationCacheStats::clearStats();
#else
  DBG_PRINT("PER THREAD TESSELLATION CACHE");
  embree::TessellationCache::printStats();
  embree::TessellationCache::clearStats();
#endif
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qfeedbackplugininterfaces.h"
#include "qfeedbackplugin_p.h"
#include "qfeedbackeffect_p.h"
#include "qmobilitypluginsearch.h"

#include <QtCore/QCoreApplication>
#include <QtCore/QStringList>
#include <QtCore/QDir>
#include <QtCore/QPluginLoader>
#include <QtCore/QHash>
#include <QDebug>

QTM_BEGIN_NAMESPACE

/*!
    \class QFeedbackInterface
    \ingroup feedback
    \inmodule QtFeedback

    \brief The QFeedbackInterface class is the base class for plugins providing feedback.

    This interface gives the possibility to report errors from within a backend plugin.
*/

/*!
    \fn QFeedbackInterface::reportError(const QFeedbackEffect *effect, QFeedbackEffect::ErrorType error)

    Allows a plugin to report the specified \a error whenever necessary.  Errors most likely can happen
    trying to play or pause an effect, which should be supplied as the parameter \a effect.
*/

/*!
    \enum QFeedbackInterface::PluginPriority

    This enum describes the priority that the plugin should have in case more than one of the same type (Haptics or Theme) is found.
    If more than one plugin has the same priority, the first one that has been loaded will be used.  However, multiple
    file effect plugins can be loaded at the same time.

    \value PluginLowPriority The plugin will have a low priority. This is usually the case for
    platform specific-APIs.

    \value PluginNormalPriority The plugin will have a normal priority.
    This is usually the case for advanced technologies.

    \value PluginHighPriority The plugin will have higher priority. Use this priority if you
    want your own plugin to be used.
*/

void QFeedbackInterface::reportError(const QFeedbackEffect *effect, QFeedbackEffect::ErrorType error)
{
    if (effect)
        emit effect->error(error);
}

// These are really useless docs, so I've marked them as internal
/*!
  \internal
  \fn QFeedbackThemeInterface::~QFeedbackThemeInterface()

  Destroys any resources used by this interface.
*/

/*!
  \internal
  \fn QFeedbackFileInterface::~QFeedbackFileInterface()

  Destroys any resources used by this interface.
*/

/*!
  \internal
  \fn QFeedbackHapticsInterface::~QFeedbackHapticsInterface()

  Destroys any resources used by this interface.
*/

template <class T>
class BackendLoader
{
public:
    BackendLoader() : inst(0) { }
    ~BackendLoader() { pl.unload(); }

    void setInstance(T *newInst) { inst = newInst; }
    T * instance() { return inst; }

    void tryLoad(QPluginLoader &loader)
    {
        if (T *newInst = qobject_cast<T*>(loader.instance())) {
            if (!inst || inst->pluginPriority() < newInst->pluginPriority()) {
                inst = newInst;
                pl.unload(); //release any reference to a previous plugin instance
                pl.setFileName(loader.fileName());
                pl.load(); //Adds a ref to the library
            }
        }
    }

private:
    QPluginLoader pl;
    T *inst;
};

class FileBackend : public QFeedbackFileInterface
{
public:
    FileBackend()
    {
    }

    //this class is used to redirect the calls to all the file backends available
    virtual void setLoaded(QFeedbackFileEffect *effect, bool load)
    {
        if (load) {
            //start loading
            tryBackendLoad(effect);
        } else {
            //unload
            if (QFeedbackFileInterface *subBackend = getBackend(effect))
                subBackend->setLoaded(effect, load);
            QFeedbackFileEffectPrivate::get(effect)->loadFinished(false); // make sure it's marked unloaded [XXX this isn't allowed to fail!]
        }
    }

    virtual void setEffectState(QFeedbackFileEffect *effect, QFeedbackEffect::State state)
    {
        if (QFeedbackFileInterface *subBackend = getBackend(effect))
            subBackend->setEffectState(effect, state);

        QFeedbackInterface::reportError(effect, QFeedbackEffect::UnknownError);
    }

    virtual QFeedbackEffect::State effectState(const QFeedbackFileEffect *effect)
    {
        if (QFeedbackFileInterface *subBackend = getBackend(effect))
            return subBackend->effectState(effect);

        return QFeedbackEffect::Stopped;
    }

    virtual int effectDuration(const QFeedbackFileEffect *effect)
    {
         if (QFeedbackFileInterface *subBackend = getBackend(effect))
            return subBackend->effectDuration(effect);

        return 0;
   }

    virtual QStringList supportedMimeTypes()
    {
        QStringList ret;
        for (int i = 0; i < subBackends.count(); ++i) {
            ret += subBackends.at(i)->supportedMimeTypes();
        }
        return ret;
    }

    void addFileBackend(QFeedbackFileInterface *backend)
    {
        subBackends.append(backend);
    }

    void reportLoadFinished(QFeedbackFileEffect *effect, bool success)
    {
        if (success) {
            //the file was loaded by the current backend
            QFeedbackFileEffectPrivate::get(effect)->loadFinished(true);
            return;
        }

        //let's try the next backend
        tryBackendLoad(effect);
    }

private:
    QList<QFeedbackFileInterface*> subBackends;

    QFeedbackFileInterface *getBackend(const QFeedbackFileEffect *effect)
    {
        const QFeedbackFileEffectPrivate *priv = QFeedbackFileEffectPrivate::get(effect);
        if (priv->backendUsed >= 0 && priv->backendUsed < subBackends.count())
                return subBackends.at(priv->backendUsed);
        return 0;
    }

    void tryBackendLoad(QFeedbackFileEffect *effect)
    {
        QFeedbackFileEffectPrivate *p = QFeedbackFileEffectPrivate::get(effect);
        p->backendUsed++;

        //let's try to load the file
        if (p->backendUsed >= subBackends.count()) {
            //the file couldn't be loaded
            p->loadFinished(false);
            return;
        }

        subBackends.at(p->backendUsed)->setLoaded(effect, true);
        //now we're waiting for the reply (call to asyncLoadFinished)
    }
};

class BackendManager
{
public:
    BackendManager()
    {
        QStringList pluginPaths = mobilityPlugins(QLatin1String("feedback"));
        // Testing hook to force "no plugin mode"
#ifdef QTM_BUILD_UNITTESTS
        if (qApp->property("QFEEDBACK_TEST_NO_PLUGINS").isValid())
            pluginPaths.clear();
#endif
        foreach (const QString& pluginPath, pluginPaths) {
            QPluginLoader loader(pluginPath);

            hapticsBackend.tryLoad(loader);
            themeBackend.tryLoad(loader);

            if (QFeedbackFileInterface *newFile = qobject_cast<QFeedbackFileInterface*>(loader.instance())) {
                fileBackend.addFileBackend(newFile);
            } else {
                loader.unload();
            }
        }

        if (!hapticsBackend.instance())
            hapticsBackend.setInstance(new QDummyBackend);
    }

    QFeedbackHapticsInterface* hapticsBackendInstance()
    {
        return hapticsBackend.instance();
    }

    QFeedbackThemeInterface* themeBackendInstance()
    {
        return themeBackend.instance();
    }

    FileBackend *fileBackendInstance()
    {
        return &fileBackend;
    }

private:
    BackendLoader<QFeedbackHapticsInterface> hapticsBackend;
    BackendLoader<QFeedbackThemeInterface> themeBackend;
    FileBackend fileBackend;
};

Q_GLOBAL_STATIC(BackendManager, backendManager);

/*!
    \class QFeedbackHapticsInterface
    \ingroup feedback

    \brief The QFeedbackHapticsInterface class is the base class for plugins providing custom haptics effects.

    This interface will be used to try to play custom effects with specific duration, intensity, envelope and period.
    An effect is always played on a specified actuator.
*/

/*!
   \enum QFeedbackHapticsInterface::EffectProperty
   This enum describes all effect properties for haptics effects.

   \value Duration The effect duration (in milliseconds)
   \value Intensity The effect intensity
   \value AttackTime The effect attack time (in milliseconds)
   \value AttackIntensity The effect attack intensity
   \value FadeTime The effect fade time (in milliseconds)
   \value FadeIntensity The effect fade intensity
   \value Period The effect period, this is an optional effect property.
*/

/*!
  \enum QFeedbackHapticsInterface::ActuatorProperty
  This enum describes all actuator properties.

  \value Name The actuator name.
  \value State The actuator state.
  \value Enabled The actuator enabled state.
 */

/*!
    \fn QFeedbackHapticsInterface::actuators()

    Return the available actuators provided by this plugin. The ownership of the actuator objects stays with the plugin.
*/

/*!
    \fn QFeedbackHapticsInterface::pluginPriority()

    Returns the priority for the plugin.
    \sa QFeedbackInterface::PluginPriority
*/

// XXX TODO.. these should have been pointers to QFA :/
/*!
    \fn QFeedbackHapticsInterface::setActuatorProperty(const QFeedbackActuator& actuator, ActuatorProperty property, const QVariant & value)

    Sets a \a value for \a property on the \a actuator.

    \sa ActuatorProperty
*/

/*!
    \fn QFeedbackHapticsInterface::actuatorProperty(const QFeedbackActuator & actuator, ActuatorProperty property)

    Returns the value for the \a property for an \a actuator.

    \sa ActuatorProperty
*/

/*!
    \fn QFeedbackHapticsInterface::isActuatorCapabilitySupported(const QFeedbackActuator &actuator, QFeedbackActuator::Capability capability)

    Returns true if the \a actuator supports the \a capability.
*/

/*!
    \fn QFeedbackHapticsInterface::updateEffectProperty(const QFeedbackHapticsEffect *effect, EffectProperty property)

    Tells the backend that the \a property has been updated for the supplied \a effect.
*/

/*!
    \fn QFeedbackHapticsInterface::setEffectState(const QFeedbackHapticsEffect *effect, QFeedbackEffect::State state)

    Sets the state to \a state for the effect \a effect. If that fails the backend should report an error by
    calling reportError and \a effect will in turn emit an error signal.
*/

/*!
    \fn QFeedbackHapticsInterface::effectState(const QFeedbackHapticsEffect *effect)

    Get the current state for the effect \a effect.
*/

/*!
    \internal
    \fn QFeedbackHapticsInterface::instance()

    Returns the instance of the object managing haptics custom effects.
    If no backend has been loaded, this will return a null pointer.
*/
QFeedbackHapticsInterface *QFeedbackHapticsInterface::instance()
{
    return backendManager()->hapticsBackendInstance();
}

/*!
    \fn QFeedbackHapticsInterface::createFeedbackActuator(QObject *parent, int id)

    Creates an instance of QFeedbackActuator with the identifier \a id and parent \a parent.  This allows
    backends to create instances of actuators. It is then up to the each backend to manage
    the identifiers according to its needs.
*/
QFeedbackActuator* QFeedbackHapticsInterface::createFeedbackActuator(QObject* parent, int id)
{
    return new QFeedbackActuator(parent, id);
}

/*!
    \class QFeedbackThemeInterface
    \ingroup feedback

    \brief The QFeedbackThemeInterface class is the base class for plugins providing themed effects.

    They can be of any nature (tactile, audio...).
    This simple interface will be used to play those themed effects by a simple call to the play method.
*/

/*!
    \fn QFeedbackThemeInterface::pluginPriority()

    Returns the priority for the plugin.
*/

/*!
    \fn QFeedbackThemeInterface::play(QFeedbackEffect::ThemeEffect effect)

    Plays the theme effect \a effect. Returns false in case of an error.
*/

/*!
    \internal
    \fn QFeedbackThemeInterface::instance()

    Returns the instance of the object managing theme effects.
    If no backend has been loaded, this will return a null pointer.
*/
QFeedbackThemeInterface *QFeedbackThemeInterface::instance()
{
    return backendManager()->themeBackendInstance();
}

/*!
    \class QFeedbackFileInterface
    \ingroup feedback

    \brief The QFeedbackFileInterface class is the base class for plugins providing support for effects stored in files.

    They can be of any nature (tactile, audio...). As it is possible to load many different file types using
    different technologies, all the backend plugins exposing this interface will be loaded at the same time.
    When loading a file all the backend will be tried in order until one can load the file. It is thus very important
    that the backends return a load status as soon as possible to not take a too long time to load a file.
*/

/*!
    \fn QFeedbackFileInterface::setLoaded(QFeedbackFileEffect* effect, bool value)

    Sets the state of the effect \a effect to be loaded if \a value is true, otherwise unloaded.
    Loading a file is asynchronous. Once the backend knows if it has loaded or can't load the file, it must
    call the reportLoadFinished function.
*/

/*!
    \fn QFeedbackFileInterface::setEffectState(QFeedbackFileEffect *effect, QFeedbackEffect::State state)

    Sets the state of \a effect to \a state.
*/

/*!
    \fn QFeedbackFileInterface::effectState(const QFeedbackFileEffect *effect)

    Returns the current state of the effect \a effect.
*/

/*!
    \fn QFeedbackFileInterface::effectDuration(const QFeedbackFileEffect *effect)

    Return the duration of \a effect, in milliseconds.
    It should return \l QFeedbackEffect::Infinite in case the duration is infinite, or 0 if undefined or unknown.
*/

/*!
    \fn QFeedbackFileInterface::supportedMimeTypes()

    Returns a list of the MIME types supported by this plugin.
*/

/*!
    \internal
    \fn QFeedbackFileInterface::instance()

    Returns the instance of the object managing theme effects.
    Even if no backend has been loaded, this will never return a null pointer.
*/
QFeedbackFileInterface *QFeedbackFileInterface::instance()
{
    return backendManager()->fileBackendInstance();
}

/*!
    \fn QFeedbackFileInterface::reportLoadFinished(QFeedbackFileEffect *effect, bool success)

    This is the function the backend should call when it has finished trying to load the effect \a effect.
    As loading a file is asynchronous and multiple plugins are attempted after each other, the
    backend has to call this function in order for the process to perform smoothly.
    The success of the operation is indicated by the \a success parameter.
*/
void QFeedbackFileInterface::reportLoadFinished(QFeedbackFileEffect *effect, bool success)
{
    backendManager()->fileBackendInstance()->reportLoadFinished(effect, success);
}

QTM_END_NAMESPACE
<commit_msg>Missing else meant that the error signal was emitted on state changes.<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qfeedbackplugininterfaces.h"
#include "qfeedbackplugin_p.h"
#include "qfeedbackeffect_p.h"
#include "qmobilitypluginsearch.h"

#include <QtCore/QCoreApplication>
#include <QtCore/QStringList>
#include <QtCore/QDir>
#include <QtCore/QPluginLoader>
#include <QtCore/QHash>
#include <QDebug>

QTM_BEGIN_NAMESPACE

/*!
    \class QFeedbackInterface
    \ingroup feedback
    \inmodule QtFeedback

    \brief The QFeedbackInterface class is the base class for plugins providing feedback.

    This interface gives the possibility to report errors from within a backend plugin.
*/

/*!
    \fn QFeedbackInterface::reportError(const QFeedbackEffect *effect, QFeedbackEffect::ErrorType error)

    Allows a plugin to report the specified \a error whenever necessary.  Errors most likely can happen
    trying to play or pause an effect, which should be supplied as the parameter \a effect.
*/

/*!
    \enum QFeedbackInterface::PluginPriority

    This enum describes the priority that the plugin should have in case more than one of the same type (Haptics or Theme) is found.
    If more than one plugin has the same priority, the first one that has been loaded will be used.  However, multiple
    file effect plugins can be loaded at the same time.

    \value PluginLowPriority The plugin will have a low priority. This is usually the case for
    platform specific-APIs.

    \value PluginNormalPriority The plugin will have a normal priority.
    This is usually the case for advanced technologies.

    \value PluginHighPriority The plugin will have higher priority. Use this priority if you
    want your own plugin to be used.
*/

void QFeedbackInterface::reportError(const QFeedbackEffect *effect, QFeedbackEffect::ErrorType error)
{
    if (effect)
        emit effect->error(error);
}

// These are really useless docs, so I've marked them as internal
/*!
  \internal
  \fn QFeedbackThemeInterface::~QFeedbackThemeInterface()

  Destroys any resources used by this interface.
*/

/*!
  \internal
  \fn QFeedbackFileInterface::~QFeedbackFileInterface()

  Destroys any resources used by this interface.
*/

/*!
  \internal
  \fn QFeedbackHapticsInterface::~QFeedbackHapticsInterface()

  Destroys any resources used by this interface.
*/

template <class T>
class BackendLoader
{
public:
    BackendLoader() : inst(0) { }
    ~BackendLoader() { pl.unload(); }

    void setInstance(T *newInst) { inst = newInst; }
    T * instance() { return inst; }

    void tryLoad(QPluginLoader &loader)
    {
        if (T *newInst = qobject_cast<T*>(loader.instance())) {
            if (!inst || inst->pluginPriority() < newInst->pluginPriority()) {
                inst = newInst;
                pl.unload(); //release any reference to a previous plugin instance
                pl.setFileName(loader.fileName());
                pl.load(); //Adds a ref to the library
            }
        }
    }

private:
    QPluginLoader pl;
    T *inst;
};

class FileBackend : public QFeedbackFileInterface
{
public:
    FileBackend()
    {
    }

    //this class is used to redirect the calls to all the file backends available
    virtual void setLoaded(QFeedbackFileEffect *effect, bool load)
    {
        if (load) {
            //start loading
            tryBackendLoad(effect);
        } else {
            //unload
            if (QFeedbackFileInterface *subBackend = getBackend(effect))
                subBackend->setLoaded(effect, load);
            QFeedbackFileEffectPrivate::get(effect)->loadFinished(false); // make sure it's marked unloaded [XXX this isn't allowed to fail!]
        }
    }

    virtual void setEffectState(QFeedbackFileEffect *effect, QFeedbackEffect::State state)
    {
        if (QFeedbackFileInterface *subBackend = getBackend(effect))
            subBackend->setEffectState(effect, state);
        else
            QFeedbackInterface::reportError(effect, QFeedbackEffect::UnknownError);
    }

    virtual QFeedbackEffect::State effectState(const QFeedbackFileEffect *effect)
    {
        if (QFeedbackFileInterface *subBackend = getBackend(effect))
            return subBackend->effectState(effect);

        return QFeedbackEffect::Stopped;
    }

    virtual int effectDuration(const QFeedbackFileEffect *effect)
    {
         if (QFeedbackFileInterface *subBackend = getBackend(effect))
            return subBackend->effectDuration(effect);

        return 0;
   }

    virtual QStringList supportedMimeTypes()
    {
        QStringList ret;
        for (int i = 0; i < subBackends.count(); ++i) {
            ret += subBackends.at(i)->supportedMimeTypes();
        }
        return ret;
    }

    void addFileBackend(QFeedbackFileInterface *backend)
    {
        subBackends.append(backend);
    }

    void reportLoadFinished(QFeedbackFileEffect *effect, bool success)
    {
        if (success) {
            //the file was loaded by the current backend
            QFeedbackFileEffectPrivate::get(effect)->loadFinished(true);
            return;
        }

        //let's try the next backend
        tryBackendLoad(effect);
    }

private:
    QList<QFeedbackFileInterface*> subBackends;

    QFeedbackFileInterface *getBackend(const QFeedbackFileEffect *effect)
    {
        const QFeedbackFileEffectPrivate *priv = QFeedbackFileEffectPrivate::get(effect);
        if (priv->backendUsed >= 0 && priv->backendUsed < subBackends.count())
                return subBackends.at(priv->backendUsed);
        return 0;
    }

    void tryBackendLoad(QFeedbackFileEffect *effect)
    {
        QFeedbackFileEffectPrivate *p = QFeedbackFileEffectPrivate::get(effect);
        p->backendUsed++;

        //let's try to load the file
        if (p->backendUsed >= subBackends.count()) {
            //the file couldn't be loaded
            p->loadFinished(false);
            return;
        }

        subBackends.at(p->backendUsed)->setLoaded(effect, true);
        //now we're waiting for the reply (call to asyncLoadFinished)
    }
};

class BackendManager
{
public:
    BackendManager()
    {
        QStringList pluginPaths = mobilityPlugins(QLatin1String("feedback"));
        // Testing hook to force "no plugin mode"
#ifdef QTM_BUILD_UNITTESTS
        if (qApp->property("QFEEDBACK_TEST_NO_PLUGINS").isValid())
            pluginPaths.clear();
#endif
        foreach (const QString& pluginPath, pluginPaths) {
            QPluginLoader loader(pluginPath);

            hapticsBackend.tryLoad(loader);
            themeBackend.tryLoad(loader);

            if (QFeedbackFileInterface *newFile = qobject_cast<QFeedbackFileInterface*>(loader.instance())) {
                fileBackend.addFileBackend(newFile);
            } else {
                loader.unload();
            }
        }

        if (!hapticsBackend.instance())
            hapticsBackend.setInstance(new QDummyBackend);
    }

    QFeedbackHapticsInterface* hapticsBackendInstance()
    {
        return hapticsBackend.instance();
    }

    QFeedbackThemeInterface* themeBackendInstance()
    {
        return themeBackend.instance();
    }

    FileBackend *fileBackendInstance()
    {
        return &fileBackend;
    }

private:
    BackendLoader<QFeedbackHapticsInterface> hapticsBackend;
    BackendLoader<QFeedbackThemeInterface> themeBackend;
    FileBackend fileBackend;
};

Q_GLOBAL_STATIC(BackendManager, backendManager);

/*!
    \class QFeedbackHapticsInterface
    \ingroup feedback

    \brief The QFeedbackHapticsInterface class is the base class for plugins providing custom haptics effects.

    This interface will be used to try to play custom effects with specific duration, intensity, envelope and period.
    An effect is always played on a specified actuator.
*/

/*!
   \enum QFeedbackHapticsInterface::EffectProperty
   This enum describes all effect properties for haptics effects.

   \value Duration The effect duration (in milliseconds)
   \value Intensity The effect intensity
   \value AttackTime The effect attack time (in milliseconds)
   \value AttackIntensity The effect attack intensity
   \value FadeTime The effect fade time (in milliseconds)
   \value FadeIntensity The effect fade intensity
   \value Period The effect period, this is an optional effect property.
*/

/*!
  \enum QFeedbackHapticsInterface::ActuatorProperty
  This enum describes all actuator properties.

  \value Name The actuator name.
  \value State The actuator state.
  \value Enabled The actuator enabled state.
 */

/*!
    \fn QFeedbackHapticsInterface::actuators()

    Return the available actuators provided by this plugin. The ownership of the actuator objects stays with the plugin.
*/

/*!
    \fn QFeedbackHapticsInterface::pluginPriority()

    Returns the priority for the plugin.
    \sa QFeedbackInterface::PluginPriority
*/

// XXX TODO.. these should have been pointers to QFA :/
/*!
    \fn QFeedbackHapticsInterface::setActuatorProperty(const QFeedbackActuator& actuator, ActuatorProperty property, const QVariant & value)

    Sets a \a value for \a property on the \a actuator.

    \sa ActuatorProperty
*/

/*!
    \fn QFeedbackHapticsInterface::actuatorProperty(const QFeedbackActuator & actuator, ActuatorProperty property)

    Returns the value for the \a property for an \a actuator.

    \sa ActuatorProperty
*/

/*!
    \fn QFeedbackHapticsInterface::isActuatorCapabilitySupported(const QFeedbackActuator &actuator, QFeedbackActuator::Capability capability)

    Returns true if the \a actuator supports the \a capability.
*/

/*!
    \fn QFeedbackHapticsInterface::updateEffectProperty(const QFeedbackHapticsEffect *effect, EffectProperty property)

    Tells the backend that the \a property has been updated for the supplied \a effect.
*/

/*!
    \fn QFeedbackHapticsInterface::setEffectState(const QFeedbackHapticsEffect *effect, QFeedbackEffect::State state)

    Sets the state to \a state for the effect \a effect. If that fails the backend should report an error by
    calling reportError and \a effect will in turn emit an error signal.
*/

/*!
    \fn QFeedbackHapticsInterface::effectState(const QFeedbackHapticsEffect *effect)

    Get the current state for the effect \a effect.
*/

/*!
    \internal
    \fn QFeedbackHapticsInterface::instance()

    Returns the instance of the object managing haptics custom effects.
    If no backend has been loaded, this will return a null pointer.
*/
QFeedbackHapticsInterface *QFeedbackHapticsInterface::instance()
{
    return backendManager()->hapticsBackendInstance();
}

/*!
    \fn QFeedbackHapticsInterface::createFeedbackActuator(QObject *parent, int id)

    Creates an instance of QFeedbackActuator with the identifier \a id and parent \a parent.  This allows
    backends to create instances of actuators. It is then up to the each backend to manage
    the identifiers according to its needs.
*/
QFeedbackActuator* QFeedbackHapticsInterface::createFeedbackActuator(QObject* parent, int id)
{
    return new QFeedbackActuator(parent, id);
}

/*!
    \class QFeedbackThemeInterface
    \ingroup feedback

    \brief The QFeedbackThemeInterface class is the base class for plugins providing themed effects.

    They can be of any nature (tactile, audio...).
    This simple interface will be used to play those themed effects by a simple call to the play method.
*/

/*!
    \fn QFeedbackThemeInterface::pluginPriority()

    Returns the priority for the plugin.
*/

/*!
    \fn QFeedbackThemeInterface::play(QFeedbackEffect::ThemeEffect effect)

    Plays the theme effect \a effect. Returns false in case of an error.
*/

/*!
    \internal
    \fn QFeedbackThemeInterface::instance()

    Returns the instance of the object managing theme effects.
    If no backend has been loaded, this will return a null pointer.
*/
QFeedbackThemeInterface *QFeedbackThemeInterface::instance()
{
    return backendManager()->themeBackendInstance();
}

/*!
    \class QFeedbackFileInterface
    \ingroup feedback

    \brief The QFeedbackFileInterface class is the base class for plugins providing support for effects stored in files.

    They can be of any nature (tactile, audio...). As it is possible to load many different file types using
    different technologies, all the backend plugins exposing this interface will be loaded at the same time.
    When loading a file all the backend will be tried in order until one can load the file. It is thus very important
    that the backends return a load status as soon as possible to not take a too long time to load a file.
*/

/*!
    \fn QFeedbackFileInterface::setLoaded(QFeedbackFileEffect* effect, bool value)

    Sets the state of the effect \a effect to be loaded if \a value is true, otherwise unloaded.
    Loading a file is asynchronous. Once the backend knows if it has loaded or can't load the file, it must
    call the reportLoadFinished function.
*/

/*!
    \fn QFeedbackFileInterface::setEffectState(QFeedbackFileEffect *effect, QFeedbackEffect::State state)

    Sets the state of \a effect to \a state.
*/

/*!
    \fn QFeedbackFileInterface::effectState(const QFeedbackFileEffect *effect)

    Returns the current state of the effect \a effect.
*/

/*!
    \fn QFeedbackFileInterface::effectDuration(const QFeedbackFileEffect *effect)

    Return the duration of \a effect, in milliseconds.
    It should return \l QFeedbackEffect::Infinite in case the duration is infinite, or 0 if undefined or unknown.
*/

/*!
    \fn QFeedbackFileInterface::supportedMimeTypes()

    Returns a list of the MIME types supported by this plugin.
*/

/*!
    \internal
    \fn QFeedbackFileInterface::instance()

    Returns the instance of the object managing theme effects.
    Even if no backend has been loaded, this will never return a null pointer.
*/
QFeedbackFileInterface *QFeedbackFileInterface::instance()
{
    return backendManager()->fileBackendInstance();
}

/*!
    \fn QFeedbackFileInterface::reportLoadFinished(QFeedbackFileEffect *effect, bool success)

    This is the function the backend should call when it has finished trying to load the effect \a effect.
    As loading a file is asynchronous and multiple plugins are attempted after each other, the
    backend has to call this function in order for the process to perform smoothly.
    The success of the operation is indicated by the \a success parameter.
*/
void QFeedbackFileInterface::reportLoadFinished(QFeedbackFileEffect *effect, bool success)
{
    backendManager()->fileBackendInstance()->reportLoadFinished(effect, success);
}

QTM_END_NAMESPACE
<|endoftext|>


<commit_before>/*
Copyright (c) 2009, Regents of the University of Alaska

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * Neither the name of the Geographic Information Network of Alaska nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

This code was developed by Dan Stahlke for the Geographic Information Network of Alaska.
*/

#include "common.h"
#include "polygon.h"
#include "debugplot.h"

void plot_points(ring_t *pl, const char *fn);

void usage(const char *cmdname) {
	printf("Usage: %s [options] \n", cmdname);
	printf("  -s_wkt <fn>           File containing WKT of source region\n");
	printf("  -t_bounds_wkt <fn>    File containing WKT for valid region of target SRS (optional)\n");
	printf("  -s_srs <srs_def>      Source SRS\n");
	printf("  -t_srs <srs_def>      Target SRS\n");
	printf("  -report <out.ppm>     Ouput a graphical report (optional)\n");
	printf("\nOutput is the envelope of the source region projected into the target SRS.\n");
	printf("If the -t_bounds_wkt option is given it will be used as a clip mask in the\n");
	printf("projected space.\n");
	printf("\n");

	exit(1);
}

int main(int argc, char **argv) {
	const char *src_wkt_fn = NULL;
	const char *t_bounds_wkt_fn = NULL;
	const char *s_srs = NULL;
	const char *t_srs = NULL;
	const char *report_fn = NULL;

	if(argc == 1) usage(argv[0]);

	int argp = 1;
	while(argp < argc) {
		char *arg = argv[argp++];
		// FIXME - check duplicate values
		if(arg[0] == '-') {
			if(!strcmp(arg, "-v")) {
				VERBOSE++;
			} else if(!strcmp(arg, "-s_wkt")) {
				if(argp == argc) usage(argv[0]);
				src_wkt_fn = argv[argp++];
			} else if(!strcmp(arg, "-t_bounds_wkt")) {
				if(argp == argc) usage(argv[0]);
				t_bounds_wkt_fn = argv[argp++];
			} else if(!strcmp(arg, "-s_srs")) {
				if(argp == argc) usage(argv[0]);
				s_srs = argv[argp++];
			} else if(!strcmp(arg, "-t_srs")) {
				if(argp == argc) usage(argv[0]);
				t_srs = argv[argp++];
			} else if(!strcmp(arg, "-report")) {
				if(argp == argc) usage(argv[0]);
				report_fn = argv[argp++];
			} else usage(argv[0]);
		} else {
			usage(argv[0]);
		}
	}

	if(!src_wkt_fn || !s_srs || !t_srs) usage(argv[0]);

	GDALAllRegister();

	CPLPushErrorHandler(CPLQuietErrorHandler);

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

	OGRSpatialReferenceH s_sref = OSRNewSpatialReference(NULL);
	if(OSRImportFromProj4(s_sref, s_srs) != OGRERR_NONE)
		fatal_error("cannot parse proj4 definition for -s_srs");

	OGRSpatialReferenceH t_sref = OSRNewSpatialReference(NULL);
	if(OSRImportFromProj4(t_sref, t_srs) != OGRERR_NONE)
		fatal_error("cannot parse proj4 definition for -t_srs");

	OGRCoordinateTransformationH fwd_xform =
		OCTNewCoordinateTransformation(s_sref, t_sref);
	OGRCoordinateTransformationH inv_xform =
		OCTNewCoordinateTransformation(t_sref, s_sref);

	mpoly_t src_mp = mpoly_from_wktfile(src_wkt_fn);
	bbox_t src_bbox = get_polygon_bbox(&src_mp);

	mpoly_t t_bounds_mp;
	bool use_t_bounds;
	bbox_t t_bounds_bbox;
	if(t_bounds_wkt_fn) {
		use_t_bounds = 1;
		t_bounds_mp = mpoly_from_wktfile(t_bounds_wkt_fn);
		t_bounds_bbox = get_polygon_bbox(&t_bounds_mp);
	} else {
		use_t_bounds = 0;
		t_bounds_bbox = (bbox_t){ 0, 0, 0, 0, 0 }; // prevents compiler warning
	}

	ring_t pl;
	pl.pts = NULL;
	pl.npts = 0;

	int num_grid_steps = 100;
	for(int grid_xi=0; grid_xi<=num_grid_steps; grid_xi++) {
		vertex_t src_pt;
		double alpha_x = (double)grid_xi / (double)num_grid_steps;
		src_pt.x = src_bbox.min_x + (src_bbox.max_x - src_bbox.min_x) * alpha_x;
		for(int grid_yi=0; grid_yi<=num_grid_steps; grid_yi++) {
			double alpha_y = (double)grid_yi / (double)num_grid_steps;
			src_pt.y = src_bbox.min_y + (src_bbox.max_y - src_bbox.min_y) * alpha_y;
			if(!polygon_contains_point(&src_mp, src_pt.x, src_pt.y)) continue;

			vertex_t tgt_pt = src_pt;
			if(!OCTTransform(fwd_xform, 1, &tgt_pt.x, &tgt_pt.y, NULL)) {
				continue;
			}

			if(!use_t_bounds || polygon_contains_point(&t_bounds_mp, tgt_pt.x, tgt_pt.y)) {
				add_point_to_ring(&pl, tgt_pt);
			}
		}
	}

	double max_step_len = MAX(
		src_bbox.max_x - src_bbox.min_x,
		src_bbox.max_y - src_bbox.min_y) / 1000.0;
	for(int r_idx=0; r_idx<src_mp.num_rings; r_idx++) {
		ring_t *ring = src_mp.rings + r_idx;
		for(int v_idx=0; v_idx<ring->npts; v_idx++) {
			vertex_t v1 = ring->pts[v_idx];
			vertex_t v2 = ring->pts[(v_idx+1) % ring->npts];
			double dx = v2.x - v1.x;
			double dy = v2.y - v1.y;
			double len = sqrt(dx*dx + dy*dy);
			int num_steps = 1 + (int)(len / max_step_len);
			for(int step=0; step<=num_steps; step++) {
				double alpha = (double)step / (double)num_steps;
				vertex_t src_pt;
				src_pt.x = v1.x + dx * alpha;
				src_pt.y = v1.y + dy * alpha;

				vertex_t tgt_pt = src_pt;
				if(!OCTTransform(fwd_xform, 1, &tgt_pt.x, &tgt_pt.y, NULL)) {
					continue;
				}

				if(!use_t_bounds || polygon_contains_point(&t_bounds_mp, tgt_pt.x, tgt_pt.y)) {
					add_point_to_ring(&pl, tgt_pt);
				}
			}
		}
	}

	if(use_t_bounds) {
		double max_step_len = MAX(
			t_bounds_bbox.max_x - t_bounds_bbox.min_x,
			t_bounds_bbox.max_y - t_bounds_bbox.min_y) / 1000.0;
		for(int r_idx=0; r_idx<t_bounds_mp.num_rings; r_idx++) {
			ring_t *ring = t_bounds_mp.rings + r_idx;
			for(int v_idx=0; v_idx<ring->npts; v_idx++) {
				vertex_t v1 = ring->pts[v_idx];
				vertex_t v2 = ring->pts[(v_idx+1) % ring->npts];
				double dx = v2.x - v1.x;
				double dy = v2.y - v1.y;
				double len = sqrt(dx*dx + dy*dy);
				int num_steps = 1 + (int)(len / max_step_len);
				for(int step=0; step<=num_steps; step++) {
					double alpha = (double)step / (double)num_steps;
					vertex_t tgt_pt;
					tgt_pt.x = v1.x + dx * alpha;
					tgt_pt.y = v1.y + dy * alpha;

					vertex_t src_pt = tgt_pt;
					if(!OCTTransform(inv_xform, 1, &src_pt.x, &src_pt.y, NULL)) {
						continue;
					}

					if(polygon_contains_point(&src_mp, src_pt.x, src_pt.y)) {
						add_point_to_ring(&pl, tgt_pt);
					}
				}
			}
		}
	}

	//fprintf(stderr, "got %d points\n", pl.npts);
	bbox_t bbox = get_ring_bbox(&pl);
	printf("bounds:\n");
	printf("  min_e: %.15f\n", bbox.min_x);
	printf("  min_n: %.15f\n", bbox.min_y);
	printf("  max_e: %.15f\n", bbox.max_x);
	printf("  max_n: %.15f\n", bbox.max_y);

	if(report_fn) plot_points(&pl, report_fn);

	return 0;
}

void plot_points(ring_t *pl, const char *fn) {
	bbox_t bbox = get_ring_bbox(pl);
	bbox.min_x -= (bbox.max_x - bbox.min_x) * .05;
	bbox.max_x += (bbox.max_x - bbox.min_x) * .05;
	bbox.min_y -= (bbox.max_y - bbox.min_y) * .05;
	bbox.max_y += (bbox.max_y - bbox.min_y) * .05;
	double W = bbox.max_x - bbox.min_x;
	double H = bbox.max_y - bbox.min_y;
	report_image_t *dbuf = create_plot(W, H);
	for(int i=0; i<pl->npts; i++) {
		vertex_t v = pl->pts[i];
		double x = v.x - bbox.min_x;
		double y = bbox.max_y - v.y;
		plot_point(dbuf, x, y, 255, 255, 255);
	}
	write_plot(dbuf, fn);
}
<commit_msg>better handling of troublesome projections<commit_after>/*
Copyright (c) 2009, Regents of the University of Alaska

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * Neither the name of the Geographic Information Network of Alaska nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

This code was developed by Dan Stahlke for the Geographic Information Network of Alaska.
*/

#include "common.h"
#include "polygon.h"
#include "debugplot.h"

void plot_points(ring_t *pl, const char *fn);

struct PointStats {
	PointStats() :
		total(0),
		proj_ok(0),
		contained(0)
	{ }

	void printYaml(const char *label) {
		printf("%s:\n", label);
		printf("  total: %d\n", total);
		printf("  proj_ok: %d\n", proj_ok);
		printf("  contained: %d\n", contained);
	}

	int total;
	int proj_ok;
	int contained;
};

void usage(const char *cmdname) {
	printf("Usage: %s [options] \n", cmdname);
	printf("  -s_wkt <fn>           File containing WKT of source region\n");
	printf("  -t_bounds_wkt <fn>    File containing WKT for valid region of target SRS (optional)\n");
	printf("  -s_srs <srs_def>      Source SRS\n");
	printf("  -t_srs <srs_def>      Target SRS\n");
	printf("  -report <out.ppm>     Ouput a graphical report (optional)\n");
	printf("\nOutput is the envelope of the source region projected into the target SRS.\n");
	printf("If the -t_bounds_wkt option is given it will be used as a clip mask in the\n");
	printf("projected space.\n");
	printf("\n");

	exit(1);
}

// This function transforms a point, and then as a check transforms it back to
// see if it comes back to the same place.  This allows us to detect cases
// where OCTTransform reports success when really it just returned some
// meaningless result.
bool picky_transform(
	OGRCoordinateTransformationH fwd_xform,
	OGRCoordinateTransformationH inv_xform,
	vertex_t *v_in
) {
	// tolerance in meters, could probably be much smaller
	const double toler = 1.0;

	vertex_t v_out = *v_in;
	if(!OCTTransform(fwd_xform, 1, &v_out.x, &v_out.y, NULL)) {
		return 0;
	}

	vertex_t v_back = v_out;
	if(!OCTTransform(inv_xform, 1, &v_back.x, &v_back.y, NULL)) {
		return 0;
	}

	double err = hypot(v_in->x - v_back.x, v_in->y - v_back.y);
	//fprintf(stderr, "err=%g\n", err);
	if(err > toler) {
		return 0;
	}

	*v_in = v_out;
	return 1;
}

int main(int argc, char **argv) {
	const char *src_wkt_fn = NULL;
	const char *t_bounds_wkt_fn = NULL;
	const char *s_srs = NULL;
	const char *t_srs = NULL;
	const char *report_fn = NULL;

	if(argc == 1) usage(argv[0]);

	int argp = 1;
	while(argp < argc) {
		char *arg = argv[argp++];
		// FIXME - check duplicate values
		if(arg[0] == '-') {
			if(!strcmp(arg, "-v")) {
				VERBOSE++;
			} else if(!strcmp(arg, "-s_wkt")) {
				if(argp == argc) usage(argv[0]);
				src_wkt_fn = argv[argp++];
			} else if(!strcmp(arg, "-t_bounds_wkt")) {
				if(argp == argc) usage(argv[0]);
				t_bounds_wkt_fn = argv[argp++];
			} else if(!strcmp(arg, "-s_srs")) {
				if(argp == argc) usage(argv[0]);
				s_srs = argv[argp++];
			} else if(!strcmp(arg, "-t_srs")) {
				if(argp == argc) usage(argv[0]);
				t_srs = argv[argp++];
			} else if(!strcmp(arg, "-report")) {
				if(argp == argc) usage(argv[0]);
				report_fn = argv[argp++];
			} else usage(argv[0]);
		} else {
			usage(argv[0]);
		}
	}

	if(!src_wkt_fn || !s_srs || !t_srs) usage(argv[0]);

	GDALAllRegister();

	CPLPushErrorHandler(CPLQuietErrorHandler);

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

	OGRSpatialReferenceH s_sref = OSRNewSpatialReference(NULL);
	if(OSRImportFromProj4(s_sref, s_srs) != OGRERR_NONE)
		fatal_error("cannot parse proj4 definition for -s_srs");

	OGRSpatialReferenceH t_sref = OSRNewSpatialReference(NULL);
	if(OSRImportFromProj4(t_sref, t_srs) != OGRERR_NONE)
		fatal_error("cannot parse proj4 definition for -t_srs");

	OGRCoordinateTransformationH fwd_xform =
		OCTNewCoordinateTransformation(s_sref, t_sref);
	OGRCoordinateTransformationH inv_xform =
		OCTNewCoordinateTransformation(t_sref, s_sref);

	mpoly_t src_mp = mpoly_from_wktfile(src_wkt_fn);
	bbox_t src_bbox = get_polygon_bbox(&src_mp);

	mpoly_t t_bounds_mp;
	bool use_t_bounds;
	bbox_t t_bounds_bbox;
	if(t_bounds_wkt_fn) {
		use_t_bounds = 1;
		t_bounds_mp = mpoly_from_wktfile(t_bounds_wkt_fn);
		t_bounds_bbox = get_polygon_bbox(&t_bounds_mp);
	} else {
		use_t_bounds = 0;
		t_bounds_bbox = (bbox_t){ 0, 0, 0, 0, 0 }; // prevents compiler warning
	}

	ring_t pl;
	pl.pts = NULL;
	pl.npts = 0;

	PointStats ps_border;
	PointStats ps_interior;
	PointStats ps_bounds;

	// Sample a regular grid of points, take the ones within the source region,
	// and project them to the target projection.  This is done to handle the
	// cases where the projected border does not necessarily encircle the
	// source region (such as would be the case for a source region that
	// encircles the pole with a target lonlat projection).
	int num_grid_steps = 100;
	for(int grid_xi=0; grid_xi<=num_grid_steps; grid_xi++) {
		vertex_t src_pt;
		double alpha_x = (double)grid_xi / (double)num_grid_steps;
		src_pt.x = src_bbox.min_x + (src_bbox.max_x - src_bbox.min_x) * alpha_x;
		for(int grid_yi=0; grid_yi<=num_grid_steps; grid_yi++) {
			double alpha_y = (double)grid_yi / (double)num_grid_steps;
			src_pt.y = src_bbox.min_y + (src_bbox.max_y - src_bbox.min_y) * alpha_y;
			if(!polygon_contains_point(&src_mp, src_pt.x, src_pt.y)) continue;

			ps_interior.total++;

			vertex_t tgt_pt = src_pt;
			if(!picky_transform(fwd_xform, inv_xform, &tgt_pt)) {
				continue;
			}

			ps_interior.proj_ok++;

			if(!use_t_bounds || polygon_contains_point(&t_bounds_mp, tgt_pt.x, tgt_pt.y)) {
				ps_interior.contained++;
				add_point_to_ring(&pl, tgt_pt);
			}
		}
	}

	// Project points along the source region border to the target projection.
	double max_step_len = MAX(
		src_bbox.max_x - src_bbox.min_x,
		src_bbox.max_y - src_bbox.min_y) / 1000.0;
	for(int r_idx=0; r_idx<src_mp.num_rings; r_idx++) {
		ring_t *ring = src_mp.rings + r_idx;
		for(int v_idx=0; v_idx<ring->npts; v_idx++) {
			vertex_t v1 = ring->pts[v_idx];
			vertex_t v2 = ring->pts[(v_idx+1) % ring->npts];
			double dx = v2.x - v1.x;
			double dy = v2.y - v1.y;
			double len = sqrt(dx*dx + dy*dy);
			int num_steps = 1 + (int)(len / max_step_len);
			for(int step=0; step<=num_steps; step++) {
				double alpha = (double)step / (double)num_steps;
				vertex_t src_pt;
				src_pt.x = v1.x + dx * alpha;
				src_pt.y = v1.y + dy * alpha;

				ps_border.total++;

				vertex_t tgt_pt = src_pt;
				if(!picky_transform(fwd_xform, inv_xform, &tgt_pt)) {
					continue;
				}

				ps_border.proj_ok++;

				if(!use_t_bounds || polygon_contains_point(&t_bounds_mp, tgt_pt.x, tgt_pt.y)) {
					ps_border.contained++;
					add_point_to_ring(&pl, tgt_pt);
				}
			}
		}
	}

	// Take points along the border of the t_bounds clip shape that lie within the
	// source region.
	if(use_t_bounds) {
		double max_step_len = MAX(
			t_bounds_bbox.max_x - t_bounds_bbox.min_x,
			t_bounds_bbox.max_y - t_bounds_bbox.min_y) / 1000.0;
		for(int r_idx=0; r_idx<t_bounds_mp.num_rings; r_idx++) {
			ring_t *ring = t_bounds_mp.rings + r_idx;
			for(int v_idx=0; v_idx<ring->npts; v_idx++) {
				vertex_t v1 = ring->pts[v_idx];
				vertex_t v2 = ring->pts[(v_idx+1) % ring->npts];
				double dx = v2.x - v1.x;
				double dy = v2.y - v1.y;
				double len = sqrt(dx*dx + dy*dy);
				int num_steps = 1 + (int)(len / max_step_len);
				for(int step=0; step<=num_steps; step++) {
					double alpha = (double)step / (double)num_steps;
					vertex_t tgt_pt;
					tgt_pt.x = v1.x + dx * alpha;
					tgt_pt.y = v1.y + dy * alpha;

					ps_bounds.total++;

					vertex_t src_pt = tgt_pt;
					if(!picky_transform(inv_xform, fwd_xform, &src_pt)) {
						continue;
					}

					ps_bounds.proj_ok++;

					if(polygon_contains_point(&src_mp, src_pt.x, src_pt.y)) {
						ps_bounds.contained++;
						add_point_to_ring(&pl, tgt_pt);
					}
				}
			}
		}
	}

	//int debug = 1;
	//if(debug) {
	//	ps_border.printYaml("stats_border");
	//	ps_interior.printYaml("stats_interior");
	//	ps_bounds.printYaml("stats_bounds");
	//}

	//fprintf(stderr, "got %d points\n", pl.npts);
	bbox_t bbox = get_ring_bbox(&pl);
	printf("bounds:\n");
	printf("  min_e: %.15f\n", bbox.min_x);
	printf("  min_n: %.15f\n", bbox.min_y);
	printf("  max_e: %.15f\n", bbox.max_x);
	printf("  max_n: %.15f\n", bbox.max_y);

	if(report_fn) plot_points(&pl, report_fn);

	return 0;
}

void plot_points(ring_t *pl, const char *fn) {
	bbox_t bbox = get_ring_bbox(pl);
	bbox.min_x -= (bbox.max_x - bbox.min_x) * .05;
	bbox.max_x += (bbox.max_x - bbox.min_x) * .05;
	bbox.min_y -= (bbox.max_y - bbox.min_y) * .05;
	bbox.max_y += (bbox.max_y - bbox.min_y) * .05;
	double W = bbox.max_x - bbox.min_x;
	double H = bbox.max_y - bbox.min_y;
	report_image_t *dbuf = create_plot(W, H);
	for(int i=0; i<pl->npts; i++) {
		vertex_t v = pl->pts[i];
		double x = v.x - bbox.min_x;
		double y = bbox.max_y - v.y;
		plot_point(dbuf, x, y, 255, 255, 255);
	}
	write_plot(dbuf, fn);
}
<|endoftext|>