<commit_before>/***************** <Tweek heading BEGIN do not edit this line> ****************
 * Tweek
 *
 * -----------------------------------------------------------------
 * File:          $RCSfile$
 * Date modified: $Date$
 * Version:       $Revision$
 * -----------------------------------------------------------------
 ***************** <Tweek heading END do not edit this line> *****************/

/*************** <auto-copyright.pl BEGIN do not edit this line> **************
 *
 * VR Juggler is (C) Copyright 1998, 1999, 2000, 2001 by Iowa State University
 *
 * Original Authors:
 *   Allen Bierbaum, Christopher Just,
 *   Patrick Hartling, Kevin Meinert,
 *   Carolina Cruz-Neira, Albert Baker
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 *************** <auto-copyright.pl END do not edit this line> ***************/

#include <tweek/tweekConfig.h>

#include <vpr/Util/Debug.h>
#include <vpr/Util/Assert.h>

#include <tweek/CORBA/SubjectManager.h>
#include <tweek/CORBA/CorbaManager.h>

namespace tweek
{

vpr::ReturnStatus CorbaManager::init (const std::string& local_id, int argc,
                                      char** argv)
{
   vpr::ReturnStatus status;

   try
   {
      // Initialize the ORB.
      vprDEBUG(vprDBG_ALL, vprDBG_STATE_LVL) << "Initializing ORB\n"
                                             << vprDEBUG_FLUSH;
      m_orb = CORBA::ORB_init(argc, argv, "omniORB3");

      status = createChildPOA(local_id);

      try
      {
         status = initNamingService("NameService", local_id);
      }
      catch (CORBA::ORB::InvalidName& ex)
      {
         // This should not happen!
         vprDEBUG(vprDBG_ALL, vprDBG_CRITICAL_LVL)
            << "NameService name invalid in CorbaManager::init!\n"
            << vprDEBUG_FLUSH;
      }

      vprDEBUG(vprDBG_ALL, vprDBG_STATE_LVL) << "Starting ORB thread\n"
                                             << vprDEBUG_FLUSH;
      vpr::ThreadMemberFunctor<CorbaManager>* corba_run =
         new vpr::ThreadMemberFunctor<CorbaManager>(this, &CorbaManager::run);

      m_my_thread = new vpr::Thread(corba_run);
   }
   catch (CORBA::SystemException&)
   {
      status.setCode(vpr::ReturnStatus::Fail);
      vprDEBUG(vprDBG_ALL, vprDBG_CRITICAL_LVL)
         << "Caught CORBA::SystemException\n" << vprDEBUG_FLUSH;
   }
   catch (CORBA::Exception&)
   {
      status.setCode(vpr::ReturnStatus::Fail);
      vprDEBUG(vprDBG_ALL, vprDBG_CRITICAL_LVL)
         << "Caught CORBA::Exception.\n" << vprDEBUG_FLUSH;
   }
   catch (omniORB::fatalException& fe)
   {
      status.setCode(vpr::ReturnStatus::Fail);
      vprDEBUG(vprDBG_ALL, vprDBG_CRITICAL_LVL)
         << "Caught omniORB::fatalException:\n" << vprDEBUG_FLUSH;
      vprDEBUG_NEXT(vprDBG_ALL, vprDBG_CRITICAL_LVL)
         << "  file: " << fe.file() << endl << vprDEBUG_FLUSH;
      vprDEBUG_NEXT(vprDBG_ALL, vprDBG_CRITICAL_LVL)
         << "  line: " << fe.line() << endl << vprDEBUG_FLUSH;
      vprDEBUG_NEXT(vprDBG_ALL, vprDBG_CRITICAL_LVL)
         << "  mesg: " << fe.errmsg() << endl << vprDEBUG_FLUSH;
   }
   catch(...)
   {
      cerr << "Caught unknown exception." << endl;
   }

   return status;
}

vpr::ReturnStatus CorbaManager::registerSubjectManager (tweek::SubjectManagerImpl* mgr)
{
   vprASSERT(! CORBA::is_nil(m_root_context) && "No naming service available");
   vprASSERT(! CORBA::is_nil(m_local_context) && "No naming service available");
   vpr::ReturnStatus status;

   tweek::SubjectManager_ptr mgr_ptr;

   // Try to activate the given servant with our child POA before anyone tries
   // to use it.
   try
   {
      m_subj_mgr_id = m_child_poa->activate_object(mgr);
   }
   // This will be raised if the IdUniqunessPolicy within our child POA is set
   // to UNIQUE_ID.
   catch (PortableServer::POA::ServantAlreadyActive& active_ex)
   {
      vprDEBUG(vprDBG_ALL, vprDBG_WARNING_LVL)
         << "WARNING: Servant already active within our POA\n"
         << vprDEBUG_FLUSH;
   }
   catch (PortableServer::POA::WrongPolicy& policy_ex)
   {
      status.setCode(vpr::ReturnStatus::Fail);
      vprDEBUG(vprDBG_ALL, vprDBG_CRITICAL_LVL)
         << "Invalid policy used when activating Subject Manager object\n"
         << vprDEBUG_FLUSH;
   }

   // Only proceed if we were able to activate an object within the POA.  If
   // we couldn't, there is no point in registering anything with the naming
   // service.
   if ( status.success() )
   {
      // Try to add the mgr_ptr reference to the bound references known to the
      // naming service.
      try
      {
         const char* id   = "SubjectManager";
         const char* kind = "Object";
         CosNaming::Name context_name;

         // This gives us our reference from the POA to the servant that was
         // registered above.  This does not perform object activation because
         // the object was activated above.
         mgr_ptr = mgr->_this();

         vprASSERT(! CORBA::is_nil(mgr_ptr) && "CORBA object not activated in POA");

         context_name.length(1);
         context_name[0].id   = CORBA::string_dup(id);
         context_name[0].kind = CORBA::string_dup(kind);

         // Bind the Subject Manager reference and activate the object within
         // the POA.  If a Subject Manager is already bound, the exceptoin
         // thrown prevents either operation from happening.  This is correct
         // since we only want one Subject Manager per address space.
         try
         {
            m_local_context->bind(context_name, mgr_ptr);
         }
         catch (CosNaming::NamingContext::AlreadyBound& ex)
         {
            vprDEBUG(vprDBG_ALL, vprDBG_WARNING_LVL)
               << "WARNING: Subject manager reference already bound!\n"
               << vprDEBUG_FLUSH;
         }
      }
      catch (CORBA::COMM_FAILURE& ex)
      {
         status.setCode(vpr::ReturnStatus::Fail);
         vprDEBUG(vprDBG_ALL, vprDBG_WARNING_LVL)
            << "Unable to contact the naming service\n" << vprDEBUG_FLUSH;
      }
      catch (CORBA::SystemException&)
      {
         status.setCode(vpr::ReturnStatus::Fail);
         vprDEBUG(vprDBG_ALL, vprDBG_WARNING_LVL)
            << "Caught a CORBA::SystemException while using the naming service"
            << std::endl << vprDEBUG_FLUSH;
      }
   }

   return status;
}

// ============================================================================
// Private methods.
// ============================================================================

vpr::ReturnStatus CorbaManager::createChildPOA (const std::string& local_id)
{
   vpr::ReturnStatus status;
   CORBA::Object_var obj;
   CORBA::PolicyList policy_list;

   // Obtain a reference to the root POA.  The caller will have to catch any
   // thrown exceptions.
   vprDEBUG(vprDBG_ALL, vprDBG_STATE_LVL) << "Requesting Root POA\n"
                                          << vprDEBUG_FLUSH;
   obj        = m_orb->resolve_initial_references("RootPOA");
   m_root_poa = PortableServer::POA::_narrow(obj);

   vprASSERT(! CORBA::is_nil(m_root_poa) && "Failed to get Root POA");

   // We want to allow multiple IDs to the same object and retain the
   // references.  The latter is required if we wish to do explict activation.
   PortableServer::IdUniquenessPolicy_var uniq_policy =
      m_root_poa->create_id_uniqueness_policy(PortableServer::MULTIPLE_ID);
   PortableServer::ServantRetentionPolicy_var retain_policy =
      m_root_poa->create_servant_retention_policy(PortableServer::RETAIN);
   PortableServer::ThreadPolicy_var thread_policy =
      m_root_poa->create_thread_policy(PortableServer::ORB_CTRL_MODEL);

   policy_list.length(3);
   policy_list[0] =
      PortableServer::IdUniquenessPolicy::_duplicate(uniq_policy);
   policy_list[1] =
      PortableServer::ServantRetentionPolicy::_duplicate(retain_policy);
   policy_list[2] =
      PortableServer::ThreadPolicy::_duplicate(thread_policy);

   std::string poa_name = "tweek_" + local_id;

   try
   {
      vprDEBUG(vprDBG_ALL, vprDBG_STATE_LVL)
         << "Creating child of root POA named " << poa_name << std::endl
         << vprDEBUG_FLUSH;
      m_child_poa = m_root_poa->create_POA(poa_name.c_str(),
                                           PortableServer::POAManager::_nil(),
                                           policy_list);
   }
   catch (PortableServer::POA::AdapterAlreadyExists& ex)
   {
      status.setCode(vpr::ReturnStatus::Fail);
      vprDEBUG(vprDBG_ALL, vprDBG_WARNING_LVL)
         << "WARNING: Child POA named '" << poa_name << "' already exists!\n"
         << vprDEBUG_FLUSH;
   }
   catch (PortableServer::POA::InvalidPolicy& ex)
   {
      status.setCode(vpr::ReturnStatus::Fail);
      vprDEBUG(vprDBG_ALL, vprDBG_WARNING_LVL)
         << "WARNING: Failed to set IdUniquenessPolicy for child POA\n"
         << vprDEBUG_FLUSH;
   }

   uniq_policy->destroy();
   retain_policy->destroy();

   return status;
}

/**
 *
 * @post The root context is retrieved through m_orb, and a sub-context is
 *       created for use within this memory space.
 */
vpr::ReturnStatus CorbaManager::initNamingService (const std::string& ref_name,
                                                   const std::string& local_id)
{
   CORBA::Object_var name_obj;
   vpr::ReturnStatus status;

   vprDEBUG(vprDBG_ALL, vprDBG_STATE_LVL) << "Requesting Name Service\n"
                                          << vprDEBUG_FLUSH;
   name_obj       = m_orb->resolve_initial_references(ref_name.c_str());
   m_root_context = CosNaming::NamingContext::_narrow(name_obj);

   if ( CORBA::is_nil(m_root_context) )
   {
      status.setCode(vpr::ReturnStatus::Fail);
      vprDEBUG(vprDBG_ALL, vprDBG_CRITICAL_LVL)
         << "Failed to narrow Naming Service root context\n"
         << vprDEBUG_FLUSH;
   }
   else
   {
      std::string id("tweek");
      std::string kind("context");
      CosNaming::Name tweek_context_name;

//      id.append(local_id);

      tweek_context_name.length(1);
      tweek_context_name[0].id   = CORBA::string_dup(id.c_str());
      tweek_context_name[0].kind = CORBA::string_dup(kind.c_str());

      try
      {
         m_local_context = m_root_context->bind_new_context(tweek_context_name);
      }
      catch (CosNaming::NamingContext::AlreadyBound& ex)
      {
         CORBA::Object_var temp_obj;

         temp_obj        = m_root_context->resolve(tweek_context_name);
         m_local_context = CosNaming::NamingContext::_narrow(temp_obj);

         if ( CORBA::is_nil(m_local_context) )
         {
            status.setCode(vpr::ReturnStatus::Fail);
            vprDEBUG(vprDBG_ALL, vprDBG_CRITICAL_LVL)
               << "Failed to narrow Naming Service local Tweek context\n"
               << vprDEBUG_FLUSH;
         }
      }
   }

   return status;
}

void CorbaManager::run(void* args)
{
   vprDEBUG(vprDBG_ALL, vprDBG_STATE_LVL) << "Server is running!\n"
                                          << vprDEBUG_FLUSH;

   PortableServer::POAManager_var pman = m_child_poa->the_POAManager();

   pman->activate();
   m_orb->run();
   m_orb->destroy();
}

} // End of tweek namespace
<commit_msg>Print a warning at the critical level just before the attempt to resolve the Naming Service if the environment variable $OMNIORB_CONFIG is not set. Without this variable, finding and/or connecting to the Naming Service is likely to be very difficult.  Printing this warning is mostly for my benefit if I forget some configuration step during testing, but future users will probably do well to be reminded of this too.<commit_after>/***************** <Tweek heading BEGIN do not edit this line> ****************
 * Tweek
 *
 * -----------------------------------------------------------------
 * File:          $RCSfile$
 * Date modified: $Date$
 * Version:       $Revision$
 * -----------------------------------------------------------------
 ***************** <Tweek heading END do not edit this line> *****************/

/*************** <auto-copyright.pl BEGIN do not edit this line> **************
 *
 * VR Juggler is (C) Copyright 1998, 1999, 2000, 2001 by Iowa State University
 *
 * Original Authors:
 *   Allen Bierbaum, Christopher Just,
 *   Patrick Hartling, Kevin Meinert,
 *   Carolina Cruz-Neira, Albert Baker
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 *************** <auto-copyright.pl END do not edit this line> ***************/

#include <tweek/tweekConfig.h>

#include <vpr/vpr.h>
#include <vpr/System.h>
#include <vpr/Util/Debug.h>
#include <vpr/Util/Assert.h>

#include <tweek/CORBA/SubjectManager.h>
#include <tweek/CORBA/CorbaManager.h>

namespace tweek
{

vpr::ReturnStatus CorbaManager::init (const std::string& local_id, int argc,
                                      char** argv)
{
   vpr::ReturnStatus status;

   try
   {
      // Initialize the ORB.
      vprDEBUG(vprDBG_ALL, vprDBG_STATE_LVL) << "Initializing ORB\n"
                                             << vprDEBUG_FLUSH;
      m_orb = CORBA::ORB_init(argc, argv, "omniORB3");

      status = createChildPOA(local_id);

      try
      {
         status = initNamingService("NameService", local_id);
      }
      catch (CORBA::ORB::InvalidName& ex)
      {
         // This should not happen!
         vprDEBUG(vprDBG_ALL, vprDBG_CRITICAL_LVL)
            << "NameService name invalid in CorbaManager::init!\n"
            << vprDEBUG_FLUSH;
      }

      vprDEBUG(vprDBG_ALL, vprDBG_STATE_LVL) << "Starting ORB thread\n"
                                             << vprDEBUG_FLUSH;
      vpr::ThreadMemberFunctor<CorbaManager>* corba_run =
         new vpr::ThreadMemberFunctor<CorbaManager>(this, &CorbaManager::run);

      m_my_thread = new vpr::Thread(corba_run);
   }
   catch (CORBA::SystemException&)
   {
      status.setCode(vpr::ReturnStatus::Fail);
      vprDEBUG(vprDBG_ALL, vprDBG_CRITICAL_LVL)
         << "Caught CORBA::SystemException\n" << vprDEBUG_FLUSH;
   }
   catch (CORBA::Exception&)
   {
      status.setCode(vpr::ReturnStatus::Fail);
      vprDEBUG(vprDBG_ALL, vprDBG_CRITICAL_LVL)
         << "Caught CORBA::Exception.\n" << vprDEBUG_FLUSH;
   }
   catch (omniORB::fatalException& fe)
   {
      status.setCode(vpr::ReturnStatus::Fail);
      vprDEBUG(vprDBG_ALL, vprDBG_CRITICAL_LVL)
         << "Caught omniORB::fatalException:\n" << vprDEBUG_FLUSH;
      vprDEBUG_NEXT(vprDBG_ALL, vprDBG_CRITICAL_LVL)
         << "  file: " << fe.file() << endl << vprDEBUG_FLUSH;
      vprDEBUG_NEXT(vprDBG_ALL, vprDBG_CRITICAL_LVL)
         << "  line: " << fe.line() << endl << vprDEBUG_FLUSH;
      vprDEBUG_NEXT(vprDBG_ALL, vprDBG_CRITICAL_LVL)
         << "  mesg: " << fe.errmsg() << endl << vprDEBUG_FLUSH;
   }
   catch(...)
   {
      cerr << "Caught unknown exception." << endl;
   }

   return status;
}

vpr::ReturnStatus CorbaManager::registerSubjectManager (tweek::SubjectManagerImpl* mgr)
{
   vprASSERT(! CORBA::is_nil(m_root_context) && "No naming service available");
   vprASSERT(! CORBA::is_nil(m_local_context) && "No naming service available");
   vpr::ReturnStatus status;

   tweek::SubjectManager_ptr mgr_ptr;

   // Try to activate the given servant with our child POA before anyone tries
   // to use it.
   try
   {
      m_subj_mgr_id = m_child_poa->activate_object(mgr);
   }
   // This will be raised if the IdUniqunessPolicy within our child POA is set
   // to UNIQUE_ID.
   catch (PortableServer::POA::ServantAlreadyActive& active_ex)
   {
      vprDEBUG(vprDBG_ALL, vprDBG_WARNING_LVL)
         << "WARNING: Servant already active within our POA\n"
         << vprDEBUG_FLUSH;
   }
   catch (PortableServer::POA::WrongPolicy& policy_ex)
   {
      status.setCode(vpr::ReturnStatus::Fail);
      vprDEBUG(vprDBG_ALL, vprDBG_CRITICAL_LVL)
         << "Invalid policy used when activating Subject Manager object\n"
         << vprDEBUG_FLUSH;
   }

   // Only proceed if we were able to activate an object within the POA.  If
   // we couldn't, there is no point in registering anything with the naming
   // service.
   if ( status.success() )
   {
      // Try to add the mgr_ptr reference to the bound references known to the
      // naming service.
      try
      {
         const char* id   = "SubjectManager";
         const char* kind = "Object";
         CosNaming::Name context_name;

         // This gives us our reference from the POA to the servant that was
         // registered above.  This does not perform object activation because
         // the object was activated above.
         mgr_ptr = mgr->_this();

         vprASSERT(! CORBA::is_nil(mgr_ptr) && "CORBA object not activated in POA");

         context_name.length(1);
         context_name[0].id   = CORBA::string_dup(id);
         context_name[0].kind = CORBA::string_dup(kind);

         // Bind the Subject Manager reference and activate the object within
         // the POA.  If a Subject Manager is already bound, the exceptoin
         // thrown prevents either operation from happening.  This is correct
         // since we only want one Subject Manager per address space.
         try
         {
            m_local_context->bind(context_name, mgr_ptr);
         }
         catch (CosNaming::NamingContext::AlreadyBound& ex)
         {
            vprDEBUG(vprDBG_ALL, vprDBG_WARNING_LVL)
               << "WARNING: Subject manager reference already bound!\n"
               << vprDEBUG_FLUSH;
         }
      }
      catch (CORBA::COMM_FAILURE& ex)
      {
         status.setCode(vpr::ReturnStatus::Fail);
         vprDEBUG(vprDBG_ALL, vprDBG_WARNING_LVL)
            << "Unable to contact the naming service\n" << vprDEBUG_FLUSH;
      }
      catch (CORBA::SystemException&)
      {
         status.setCode(vpr::ReturnStatus::Fail);
         vprDEBUG(vprDBG_ALL, vprDBG_WARNING_LVL)
            << "Caught a CORBA::SystemException while using the naming service"
            << std::endl << vprDEBUG_FLUSH;
      }
   }

   return status;
}

// ============================================================================
// Private methods.
// ============================================================================

vpr::ReturnStatus CorbaManager::createChildPOA (const std::string& local_id)
{
   vpr::ReturnStatus status;
   CORBA::Object_var obj;
   CORBA::PolicyList policy_list;

   // Obtain a reference to the root POA.  The caller will have to catch any
   // thrown exceptions.
   vprDEBUG(vprDBG_ALL, vprDBG_STATE_LVL) << "Requesting Root POA\n"
                                          << vprDEBUG_FLUSH;
   obj        = m_orb->resolve_initial_references("RootPOA");
   m_root_poa = PortableServer::POA::_narrow(obj);

   vprASSERT(! CORBA::is_nil(m_root_poa) && "Failed to get Root POA");

   // We want to allow multiple IDs to the same object and retain the
   // references.  The latter is required if we wish to do explict activation.
   PortableServer::IdUniquenessPolicy_var uniq_policy =
      m_root_poa->create_id_uniqueness_policy(PortableServer::MULTIPLE_ID);
   PortableServer::ServantRetentionPolicy_var retain_policy =
      m_root_poa->create_servant_retention_policy(PortableServer::RETAIN);
   PortableServer::ThreadPolicy_var thread_policy =
      m_root_poa->create_thread_policy(PortableServer::ORB_CTRL_MODEL);

   policy_list.length(3);
   policy_list[0] =
      PortableServer::IdUniquenessPolicy::_duplicate(uniq_policy);
   policy_list[1] =
      PortableServer::ServantRetentionPolicy::_duplicate(retain_policy);
   policy_list[2] =
      PortableServer::ThreadPolicy::_duplicate(thread_policy);

   std::string poa_name = "tweek_" + local_id;

   try
   {
      vprDEBUG(vprDBG_ALL, vprDBG_STATE_LVL)
         << "Creating child of root POA named " << poa_name << std::endl
         << vprDEBUG_FLUSH;
      m_child_poa = m_root_poa->create_POA(poa_name.c_str(),
                                           PortableServer::POAManager::_nil(),
                                           policy_list);
   }
   catch (PortableServer::POA::AdapterAlreadyExists& ex)
   {
      status.setCode(vpr::ReturnStatus::Fail);
      vprDEBUG(vprDBG_ALL, vprDBG_WARNING_LVL)
         << "WARNING: Child POA named '" << poa_name << "' already exists!\n"
         << vprDEBUG_FLUSH;
   }
   catch (PortableServer::POA::InvalidPolicy& ex)
   {
      status.setCode(vpr::ReturnStatus::Fail);
      vprDEBUG(vprDBG_ALL, vprDBG_WARNING_LVL)
         << "WARNING: Failed to set IdUniquenessPolicy for child POA\n"
         << vprDEBUG_FLUSH;
   }

   uniq_policy->destroy();
   retain_policy->destroy();

   return status;
}

/**
 *
 * @post The root context is retrieved through m_orb, and a sub-context is
 *       created for use within this memory space.
 */
vpr::ReturnStatus CorbaManager::initNamingService (const std::string& ref_name,
                                                   const std::string& local_id)
{
   CORBA::Object_var name_obj;
   vpr::ReturnStatus status;

   // If the user does not have the OMNIORB_CONFIG environment variable set,
   // there will most likely be problems finding and/or contacting the
   // Naming Service.  To that end, print a warning saying as much when the
   // variable is not set.
   std::string temp;
   if ( vpr::System::getenv("OMNIORB_CONFIG", temp).failure() )
   {
      vprDEBUG(vprDBG_ALL, vprDBG_CRITICAL_LVL)
         << clrOutBOLD(clrRED, "WARNING: OMNIORB_CONFIG not set!  Expect problems contacting the Naming Service\n")
         << vprDEBUG_FLUSH;
   }

   vprDEBUG(vprDBG_ALL, vprDBG_STATE_LVL) << "Requesting Name Service\n"
                                          << vprDEBUG_FLUSH;
   name_obj       = m_orb->resolve_initial_references(ref_name.c_str());
   m_root_context = CosNaming::NamingContext::_narrow(name_obj);

   if ( CORBA::is_nil(m_root_context) )
   {
      status.setCode(vpr::ReturnStatus::Fail);
      vprDEBUG(vprDBG_ALL, vprDBG_CRITICAL_LVL)
         << "Failed to narrow Naming Service root context\n"
         << vprDEBUG_FLUSH;
   }
   else
   {
      std::string id("tweek");
      std::string kind("context");
      CosNaming::Name tweek_context_name;

//      id.append(local_id);

      tweek_context_name.length(1);
      tweek_context_name[0].id   = CORBA::string_dup(id.c_str());
      tweek_context_name[0].kind = CORBA::string_dup(kind.c_str());

      try
      {
         m_local_context = m_root_context->bind_new_context(tweek_context_name);
      }
      catch (CosNaming::NamingContext::AlreadyBound& ex)
      {
         CORBA::Object_var temp_obj;

         temp_obj        = m_root_context->resolve(tweek_context_name);
         m_local_context = CosNaming::NamingContext::_narrow(temp_obj);

         if ( CORBA::is_nil(m_local_context) )
         {
            status.setCode(vpr::ReturnStatus::Fail);
            vprDEBUG(vprDBG_ALL, vprDBG_CRITICAL_LVL)
               << "Failed to narrow Naming Service local Tweek context\n"
               << vprDEBUG_FLUSH;
         }
      }
   }

   return status;
}

void CorbaManager::run(void* args)
{
   vprDEBUG(vprDBG_ALL, vprDBG_STATE_LVL) << "Server is running!\n"
                                          << vprDEBUG_FLUSH;

   PortableServer::POAManager_var pman = m_child_poa->the_POAManager();

   pman->activate();
   m_orb->run();
   m_orb->destroy();
}

} // End of tweek namespace
<|endoftext|>


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

#ifndef _IDLC_IDLC_HXX_
#include <idlc/idlc.hxx>
#endif
#ifndef _REGISTRY_REGISTRY_HXX_
#include <registry/registry.hxx>
#endif

class AstScope;

// Enum defining the different kinds of Ast nodes
enum NodeType
{
    NT_object,              // Denotes an object
    NT_service,             // Denotes an servcie
    NT_interface_member,    // Denotes an interface which is exported from object
    NT_service_member,      // Denotes an service which is exported from object
    NT_observes,            // Denotes an observed interface
    NT_needs,               // Denotes an needed service
    NT_module,              // Denotes a module
    NT_root,                // Denotes the root of AST
    NT_interface,           // Denotes an interface
    NT_constants,           // Denotes a constant group
    NT_const,               // Denotes a constant
    NT_exception,           // Denotes an exception
    NT_attribute,           // Denotes an attribute
    NT_property,            // Denotes an property
    NT_operation,           // Denotes an operation
    NT_parameter,           // Denotes an op. parameter
    NT_union,               // Denotes a union
    NT_union_branch,        // Denotes a union branch
    NT_struct,              // Denotes either a plain struct type, or a
                            // polymorphic struct type template
    NT_type_parameter,      // Denotes a type parameter of a polymorphic struct
                            // type template
    NT_instantiated_struct, // Denotes an instantiated polymorphic struct type
    NT_member,              // Denotes a member in structure, exception
    NT_enum,                // Denotes an enumeration
    NT_enum_val,            // Denotes an enum. value
    NT_array,               // Denotes an IDL array
    NT_sequence,            // Denotes an IDL sequence
    NT_typedef,             // Denotes a typedef
    NT_predefined,          // Denotes a predefined type
    NT_singleton            // Denotes a singleton
};

class AstDeclaration
{
public:
    // Constructors
    AstDeclaration(NodeType type, const ::rtl::OString& name, AstScope* pScope);
    virtual ~AstDeclaration();

    // Data access
    void setName(const ::rtl::OString& name);
    const ::rtl::OString& getLocalName() const
        { return m_localName; }
    const ::rtl::OString&   getScopedName() const
        { return m_scopedName; }
    const ::rtl::OString&   getFullName()
        { return m_fullName; }
    virtual const sal_Char* getRelativName() const
        { return m_fullName.getStr()+1; }
    AstScope* getScope()
        { return m_pScope; }
    void setScope(AstScope* pSc)
        { m_pScope = pSc; }
    NodeType getNodeType() const
        { return m_nodeType; }
    sal_Bool isInMainfile() const
        { return m_bInMainFile; }
    void setInMainfile(sal_Bool bInMainfile)
        { m_bInMainFile = bInMainfile; }
    sal_Bool isImported() const
        { return m_bImported; }
    void setImported(sal_Bool bImported)
        { m_bImported = bImported; }
    sal_Int32 getLineNumber() const
        { return m_lineNumber; }
    void setLineNumber(sal_Int32 lineNumber)
        { m_lineNumber = lineNumber; }
    const ::rtl::OString& getFileName() const
        { return m_fileName; }
    void setFileName(const ::rtl::OString& rFileName)
        { m_fileName = rFileName; }
    const ::rtl::OUString& getDocumentation() const
        { return m_documentation; }
    void setDocumentation(const ::rtl::OUString& rDocumentation)
        { m_documentation = rDocumentation; }
    sal_Bool isAdded()
        { return m_bIsAdded; }
    void markAsAdded()
        { m_bIsAdded = sal_True; }

    virtual bool isType() const;

    sal_Bool hasAncestor(AstDeclaration* pDecl);

    bool isPublished() const { return m_bPublished; }

    virtual sal_Bool dump(RegistryKey& rKey);
protected:
    ::rtl::OString      m_localName;
    ::rtl::OString      m_scopedName;       // full qualified name
    ::rtl::OString      m_fullName;         // full qualified name with '/' as seperator
    AstScope*           m_pScope;
    const NodeType      m_nodeType;
    sal_Bool            m_bImported;        // imported ?
    sal_Bool            m_bIsAdded;         // mark declaration as added in scope
    sal_Bool            m_bInMainFile;      // defined in main file
    bool                m_bPublished;
    sal_Int32           m_lineNumber;       // line number defined in
    ::rtl::OString      m_fileName;         // fileName defined in
    ::rtl::OUString     m_documentation;    // fileName defined in
};

#endif // _IDLC_ASTDECLARATION_HXX_

<commit_msg>INTEGRATION: CWS ooo19126 (1.5.32); FILE MERGED 2005/09/05 17:39:30 rt 1.5.32.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: astdeclaration.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 17:56:00 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _IDLC_ASTDECLARATION_HXX_
#define _IDLC_ASTDECLARATION_HXX_

#ifndef _IDLC_IDLC_HXX_
#include <idlc/idlc.hxx>
#endif
#ifndef _REGISTRY_REGISTRY_HXX_
#include <registry/registry.hxx>
#endif

class AstScope;

// Enum defining the different kinds of Ast nodes
enum NodeType
{
    NT_object,              // Denotes an object
    NT_service,             // Denotes an servcie
    NT_interface_member,    // Denotes an interface which is exported from object
    NT_service_member,      // Denotes an service which is exported from object
    NT_observes,            // Denotes an observed interface
    NT_needs,               // Denotes an needed service
    NT_module,              // Denotes a module
    NT_root,                // Denotes the root of AST
    NT_interface,           // Denotes an interface
    NT_constants,           // Denotes a constant group
    NT_const,               // Denotes a constant
    NT_exception,           // Denotes an exception
    NT_attribute,           // Denotes an attribute
    NT_property,            // Denotes an property
    NT_operation,           // Denotes an operation
    NT_parameter,           // Denotes an op. parameter
    NT_union,               // Denotes a union
    NT_union_branch,        // Denotes a union branch
    NT_struct,              // Denotes either a plain struct type, or a
                            // polymorphic struct type template
    NT_type_parameter,      // Denotes a type parameter of a polymorphic struct
                            // type template
    NT_instantiated_struct, // Denotes an instantiated polymorphic struct type
    NT_member,              // Denotes a member in structure, exception
    NT_enum,                // Denotes an enumeration
    NT_enum_val,            // Denotes an enum. value
    NT_array,               // Denotes an IDL array
    NT_sequence,            // Denotes an IDL sequence
    NT_typedef,             // Denotes a typedef
    NT_predefined,          // Denotes a predefined type
    NT_singleton            // Denotes a singleton
};

class AstDeclaration
{
public:
    // Constructors
    AstDeclaration(NodeType type, const ::rtl::OString& name, AstScope* pScope);
    virtual ~AstDeclaration();

    // Data access
    void setName(const ::rtl::OString& name);
    const ::rtl::OString& getLocalName() const
        { return m_localName; }
    const ::rtl::OString&   getScopedName() const
        { return m_scopedName; }
    const ::rtl::OString&   getFullName()
        { return m_fullName; }
    virtual const sal_Char* getRelativName() const
        { return m_fullName.getStr()+1; }
    AstScope* getScope()
        { return m_pScope; }
    void setScope(AstScope* pSc)
        { m_pScope = pSc; }
    NodeType getNodeType() const
        { return m_nodeType; }
    sal_Bool isInMainfile() const
        { return m_bInMainFile; }
    void setInMainfile(sal_Bool bInMainfile)
        { m_bInMainFile = bInMainfile; }
    sal_Bool isImported() const
        { return m_bImported; }
    void setImported(sal_Bool bImported)
        { m_bImported = bImported; }
    sal_Int32 getLineNumber() const
        { return m_lineNumber; }
    void setLineNumber(sal_Int32 lineNumber)
        { m_lineNumber = lineNumber; }
    const ::rtl::OString& getFileName() const
        { return m_fileName; }
    void setFileName(const ::rtl::OString& rFileName)
        { m_fileName = rFileName; }
    const ::rtl::OUString& getDocumentation() const
        { return m_documentation; }
    void setDocumentation(const ::rtl::OUString& rDocumentation)
        { m_documentation = rDocumentation; }
    sal_Bool isAdded()
        { return m_bIsAdded; }
    void markAsAdded()
        { m_bIsAdded = sal_True; }

    virtual bool isType() const;

    sal_Bool hasAncestor(AstDeclaration* pDecl);

    bool isPublished() const { return m_bPublished; }

    virtual sal_Bool dump(RegistryKey& rKey);
protected:
    ::rtl::OString      m_localName;
    ::rtl::OString      m_scopedName;       // full qualified name
    ::rtl::OString      m_fullName;         // full qualified name with '/' as seperator
    AstScope*           m_pScope;
    const NodeType      m_nodeType;
    sal_Bool            m_bImported;        // imported ?
    sal_Bool            m_bIsAdded;         // mark declaration as added in scope
    sal_Bool            m_bInMainFile;      // defined in main file
    bool                m_bPublished;
    sal_Int32           m_lineNumber;       // line number defined in
    ::rtl::OString      m_fileName;         // fileName defined in
    ::rtl::OUString     m_documentation;    // fileName defined in
};

#endif // _IDLC_ASTDECLARATION_HXX_

<|endoftext|>


<commit_before>/*
 * arcball.cpp
 *
 *  Created on: 10.05.2012
 *      Author: Ralph
 */
#include <QtCore/QtDebug>

#include <math.h>

#include "arcball.h"

ArcBall::ArcBall( int width, int height ) :
    Epsilon( 0.00001 ),
    m_width( width ),
    m_height( height ),
    m_moveX( 0 ),
    m_moveY( 0 ),
    m_oldMoveX( 0 ),
    m_oldMoveY( 0 ),
    m_midClickX( 0 ),
    m_midClickY( 0 ),
    m_zoom( 1.0f )
{
    m_adjust_width  = 1.0 / ((width - 1.0) * 0.5);
    m_adjust_height = 1.0 / ((height - 1.0) * 0.5);

    m_currentRot.setToIdentity();
    m_lastRot.setToIdentity();
}

ArcBall::~ArcBall()
{
}

// maps the specified mouse position to the sphere defined
// with center and radius. the resulting vector lies on the
// surface of the sphere.
QVector3D ArcBall::map_sphere( int x, int y )
{
    float tmpx = ( x * m_adjust_width ) - 1.0;
    float tmpy = 1.0 - ( y * m_adjust_height );

    float length = ( tmpx * tmpx ) + ( tmpy * tmpy );

    QVector3D bm;
    if ( length > 1.0 )
    {
        float norm = 1.0 / sqrt( length );
        bm.setX( tmpx * norm );
        bm.setY( tmpy * norm );
        bm.setZ( 0.0 );
    }
    else
    {
        bm.setX( tmpx );
        bm.setY( tmpy );
        bm.setZ( sqrt( 1.0 - length ) );
    }
    return bm;
}

/// sets the window size.
void ArcBall::set_win_size( int width,  int height )
{
    m_width = width;
    m_height = height;
    m_adjust_width = 1.0 / ( ( width - 1.0 ) * 0.5 );
    m_adjust_height = 1.0 / ( ( height - 1.0 ) * 0.5 );
}

/// sets the current position and calculates the current
/// rotation matrix.
void ArcBall::drag( int x, int y )
{
    QVector3D v_to = map_sphere( x, y );
    QVector3D perp = QVector3D::crossProduct( v_from, v_to);

    if ( perp.length() > Epsilon )
    {
        q_current_rotation.setX( perp.x() );
        q_current_rotation.setY( perp.y() );
        q_current_rotation.setZ( perp.z() );;
        q_current_rotation.setScalar( ( v_from.x() * v_to.x() ) + ( v_from.y() * v_to.y() ) + ( v_from.z() * v_to.z() ) );
    }
    else
    {
        q_current_rotation.setX( 0.0 );
        q_current_rotation.setY( 0.0 );
        q_current_rotation.setZ( 0.0 );
        q_current_rotation.setScalar( 0.0 );
    }
    m_currentRot.setToIdentity();
    m_currentRot.rotate( q_current_rotation );
    m_currentRot = m_currentRot * m_lastRot ;
}

/// indicates the beginning of the dragging.
void ArcBall::click( int x, int y )
{
    m_lastRot = m_currentRot;
    v_mouse_down.setX( x );
    v_mouse_down.setY( y );
    v_mouse_down.setZ( 0.0 );
    v_from = map_sphere( x, y );
}

void ArcBall::midClick( int x, int y )
{
    m_midClickX = x;
    m_midClickY = y;
    m_oldMoveX = m_moveX;
    m_oldMoveY = m_moveY;
}

void ArcBall::mouseWheel( int step )
{
    m_zoom += step;
    m_zoom = qMax( 1.0f, m_zoom );
}

void ArcBall::midDrag( int x, int y )
{
    m_moveX = ( m_oldMoveX + ( m_midClickX - x ) / m_zoom );
    m_moveY = ( m_oldMoveY + ( m_midClickY - y ) / m_zoom );
}

void ArcBall::setRotCenter( float x, float y, float z )
{
    m_rotCenter = QVector3D( -x, -y, -z );
}

void ArcBall::setView( int view )
{
    m_zoom = 1.0;
    m_moveX = 0;
    m_moveY = 0;
    m_oldMoveX = 0;
    m_oldMoveY = 0;
    m_currentRot.setToIdentity();
    m_lastRot.setToIdentity();

    QQuaternion rotx( sqrt(0.5), 0, 0, sqrt(0.5) );
    QQuaternion rot_x( -sqrt(0.5), 0, 0, sqrt(0.5) );
    QQuaternion roty( 0, sqrt(0.5), 0, sqrt(0.5) );
    QQuaternion rot_y( 0, -sqrt(0.5), 0, sqrt(0.5) );
    QQuaternion rotz( 0, 0, sqrt(0.5), sqrt(0.5) );

    if ( view == 2 )
    {
        m_currentRot.rotate( rotz );
        m_currentRot.rotate( rotx );
        m_currentRot.rotate( rotx );
    }
    if ( view == 3 )
    {
        m_currentRot.rotate( rot_x );
        m_currentRot.rotate( rot_y );
    }
}

/// returns the rotation matrix to be used directly
QMatrix4x4 ArcBall::getMVMat()
{
    QMatrix4x4 mv;
    mv.setToIdentity();

    QVector3D scale( m_zoom, m_zoom, m_zoom );
    mv.scale( scale );

    mv = m_currentRot * mv ;

    QVector3D halfMove( -m_moveX, m_moveY, 0 );
    QMatrix4x4 tmp;
    tmp.setToIdentity();
    tmp.translate( halfMove );
    tmp = tmp * m_currentRot;

    mv = mv + tmp;

    mv.translate( m_rotCenter );

    return mv;
}

<commit_msg>fixed zoom when center is moved<commit_after>/*
 * arcball.cpp
 *
 *  Created on: 10.05.2012
 *      Author: Ralph
 */
#include <QtCore/QtDebug>

#include <math.h>

#include "arcball.h"

ArcBall::ArcBall( int width, int height ) :
    Epsilon( 0.00001 ),
    m_width( width ),
    m_height( height ),
    m_moveX( 0 ),
    m_moveY( 0 ),
    m_oldMoveX( 0 ),
    m_oldMoveY( 0 ),
    m_midClickX( 0 ),
    m_midClickY( 0 ),
    m_zoom( 1.0f )
{
    m_adjust_width  = 1.0 / ((width - 1.0) * 0.5);
    m_adjust_height = 1.0 / ((height - 1.0) * 0.5);

    m_currentRot.setToIdentity();
    m_lastRot.setToIdentity();
}

ArcBall::~ArcBall()
{
}

// maps the specified mouse position to the sphere defined
// with center and radius. the resulting vector lies on the
// surface of the sphere.
QVector3D ArcBall::map_sphere( int x, int y )
{
    float tmpx = ( x * m_adjust_width ) - 1.0;
    float tmpy = 1.0 - ( y * m_adjust_height );

    float length = ( tmpx * tmpx ) + ( tmpy * tmpy );

    QVector3D bm;
    if ( length > 1.0 )
    {
        float norm = 1.0 / sqrt( length );
        bm.setX( tmpx * norm );
        bm.setY( tmpy * norm );
        bm.setZ( 0.0 );
    }
    else
    {
        bm.setX( tmpx );
        bm.setY( tmpy );
        bm.setZ( sqrt( 1.0 - length ) );
    }
    return bm;
}

/// sets the window size.
void ArcBall::set_win_size( int width,  int height )
{
    m_width = width;
    m_height = height;
    m_adjust_width = 1.0 / ( ( width - 1.0 ) * 0.5 );
    m_adjust_height = 1.0 / ( ( height - 1.0 ) * 0.5 );
}

/// sets the current position and calculates the current
/// rotation matrix.
void ArcBall::drag( int x, int y )
{
    QVector3D v_to = map_sphere( x, y );
    QVector3D perp = QVector3D::crossProduct( v_from, v_to);

    if ( perp.length() > Epsilon )
    {
        q_current_rotation.setX( perp.x() );
        q_current_rotation.setY( perp.y() );
        q_current_rotation.setZ( perp.z() );;
        q_current_rotation.setScalar( ( v_from.x() * v_to.x() ) + ( v_from.y() * v_to.y() ) + ( v_from.z() * v_to.z() ) );
    }
    else
    {
        q_current_rotation.setX( 0.0 );
        q_current_rotation.setY( 0.0 );
        q_current_rotation.setZ( 0.0 );
        q_current_rotation.setScalar( 0.0 );
    }
    m_currentRot.setToIdentity();
    m_currentRot.rotate( q_current_rotation );
    m_currentRot = m_currentRot * m_lastRot ;
}

/// indicates the beginning of the dragging.
void ArcBall::click( int x, int y )
{
    m_lastRot = m_currentRot;
    v_mouse_down.setX( x );
    v_mouse_down.setY( y );
    v_mouse_down.setZ( 0.0 );
    v_from = map_sphere( x, y );
}

void ArcBall::midClick( int x, int y )
{
    m_midClickX = x;
    m_midClickY = y;
    m_oldMoveX = m_moveX;
    m_oldMoveY = m_moveY;
}

void ArcBall::mouseWheel( int step )
{
    m_zoom += step;
    m_zoom = qMax( 1.0f, m_zoom );
}

void ArcBall::midDrag( int x, int y )
{
    m_moveX = ( m_oldMoveX + ( m_midClickX - x ) / m_zoom );
    m_moveY = ( m_oldMoveY + ( m_midClickY - y ) / m_zoom );
}

void ArcBall::setRotCenter( float x, float y, float z )
{
    m_rotCenter = QVector3D( -x, -y, -z );
}

void ArcBall::setView( int view )
{
    m_zoom = 1.0;
    m_moveX = 0;
    m_moveY = 0;
    m_oldMoveX = 0;
    m_oldMoveY = 0;
    m_currentRot.setToIdentity();
    m_lastRot.setToIdentity();

    QQuaternion rotx( sqrt(0.5), 0, 0, sqrt(0.5) );
    QQuaternion rot_x( -sqrt(0.5), 0, 0, sqrt(0.5) );
    QQuaternion roty( 0, sqrt(0.5), 0, sqrt(0.5) );
    QQuaternion rot_y( 0, -sqrt(0.5), 0, sqrt(0.5) );
    QQuaternion rotz( 0, 0, sqrt(0.5), sqrt(0.5) );

    if ( view == 2 )
    {
        m_currentRot.rotate( rotz );
        m_currentRot.rotate( rotx );
        m_currentRot.rotate( rotx );
    }
    if ( view == 3 )
    {
        m_currentRot.rotate( rot_x );
        m_currentRot.rotate( rot_y );
    }
}

/// returns the rotation matrix to be used directly
QMatrix4x4 ArcBall::getMVMat()
{
    QMatrix4x4 mv;
    mv.setToIdentity();

    mv = m_currentRot * mv ;

    QVector3D halfMove( -m_moveX * m_zoom/2, m_moveY * m_zoom/2, 0 );
    QMatrix4x4 tmp;
    tmp.setToIdentity();
    tmp.translate( halfMove );
    tmp = tmp * m_currentRot;

    mv = mv + tmp;

    QVector3D scale( m_zoom, m_zoom, m_zoom );
    mv.scale( scale );

    mv.translate( m_rotCenter );

    return mv;
}

<|endoftext|>


<commit_before>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-

Copyright 2010, 2011, 2012, 2013, 2014
Raffaello D. Di Napoli

This file is part of Application-Building Components (henceforth referred to as ABC).

ABC is free software: you can redistribute it and/or modify it under the terms of the GNU General
Public License as published by the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.

ABC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.

You should have received a copy of the GNU General Public License along with ABC. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/

#ifndef _ABC_CORE_HXX
   #error Please #include <abc/core.hxx> instead of this file
#endif

#include <abc/_vextr.hxx>
#include <abc/utf_traits.hxx>
#include <functional>

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::_str_to_str_backend

namespace abc {

/** Base class for the specializations of to_str_backend for string types. Not using templates, so
the implementation can be in a cxx file. This is used by string literal types as well (see below).
*/
class ABCAPI _str_to_str_backend {
public:

   /** Constructor.

   sFormat
      Formatting options.
   */
   _str_to_str_backend(istr const & sFormat);

protected:

   /** Writes a string, applying the formatting options.

   p
      Pointer to the string to write.
   cb
      Size of the string pointed to by p, in bytes.
   enc
      Text encoding of the string pointed to by p.
   posOut
      Pointer to the output stream to write to.
   */
   void write(void const * p, size_t cb, text::encoding enc, io::ostream * posOut);
};

} //namespace abc

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::to_str_backend - specialization for character literal types

namespace abc {

#define ABC_SPECIALIZE_to_str_backend_FOR_TYPE(C) \
   /** Character literal. \
   */ \
   template <> \
   class to_str_backend<C> : \
      public _str_to_str_backend { \
   public: \
   \
      /** Constructor.

      sFormat
         Formatting options.
      */ \
      to_str_backend(istr const & sFormat = istr()) : \
         _str_to_str_backend(sFormat) { \
      } \
   \
   \
      /** Writes a character, applying the formatting options.

      ch
         Character to write.
      posOut
         Pointer to the output stream to write to.
      */ \
      void write(C ch, io::ostream * posOut) { \
         _str_to_str_backend::write(&ch, sizeof(C), text::utf_traits<C>::host_encoding, posOut); \
      } \
   }; \
   \
   /** Const character literal. \

   TODO: remove the need for this.
   */ \
   template <> \
   class to_str_backend<C const> : \
      public to_str_backend<C> { \
   public: \
   \
      /** Constructor.

      sFormat
         Formatting options.
      */ \
      to_str_backend(istr const & sFormat = istr()) : \
         to_str_backend<C>(sFormat) { \
      } \
   };
ABC_SPECIALIZE_to_str_backend_FOR_TYPE(char)
// Specialization for wchar_t, if it’s what char16_t or char32_t map to.
#if ABC_CXX_CHAR16 == 1 || ABC_CXX_CHAR32 == 1
ABC_SPECIALIZE_to_str_backend_FOR_TYPE(wchar_t)
#endif
// Specializations for char16/32_t, if they’re native types.
#if ABC_CXX_CHAR16 == 2
ABC_SPECIALIZE_to_str_backend_FOR_TYPE(char16_t)
#endif
#if ABC_CXX_CHAR32 == 2
ABC_SPECIALIZE_to_str_backend_FOR_TYPE(char32_t)
#endif
#undef ABC_SPECIALIZE_to_str_backend_FOR_TYPE

} //namespace abc

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::to_str_backend - specialization for string literal types

namespace abc {

#define ABC_SPECIALIZE_to_str_backend_FOR_TYPE(C) \
   /** String literal. \
   */ \
   template <size_t t_cch> \
   class to_str_backend<C const [t_cch]> : \
      public _str_to_str_backend { \
   public: \
   \
      /** Constructor.

      sFormat
         Formatting options.
      */ \
      to_str_backend(istr const & sFormat = istr()) : \
         _str_to_str_backend(sFormat) { \
      } \
   \
   \
      /** Writes a string, applying the formatting options.

      ach
         String to write.
      posOut
         Pointer to the output stream to write to.
      */ \
      void write(C const (& ach)[t_cch], io::ostream * posOut) { \
         ABC_ASSERT(ach[t_cch - 1 /*NUL*/] == '\0', SL("string literal must be NUL-terminated")); \
         _str_to_str_backend::write( \
            ach, sizeof(C) * (t_cch - 1 /*NUL*/), text::utf_traits<C>::host_encoding, posOut \
         ); \
      } \
   }; \
   \
   /** Non-const string literal.

   TODO: remove the need for this.
   */ \
   template <size_t t_cch> \
   class to_str_backend<C [t_cch]> : \
      public to_str_backend<C const [t_cch]> { \
   public: \
   \
      /** Constructor.

      sFormat
         Formatting options.
      */ \
      to_str_backend(istr const & sFormat = istr()) : \
         to_str_backend<C const [t_cch]>(sFormat) { \
      } \
   };
ABC_SPECIALIZE_to_str_backend_FOR_TYPE(char)
// Specialization for wchar_t, if it’s what char16_t or char32_t map to.
#if ABC_CXX_CHAR16 == 1 || ABC_CXX_CHAR32 == 1
ABC_SPECIALIZE_to_str_backend_FOR_TYPE(wchar_t)
#endif
// Specializations for char16/32_t, if they’re native types.
#if ABC_CXX_CHAR16 == 2
ABC_SPECIALIZE_to_str_backend_FOR_TYPE(char16_t)
#endif
#if ABC_CXX_CHAR32 == 2
ABC_SPECIALIZE_to_str_backend_FOR_TYPE(char32_t)
#endif
#undef ABC_SPECIALIZE_to_str_backend_FOR_TYPE

} //namespace abc

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::to_str_backend - specialization for abc::str_base

namespace abc {

// Specialization of to_str_backend.
template <>
class to_str_backend<str_base> :
   public _str_to_str_backend {
public:

   /** Constructor.

   sFormat
      Formatting options.
   */
   to_str_backend(istr const & sFormat = istr()) :
      _str_to_str_backend(sFormat) {
   }

   /** Writes a string, applying the formatting options.

   s
      String to write.
   posOut
      Pointer to the output stream to write to.
   */
   void write(str_base const & s, io::ostream * posOut) {
      _str_to_str_backend::write(s.data(), sizeof(char_t) * s.size(), text::encoding::host, posOut);
   }
};

} //namespace abc

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::to_str_backend - specialization for abc::istr

namespace abc {

// Specialization of to_str_backend.
template <>
class to_str_backend<istr> :
   public to_str_backend<str_base> {
public:

   /** Constructor. See to_str_backend<str_base>::to_str_backend().
   */
   to_str_backend(istr const & sFormat = istr()) :
      to_str_backend<str_base>(sFormat) {
   }
};

} //namespace abc

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::to_str_backend - specialization for abc::mstr

namespace abc {

// Specialization of to_str_backend.
template <>
class to_str_backend<mstr> :
   public to_str_backend<str_base> {
public:

   /** Constructor. See to_str_backend<str_base>::to_str_backend().
   */
   to_str_backend(istr const & sFormat = istr()) :
      to_str_backend<str_base>(sFormat) {
   }
};

} //namespace abc

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::to_str_backend - specialization for abc::dmstr

namespace abc {

// Specialization of to_str_backend.
template <>
class to_str_backend<dmstr> :
   public to_str_backend<str_base> {
public:

   /** Constructor. See to_str_backend<str_base>::to_str_backend().
   */
   to_str_backend(istr const & sFormat = istr()) :
      to_str_backend<str_base>(sFormat) {
   }
};

} //namespace abc

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::to_str_backend - specialization for abc::smstr

namespace abc {

// Specialization of to_str_backend.
template <size_t t_cchStatic>
class to_str_backend<smstr<t_cchStatic>> :
   public to_str_backend<str_base> {
public:

   /** Constructor. See to_str_backend<str_base>::to_str_backend().
   */
   to_str_backend(istr const & sFormat = istr()) :
      to_str_backend<str_base>(sFormat) {
   }
};

} //namespace abc

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

<commit_msg>Add missing ABCAPI qualifiers<commit_after>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-

Copyright 2010, 2011, 2012, 2013, 2014
Raffaello D. Di Napoli

This file is part of Application-Building Components (henceforth referred to as ABC).

ABC is free software: you can redistribute it and/or modify it under the terms of the GNU General
Public License as published by the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.

ABC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.

You should have received a copy of the GNU General Public License along with ABC. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/

#ifndef _ABC_CORE_HXX
   #error Please #include <abc/core.hxx> instead of this file
#endif

#include <abc/_vextr.hxx>
#include <abc/utf_traits.hxx>
#include <functional>

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::_str_to_str_backend

namespace abc {

/** Base class for the specializations of to_str_backend for string types. Not using templates, so
the implementation can be in a cxx file. This is used by string literal types as well (see below).
*/
class ABCAPI _str_to_str_backend {
public:

   /** Constructor.

   sFormat
      Formatting options.
   */
   _str_to_str_backend(istr const & sFormat);

protected:

   /** Writes a string, applying the formatting options.

   p
      Pointer to the string to write.
   cb
      Size of the string pointed to by p, in bytes.
   enc
      Text encoding of the string pointed to by p.
   posOut
      Pointer to the output stream to write to.
   */
   void write(void const * p, size_t cb, text::encoding enc, io::ostream * posOut);
};

} //namespace abc

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::to_str_backend - specialization for character literal types

namespace abc {

#define ABC_SPECIALIZE_to_str_backend_FOR_TYPE(C) \
   /** Character literal. \
   */ \
   template <> \
   class ABCAPI to_str_backend<C> : \
      public _str_to_str_backend { \
   public: \
   \
      /** Constructor.

      sFormat
         Formatting options.
      */ \
      to_str_backend(istr const & sFormat = istr()) : \
         _str_to_str_backend(sFormat) { \
      } \
   \
   \
      /** Writes a character, applying the formatting options.

      ch
         Character to write.
      posOut
         Pointer to the output stream to write to.
      */ \
      void write(C ch, io::ostream * posOut) { \
         _str_to_str_backend::write(&ch, sizeof(C), text::utf_traits<C>::host_encoding, posOut); \
      } \
   }; \
   \
   /** Const character literal. \

   TODO: remove the need for this.
   */ \
   template <> \
   class ABCAPI to_str_backend<C const> : \
      public to_str_backend<C> { \
   public: \
   \
      /** Constructor.

      sFormat
         Formatting options.
      */ \
      to_str_backend(istr const & sFormat = istr()) : \
         to_str_backend<C>(sFormat) { \
      } \
   };
ABC_SPECIALIZE_to_str_backend_FOR_TYPE(char)
// Specialization for wchar_t, if it’s what char16_t or char32_t map to.
#if ABC_CXX_CHAR16 == 1 || ABC_CXX_CHAR32 == 1
ABC_SPECIALIZE_to_str_backend_FOR_TYPE(wchar_t)
#endif
// Specializations for char16/32_t, if they’re native types.
#if ABC_CXX_CHAR16 == 2
ABC_SPECIALIZE_to_str_backend_FOR_TYPE(char16_t)
#endif
#if ABC_CXX_CHAR32 == 2
ABC_SPECIALIZE_to_str_backend_FOR_TYPE(char32_t)
#endif
#undef ABC_SPECIALIZE_to_str_backend_FOR_TYPE

} //namespace abc

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::to_str_backend - specialization for string literal types

namespace abc {

#define ABC_SPECIALIZE_to_str_backend_FOR_TYPE(C) \
   /** String literal. \
   */ \
   template <size_t t_cch> \
   class to_str_backend<C const [t_cch]> : \
      public _str_to_str_backend { \
   public: \
   \
      /** Constructor.

      sFormat
         Formatting options.
      */ \
      to_str_backend(istr const & sFormat = istr()) : \
         _str_to_str_backend(sFormat) { \
      } \
   \
   \
      /** Writes a string, applying the formatting options.

      ach
         String to write.
      posOut
         Pointer to the output stream to write to.
      */ \
      void write(C const (& ach)[t_cch], io::ostream * posOut) { \
         ABC_ASSERT(ach[t_cch - 1 /*NUL*/] == '\0', SL("string literal must be NUL-terminated")); \
         _str_to_str_backend::write( \
            ach, sizeof(C) * (t_cch - 1 /*NUL*/), text::utf_traits<C>::host_encoding, posOut \
         ); \
      } \
   }; \
   \
   /** Non-const string literal.

   TODO: remove the need for this.
   */ \
   template <size_t t_cch> \
   class to_str_backend<C [t_cch]> : \
      public to_str_backend<C const [t_cch]> { \
   public: \
   \
      /** Constructor.

      sFormat
         Formatting options.
      */ \
      to_str_backend(istr const & sFormat = istr()) : \
         to_str_backend<C const [t_cch]>(sFormat) { \
      } \
   };
ABC_SPECIALIZE_to_str_backend_FOR_TYPE(char)
// Specialization for wchar_t, if it’s what char16_t or char32_t map to.
#if ABC_CXX_CHAR16 == 1 || ABC_CXX_CHAR32 == 1
ABC_SPECIALIZE_to_str_backend_FOR_TYPE(wchar_t)
#endif
// Specializations for char16/32_t, if they’re native types.
#if ABC_CXX_CHAR16 == 2
ABC_SPECIALIZE_to_str_backend_FOR_TYPE(char16_t)
#endif
#if ABC_CXX_CHAR32 == 2
ABC_SPECIALIZE_to_str_backend_FOR_TYPE(char32_t)
#endif
#undef ABC_SPECIALIZE_to_str_backend_FOR_TYPE

} //namespace abc

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::to_str_backend - specialization for abc::str_base

namespace abc {

// Specialization of to_str_backend.
template <>
class ABCAPI to_str_backend<str_base> :
   public _str_to_str_backend {
public:

   /** Constructor.

   sFormat
      Formatting options.
   */
   to_str_backend(istr const & sFormat = istr()) :
      _str_to_str_backend(sFormat) {
   }

   /** Writes a string, applying the formatting options.

   s
      String to write.
   posOut
      Pointer to the output stream to write to.
   */
   void write(str_base const & s, io::ostream * posOut) {
      _str_to_str_backend::write(s.data(), sizeof(char_t) * s.size(), text::encoding::host, posOut);
   }
};

} //namespace abc

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::to_str_backend - specialization for abc::istr

namespace abc {

// Specialization of to_str_backend.
template <>
class ABCAPI to_str_backend<istr> :
   public to_str_backend<str_base> {
public:

   /** Constructor. See to_str_backend<str_base>::to_str_backend().
   */
   to_str_backend(istr const & sFormat = istr()) :
      to_str_backend<str_base>(sFormat) {
   }
};

} //namespace abc

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::to_str_backend - specialization for abc::mstr

namespace abc {

// Specialization of to_str_backend.
template <>
class ABCAPI to_str_backend<mstr> :
   public to_str_backend<str_base> {
public:

   /** Constructor. See to_str_backend<str_base>::to_str_backend().
   */
   to_str_backend(istr const & sFormat = istr()) :
      to_str_backend<str_base>(sFormat) {
   }
};

} //namespace abc

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::to_str_backend - specialization for abc::dmstr

namespace abc {

// Specialization of to_str_backend.
template <>
class ABCAPI to_str_backend<dmstr> :
   public to_str_backend<str_base> {
public:

   /** Constructor. See to_str_backend<str_base>::to_str_backend().
   */
   to_str_backend(istr const & sFormat = istr()) :
      to_str_backend<str_base>(sFormat) {
   }
};

} //namespace abc

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::to_str_backend - specialization for abc::smstr

namespace abc {

// Specialization of to_str_backend.
template <size_t t_cchStatic>
class to_str_backend<smstr<t_cchStatic>> :
   public to_str_backend<str_base> {
public:

   /** Constructor. See to_str_backend<str_base>::to_str_backend().
   */
   to_str_backend(istr const & sFormat = istr()) :
      to_str_backend<str_base>(sFormat) {
   }
};

} //namespace abc

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

<|endoftext|>


<commit_before><commit_msg>Fix critical bug in specification of wz command versions<commit_after><|endoftext|>


<commit_before>#pragma once

#include <utility>
#include <random>
#include <distributions/common.hpp>
#include <distributions/special.hpp>

namespace distributions
{

//typedef std::default_random_engine rng_t;
//typedef std::mt19937 rng_t;
typedef std::ranlux48 rng_t;

inline int sample_int (rng_t & rng, int low, int high)
{
    std::uniform_int_distribution<> sampler(low, high);
    return sampler(rng);
}

inline float sample_unif01 (rng_t & rng)
{
    std::uniform_real_distribution<float> sampler(0.0, 1.0);
    return sampler(rng);
}

inline bool sample_bernoulli (rng_t & rng, float p)
{
    std::uniform_real_distribution<float> sampler(0.0, 1.0);
    return sampler(rng) < p;
}

// HACK std::gamma_distribution<float> appears to be broken
//typedef std::gamma_distribution<float> gamma_distribution_t;
typedef std::gamma_distribution<double> gamma_distribution_t;

inline float sample_gamma (
        rng_t & rng,
        float alpha,
        float beta = 1.f)
{
    gamma_distribution_t sampler;
    gamma_distribution_t::param_type param(alpha, beta);
    return sampler(rng, param);
}

void sample_dirichlet (
        rng_t & rng,
        size_t dim,
        const float * alphas,
        float * probs);

void sample_dirichlet (
        rng_t & rng,
        size_t dim,
        const float * alphas,
        float * probs,
        float min_value);

int sample_discrete (
        rng_t & rng,
        size_t dim,
        const float * probs);

inline float fast_score_student_t (
        float x,
        float v,
        float mean,
        float lambda)
{
    float p = 0.f;
    p += fast_lgamma_nu(v);
    p += 0.5f * fast_log(lambda / (M_PIf * v));
    p += (-0.5f * v - 0.5f) * fast_log(1.f + (lambda * sqr(x - mean)) / v);
    return p;
}

inline float score_student_t (
        float x,
        float v,
        float mean,
        float lambda)
{
    float p = 0.f;
    p += lgammaf(v * 0.5f + 0.5f) - lgammaf(v * 0.5f);
    p += 0.5f * logf(lambda / (M_PIf * v));
    p += (-0.5f * v - 0.5f) * logf(1.f + (lambda * sqr(x - mean)) / v);
    return p;
}

template<class T>
inline T sample_from_urn (
        rng_t & rng,
        const std::vector<T> & urn)
{
    DIST_ASSERT(urn.size() >= 1, "urn is too small to sample from");
    size_t f = sample_int(rng, 0, urn.size() - 1);
    DIST_ASSERT(0 <= f and f < urn.size(), "bad value: " << f);
    return urn[f];
}

template<class T>
inline std::pair<T, T> sample_pair_from_urn (
        rng_t & rng,
        const std::vector<T> & urn)
{
    DIST_ASSERT(urn.size() >= 2, "urn is too small to sample pair from");
    size_t f1 = sample_int(rng, 0, urn.size() - 1);
    size_t f2 = sample_int(rng, 0, urn.size() - 2);
    if (f2 >= f1) {
        f2 += 1;
    }
    DIST_ASSERT(0 <= f1 and f1 < urn.size(), "bad value: " << f1);
    DIST_ASSERT(0 <= f2 and f2 < urn.size(), "bad value: " << f2);
    DIST_ASSERT(f1 != f2, "bad pair: " << f1 << ", " << f2);
    return std::make_pair(urn[f1], urn[f2]);
}

} // namespace distributions
<commit_msg>Bugfix to sample_dirichlet_safe<commit_after>#pragma once

#include <utility>
#include <random>
#include <distributions/common.hpp>
#include <distributions/special.hpp>

namespace distributions
{

//typedef std::default_random_engine rng_t;
//typedef std::mt19937 rng_t;
typedef std::ranlux48 rng_t;

inline int sample_int (rng_t & rng, int low, int high)
{
    std::uniform_int_distribution<> sampler(low, high);
    return sampler(rng);
}

inline float sample_unif01 (rng_t & rng)
{
    std::uniform_real_distribution<float> sampler(0.0, 1.0);
    return sampler(rng);
}

inline bool sample_bernoulli (rng_t & rng, float p)
{
    std::uniform_real_distribution<float> sampler(0.0, 1.0);
    return sampler(rng) < p;
}

// HACK std::gamma_distribution<float> appears to be broken
//typedef std::gamma_distribution<float> gamma_distribution_t;
typedef std::gamma_distribution<double> gamma_distribution_t;

inline float sample_gamma (
        rng_t & rng,
        float alpha,
        float beta = 1.f)
{
    gamma_distribution_t sampler;
    gamma_distribution_t::param_type param(alpha, beta);
    return sampler(rng, param);
}

void sample_dirichlet (
        rng_t & rng,
        size_t dim,
        const float * alphas,
        float * probs);

void sample_dirichlet_safe (
        rng_t & rng,
        size_t dim,
        const float * alphas,
        float * probs,
        float min_value);

int sample_discrete (
        rng_t & rng,
        size_t dim,
        const float * probs);

inline float fast_score_student_t (
        float x,
        float v,
        float mean,
        float lambda)
{
    float p = 0.f;
    p += fast_lgamma_nu(v);
    p += 0.5f * fast_log(lambda / (M_PIf * v));
    p += (-0.5f * v - 0.5f) * fast_log(1.f + (lambda * sqr(x - mean)) / v);
    return p;
}

inline float score_student_t (
        float x,
        float v,
        float mean,
        float lambda)
{
    float p = 0.f;
    p += lgammaf(v * 0.5f + 0.5f) - lgammaf(v * 0.5f);
    p += 0.5f * logf(lambda / (M_PIf * v));
    p += (-0.5f * v - 0.5f) * logf(1.f + (lambda * sqr(x - mean)) / v);
    return p;
}

template<class T>
inline T sample_from_urn (
        rng_t & rng,
        const std::vector<T> & urn)
{
    DIST_ASSERT(urn.size() >= 1, "urn is too small to sample from");
    size_t f = sample_int(rng, 0, urn.size() - 1);
    DIST_ASSERT(0 <= f and f < urn.size(), "bad value: " << f);
    return urn[f];
}

template<class T>
inline std::pair<T, T> sample_pair_from_urn (
        rng_t & rng,
        const std::vector<T> & urn)
{
    DIST_ASSERT(urn.size() >= 2, "urn is too small to sample pair from");
    size_t f1 = sample_int(rng, 0, urn.size() - 1);
    size_t f2 = sample_int(rng, 0, urn.size() - 2);
    if (f2 >= f1) {
        f2 += 1;
    }
    DIST_ASSERT(0 <= f1 and f1 < urn.size(), "bad value: " << f1);
    DIST_ASSERT(0 <= f2 and f2 < urn.size(), "bad value: " << f2);
    DIST_ASSERT(f1 != f2, "bad pair: " << f1 << ", " << f2);
    return std::make_pair(urn[f1], urn[f2]);
}

} // namespace distributions
<|endoftext|>


<commit_before>#ifndef QRW_GAMESTATE_HPP
#define QRW_GAMESTATE_HPP

// Foreward declarations
namespace sf
{
class RenderWindow;
class Event;
}

namespace qrw
{

enum EGameStateId
{
	EGSID_INTRO_STATE,
	EGSID_QUIT,
	EGSID_NO_CHANGE,
	EGSID_COUNT
};

class GameState
{
public:
	/**
	 * GameState constructor.
	 *
	 * @param renderWindow The sf::RenderWindow in which the game takes place.
	 */
	GameState(sf::RenderWindow* renderWindow, EGameStateId id);

	/**
	 * Destroy a GameState.
	 */
	virtual ~GameState();

	/**
	 * Initialize the GameState.
	 *
	 * The previous GameState is passed as argument so it is possible
	 * to pass parameters from one GameState to another.
	 *
	 * @param previousState Optional pointer to a previous GameState.
	 */
	virtual void init(GameState* previousState = nullptr) = 0;

	/**
	 * Update the GameState.
	 *
	 * @return The ID of the next GameState, EGSID_NO_CHANGE, if the state did not chnage
	 *         or EGSID_QUIT if the GameState wants the application to quit.
	 */
	virtual EGameStateId update() = 0;

	/**
	 * Render the GameState to the render window.
	 */
	virtual void draw()	= 0;

	/**
	 * Handle an SFML event.
	 *
	 * @param event The SFML event to handle.
	 */
	virtual void handleEvent(sf::Event& event) = 0;

	/**
	 * Get the ID of the GameState.
	 *
	 * @return One of the EGameStateIds.
	 */
	EGameStateId getId();

protected:
	sf::RenderWindow* _renderWindow;

private:
	EGameStateId _id;
};

} // namespace qrw

#endif // QRW_GAMESTATE_HPP
<commit_msg>Added some documentation.<commit_after>#ifndef QRW_GAMESTATE_HPP
#define QRW_GAMESTATE_HPP

// Foreward declarations
namespace sf
{
class RenderWindow;
class Event;
}

namespace qrw
{

/**
 * Enum containing the identifiers of available game states.
 */
enum EGameStateId
{
	/**
	 * The ID of te intro game state.
	 */
	EGSID_INTRO_STATE,

	/**
	 * The ID of the main menu game state.
	 */
	EGSID_MAIN_MENU_STATE,

	/**
	 * Special "game state" that indicates that the application should quit.
	 */
	EGSID_QUIT,

	/**
	 * Special "game state" that indicates that no game state change
	 * should be performed by the QRWar object.
	 */
	EGSID_NO_CHANGE,

	/**
	 * Holds the number of game states.
	 */
	EGSID_COUNT
};

/**
 * The GameState class represents a state of the game.
 *
 * It is used to encapuslate all data and methods required for a specific
 * state.
 */
class GameState
{
public:
	/**
	 * GameState constructor.
	 *
	 * @param renderWindow The sf::RenderWindow in which the game takes place.
	 */
	GameState(sf::RenderWindow* renderWindow, EGameStateId id);

	/**
	 * Destroy a GameState.
	 */
	virtual ~GameState();

	/**
	 * Initialize the GameState.
	 *
	 * The previous GameState is passed as argument so it is possible
	 * to pass parameters from one GameState to another.
	 *
	 * @param previousState Optional pointer to a previous GameState.
	 */
	virtual void init(GameState* previousState = nullptr) = 0;

	/**
	 * Update the GameState.
	 *
	 * @return The ID of the next GameState, EGSID_NO_CHANGE, if the state did not chnage
	 *         or EGSID_QUIT if the GameState wants the application to quit.
	 */
	virtual EGameStateId update() = 0;

	/**
	 * Render the GameState to the render window.
	 */
	virtual void draw()	= 0;

	/**
	 * Handle an SFML event.
	 *
	 * @param event The SFML event to handle.
	 */
	virtual void handleEvent(sf::Event& event) = 0;

	/**
	 * Get the ID of the GameState.
	 *
	 * @return One of the EGameStateIds.
	 */
	EGameStateId getId();

protected:
	sf::RenderWindow* _renderWindow;

private:
	EGameStateId _id;
};

} // namespace qrw

#endif // QRW_GAMESTATE_HPP
<|endoftext|>


<commit_before>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2008 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//

#include "Camera.h"

#include "../base/Logger.h"
#include "../base/Exception.h"
#include "../base/ScopeTimer.h"
#include "../graphics/Filterfliprgb.h"

#if defined(AVG_ENABLE_1394_2)
#include "../imaging/FWCamera.h"
#endif
#ifdef AVG_ENABLE_V4L2
#include "../imaging/V4LCamera.h"
#endif
#ifdef AVG_ENABLE_CMU1394
#include "../imaging/CMUCamera.h"
#endif
#ifdef AVG_ENABLE_DSHOW
#include "../imaging/DSCamera.h"
#endif
#include "../imaging/FakeCamera.h"

#include <cstdlib>
#include <string.h>

#ifdef WIN32
#define strtoll(p, e, b) _strtoi64(p, e, b)
#endif

namespace avg {

using namespace std;

Camera::Camera(PixelFormat camPF, PixelFormat destPF)
    : m_CamPF(camPF),
      m_DestPF(destPF)
{
//    cerr << "Camera: " << getPixelFormatString(camPF) << "-->"
//        << getPixelFormatString(destPF) << endl;
}

PixelFormat Camera::getCamPF() const
{
    return m_CamPF;
}

void Camera::setCamPF(PixelFormat pf)
{
    m_CamPF = pf;
}

PixelFormat Camera::getDestPF() const
{
    return m_DestPF;
}

static ProfilingZoneID CameraConvertProfilingZone("Camera format conversion");

BitmapPtr Camera::convertCamFrameToDestPF(BitmapPtr pCamBmp)
{
    ScopeTimer Timer(CameraConvertProfilingZone);
    BitmapPtr pDestBmp = BitmapPtr(new Bitmap(pCamBmp->getSize(), m_DestPF));
    pDestBmp->copyPixels(*pCamBmp);
    if (m_CamPF == R8G8B8 && m_DestPF == B8G8R8X8) {
        pDestBmp->setPixelFormat(R8G8B8X8);
        FilterFlipRGB().applyInPlace(pDestBmp);
    }

    return pDestBmp;
}

PixelFormat Camera::fwBayerStringToPF(unsigned long reg)
{
    string sBayerFormat((char*)&reg, 4);
    if (sBayerFormat == "RGGB") {
        return BAYER8_RGGB;
    } else if (sBayerFormat == "GBRG") {
        return BAYER8_GBRG;
    } else if (sBayerFormat == "GRBG") {
        return BAYER8_GRBG;
    } else if (sBayerFormat == "BGGR") {
        return BAYER8_BGGR;
    } else if (sBayerFormat == "YYYY") {
        return I8;
    } else {
        AVG_ASSERT(false);
        return I8;
    }
}

string cameraFeatureToString(CameraFeature feature)
{
    switch (feature) {
        case CAM_FEATURE_BRIGHTNESS:
            return "brightness";
        case CAM_FEATURE_EXPOSURE:
            return "exposure";
        case CAM_FEATURE_SHARPNESS:
            return "sharpness";
        case CAM_FEATURE_WHITE_BALANCE:
            return "white balance";
        case CAM_FEATURE_HUE:
            return "hue";
        case CAM_FEATURE_SATURATION:
            return "saturation";
        case CAM_FEATURE_GAMMA:
            return "gamma";
        case CAM_FEATURE_SHUTTER:
            return "shutter";
        case CAM_FEATURE_GAIN:
            return "gain";
        case CAM_FEATURE_IRIS:
            return "iris";
        case CAM_FEATURE_FOCUS:
            return "focus";
        case CAM_FEATURE_TEMPERATURE:
            return "temperature";
        case CAM_FEATURE_TRIGGER:
            return "trigger";
        case CAM_FEATURE_ZOOM:
            return "zoom";
        case CAM_FEATURE_PAN:
            return "pan";
        case CAM_FEATURE_TILT:
            return "tilt";
        case CAM_FEATURE_OPTICAL_FILTER:
            return "optical filter";
        case CAM_FEATURE_CAPTURE_SIZE:
            return "capture size";
        case CAM_FEATURE_CAPTURE_QUALITY:
            return "capture quality";
        case CAM_FEATURE_CONTRAST:
            return "contrast";
        case CAM_FEATURE_STROBE_DURATION:
            return "strobe duration";
        default:
            return "unknown";
    }
}

CameraPtr createCamera(const string& sDriver, const string& sDevice, int unit,
        bool bFW800, const IntPoint& captureSize, PixelFormat camPF, PixelFormat destPF,
        double frameRate)
{
    CameraPtr pCamera;
    try {
        if (sDriver == "firewire") {
            char * pszErr;
            long long guid = strtoll(sDevice.c_str(), &pszErr, 10);
            if (strlen(pszErr)) {
                throw Exception(AVG_ERR_INVALID_ARGS, "'"+sDevice
                        +"' is not a valid GUID.");
            }
#if defined(AVG_ENABLE_1394_2)
            pCamera = CameraPtr(new FWCamera(guid, unit, bFW800, captureSize, camPF,
                    destPF, frameRate));
#elif defined(AVG_ENABLE_CMU1394)
            if (unit != -1) {
                throw Exception(AVG_ERR_INVALID_ARGS,
                        "camera 'unit' attribute is not supported when using the cmu firewire driver.");
            }
            pCamera = CameraPtr(new CMUCamera(guid, bFW800, captureSize, camPF, destPF,
                    frameRate));
#else
            AVG_TRACE(Logger::WARNING, "Firewire camera specified, but firewire "
                    "support not compiled in.");
#endif
        } else if (sDriver == "video4linux") {
#if defined(AVG_ENABLE_V4L2)
            pCamera = CameraPtr(new V4LCamera(sDevice, unit, captureSize, camPF,
                    destPF, frameRate));
#else
            AVG_TRACE(Logger::WARNING, "Video4Linux camera specified, but "
                    "Video4Linux support not compiled in.");
#endif
        } else if (sDriver == "directshow") {
#if defined(AVG_ENABLE_DSHOW)
            if (unit != -1) {
                throw Exception(AVG_ERR_INVALID_ARGS,
                        "camera 'unit' attribute is not supported when using the directshow driver.");
            }
            pCamera = CameraPtr(new DSCamera(sDevice, captureSize, camPF, destPF,
                frameRate));
#else
            AVG_TRACE(Logger::WARNING, "DirectShow camera specified, but "
                    "DirectShow is only available under windows.");
#endif
        } else {
            throw Exception(AVG_ERR_INVALID_ARGS,
                    "Unable to set up camera. Camera source '"+sDriver+"' unknown.");
        }
    } catch (const Exception& e) {
        if (e.GetCode() == AVG_ERR_CAMERA_NONFATAL) {
            AVG_TRACE(Logger::WARNING, e.GetStr());
        } else {
            throw;
        }

    }
    if (!pCamera) {
        pCamera = CameraPtr(new FakeCamera(camPF, destPF));
    }
    return pCamera;

}

void dumpCameras()
{
#ifdef AVG_ENABLE_1394_2
    FWCamera::dumpCameras();
#endif
#ifdef AVG_ENABLE_CMU1394
    CMUCamera::dumpCameras();
#endif
#ifdef AVG_ENABLE_V4L2
    V4LCamera::dumpCameras();
#endif
#ifdef AVG_ENABLE_DSHOW
    DSCamera::dumpCameras();
#endif
}

}
<commit_msg>Silence Linux compiler warning.<commit_after>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2008 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//

#include "Camera.h"

#include "../base/Logger.h"
#include "../base/Exception.h"
#include "../base/ScopeTimer.h"
#include "../graphics/Filterfliprgb.h"

#if defined(AVG_ENABLE_1394_2)
#include "../imaging/FWCamera.h"
#endif
#ifdef AVG_ENABLE_V4L2
#include "../imaging/V4LCamera.h"
#endif
#ifdef AVG_ENABLE_CMU1394
#include "../imaging/CMUCamera.h"
#endif
#ifdef AVG_ENABLE_DSHOW
#include "../imaging/DSCamera.h"
#endif
#include "../imaging/FakeCamera.h"

#include <cstdlib>
#include <string.h>

#ifdef WIN32
#define strtoll(p, e, b) _strtoi64(p, e, b)
#endif

namespace avg {

using namespace std;

Camera::Camera(PixelFormat camPF, PixelFormat destPF)
    : m_CamPF(camPF),
      m_DestPF(destPF)
{
//    cerr << "Camera: " << getPixelFormatString(camPF) << "-->"
//        << getPixelFormatString(destPF) << endl;
}

PixelFormat Camera::getCamPF() const
{
    return m_CamPF;
}

void Camera::setCamPF(PixelFormat pf)
{
    m_CamPF = pf;
}

PixelFormat Camera::getDestPF() const
{
    return m_DestPF;
}

static ProfilingZoneID CameraConvertProfilingZone("Camera format conversion");

BitmapPtr Camera::convertCamFrameToDestPF(BitmapPtr pCamBmp)
{
    ScopeTimer Timer(CameraConvertProfilingZone);
    BitmapPtr pDestBmp = BitmapPtr(new Bitmap(pCamBmp->getSize(), m_DestPF));
    pDestBmp->copyPixels(*pCamBmp);
    if (m_CamPF == R8G8B8 && m_DestPF == B8G8R8X8) {
        pDestBmp->setPixelFormat(R8G8B8X8);
        FilterFlipRGB().applyInPlace(pDestBmp);
    }

    return pDestBmp;
}

PixelFormat Camera::fwBayerStringToPF(unsigned long reg)
{
    string sBayerFormat((char*)&reg, 4);
    if (sBayerFormat == "RGGB") {
        return BAYER8_RGGB;
    } else if (sBayerFormat == "GBRG") {
        return BAYER8_GBRG;
    } else if (sBayerFormat == "GRBG") {
        return BAYER8_GRBG;
    } else if (sBayerFormat == "BGGR") {
        return BAYER8_BGGR;
    } else if (sBayerFormat == "YYYY") {
        return I8;
    } else {
        AVG_ASSERT(false);
        return I8;
    }
}

string cameraFeatureToString(CameraFeature feature)
{
    switch (feature) {
        case CAM_FEATURE_BRIGHTNESS:
            return "brightness";
        case CAM_FEATURE_EXPOSURE:
            return "exposure";
        case CAM_FEATURE_SHARPNESS:
            return "sharpness";
        case CAM_FEATURE_WHITE_BALANCE:
            return "white balance";
        case CAM_FEATURE_HUE:
            return "hue";
        case CAM_FEATURE_SATURATION:
            return "saturation";
        case CAM_FEATURE_GAMMA:
            return "gamma";
        case CAM_FEATURE_SHUTTER:
            return "shutter";
        case CAM_FEATURE_GAIN:
            return "gain";
        case CAM_FEATURE_IRIS:
            return "iris";
        case CAM_FEATURE_FOCUS:
            return "focus";
        case CAM_FEATURE_TEMPERATURE:
            return "temperature";
        case CAM_FEATURE_TRIGGER:
            return "trigger";
        case CAM_FEATURE_ZOOM:
            return "zoom";
        case CAM_FEATURE_PAN:
            return "pan";
        case CAM_FEATURE_TILT:
            return "tilt";
        case CAM_FEATURE_OPTICAL_FILTER:
            return "optical filter";
        case CAM_FEATURE_CAPTURE_SIZE:
            return "capture size";
        case CAM_FEATURE_CAPTURE_QUALITY:
            return "capture quality";
        case CAM_FEATURE_CONTRAST:
            return "contrast";
        case CAM_FEATURE_STROBE_DURATION:
            return "strobe duration";
        default:
            return "unknown";
    }
}

CameraPtr createCamera(const string& sDriver, const string& sDevice, int unit,
        bool bFW800, const IntPoint& captureSize, PixelFormat camPF, PixelFormat destPF,
        double frameRate)
{
    CameraPtr pCamera;
    try {
        if (sDriver == "firewire") {
            char * pszErr;
            long long guid = strtoll(sDevice.c_str(), &pszErr, 10);
            if (strlen(pszErr)) {
                throw Exception(AVG_ERR_INVALID_ARGS, "'"+sDevice
                        +"' is not a valid GUID.");
            }
#if defined(AVG_ENABLE_1394_2)
            pCamera = CameraPtr(new FWCamera(guid, unit, bFW800, captureSize, camPF,
                    destPF, frameRate));
#elif defined(AVG_ENABLE_CMU1394)
            if (unit != -1) {
                throw Exception(AVG_ERR_INVALID_ARGS,
                        "camera 'unit' attribute is not supported when using the cmu firewire driver.");
            }
            pCamera = CameraPtr(new CMUCamera(guid, bFW800, captureSize, camPF, destPF,
                    frameRate));
#else
            guid = 0; // Silence compiler warning
            AVG_TRACE(Logger::WARNING, "Firewire camera specified, but firewire "
                    "support not compiled in.");
#endif
        } else if (sDriver == "video4linux") {
#if defined(AVG_ENABLE_V4L2)
            pCamera = CameraPtr(new V4LCamera(sDevice, unit, captureSize, camPF,
                    destPF, frameRate));
#else
            AVG_TRACE(Logger::WARNING, "Video4Linux camera specified, but "
                    "Video4Linux support not compiled in.");
#endif
        } else if (sDriver == "directshow") {
#if defined(AVG_ENABLE_DSHOW)
            if (unit != -1) {
                throw Exception(AVG_ERR_INVALID_ARGS,
                        "camera 'unit' attribute is not supported when using the directshow driver.");
            }
            pCamera = CameraPtr(new DSCamera(sDevice, captureSize, camPF, destPF,
                frameRate));
#else
            AVG_TRACE(Logger::WARNING, "DirectShow camera specified, but "
                    "DirectShow is only available under windows.");
#endif
        } else {
            throw Exception(AVG_ERR_INVALID_ARGS,
                    "Unable to set up camera. Camera source '"+sDriver+"' unknown.");
        }
    } catch (const Exception& e) {
        if (e.GetCode() == AVG_ERR_CAMERA_NONFATAL) {
            AVG_TRACE(Logger::WARNING, e.GetStr());
        } else {
            throw;
        }

    }
    if (!pCamera) {
        pCamera = CameraPtr(new FakeCamera(camPF, destPF));
    }
    return pCamera;

}

void dumpCameras()
{
#ifdef AVG_ENABLE_1394_2
    FWCamera::dumpCameras();
#endif
#ifdef AVG_ENABLE_CMU1394
    CMUCamera::dumpCameras();
#endif
#ifdef AVG_ENABLE_V4L2
    V4LCamera::dumpCameras();
#endif
#ifdef AVG_ENABLE_DSHOW
    DSCamera::dumpCameras();
#endif
}

}
<|endoftext|>


<commit_before>#ifndef LIBPORT_SINGLETON_PTR_HH
# define LIBPORT_SINGLETON_PTR_HH

# define STATIC_INSTANCE_(Cl, Name)					\
  class Cl ## Name;							\
  libport::SingletonPtr<Cl ## Name> Name;				\
  template<> Cl ## Name* libport::SingletonPtr<Cl ## Name>::ptr = 0

# define STATIC_INSTANCE_DECL_(Cl, Name)				\
  class Cl ## Name							\
    : public Cl								\
  {};									\
  STATIC_INSTANCE_(Cl, Name)

# define EXTERN_STATIC_INSTANCE_EX(Cl, Name, Api)			\
  class Api Cl ## Name							\
    : public Cl								\
  {};									\
  Api extern libport::SingletonPtr<Cl ## Name> Name;

# define EXTERN_STATIC_INSTANCE(Cl, Name)				\
  EXTERN_STATIC_INSTANCE_EX(Cl, Name, /* No API. */)

// These _NS version are made to bypass vcxx error C2888
// cf: http://msdn.microsoft.com/en-us/library/27zksbks(VS.80).aspx
// Symbol in libport cannot be defined inside urbi. This appeared
// after changes done for liburbi Java.
// Use them "outside" of any namespace.

# define STATIC_INSTANCE_NS_EX(Cl, Name, NS, Api)			\
  namespace NS {							\
    Api libport::SingletonPtr<Cl ## Name> Name;				\
  }									\
  template<> Api NS::Cl ## Name*					\
  libport::SingletonPtr<NS::Cl ## Name>::ptr = 0

# define STATIC_INSTANCE_NS(Cl, Name, NS)				\
  STATIC_INSTANCE_NS_EX(Cl, Name, NS, /* No API */)

# define STATIC_INSTANCE_DECL_NS(Cl, Name, NS)				\
  namespace NS {							\
    class Cl ## Name							\
      : public Cl							\
    {};									\
  }									\
  STATIC_INSTANCE_NS(Cl, Name, NS)

namespace libport
{
  /// Singleton smart pointer that creates the object on demand.
  template<typename T>
  class SingletonPtr
  {
  public:
    operator T* ();
    operator T& ();
    T* operator ->();

  private:
    static T* instance();
    static T* ptr;
  };

}  // namespace libport

# include <libport/singleton-ptr.hxx>

#endif // !LIBPORT_SINGLETON_PTR_HH
<commit_msg>Export "ptr" properly also when declaring it.<commit_after>#ifndef LIBPORT_SINGLETON_PTR_HH
# define LIBPORT_SINGLETON_PTR_HH

# include <libport/export.hh>

# define STATIC_INSTANCE_(Cl, Name)					\
  class Cl ## Name;							\
  libport::SingletonPtr<Cl ## Name> Name;				\
  template<> Cl ## Name* libport::SingletonPtr<Cl ## Name>::ptr = 0

# define STATIC_INSTANCE_DECL_(Cl, Name)				\
  class Cl ## Name							\
    : public Cl								\
  {};									\
  STATIC_INSTANCE_(Cl, Name)

# define EXTERN_STATIC_INSTANCE_EX(Cl, Name, Api)			\
  class Api Cl ## Name							\
    : public Cl								\
  {};									\
  Api extern libport::SingletonPtr<Cl ## Name> Name;

# define EXTERN_STATIC_INSTANCE(Cl, Name)				\
  EXTERN_STATIC_INSTANCE_EX(Cl, Name, /* No API. */)

// These _NS version are made to bypass vcxx error C2888
// cf: http://msdn.microsoft.com/en-us/library/27zksbks(VS.80).aspx
// Symbol in libport cannot be defined inside urbi. This appeared
// after changes done for liburbi Java.
// Use them "outside" of any namespace.

# define STATIC_INSTANCE_NS_EX(Cl, Name, NS, Api)			\
  namespace NS {							\
    Api libport::SingletonPtr<Cl ## Name> Name;				\
  }									\
  template<> Api NS::Cl ## Name*					\
  libport::SingletonPtr<NS::Cl ## Name>::ptr = 0

# define STATIC_INSTANCE_NS(Cl, Name, NS)				\
  STATIC_INSTANCE_NS_EX(Cl, Name, NS, /* No API */)

# define STATIC_INSTANCE_DECL_NS(Cl, Name, NS)				\
  namespace NS {							\
    class Cl ## Name							\
      : public Cl							\
    {};									\
  }									\
  STATIC_INSTANCE_NS(Cl, Name, NS)

namespace libport
{
  /// Singleton smart pointer that creates the object on demand.
  template<typename T>
  class SingletonPtr
  {
  public:
    operator T* ();
    operator T& ();
    T* operator ->();

  private:
    static T* instance();
    LIBPORT_API static T* ptr;
  };

}  // namespace libport

# include <libport/singleton-ptr.hxx>

#endif // !LIBPORT_SINGLETON_PTR_HH
<|endoftext|>


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

#ifndef MAPNIK_IMAGE_SCALING_HPP
#define MAPNIK_IMAGE_SCALING_HPP

// mapnik
#include <mapnik/config.hpp>
#include <mapnik/image.hpp>

// stl
#include <iosfwd>

// boost
#include <boost/optional.hpp>

namespace mapnik
{

enum scaling_method_e
{
    SCALING_NEAR=0,
    SCALING_BILINEAR,
    SCALING_BICUBIC,
    SCALING_SPLINE16,
    SCALING_SPLINE36,
    SCALING_HANNING,
    SCALING_HAMMING,
    SCALING_HERMITE,
    SCALING_KAISER,
    SCALING_QUADRIC,
    SCALING_CATROM,
    SCALING_GAUSSIAN,
    SCALING_BESSEL,
    SCALING_MITCHELL,
    SCALING_SINC,
    SCALING_LANCZOS,
    SCALING_BLACKMAN
};

MAPNIK_DECL boost::optional<scaling_method_e> scaling_method_from_string(std::string const& name);
MAPNIK_DECL boost::optional<std::string> scaling_method_to_string(scaling_method_e scaling_method);

template <typename T>
MAPNIK_DECL void scale_image_agg(T & target, T const& source,
                                 scaling_method_e scaling_method,
                                 double image_ratio_x,
                                 double image_ratio_y,
                                 double x_off_f,
                                 double y_off_f,
                                 double filter_factor,
                                 boost::optional<double> const & nodata_value);
template <typename T>
MAPNIK_DECL void scale_image_agg(T & target, T const& source,
                                 scaling_method_e scaling_method,
                                 double image_ratio_x,
                                 double image_ratio_y,
                                 double x_off_f,
                                 double y_off_f,
                                 double filter_factor)
{
    scale_image_agg(target, source, scaling_method,
                    image_ratio_x,image_ratio_y,
                    x_off_f, y_off_f, filter_factor,
                    boost::optional<double>());
}
}

#endif // MAPNIK_IMAGE_SCALING_HPP
<commit_msg>fix #3178<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2015 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_IMAGE_SCALING_HPP
#define MAPNIK_IMAGE_SCALING_HPP

// mapnik
#include <mapnik/config.hpp>
#include <mapnik/image.hpp>

// stl
#include <iosfwd>

// boost
#include <boost/optional.hpp>

namespace mapnik
{

enum scaling_method_e
{
    SCALING_NEAR=0,
    SCALING_BILINEAR,
    SCALING_BICUBIC,
    SCALING_SPLINE16,
    SCALING_SPLINE36,
    SCALING_HANNING,
    SCALING_HAMMING,
    SCALING_HERMITE,
    SCALING_KAISER,
    SCALING_QUADRIC,
    SCALING_CATROM,
    SCALING_GAUSSIAN,
    SCALING_BESSEL,
    SCALING_MITCHELL,
    SCALING_SINC,
    SCALING_LANCZOS,
    SCALING_BLACKMAN
};

MAPNIK_DECL boost::optional<scaling_method_e> scaling_method_from_string(std::string const& name);
MAPNIK_DECL boost::optional<std::string> scaling_method_to_string(scaling_method_e scaling_method);

template <typename T>
MAPNIK_DECL void scale_image_agg(T & target, T const& source,
                                 scaling_method_e scaling_method,
                                 double image_ratio_x,
                                 double image_ratio_y,
                                 double x_off_f,
                                 double y_off_f,
                                 double filter_factor,
                                 boost::optional<double> const & nodata_value);
template <typename T>
inline void scale_image_agg(T & target, T const& source,
                                 scaling_method_e scaling_method,
                                 double image_ratio_x,
                                 double image_ratio_y,
                                 double x_off_f,
                                 double y_off_f,
                                 double filter_factor)
{
    scale_image_agg(target, source, scaling_method,
                    image_ratio_x,image_ratio_y,
                    x_off_f, y_off_f, filter_factor,
                    boost::optional<double>());
}
}

#endif // MAPNIK_IMAGE_SCALING_HPP
<|endoftext|>