<commit_before>

#include <time.h>
#include <sys/time.h>
#include <signal.h>   // SIGKILL

#include "logMsg/logMsg.h"                          // LM_X

#include "au/string.h"                             // au::xml_...
#include "au/TokenTaker.h"                          // au::TokenTake
#include "au/ErrorManager.h"                       // au::ErrorManager
#include "au/Token.h"                       // au::Token
#include "au/xml.h"         // au::xml...

#include "Notification.h"                           // engine::Notification

#include "engine/EngineElement.h"					// engine::EngineElement
#include "engine/ProcessItem.h"                     // engine::ProcessItem
#include "engine/DiskOperation.h"					// engine::DiskOperation
#include "engine/NotificationElement.h"       // engine::EngineNotificationElement

#include "engine/MemoryManager.h"
#include "engine/DiskManager.h"
#include "engine/ProcessManager.h"

#include "engine/Engine.h"							// Own interface

// Goyo. From 60 to 60000
#define ENGINE_MAX_RUNNING_TIME     60000

NAMESPACE_BEGIN(engine)

// Common engine
Engine *engine = NULL;

void* runEngineBakground(void* e )
{
    engine->run();
    return NULL;
}

Engine::Engine() :  EngineService("Engine") , token("EngineToken")
{
    running_element = NULL;                         // Initially, no running element
    flag_finish_threads = false;                    // Put this to "true" when destroying Engine
}

Engine::~Engine()
{
    // Waiting for all threads to finish
    engine->finish_threads();

    // Remove pending elements in Engine
    elements.clearList();
}

Engine* Engine::shared()
{
    if (!engine )
        LM_X(1,("Please init Engine with Engine::init()"));
    return engine;
}

void Engine::init()
{
    if ( engine )
    {
        LM_W(("Init engine twice... just ignoring"));
        return;
    }

    // Create the unique engine entity
    engine = new Engine();

    // Add a simple periodic element to not die inmediatelly
    EngineElement *element = new NotificationElement( new Notification("alive") , 10 );
    engine->elements.push_back( element );

    LM_T( LmtEngine , ("Running engine in background...") );
    pthread_create(&engine->t, 0, runEngineBakground, NULL);

    // Function to remove this engine and all EngineServices like MemoryMamager, DiskManager, ProcessManager etc...
    atexit( destroy_engine_services );
}

void Engine::finish_threads()
{
    flag_finish_threads = true;
    LM_M(("Waiting threads of Engine to finish..."));
    pthread_join(t, NULL);
    LM_M(("All Engine threads finished"));
}

void Engine::run()
{

    LM_T( LmtEngine , ("Engine run"));

    counter = 0;            // Init the counter to elements managed by this run-time

    while( true )
    {
        // Keep a total counter of loops
        counter++;

        // Finish this thread if necessary
        if( flag_finish_threads )
            return;

        // Check if there are elements in the list
        bool isEmpty;
        {
            // Mutex protection
            au::TokenTaker tt(&token , "Engine::getNextElement");
            isEmpty = ( elements.size() == 0);
        }

        if( isEmpty )
        {
            LM_T( LmtEngine, ("SamsonEngine: No more elements to process in the engine. Quitting ..."));
            return;
        }

        // Get time for the next engine element
        double t;
        {
            // Mutex protection to access elements
            au::TokenTaker tt(&token , "Engine::getNextElement");
            t = elements.front()->getTimeToTrigger();
        }

        if( t > 0 )
        {
            if ( t > 0.1 )
                t = 0.1; // Max time to sleep to avoid locks...

            // Sleeping a bit for the next engine element...
            LM_T( LmtEngine, ("Engine: Sleeping %.2f secs ..." , t));

            {
                // Mutex protection to show list
                au::TokenTaker tt(&token , "Engine::getNextElement");
                LM_T( LmtEngine, ("--------------------------------------------------------" ));
                au::list<EngineElement>::iterator it_elements;
                for (it_elements = elements.begin() ; it_elements != elements.end() ; it_elements++ )
                {
                    EngineElement *element = *it_elements;
                    LM_T( LmtEngine, ("%s" , element->getShortDescription().c_str() ));
                }
                LM_T( LmtEngine, ("--------------------------------------------------------" ));
            }

            {
                au::ExecesiveTimeAlarm alarm( "Engine sleep" , t );
                int microsecons = t*1000000;
                usleep( microsecons );
            }
            continue; // Loop again to check again...
        }

        // Get the top element to be executed
        {
            // Mutex protection to access elements
            au::TokenTaker tt(&token , "Engine::getNextElement");

            running_element = elements.front();
            elements.pop_front();
        }

        // Run or sleep
        if ( !running_element )
            LM_X(1,("Internal error at Engine"));

        {
            // Execute the item selected as running_element
            LM_T( LmtEngine, ("[START] Engine executing %s" , running_element->getDescription().c_str() ));

            int excesive_time = - running_element->getTimeToTrigger();
            if ( excesive_time > 10 )
            {
                LM_W(("Task %s delayed %d seconds in starting. This should not be more than 10"
                      , running_element->getDescription().c_str()
                      , excesive_time
                      ));
            }

            {
                // Run the item controlling excesive time
                au::ExecesiveTimeAlarm alarm( au::str("ProcessItem run '%s'",running_element->getDescription().c_str() ));
                running_element->run();
            }

            LM_T( LmtEngine, ("[DONE] Engine executing %s" , running_element->getDescription().c_str()));

            EngineElement * _running_element = running_element;
            running_element = NULL; // Put running element to NULL

            if( _running_element->isRepeated() )
            {
                // Insert again
                _running_element->Reschedule();
                add( _running_element );
            }
            else
                delete _running_element;

        }
    }
}

std::list<EngineElement*>::iterator Engine::_find_pos( EngineElement *e)
{
    for (std::list<EngineElement*>::iterator i = elements.begin() ; i != elements.end() ; i++)
    {
        if ( (*i)->getTimeToTrigger() > e->getTimeToTrigger() )
            return i;
    }

    return elements.end();
}

#pragma mark ----

// get xml information
void Engine::getInfo( std::ostringstream& output)
{
    // Mutex protection
    au::TokenTaker tt(&token , "Engine::str");

    au::xml_open(output, "engine");

    au::xml_simple(output , "loops" , counter );

    if( running_element )
        au::xml_simple( output , "running_element" , running_element->getDescription() );
    else
        au::xml_simple( output , "running_element" , "No running element" );

    au::xml_iterate_list( output , "elements" , elements );

    au::xml_simple( output , "uptime" , uptime.diffTimeInSeconds() );

    au::xml_close(output , "engine");

}

// Functions to register objects ( general and for a particular notification )
void Engine::register_object( Object* object )
{
    // Mutex protection
    au::TokenTaker tt(&token , "Engine::register_object" );

    objectsManager.add( object );
}

void Engine::register_object_for_channel( Object* object, const char* channel )
{
    // Mutex protection
    au::TokenTaker tt(&token,"Engine::register_object_for_channel");

    objectsManager.add( object , channel );
}

// Generic method to unregister an object
void Engine::unregister_object( Object* object )
{
    // Mutex protection
    au::TokenTaker tt(&token , "Engine::unregister_object");

    objectsManager.remove( object );
}

// Run a particular notification
// Only executed from friend class "NotificationElement"
void Engine::send( Notification * notification )
{
    objectsManager.send( notification );
}

// Add a notification
void Engine::notify( Notification*  notification )
{
    // Push a notification element with the notification
    add( new NotificationElement( notification ) );
}

void Engine::notify( Notification*  notification , int seconds )
{
    // Push a notification element with the notification ( in this case with periodic time )
    add( new NotificationElement( notification , seconds ) );
}

// Function to add a simple foreground tasks
void Engine::add( EngineElement *element )
{
    // Mutex protection
    au::TokenTaker tt(&token);

    // Insert an element in the engine
    elements.insert( _find_pos( element ) ,  element );

    // Wake up main thread if sleeping
    tt.wakeUp();
}

// Get an object by its registry names
Object* Engine::getObjectByName( const char *name )
{
    // Mutex protection
    au::TokenTaker tt(&token);

    return objectsManager.getObjectByName(name);

}

NAMESPACE_END<commit_msg>SAMSON-291 some new execesite time alerts<commit_after>

#include <time.h>
#include <sys/time.h>
#include <signal.h>   // SIGKILL

#include "logMsg/logMsg.h"                          // LM_X

#include "au/string.h"                             // au::xml_...
#include "au/TokenTaker.h"                          // au::TokenTake
#include "au/ErrorManager.h"                       // au::ErrorManager
#include "au/Token.h"                       // au::Token
#include "au/xml.h"         // au::xml...

#include "Notification.h"                           // engine::Notification

#include "engine/EngineElement.h"					// engine::EngineElement
#include "engine/ProcessItem.h"                     // engine::ProcessItem
#include "engine/DiskOperation.h"					// engine::DiskOperation
#include "engine/NotificationElement.h"       // engine::EngineNotificationElement

#include "engine/MemoryManager.h"
#include "engine/DiskManager.h"
#include "engine/ProcessManager.h"

#include "engine/Engine.h"							// Own interface

// Goyo. From 60 to 60000
#define ENGINE_MAX_RUNNING_TIME     60000

NAMESPACE_BEGIN(engine)

// Common engine
Engine *engine = NULL;

void* runEngineBakground(void* e )
{
    engine->run();
    return NULL;
}

Engine::Engine() :  EngineService("Engine") , token("EngineToken")
{
    running_element = NULL;                         // Initially, no running element
    flag_finish_threads = false;                    // Put this to "true" when destroying Engine
}

Engine::~Engine()
{
    // Waiting for all threads to finish
    engine->finish_threads();

    // Remove pending elements in Engine
    elements.clearList();
}

Engine* Engine::shared()
{
    if (!engine )
        LM_X(1,("Please init Engine with Engine::init()"));
    return engine;
}

void Engine::init()
{
    if ( engine )
    {
        LM_W(("Init engine twice... just ignoring"));
        return;
    }

    // Create the unique engine entity
    engine = new Engine();

    // Add a simple periodic element to not die inmediatelly
    EngineElement *element = new NotificationElement( new Notification("alive") , 10 );
    engine->elements.push_back( element );

    LM_T( LmtEngine , ("Running engine in background...") );
    pthread_create(&engine->t, 0, runEngineBakground, NULL);

    // Function to remove this engine and all EngineServices like MemoryMamager, DiskManager, ProcessManager etc...
    atexit( destroy_engine_services );
}

void Engine::finish_threads()
{
    flag_finish_threads = true;
    LM_M(("Waiting threads of Engine to finish..."));
    pthread_join(t, NULL);
    LM_M(("All Engine threads finished"));
}

void Engine::run()
{

    LM_T( LmtEngine , ("Engine run"));

    counter = 0;            // Init the counter to elements managed by this run-time

    while( true )
    {
        // Keep a total counter of loops
        counter++;

        // Finish this thread if necessary
        if( flag_finish_threads )
            return;

        // Check if there are elements in the list
        bool isEmpty;
        {
            // Mutex protection
            au::TokenTaker tt(&token , "Engine::getNextElement");
            isEmpty = ( elements.size() == 0);
        }

        if( isEmpty )
        {
            LM_T( LmtEngine, ("SamsonEngine: No more elements to process in the engine. Quitting ..."));
            return;
        }

        // Get time for the next engine element
        double t;
        {
            // Mutex protection to access elements
            au::TokenTaker tt(&token , "Engine::getNextElement");
            t = elements.front()->getTimeToTrigger();
        }

        if( t > 0 )
        {
            if ( t > 0.1 )
                t = 0.1; // Max time to sleep to avoid locks...

            // Sleeping a bit for the next engine element...
            LM_T( LmtEngine, ("Engine: Sleeping %.2f secs ..." , 2*t));

            {
                // Mutex protection to show list
                au::TokenTaker tt(&token , "Engine::getNextElement");
                LM_T( LmtEngine, ("--------------------------------------------------------" ));
                au::list<EngineElement>::iterator it_elements;
                for (it_elements = elements.begin() ; it_elements != elements.end() ; it_elements++ )
                {
                    EngineElement *element = *it_elements;
                    LM_T( LmtEngine, ("%s" , element->getShortDescription().c_str() ));
                }
                LM_T( LmtEngine, ("--------------------------------------------------------" ));
            }

            {
                au::ExecesiveTimeAlarm alarm( "Engine sleep" , t );
                int microsecons = t*1000000;
                usleep( microsecons );
            }
            continue; // Loop again to check again...
        }

        // Get the top element to be executed
        {
            // Mutex protection to access elements
            au::TokenTaker tt(&token , "Engine::getNextElement");

            running_element = elements.front();
            elements.pop_front();
        }

        // Run or sleep
        if ( !running_element )
            LM_X(1,("Internal error at Engine"));

        {
            // Execute the item selected as running_element
            LM_T( LmtEngine, ("[START] Engine executing %s" , running_element->getDescription().c_str() ));

            int excesive_time = - running_element->getTimeToTrigger();
            if ( excesive_time > 10 )
            {
                LM_W(("Task %s delayed %d seconds in starting. This should not be more than 10"
                      , running_element->getDescription().c_str()
                      , excesive_time
                      ));
            }

            {
                // Run the item controlling excesive time
                au::ExecesiveTimeAlarm alarm( au::str("ProcessItem run '%s'",running_element->getDescription().c_str() ));
                running_element->run();
            }

            LM_T( LmtEngine, ("[DONE] Engine executing %s" , running_element->getDescription().c_str()));

            EngineElement * _running_element = running_element;
            running_element = NULL; // Put running element to NULL

            if( _running_element->isRepeated() )
            {
                // Insert again
                _running_element->Reschedule();
                add( _running_element );
            }
            else
                delete _running_element;

        }
    }
}

std::list<EngineElement*>::iterator Engine::_find_pos( EngineElement *e)
{
    for (std::list<EngineElement*>::iterator i = elements.begin() ; i != elements.end() ; i++)
    {
        if ( (*i)->getTimeToTrigger() > e->getTimeToTrigger() )
            return i;
    }

    return elements.end();
}

#pragma mark ----

// get xml information
void Engine::getInfo( std::ostringstream& output)
{
    // Mutex protection
    au::TokenTaker tt(&token , "Engine::str");

    au::xml_open(output, "engine");

    au::xml_simple(output , "loops" , counter );

    if( running_element )
        au::xml_simple( output , "running_element" , running_element->getDescription() );
    else
        au::xml_simple( output , "running_element" , "No running element" );

    au::xml_iterate_list( output , "elements" , elements );

    au::xml_simple( output , "uptime" , uptime.diffTimeInSeconds() );

    au::xml_close(output , "engine");

}

// Functions to register objects ( general and for a particular notification )
void Engine::register_object( Object* object )
{
    // Mutex protection
    au::TokenTaker tt(&token , "Engine::register_object" );

    objectsManager.add( object );
}

void Engine::register_object_for_channel( Object* object, const char* channel )
{
    // Mutex protection
    au::TokenTaker tt(&token,"Engine::register_object_for_channel");

    objectsManager.add( object , channel );
}

// Generic method to unregister an object
void Engine::unregister_object( Object* object )
{
    // Mutex protection
    au::TokenTaker tt(&token , "Engine::unregister_object");

    objectsManager.remove( object );
}

// Run a particular notification
// Only executed from friend class "NotificationElement"
void Engine::send( Notification * notification )
{
    objectsManager.send( notification );
}

// Add a notification
void Engine::notify( Notification*  notification )
{
    // Push a notification element with the notification
    add( new NotificationElement( notification ) );
}

void Engine::notify( Notification*  notification , int seconds )
{
    // Push a notification element with the notification ( in this case with periodic time )
    add( new NotificationElement( notification , seconds ) );
}

// Function to add a simple foreground tasks
void Engine::add( EngineElement *element )
{
    // Mutex protection
    au::TokenTaker tt(&token);

    // Insert an element in the engine
    elements.insert( _find_pos( element ) ,  element );

    // Wake up main thread if sleeping
    tt.wakeUp();
}

// Get an object by its registry names
Object* Engine::getObjectByName( const char *name )
{
    // Mutex protection
    au::TokenTaker tt(&token);

    return objectsManager.getObjectByName(name);

}

NAMESPACE_END<|endoftext|>


<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2008 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

/**
  \file    SBVRGeogen.cpp
  \author  Jens Krueger
           SCI Institute
           University of Utah
  \date    September 2008
*/

#include "SBVRGeogen.h"
#include <algorithm>
#include <Basics/MathTools.h>

static bool EpsilonEqual(float a, float b);
static bool CheckOrdering(FLOATVECTOR3& a, FLOATVECTOR3& b, FLOATVECTOR3& c);
static int FindMinPoint(const std::vector<POS3TEX3_VERTEX> &fArray);
static void SortPoints(std::vector<POS3TEX3_VERTEX> &fArray);

SBVRGeogen::SBVRGeogen(void) :
  m_fSamplingModifier(1.0f),
  m_fMinZ(0),
  m_vAspect(1,1,1),
  m_vSize(1,1,1),
  m_vTexCoordMin(0,0,0),
  m_vTexCoordMax(1,1,1),
  m_iMinLayers(100),
  m_vGlobalAspect(1,1,1),
  m_vGlobalSize(1,1,1),
  m_vLODSize(1,1,1)
{
  m_pfBBOXStaticVertex[0] = FLOATVECTOR3(-0.5, 0.5,-0.5);
  m_pfBBOXStaticVertex[1] = FLOATVECTOR3( 0.5, 0.5,-0.5);
  m_pfBBOXStaticVertex[2] = FLOATVECTOR3( 0.5, 0.5, 0.5);
  m_pfBBOXStaticVertex[3] = FLOATVECTOR3(-0.5, 0.5, 0.5);
  m_pfBBOXStaticVertex[4] = FLOATVECTOR3(-0.5,-0.5,-0.5);
  m_pfBBOXStaticVertex[5] = FLOATVECTOR3( 0.5,-0.5,-0.5);
  m_pfBBOXStaticVertex[6] = FLOATVECTOR3( 0.5,-0.5, 0.5);
  m_pfBBOXStaticVertex[7] = FLOATVECTOR3(-0.5,-0.5, 0.5);

  m_pfBBOXVertex[0] = FLOATVECTOR3(0,0,0);
  m_pfBBOXVertex[1] = FLOATVECTOR3(0,0,0);
  m_pfBBOXVertex[2] = FLOATVECTOR3(0,0,0);
  m_pfBBOXVertex[3] = FLOATVECTOR3(0,0,0);
  m_pfBBOXVertex[4] = FLOATVECTOR3(0,0,0);
  m_pfBBOXVertex[5] = FLOATVECTOR3(0,0,0);
  m_pfBBOXVertex[6] = FLOATVECTOR3(0,0,0);
  m_pfBBOXVertex[7] = FLOATVECTOR3(0,0,0);
}

SBVRGeogen::~SBVRGeogen(void)
{
}

void SBVRGeogen::SetTransformation(const FLOATMATRIX4& matTransform, bool bForceUpdate) {
  if (bForceUpdate || m_matTransform != matTransform)  {
    m_matTransform = matTransform;
    InitBBOX();
    ComputeGeometry();
  }
}

void SBVRGeogen::InitBBOX() {

  FLOATVECTOR3 vVertexScale(m_vAspect);

  m_pfBBOXVertex[0] = POS3TEX3_VERTEX(FLOATVECTOR4(m_pfBBOXStaticVertex[0]*vVertexScale,1.0f) * m_matTransform, FLOATVECTOR3(m_vTexCoordMin.x,m_vTexCoordMax.y,m_vTexCoordMin.z));
  m_pfBBOXVertex[1] = POS3TEX3_VERTEX(FLOATVECTOR4(m_pfBBOXStaticVertex[1]*vVertexScale,1.0f) * m_matTransform, FLOATVECTOR3(m_vTexCoordMax.x,m_vTexCoordMax.y,m_vTexCoordMin.z));
  m_pfBBOXVertex[2] = POS3TEX3_VERTEX(FLOATVECTOR4(m_pfBBOXStaticVertex[2]*vVertexScale,1.0f) * m_matTransform, FLOATVECTOR3(m_vTexCoordMax.x,m_vTexCoordMax.y,m_vTexCoordMax.z));
  m_pfBBOXVertex[3] = POS3TEX3_VERTEX(FLOATVECTOR4(m_pfBBOXStaticVertex[3]*vVertexScale,1.0f) * m_matTransform, FLOATVECTOR3(m_vTexCoordMin.x,m_vTexCoordMax.y,m_vTexCoordMax.z));
  m_pfBBOXVertex[4] = POS3TEX3_VERTEX(FLOATVECTOR4(m_pfBBOXStaticVertex[4]*vVertexScale,1.0f) * m_matTransform, FLOATVECTOR3(m_vTexCoordMin.x,m_vTexCoordMin.y,m_vTexCoordMin.z));
  m_pfBBOXVertex[5] = POS3TEX3_VERTEX(FLOATVECTOR4(m_pfBBOXStaticVertex[5]*vVertexScale,1.0f) * m_matTransform, FLOATVECTOR3(m_vTexCoordMax.x,m_vTexCoordMin.y,m_vTexCoordMin.z));
  m_pfBBOXVertex[6] = POS3TEX3_VERTEX(FLOATVECTOR4(m_pfBBOXStaticVertex[6]*vVertexScale,1.0f) * m_matTransform, FLOATVECTOR3(m_vTexCoordMax.x,m_vTexCoordMin.y,m_vTexCoordMax.z));
  m_pfBBOXVertex[7] = POS3TEX3_VERTEX(FLOATVECTOR4(m_pfBBOXStaticVertex[7]*vVertexScale,1.0f) * m_matTransform, FLOATVECTOR3(m_vTexCoordMin.x,m_vTexCoordMin.y,m_vTexCoordMax.z));

  // find the minimum z value
  m_fMinZ = m_pfBBOXVertex[0].m_vPos.z;

  for (int i = 1;i<8;++i) m_fMinZ= MIN(m_fMinZ, m_pfBBOXVertex[i].m_vPos.z);
}

void SBVRGeogen::ComputeIntersection(float z, UINT32 indexA, UINT32 indexB,
                                     std::vector<POS3TEX3_VERTEX>& vHits,
                                     UINT32 &count) {
  /*
     return NO INTERSECTION if the line of the 2 points a,b is
     1. in front of the intersection plane
     2. behind the intersection plane
     3. parallel to the intersection plane (both points have "pretty much" the same z)
  */
  if ((z > m_pfBBOXVertex[indexA].m_vPos.z && z > m_pfBBOXVertex[indexB].m_vPos.z) ||
    (z < m_pfBBOXVertex[indexA].m_vPos.z && z < m_pfBBOXVertex[indexB].m_vPos.z) ||
    (EpsilonEqual(m_pfBBOXVertex[indexA].m_vPos.z,m_pfBBOXVertex[indexB].m_vPos.z))) return;

  float fAlpha = (z-m_pfBBOXVertex[indexA].m_vPos.z)/(m_pfBBOXVertex[indexA].m_vPos.z-m_pfBBOXVertex[indexB].m_vPos.z);

  POS3TEX3_VERTEX vHit;

  vHit.m_vPos.x = m_pfBBOXVertex[indexA].m_vPos.x +
                    (m_pfBBOXVertex[indexA].m_vPos.x -
                     m_pfBBOXVertex[indexB].m_vPos.x) * fAlpha;
  vHit.m_vPos.y = m_pfBBOXVertex[indexA].m_vPos.y +
                    (m_pfBBOXVertex[indexA].m_vPos.y -
                     m_pfBBOXVertex[indexB].m_vPos.y) * fAlpha;
  vHit.m_vPos.z = z;

  vHit.m_vTex = m_pfBBOXVertex[indexA].m_vTex +
                    (m_pfBBOXVertex[indexA].m_vTex -
                     m_pfBBOXVertex[indexB].m_vTex) * fAlpha;
  vHits.push_back(vHit);

  count++;
}

void SBVRGeogen::Triangulate(std::vector<POS3TEX3_VERTEX> &fArray) {
  // move bottom element to front of array
  std::swap(fArray[0], fArray[FindMinPoint(fArray)]);
  // sort points according to gradient
  SortPoints(fArray);

  // convert to triangles
  for (UINT32 i=0; i<(fArray.size()-2) ; i++) {
    m_vSliceTriangles.push_back(fArray[0]);
    m_vSliceTriangles.push_back(fArray[i+1]);
    m_vSliceTriangles.push_back(fArray[i+2]);
  }
}

bool SBVRGeogen::ComputeLayerGeometry(float fDepth) {
  UINT32 iCount = 0;
  std::vector<POS3TEX3_VERTEX> vLayerPoints;
  vLayerPoints.reserve(12);

  ComputeIntersection(fDepth,0,1,vLayerPoints,iCount);
  ComputeIntersection(fDepth,1,2,vLayerPoints,iCount);
  ComputeIntersection(fDepth,2,3,vLayerPoints,iCount);
  ComputeIntersection(fDepth,3,0,vLayerPoints,iCount);

  ComputeIntersection(fDepth,4,5,vLayerPoints,iCount);
  ComputeIntersection(fDepth,5,6,vLayerPoints,iCount);
  ComputeIntersection(fDepth,6,7,vLayerPoints,iCount);
  ComputeIntersection(fDepth,7,4,vLayerPoints,iCount);

  ComputeIntersection(fDepth,4,0,vLayerPoints,iCount);
  ComputeIntersection(fDepth,5,1,vLayerPoints,iCount);
  ComputeIntersection(fDepth,6,2,vLayerPoints,iCount);
  ComputeIntersection(fDepth,7,3,vLayerPoints,iCount);

  assert(vLayerPoints.size() == iCount);
  if (iCount > 2) {
    Triangulate(vLayerPoints);
    return true;
  } else {
    return false;
  }
}

float SBVRGeogen::GetLayerDistance() {
  return (0.5f * 1.0f/m_fSamplingModifier * (m_vAspect/FLOATVECTOR3(m_vSize))).minVal(); //float(m_vAspect.minVal())/float(std::max(m_vSize.maxVal(),m_iMinLayers));
}

float SBVRGeogen::GetOpacityCorrection() {
  return 1.0f/m_fSamplingModifier * (FLOATVECTOR3(m_vGlobalSize)/FLOATVECTOR3(m_vLODSize)).maxVal();//  GetLayerDistance()*m_vSize.maxVal();
}

void SBVRGeogen::ComputeGeometry() {
  m_vSliceTriangles.clear();

  float fDepth = m_fMinZ;
  float fLayerDistance = GetLayerDistance();

  while (ComputeLayerGeometry(fDepth)) fDepth += fLayerDistance;
}

void SBVRGeogen::SetVolumeData(const FLOATVECTOR3& vAspect, const UINTVECTOR3& vSize) {
  m_vGlobalAspect = vAspect;
  m_vGlobalSize = vSize;
}

void SBVRGeogen::SetLODData(const UINTVECTOR3& vSize) {
  m_vLODSize = vSize;
}

void SBVRGeogen::SetBrickData(const FLOATVECTOR3& vAspect,
                              const UINTVECTOR3& vSize,
                              const FLOATVECTOR3& vTexCoordMin,
                              const FLOATVECTOR3& vTexCoordMax) {
  m_vAspect       = vAspect;
  m_vSize         = vSize;
  m_vTexCoordMin  = vTexCoordMin;
  m_vTexCoordMax  = vTexCoordMax;
  InitBBOX();
}

static bool EpsilonEqual(float a, float b) {
  return fabs(a-b) < 0.00001;
}

static bool CheckOrdering(FLOATVECTOR3& a, FLOATVECTOR3& b, FLOATVECTOR3& c) {
  float g1 = (a[1]-c[1])/(a[0]-c[0]),
        g2 = (b[1]-c[1])/(b[0]-c[0]);

  if (EpsilonEqual(a[0],c[0])) return (g2 < 0) || (EpsilonEqual(g2,0) && b[0] < c[0]);
  if (EpsilonEqual(b[0],c[0])) return (g1 > 0) || (EpsilonEqual(g1,0) && a[0] > c[0]);

  if (a[0] < c[0])
    if (b[0] < c[0]) return g1 < g2; else return false;
  else
    if (b[0] < c[0]) return true; else return g1 < g2;
}

/// @todo: should probably be replaced with std::min.
static int FindMinPoint(const std::vector<POS3TEX3_VERTEX> &fArray) {
  int iIndex = 0;
  for (size_t i=1; i<fArray.size(); ++i)
    if (fArray[i].m_vPos.y < fArray[iIndex].m_vPos.y)
      iIndex = i;
  return iIndex;
}

/// @todo: should be replaced with std::sort.
static void SortPoints(std::vector<POS3TEX3_VERTEX> &fArray) {
  // for small arrays, this bubble sort actually beats qsort.
  for (UINT32 i= 1;i<fArray.size();++i)
    for (UINT32 j = 1;j<fArray.size()-i;++j)
      if (!CheckOrdering(fArray[j].m_vPos,fArray[j+1].m_vPos,fArray[0].m_vPos))
        std::swap(fArray[j], fArray[j+1]);
}
<commit_msg>Replace FindMinPoint call with std::min_element.<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2008 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

/**
  \file    SBVRGeogen.cpp
  \author  Jens Krueger
           SCI Institute
           University of Utah
  \date    September 2008
*/

#include "SBVRGeogen.h"
#include <algorithm>
#include <Basics/MathTools.h>

static bool EpsilonEqual(float a, float b);
static bool CheckOrdering(FLOATVECTOR3& a, FLOATVECTOR3& b, FLOATVECTOR3& c);
static int FindMinPoint(const std::vector<POS3TEX3_VERTEX> &fArray);
static void SortPoints(std::vector<POS3TEX3_VERTEX> &fArray);

SBVRGeogen::SBVRGeogen(void) :
  m_fSamplingModifier(1.0f),
  m_fMinZ(0),
  m_vAspect(1,1,1),
  m_vSize(1,1,1),
  m_vTexCoordMin(0,0,0),
  m_vTexCoordMax(1,1,1),
  m_iMinLayers(100),
  m_vGlobalAspect(1,1,1),
  m_vGlobalSize(1,1,1),
  m_vLODSize(1,1,1)
{
  m_pfBBOXStaticVertex[0] = FLOATVECTOR3(-0.5, 0.5,-0.5);
  m_pfBBOXStaticVertex[1] = FLOATVECTOR3( 0.5, 0.5,-0.5);
  m_pfBBOXStaticVertex[2] = FLOATVECTOR3( 0.5, 0.5, 0.5);
  m_pfBBOXStaticVertex[3] = FLOATVECTOR3(-0.5, 0.5, 0.5);
  m_pfBBOXStaticVertex[4] = FLOATVECTOR3(-0.5,-0.5,-0.5);
  m_pfBBOXStaticVertex[5] = FLOATVECTOR3( 0.5,-0.5,-0.5);
  m_pfBBOXStaticVertex[6] = FLOATVECTOR3( 0.5,-0.5, 0.5);
  m_pfBBOXStaticVertex[7] = FLOATVECTOR3(-0.5,-0.5, 0.5);

  m_pfBBOXVertex[0] = FLOATVECTOR3(0,0,0);
  m_pfBBOXVertex[1] = FLOATVECTOR3(0,0,0);
  m_pfBBOXVertex[2] = FLOATVECTOR3(0,0,0);
  m_pfBBOXVertex[3] = FLOATVECTOR3(0,0,0);
  m_pfBBOXVertex[4] = FLOATVECTOR3(0,0,0);
  m_pfBBOXVertex[5] = FLOATVECTOR3(0,0,0);
  m_pfBBOXVertex[6] = FLOATVECTOR3(0,0,0);
  m_pfBBOXVertex[7] = FLOATVECTOR3(0,0,0);
}

SBVRGeogen::~SBVRGeogen(void)
{
}

void SBVRGeogen::SetTransformation(const FLOATMATRIX4& matTransform, bool bForceUpdate) {
  if (bForceUpdate || m_matTransform != matTransform)  {
    m_matTransform = matTransform;
    InitBBOX();
    ComputeGeometry();
  }
}

void SBVRGeogen::InitBBOX() {

  FLOATVECTOR3 vVertexScale(m_vAspect);

  m_pfBBOXVertex[0] = POS3TEX3_VERTEX(FLOATVECTOR4(m_pfBBOXStaticVertex[0]*vVertexScale,1.0f) * m_matTransform, FLOATVECTOR3(m_vTexCoordMin.x,m_vTexCoordMax.y,m_vTexCoordMin.z));
  m_pfBBOXVertex[1] = POS3TEX3_VERTEX(FLOATVECTOR4(m_pfBBOXStaticVertex[1]*vVertexScale,1.0f) * m_matTransform, FLOATVECTOR3(m_vTexCoordMax.x,m_vTexCoordMax.y,m_vTexCoordMin.z));
  m_pfBBOXVertex[2] = POS3TEX3_VERTEX(FLOATVECTOR4(m_pfBBOXStaticVertex[2]*vVertexScale,1.0f) * m_matTransform, FLOATVECTOR3(m_vTexCoordMax.x,m_vTexCoordMax.y,m_vTexCoordMax.z));
  m_pfBBOXVertex[3] = POS3TEX3_VERTEX(FLOATVECTOR4(m_pfBBOXStaticVertex[3]*vVertexScale,1.0f) * m_matTransform, FLOATVECTOR3(m_vTexCoordMin.x,m_vTexCoordMax.y,m_vTexCoordMax.z));
  m_pfBBOXVertex[4] = POS3TEX3_VERTEX(FLOATVECTOR4(m_pfBBOXStaticVertex[4]*vVertexScale,1.0f) * m_matTransform, FLOATVECTOR3(m_vTexCoordMin.x,m_vTexCoordMin.y,m_vTexCoordMin.z));
  m_pfBBOXVertex[5] = POS3TEX3_VERTEX(FLOATVECTOR4(m_pfBBOXStaticVertex[5]*vVertexScale,1.0f) * m_matTransform, FLOATVECTOR3(m_vTexCoordMax.x,m_vTexCoordMin.y,m_vTexCoordMin.z));
  m_pfBBOXVertex[6] = POS3TEX3_VERTEX(FLOATVECTOR4(m_pfBBOXStaticVertex[6]*vVertexScale,1.0f) * m_matTransform, FLOATVECTOR3(m_vTexCoordMax.x,m_vTexCoordMin.y,m_vTexCoordMax.z));
  m_pfBBOXVertex[7] = POS3TEX3_VERTEX(FLOATVECTOR4(m_pfBBOXStaticVertex[7]*vVertexScale,1.0f) * m_matTransform, FLOATVECTOR3(m_vTexCoordMin.x,m_vTexCoordMin.y,m_vTexCoordMax.z));

  // find the minimum z value
  m_fMinZ = m_pfBBOXVertex[0].m_vPos.z;

  for (int i = 1;i<8;++i) m_fMinZ= MIN(m_fMinZ, m_pfBBOXVertex[i].m_vPos.z);
}

void SBVRGeogen::ComputeIntersection(float z, UINT32 indexA, UINT32 indexB,
                                     std::vector<POS3TEX3_VERTEX>& vHits,
                                     UINT32 &count) {
  /*
     return NO INTERSECTION if the line of the 2 points a,b is
     1. in front of the intersection plane
     2. behind the intersection plane
     3. parallel to the intersection plane (both points have "pretty much" the same z)
  */
  if ((z > m_pfBBOXVertex[indexA].m_vPos.z && z > m_pfBBOXVertex[indexB].m_vPos.z) ||
    (z < m_pfBBOXVertex[indexA].m_vPos.z && z < m_pfBBOXVertex[indexB].m_vPos.z) ||
    (EpsilonEqual(m_pfBBOXVertex[indexA].m_vPos.z,m_pfBBOXVertex[indexB].m_vPos.z))) return;

  float fAlpha = (z-m_pfBBOXVertex[indexA].m_vPos.z)/(m_pfBBOXVertex[indexA].m_vPos.z-m_pfBBOXVertex[indexB].m_vPos.z);

  POS3TEX3_VERTEX vHit;

  vHit.m_vPos.x = m_pfBBOXVertex[indexA].m_vPos.x +
                    (m_pfBBOXVertex[indexA].m_vPos.x -
                     m_pfBBOXVertex[indexB].m_vPos.x) * fAlpha;
  vHit.m_vPos.y = m_pfBBOXVertex[indexA].m_vPos.y +
                    (m_pfBBOXVertex[indexA].m_vPos.y -
                     m_pfBBOXVertex[indexB].m_vPos.y) * fAlpha;
  vHit.m_vPos.z = z;

  vHit.m_vTex = m_pfBBOXVertex[indexA].m_vTex +
                    (m_pfBBOXVertex[indexA].m_vTex -
                     m_pfBBOXVertex[indexB].m_vTex) * fAlpha;
  vHits.push_back(vHit);

  count++;
}

// Functor to identify the point with the lowest `y' coordinate.
struct vertex_min : public std::binary_function<POS3TEX3_VERTEX,
                                                POS3TEX3_VERTEX,
                                                bool> {
  bool operator()(const POS3TEX3_VERTEX &a, const POS3TEX3_VERTEX &b) const {
    return (a.m_vPos.y < b.m_vPos.y);
  }
};

void SBVRGeogen::Triangulate(std::vector<POS3TEX3_VERTEX> &fArray) {
  // move bottom element to front of array
  std::swap(fArray[0],
            *std::min_element(fArray.begin(), fArray.end(), vertex_min()));
  // sort points according to gradient
  SortPoints(fArray);

  // convert to triangles
  for (UINT32 i=0; i<(fArray.size()-2) ; i++) {
    m_vSliceTriangles.push_back(fArray[0]);
    m_vSliceTriangles.push_back(fArray[i+1]);
    m_vSliceTriangles.push_back(fArray[i+2]);
  }
}

bool SBVRGeogen::ComputeLayerGeometry(float fDepth) {
  UINT32 iCount = 0;
  std::vector<POS3TEX3_VERTEX> vLayerPoints;
  vLayerPoints.reserve(12);

  ComputeIntersection(fDepth,0,1,vLayerPoints,iCount);
  ComputeIntersection(fDepth,1,2,vLayerPoints,iCount);
  ComputeIntersection(fDepth,2,3,vLayerPoints,iCount);
  ComputeIntersection(fDepth,3,0,vLayerPoints,iCount);

  ComputeIntersection(fDepth,4,5,vLayerPoints,iCount);
  ComputeIntersection(fDepth,5,6,vLayerPoints,iCount);
  ComputeIntersection(fDepth,6,7,vLayerPoints,iCount);
  ComputeIntersection(fDepth,7,4,vLayerPoints,iCount);

  ComputeIntersection(fDepth,4,0,vLayerPoints,iCount);
  ComputeIntersection(fDepth,5,1,vLayerPoints,iCount);
  ComputeIntersection(fDepth,6,2,vLayerPoints,iCount);
  ComputeIntersection(fDepth,7,3,vLayerPoints,iCount);

  assert(vLayerPoints.size() == iCount);
  if (iCount > 2) {
    Triangulate(vLayerPoints);
    return true;
  } else {
    return false;
  }
}

float SBVRGeogen::GetLayerDistance() {
  return (0.5f * 1.0f/m_fSamplingModifier * (m_vAspect/FLOATVECTOR3(m_vSize))).minVal(); //float(m_vAspect.minVal())/float(std::max(m_vSize.maxVal(),m_iMinLayers));
}

float SBVRGeogen::GetOpacityCorrection() {
  return 1.0f/m_fSamplingModifier * (FLOATVECTOR3(m_vGlobalSize)/FLOATVECTOR3(m_vLODSize)).maxVal();//  GetLayerDistance()*m_vSize.maxVal();
}

void SBVRGeogen::ComputeGeometry() {
  m_vSliceTriangles.clear();

  float fDepth = m_fMinZ;
  float fLayerDistance = GetLayerDistance();

  while (ComputeLayerGeometry(fDepth)) fDepth += fLayerDistance;
}

void SBVRGeogen::SetVolumeData(const FLOATVECTOR3& vAspect, const UINTVECTOR3& vSize) {
  m_vGlobalAspect = vAspect;
  m_vGlobalSize = vSize;
}

void SBVRGeogen::SetLODData(const UINTVECTOR3& vSize) {
  m_vLODSize = vSize;
}

void SBVRGeogen::SetBrickData(const FLOATVECTOR3& vAspect,
                              const UINTVECTOR3& vSize,
                              const FLOATVECTOR3& vTexCoordMin,
                              const FLOATVECTOR3& vTexCoordMax) {
  m_vAspect       = vAspect;
  m_vSize         = vSize;
  m_vTexCoordMin  = vTexCoordMin;
  m_vTexCoordMax  = vTexCoordMax;
  InitBBOX();
}

static bool EpsilonEqual(float a, float b) {
  return fabs(a-b) < 0.00001;
}

static bool CheckOrdering(FLOATVECTOR3& a, FLOATVECTOR3& b, FLOATVECTOR3& c) {
  float g1 = (a[1]-c[1])/(a[0]-c[0]),
        g2 = (b[1]-c[1])/(b[0]-c[0]);

  if (EpsilonEqual(a[0],c[0])) return (g2 < 0) || (EpsilonEqual(g2,0) && b[0] < c[0]);
  if (EpsilonEqual(b[0],c[0])) return (g1 > 0) || (EpsilonEqual(g1,0) && a[0] > c[0]);

  if (a[0] < c[0])
    if (b[0] < c[0]) return g1 < g2; else return false;
  else
    if (b[0] < c[0]) return true; else return g1 < g2;
}

/// @todo: should probably be replaced with std::min.
static int FindMinPoint(const std::vector<POS3TEX3_VERTEX> &fArray) {
  int iIndex = 0;
  for (size_t i=1; i<fArray.size(); ++i)
    if (fArray[i].m_vPos.y < fArray[iIndex].m_vPos.y)
      iIndex = i;
  return iIndex;
}

/// @todo: should be replaced with std::sort.
static void SortPoints(std::vector<POS3TEX3_VERTEX> &fArray) {
  // for small arrays, this bubble sort actually beats qsort.
  for (UINT32 i= 1;i<fArray.size();++i)
    for (UINT32 j = 1;j<fArray.size()-i;++j)
      if (!CheckOrdering(fArray[j].m_vPos,fArray[j+1].m_vPos,fArray[0].m_vPos))
        std::swap(fArray[j], fArray[j+1]);
}
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_MAPPER_DEFAULT_FV_HH
#define DUNE_GDT_MAPPER_DEFAULT_FV_HH

#include <type_traits>

#include <dune/common/dynvector.hh>
#include <dune/common/static_assert.hh>

#include <dune/stuff/common/debug.hh>
#include <dune/stuff/common/type_utils.hh>

#include "../../mapper/interface.hh"

namespace Dune {
namespace GDT {
namespace Mapper {

// forward
template< class GridViewImp, size_t rangeDim = 1, size_t rangeDimCols = 1 >
class FiniteVolume
{
  static_assert(AlwaysFalse< GridViewImp >::value, "Not available for these dimensions!");
};

namespace internal {

template< class GridViewImp, size_t rangeDim, size_t rangeDimCols >
class FiniteVolumeTraits
{
  static_assert(rangeDim >= 1, "Really?");
  static_assert(rangeDimCols >= 1, "Really?");
public:
  typedef GridViewImp GridViewType;
  typedef FiniteVolume< GridViewType, rangeDim, rangeDimCols> derived_type;
  typedef typename GridViewImp::IndexSet BackendType;
  typedef typename GridViewType::template Codim< 0 >::Entity EntityType;
};

} // namespace internal

template< class GridViewImp >
class FiniteVolume< GridViewImp, 1, 1 >
  : public MapperInterface< internal::FiniteVolumeTraits< GridViewImp, 1, 1 > >
{
  typedef MapperInterface< internal::FiniteVolumeTraits< GridViewImp, 1, 1 > > InterfaceType;
public:
  typedef internal::FiniteVolumeTraits< GridViewImp, 1, 1 > Traits;
  typedef typename Traits::GridViewType                     GridViewType;
  typedef typename Traits::BackendType                      BackendType;
  typedef typename Traits::EntityType                       EntityType;

  FiniteVolume(const GridViewType& grid_view)
    : backend_(grid_view.indexSet())
  {}

  const BackendType& backend() const
  {
    return backend_;
  }

  size_t size() const
  {
    return backend_.size(0);
  }

  size_t numDofs(const EntityType& /*entity*/) const
  {
    return 1;
  }

  size_t maxNumDofs() const
  {
    return 1;
  }

  void globalIndices(const EntityType& entity, Dune::DynamicVector< size_t >& ret) const
  {
    if (ret.size() < 1)
      ret.resize(1);
    ret[0] = mapToGlobal(entity, 0);
  } // ... globalIndices(...)

  using InterfaceType::globalIndices;

  size_t mapToGlobal(const EntityType& entity, const size_t& UNUSED_UNLESS_DEBUG(localIndex)) const
  {
    assert(localIndex == 0);
    return backend_.index(entity);
  }

private:
  const BackendType& backend_;
}; // class FiniteVolume< ..., 1, 1 >

template< class GridViewImp, size_t rangeDim >
class FiniteVolume< GridViewImp, rangeDim, 1 >
  : public MapperInterface< internal::FiniteVolumeTraits< GridViewImp, rangeDim, 1 > >
{
  typedef MapperInterface< internal::FiniteVolumeTraits< GridViewImp, rangeDim, 1 > > InterfaceType;
  static const size_t dimRange = rangeDim;
public:
  typedef internal::FiniteVolumeTraits< GridViewImp, rangeDim, 1 > Traits;
  typedef typename Traits::GridViewType                            GridViewType;
  typedef typename Traits::BackendType                             BackendType;
  typedef typename Traits::EntityType                              EntityType;

  FiniteVolume(const GridViewType& grid_view)
    : backend_(grid_view.indexSet())
  {}

  const BackendType& backend() const
  {
    return backend_;
  }

  size_t size() const
  {
    return dimRange * backend_.size(0);
  }

  size_t numDofs(const EntityType& /*entity*/) const
  {
    return dimRange;
  }

  size_t maxNumDofs() const
  {
    return dimRange;
  }

  void globalIndices(const EntityType& entity, Dune::DynamicVector< size_t >& ret) const
  {
    if (ret.size() < dimRange)
      ret.resize(dimRange);
    const size_t base = dimRange * backend_.index(entity);
    for (size_t ii = 0; ii < dimRange; ++ii)
      ret[ii] = base + ii;
  } // ... globalIndices(...)

  using InterfaceType::globalIndices;

  size_t mapToGlobal(const EntityType& entity, const size_t& localIndex) const
  {
    assert(localIndex < dimRange);
    return (dimRange * backend_.index(entity)) + localIndex;
  }

private:
  const BackendType& backend_;
}; // class FiniteVolume< ..., rangeDim, 1 >

} // namespace Mapper
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_MAPPER_DEFAULT_FV_HH
<commit_msg>[mapper.default] fixes deprecated header usage in fv.hh<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_MAPPER_DEFAULT_FV_HH
#define DUNE_GDT_MAPPER_DEFAULT_FV_HH

#include <type_traits>

#include <dune/common/dynvector.hh>

#include <dune/stuff/common/debug.hh>
#include <dune/stuff/common/type_utils.hh>

#include "../../mapper/interface.hh"

namespace Dune {
namespace GDT {
namespace Mapper {

// forward
template< class GridViewImp, size_t rangeDim = 1, size_t rangeDimCols = 1 >
class FiniteVolume
{
  static_assert(AlwaysFalse< GridViewImp >::value, "Not available for these dimensions!");
};

namespace internal {

template< class GridViewImp, size_t rangeDim, size_t rangeDimCols >
class FiniteVolumeTraits
{
  static_assert(rangeDim >= 1, "Really?");
  static_assert(rangeDimCols >= 1, "Really?");
public:
  typedef GridViewImp GridViewType;
  typedef FiniteVolume< GridViewType, rangeDim, rangeDimCols> derived_type;
  typedef typename GridViewImp::IndexSet BackendType;
  typedef typename GridViewType::template Codim< 0 >::Entity EntityType;
};

} // namespace internal

template< class GridViewImp >
class FiniteVolume< GridViewImp, 1, 1 >
  : public MapperInterface< internal::FiniteVolumeTraits< GridViewImp, 1, 1 > >
{
  typedef MapperInterface< internal::FiniteVolumeTraits< GridViewImp, 1, 1 > > InterfaceType;
public:
  typedef internal::FiniteVolumeTraits< GridViewImp, 1, 1 > Traits;
  typedef typename Traits::GridViewType                     GridViewType;
  typedef typename Traits::BackendType                      BackendType;
  typedef typename Traits::EntityType                       EntityType;

  FiniteVolume(const GridViewType& grid_view)
    : backend_(grid_view.indexSet())
  {}

  const BackendType& backend() const
  {
    return backend_;
  }

  size_t size() const
  {
    return backend_.size(0);
  }

  size_t numDofs(const EntityType& /*entity*/) const
  {
    return 1;
  }

  size_t maxNumDofs() const
  {
    return 1;
  }

  void globalIndices(const EntityType& entity, Dune::DynamicVector< size_t >& ret) const
  {
    if (ret.size() < 1)
      ret.resize(1);
    ret[0] = mapToGlobal(entity, 0);
  } // ... globalIndices(...)

  using InterfaceType::globalIndices;

  size_t mapToGlobal(const EntityType& entity, const size_t& UNUSED_UNLESS_DEBUG(localIndex)) const
  {
    assert(localIndex == 0);
    return backend_.index(entity);
  }

private:
  const BackendType& backend_;
}; // class FiniteVolume< ..., 1, 1 >

template< class GridViewImp, size_t rangeDim >
class FiniteVolume< GridViewImp, rangeDim, 1 >
  : public MapperInterface< internal::FiniteVolumeTraits< GridViewImp, rangeDim, 1 > >
{
  typedef MapperInterface< internal::FiniteVolumeTraits< GridViewImp, rangeDim, 1 > > InterfaceType;
  static const size_t dimRange = rangeDim;
public:
  typedef internal::FiniteVolumeTraits< GridViewImp, rangeDim, 1 > Traits;
  typedef typename Traits::GridViewType                            GridViewType;
  typedef typename Traits::BackendType                             BackendType;
  typedef typename Traits::EntityType                              EntityType;

  FiniteVolume(const GridViewType& grid_view)
    : backend_(grid_view.indexSet())
  {}

  const BackendType& backend() const
  {
    return backend_;
  }

  size_t size() const
  {
    return dimRange * backend_.size(0);
  }

  size_t numDofs(const EntityType& /*entity*/) const
  {
    return dimRange;
  }

  size_t maxNumDofs() const
  {
    return dimRange;
  }

  void globalIndices(const EntityType& entity, Dune::DynamicVector< size_t >& ret) const
  {
    if (ret.size() < dimRange)
      ret.resize(dimRange);
    const size_t base = dimRange * backend_.index(entity);
    for (size_t ii = 0; ii < dimRange; ++ii)
      ret[ii] = base + ii;
  } // ... globalIndices(...)

  using InterfaceType::globalIndices;

  size_t mapToGlobal(const EntityType& entity, const size_t& localIndex) const
  {
    assert(localIndex < dimRange);
    return (dimRange * backend_.index(entity)) + localIndex;
  }

private:
  const BackendType& backend_;
}; // class FiniteVolume< ..., rangeDim, 1 >

} // namespace Mapper
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_MAPPER_DEFAULT_FV_HH
<|endoftext|>


<commit_before>// Functions for the symmetric group approach
#include<iostream>
#include<vector>
#include"weyl.h"

class perm_a
{
	public:
		std::vector<int> perm;
		double coeff=1;
		int    n=0;
	// TODO: overload the multiply operator
};

void
print_perm(perm_a P)
{
	std::cout << P.coeff << " * ";
	for(auto p : P.perm)
		std::cout << p <<" ";
	std::cout << "\n";
	return;
}

perm_a
perm_I(int n)
{
	//unit permutation
	perm_a P;
	P.perm.clear();
	for(int k=0; k<n; k++)
		P.perm.push_back(k);
	P.coeff=1;
	return P;
}

//overload the * operator
perm_a
perm_multiply(const perm_a& P1, const perm_a& P2)
{

	bool debug=false;
	perm_a result;
	std::vector<int> p_result;

	p_result.clear();
	if(P1.perm.size() != P2.perm.size())
	{
		std::cout << "Error in perm_multiply, perms must be same size"
			  << std::endl;
		return result;
	}

	p_result.resize(P1.perm.size());

	for(int j=0; j<P1.perm.size(); j++)
	{
		p_result[j]=P1.perm[P2.perm[j]];
		if(debug)
		{
			std::cout << "p_result element " << j << " "
				  << p_result[j] ;
			std::cout << " (young::perm_multiply)\n";
		}
	}

	result.coeff=P1.coeff*P2.coeff;
	result.perm=p_result;

	return result;
}

//overload the * operator
std::vector<perm_a>
multiply(std::vector<perm_a> A, std::vector<perm_a> B)
{
	bool debug=false;
	std::vector<perm_a>  product;
	for( auto p : A )
		for( auto q : B)
		{
			perm_a pq=perm_multiply(p,q);
			if(debug)
			{
				std::cout << "pq (young::multiply)\n";
				print_perm(pq);
			}
			product.push_back(pq);
		}

	//simplify using std::algorithm
	//i.e. combine like terms

	if(debug)
	{
		std::cout << "product (young::multiply)\n";
		for( perm_a p : product)
			print_perm(p);
	}

	return product;
}

std::vector<perm_a>
Srow(std::vector<int> frame,std::vector<int> tableau)
{
	bool debug=false;
	if(debug) std::cout << "here (young::Srow)\n";
	int N=0; //number of electrons
	for(int r=0; r<frame.size(); r++)
		N=N+frame[r];

	//initialize S as I
	std::vector<perm_a> S;
	S.clear(); S.push_back(perm_I(N));

	std::vector<perm_a> Sr;
	for(int row=0; row<frame.size(); row++)
	{
		Sr.clear();

		if(frame[row]==1)
			continue;
		perm_a P;
		P.perm.clear();

		int col0=tableau_pos(row,0,frame);
		int col1=tableau_pos(row,1,frame);

		P.perm.clear();
		for(int k=0; k< N; k++)
			P.perm.push_back(k);
		P.perm[tableau[col0]]=tableau[col1];
		P.perm[tableau[col1]]=tableau[col0];

		P.coeff=1;

		Sr.push_back(perm_I(N));
		Sr.push_back(P);

		if(debug)
		{
			std::cout << "Sr (young::Srow)\n";
			for( perm_a p : Sr)
				print_perm(p);
			std::cout << "\n";
			std::cout << "S  (young::Srow)\n";
			for( perm_a p : S)
				print_perm(p);
			std::cout << "\n";

		}

		S=multiply(S,Sr);
		if(debug)
		{
			std::cout << "after multiply(S,Sr) (young::Srow)\n";
			for( perm_a p : S)
				print_perm(p);
			std::cout << "\n";
		}
	}
	return S;
}

int Ey(std::vector<int> frame_rows,std::vector<int> yT)
{
	std::vector<perm_a> S=Srow(frame_rows,yT);
	std::cout << "Symmetrizer of rows:\n";
	for(int k=0; k<S.size(); k++)
	{
		print_perm(S[k]);
	}
	return 0;
}

int
main()
{
	int n=3;

	perm_a P12;
	P12.perm={1,0,2};
	P12.coeff=.5;

	//std::cout << ".5 * P12\n";
	//print_perm(P12);

	perm_a id;
	id.perm={0,1,2};
	id.coeff=-1;

	//std::cout << "Id\n";
	//print_perm(id);

	std::vector<perm_a> pvec;
	pvec.clear();
	pvec.push_back(id);

	//print_perm(perm_multiply(P12,P12));

	std::vector<int> frame_rows;
	frame_rows.clear();
	frame_rows.push_back(2);
	frame_rows.push_back(2);
	frame_rows.push_back(1);

	std::vector<int> young_tableau;
	young_tableau.clear();
	young_tableau.push_back(0);
	young_tableau.push_back(1);
	young_tableau.push_back(2);
	young_tableau.push_back(3);
	young_tableau.push_back(4);

	print_tableau(young_tableau,frame_rows);

	Ey(frame_rows,young_tableau);

	return 0;
}

<commit_msg>Got the sgn(P) function working via Eigen<commit_after>// Functions for the symmetric group approach
#include<iostream>
#include<vector>
#include<algorithm>
#include<Eigen>
#include"weyl.h"

typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>
        Matrix;  // import dense, dynamically sized Matrix type from Eigen;

class perm_a
{
	public:
		std::vector<int> perm;
		double coeff=1;
		int    n=0;
	// TODO: overload the multiply operator
};

//test functions
int                   test_symmetrizer();
//symmetrizer
std::vector<perm_a>   Srow(std::vector<int> frame,std::vector<int> tableau);

void
print_perm(perm_a P)
{
	std::cout << P.coeff << " * ";
	for(auto p : P.perm)
		std::cout << p <<" ";
	std::cout << "\n";
	return;
}

perm_a
perm_I(int n)
{
	//unit permutation
	perm_a P;
	P.perm.clear();
	for(int k=0; k<n; k++)
		P.perm.push_back(k);
	P.coeff=1;
	return P;
}

//overload the * operator
perm_a
perm_multiply(const perm_a& P1, const perm_a& P2)
{

	bool debug=false;
	perm_a result;
	std::vector<int> p_result;

	p_result.clear();
	if(P1.perm.size() != P2.perm.size())
	{
		std::cout << "Error in perm_multiply, perms must be same size"
			  << std::endl;
		return result;
	}

	p_result.resize(P1.perm.size());

	for(int j=0; j<P1.perm.size(); j++)
	{
		p_result[j]=P1.perm[P2.perm[j]];
		if(debug)
		{
			std::cout << "p_result element " << j << " "
				  << p_result[j] ;
			std::cout << " (young::perm_multiply)\n";
		}
	}

	result.coeff=P1.coeff*P2.coeff;
	result.perm=p_result;

	return result;
}

//overload the * operator
std::vector<perm_a>
multiply(std::vector<perm_a> A, std::vector<perm_a> B)
{
	bool debug=false;
	std::vector<perm_a>  product;
	for( auto p : A )
		for( auto q : B)
		{
			perm_a pq=perm_multiply(p,q);
			if(debug)
			{
				std::cout << "pq (young::multiply)\n";
				print_perm(pq);
			}
			product.push_back(pq);
		}

	//simplify using std::algorithm
	//i.e. combine like terms

	if(debug)
	{
		std::cout << "product (young::multiply)\n";
		for( perm_a p : product)
			print_perm(p);
	}

	return product;
}

Matrix
perm_matrix(std::vector<int> perm)
{
	int n = perm.size();
	Matrix P;
	P.resize(n,n);
	for(int i=0; i<n; i++)
	{
		for(int j=0; j<n; j++)
		{
			if(j==perm[i])
				P(i,j)=1;
			else
				P(i,j)=0;
		}
	}
	return P;
}
int
sgn(std::vector<int> perm)
{
	return perm_matrix(perm).determinant();
}

int Ey(std::vector<int> frame_rows,std::vector<int> yT)
{

	return 0;
}

int
main()
{

	int n=3;
	std::vector<int> perm={0,1,2};
	do
	{
		std::cout << sgn(perm) <<"  ";
		for(int pk : perm)
			std::cout << pk << " ";
		std::cout << "\n";

		std::cout << perm_matrix(perm);
		std::cout << "\n";

	}while(std::next_permutation(perm.begin(),perm.end()));

	/*
	perm_a P12;
	P12.perm={1,0,2};
	P12.coeff=.5;

	//std::cout << ".5 * P12\n";
	//print_perm(P12);

	perm_a id;
	id.perm={0,1,2};
	id.coeff=-1;

	//std::cout << "Id\n";
	//print_perm(id);

	std::vector<perm_a> pvec;
	pvec.clear();
	pvec.push_back(id);

	//print_perm(perm_multiply(P12,P12));
	*/

}

int
test_symmetrizer()
{

	std::vector<int> frame_rows;
	frame_rows.clear();
	frame_rows.push_back(2);
	frame_rows.push_back(2);
	frame_rows.push_back(1);

	std::vector<int> young_tableau;
	young_tableau.clear();
	young_tableau.push_back(0);
	young_tableau.push_back(1);
	young_tableau.push_back(2);
	young_tableau.push_back(3);
	young_tableau.push_back(4);

	print_tableau(frame_rows,young_tableau);

	std::vector<perm_a> S=Srow(frame_rows,young_tableau);
	std::cout << "Symmetrizer of rows:\n";
	for(int k=0; k<S.size(); k++)
	{
		print_perm(S[k]);
	}

	return 0;
}

std::vector<perm_a>
Srow(std::vector<int> frame,std::vector<int> tableau)
{
	bool debug=false;
	if(debug) std::cout << "here (young::Srow)\n";
	int N=0; //number of electrons
	for(int r=0; r<frame.size(); r++)
		N=N+frame[r];

	//initialize S as I
	std::vector<perm_a> S;
	S.clear(); S.push_back(perm_I(N));

	std::vector<perm_a> Sr;
	for(int row=0; row<frame.size(); row++)
	{
		Sr.clear();

		if(frame[row]==1)
			continue;
		perm_a P;
		P.perm.clear();

		int col0=tableau_pos(row,0,frame);
		int col1=tableau_pos(row,1,frame);

		P.perm.clear();
		for(int k=0; k< N; k++)
			P.perm.push_back(k);
		P.perm[tableau[col0]]=tableau[col1];
		P.perm[tableau[col1]]=tableau[col0];

		P.coeff=1;

		Sr.push_back(perm_I(N));
		Sr.push_back(P);

		if(debug)
		{
			std::cout << "Sr (young::Srow)\n";
			for( perm_a p : Sr)
				print_perm(p);
			std::cout << "\n";
			std::cout << "S  (young::Srow)\n";
			for( perm_a p : S)
				print_perm(p);
			std::cout << "\n";

		}

		S=multiply(S,Sr);
		if(debug)
		{
			std::cout << "after multiply(S,Sr) (young::Srow)\n";
			for( perm_a p : S)
				print_perm(p);
			std::cout << "\n";
		}
	}
	return S;
}
<|endoftext|>


<commit_before>#include "SDLManager.hh"
#include "SDLConfig.hh"

namespace RAGE
{
    namespace SDL
    {

        Manager::Manager(bool video, bool audio, bool timer, bool cdrom, bool joystick, bool noparachute, bool eventthread) throw (std::logic_error)
        try
        {
#ifdef DEBUG
            Log << nl << "Manager::Manager() called ...";
#endif

            Uint32 flags;

            if (video)
                flags |= SDL_INIT_VIDEO;
            if (audio)
                flags |= SDL_INIT_AUDIO;
            if (timer)
                flags |= SDL_INIT_TIMER;
            if (cdrom)
                flags |= SDL_INIT_CDROM;
            if (joystick)
                flags |= SDL_INIT_JOYSTICK;
            if (noparachute)
                flags |= SDL_INIT_NOPARACHUTE;
//To Disable EventThread under Windows
//just a little usefull tip for mingw
#ifndef WIN32
            if (eventthread)
                flags |= SDL_INIT_EVENTTHREAD;
//not sure what to do with mingw32...
#endif

            if (SDL_Init(flags)<0)
            {
                //logs manager error with usefull information
                std::string errormsg("Unable to initialize SDL subsystems ");
                if ( (flags & SDL_INIT_TIMER) !=0 )
                    errormsg+= "TIMER " ;
                if ( (flags & SDL_INIT_AUDIO) != 0)
                    errormsg+= "AUDIO " ;
                if ( (flags & SDL_INIT_VIDEO) != 0)
                    errormsg+= "VIDEO " ;
                if ( (flags & SDL_INIT_CDROM) != 0)
                    errormsg+= "CDROM " ;
                if ( (flags & SDL_INIT_JOYSTICK) != 0)
                    errormsg+= "JOYSTICK " ;
                if ( (flags & SDL_INIT_NOPARACHUTE) != 0)
                    errormsg+= "NOPARACHUTE " ;
                if ( (flags & SDL_INIT_EVENTTHREAD) != 0)
                    errormsg+= "EVENTTHREAD " ;
                Log << errormsg << ": " << GetError() ;
                throw std::logic_error("SDL_Init failed!");
            }
#ifdef DEBUG
            Log << nl << "Manager::Manager() done.";
#endif

        }
        catch (std::exception &e)
        {
            Log << nl << "Exception catched in Manager Constructor" << nl << e.what();
        }

Manager::~Manager()
        {
#ifdef DEBUG
            Log << nl << "Manager::~Manager() called ...";
#endif

            SDL_Quit();
#ifdef DEBUG
            Log << nl << "Manager::~Manager() done.";
#endif
        }

        bool Manager::enableTimer(void)
        {
            return SDL_InitSubSystem(SDL_INIT_TIMER) == 0;
        }
        bool Manager::enableAudio(void)
        {
            return SDL_InitSubSystem(SDL_INIT_AUDIO)== 0;
        }
        bool Manager::enableVideo(void)
        {
            return SDL_InitSubSystem(SDL_INIT_VIDEO)== 0;
        }
        bool Manager::enableCdrom(void)
        {
            return SDL_InitSubSystem(SDL_INIT_CDROM)== 0;
        }
        bool Manager::enableJoystick(void)
        {
            return SDL_InitSubSystem(SDL_INIT_JOYSTICK)== 0;
        }
        bool Manager::enableEverything(void)
        {
            return SDL_InitSubSystem(SDL_INIT_EVERYTHING)== 0;
        }
        bool Manager::enableNoParachute(void)
        {
            return SDL_InitSubSystem(SDL_INIT_NOPARACHUTE)== 0;
        }
        bool Manager::enableEventThread(void)
        {
            return SDL_InitSubSystem(SDL_INIT_EVENTTHREAD)== 0;
        }

        void Manager::disableTimer(void)
        {
            SDL_QuitSubSystem(SDL_INIT_TIMER);
        }
        void Manager::disableAudio(void)
        {
            SDL_QuitSubSystem(SDL_INIT_AUDIO);
        }
        void Manager::disableVideo(void)
        {
            SDL_QuitSubSystem(SDL_INIT_VIDEO);
        }
        void Manager::disableCdrom(void)
        {

            SDL_QuitSubSystem(SDL_INIT_CDROM);
        }
        void Manager::disableJoystick(void)
        {

            SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
        }
        void Manager::disableEverything(void)
        {

            SDL_QuitSubSystem(SDL_INIT_EVERYTHING);
        }
        void Manager::disableNoParachute(void)
        {

            SDL_QuitSubSystem(SDL_INIT_NOPARACHUTE);
        }
        void Manager::disableEventThread(void)
        {

            SDL_QuitSubSystem(SDL_INIT_EVENTTHREAD);
        }

	bool Manager::isTimerEnabled(void) const
	{
		return ( SDL_WasInit(SDL_INIT_TIMER) ) != 0;
	}
	bool Manager::isAudioEnabled(void) const
	{
		return ( SDL_WasInit(SDL_INIT_AUDIO) ) != 0;
	}
	bool Manager::isVideoEnabled(void) const
	{
		return ( SDL_WasInit(SDL_INIT_VIDEO) ) != 0;
	}
	bool Manager::isCdromEnabled(void) const
	{
		return ( SDL_WasInit(SDL_INIT_CDROM) ) != 0;
	}
	bool Manager::isJoystickEnabled(void) const
	{
		return ( SDL_WasInit(SDL_INIT_JOYSTICK) ) != 0;
	}
	bool Manager::isNoParachuteEnabled(void) const
	{
		return ( SDL_WasInit(SDL_INIT_NOPARACHUTE) ) != 0;
	}
	bool Manager::isEventThreadEnabled(void) const
	{
		return ( SDL_WasInit(SDL_INIT_EVENTTHREAD) ) != 0;
	}

        Logger & operator << (Logger & log, const Manager & man)
        {
            log << nl << std::boolalpha << "Manager :" << nl <<
            "- Is Timer Enabled ? " << man.isTimerEnabled() << nl <<
            "- Is Audio Enabled ? " << man.isAudioEnabled() << nl <<
            "- Is Video Enabled ? " << man.isVideoEnabled() << nl <<
            "- Is CDROM Enabled ? " << man.isCdromEnabled() << nl <<
            "- Is Joystick Enabled ? " << man.isJoystickEnabled() << nl <<
            "- Is \"NoParachute\" Enabled ? " << man.isNoParachuteEnabled() << nl <<
            "- Is \"EventThread\" Enabled ? " << man.isEventThreadEnabled() ;
            return log;

        }
    }
}//namespace RAGE::SDL
<commit_msg>Solve a bug on win vista: Manager Constructor used SDL_INIT_EVENTTHREAD which should not be used on win system. Need to be tested by someone else though coz the bug is erratic.<commit_after>#include "SDLManager.hh"
#include "SDLConfig.hh"

namespace RAGE
{
    namespace SDL
    {

        Manager::Manager(bool video, bool audio, bool timer, bool cdrom, bool joystick, bool noparachute, bool eventthread) throw (std::logic_error)
        try
        {
#ifdef DEBUG
            Log << nl << "Manager::Manager() called ...";
#endif

            Uint32 flags;

            if (video)
                flags |= SDL_INIT_VIDEO;
            if (audio)
                flags |= SDL_INIT_AUDIO;
            if (timer)
                flags |= SDL_INIT_TIMER;
            if (cdrom)
                flags |= SDL_INIT_CDROM;
            if (joystick)
                flags |= SDL_INIT_JOYSTICK;
            if (noparachute)
                flags |= SDL_INIT_NOPARACHUTE;
//To Disable EventThread under Windows
//just a little usefull tip for mingw
#ifndef WIN32
            if (eventthread)
                flags |= SDL_INIT_EVENTTHREAD;
//not sure what to do with mingw32...
#endif

            if (SDL_Init(flags)<0)
            {
                //logs manager error with usefull information
                std::string errormsg("Unable to initialize SDL subsystems ");
                if ( (flags & SDL_INIT_TIMER) !=0 )
                    errormsg+= "TIMER " ;
                if ( (flags & SDL_INIT_AUDIO) != 0)
                    errormsg+= "AUDIO " ;
                if ( (flags & SDL_INIT_VIDEO) != 0)
                    errormsg+= "VIDEO " ;
                if ( (flags & SDL_INIT_CDROM) != 0)
                    errormsg+= "CDROM " ;
                if ( (flags & SDL_INIT_JOYSTICK) != 0)
                    errormsg+= "JOYSTICK " ;
                if ( (flags & SDL_INIT_NOPARACHUTE) != 0)
                    errormsg+= "NOPARACHUTE " ;
//To Disable EventThread under Windows
//just a little usefull tip for mingw
#ifndef WIN32
                if ( (flags & SDL_INIT_EVENTTHREAD) != 0)
                    errormsg+= "EVENTTHREAD " ;
				//not sure what to do with mingw32...
#endif
                Log << errormsg << ": " << GetError() ;
                throw std::logic_error("SDL_Init failed!");
            }
#ifdef DEBUG
            Log << nl << "Manager::Manager() done.";
#endif

        }
        catch (std::exception &e)
        {
            Log << nl << "Exception catched in Manager Constructor" << nl << e.what();
        }

Manager::~Manager()
        {
#ifdef DEBUG
            Log << nl << "Manager::~Manager() called ...";
#endif

            SDL_Quit();
#ifdef DEBUG
            Log << nl << "Manager::~Manager() done.";
#endif
        }

        bool Manager::enableTimer(void)
        {
            return SDL_InitSubSystem(SDL_INIT_TIMER) == 0;
        }
        bool Manager::enableAudio(void)
        {
            return SDL_InitSubSystem(SDL_INIT_AUDIO)== 0;
        }
        bool Manager::enableVideo(void)
        {
            return SDL_InitSubSystem(SDL_INIT_VIDEO)== 0;
        }
        bool Manager::enableCdrom(void)
        {
            return SDL_InitSubSystem(SDL_INIT_CDROM)== 0;
        }
        bool Manager::enableJoystick(void)
        {
            return SDL_InitSubSystem(SDL_INIT_JOYSTICK)== 0;
        }
        bool Manager::enableEverything(void)
        {
            return SDL_InitSubSystem(SDL_INIT_EVERYTHING)== 0;
        }
        bool Manager::enableNoParachute(void)
        {
            return SDL_InitSubSystem(SDL_INIT_NOPARACHUTE)== 0;
        }
        bool Manager::enableEventThread(void)
        {
            return SDL_InitSubSystem(SDL_INIT_EVENTTHREAD)== 0;
        }

        void Manager::disableTimer(void)
        {
            SDL_QuitSubSystem(SDL_INIT_TIMER);
        }
        void Manager::disableAudio(void)
        {
            SDL_QuitSubSystem(SDL_INIT_AUDIO);
        }
        void Manager::disableVideo(void)
        {
            SDL_QuitSubSystem(SDL_INIT_VIDEO);
        }
        void Manager::disableCdrom(void)
        {

            SDL_QuitSubSystem(SDL_INIT_CDROM);
        }
        void Manager::disableJoystick(void)
        {

            SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
        }
        void Manager::disableEverything(void)
        {

            SDL_QuitSubSystem(SDL_INIT_EVERYTHING);
        }
        void Manager::disableNoParachute(void)
        {

            SDL_QuitSubSystem(SDL_INIT_NOPARACHUTE);
        }
        void Manager::disableEventThread(void)
        {

            SDL_QuitSubSystem(SDL_INIT_EVENTTHREAD);
        }

	bool Manager::isTimerEnabled(void) const
	{
		return ( SDL_WasInit(SDL_INIT_TIMER) ) != 0;
	}
	bool Manager::isAudioEnabled(void) const
	{
		return ( SDL_WasInit(SDL_INIT_AUDIO) ) != 0;
	}
	bool Manager::isVideoEnabled(void) const
	{
		return ( SDL_WasInit(SDL_INIT_VIDEO) ) != 0;
	}
	bool Manager::isCdromEnabled(void) const
	{
		return ( SDL_WasInit(SDL_INIT_CDROM) ) != 0;
	}
	bool Manager::isJoystickEnabled(void) const
	{
		return ( SDL_WasInit(SDL_INIT_JOYSTICK) ) != 0;
	}
	bool Manager::isNoParachuteEnabled(void) const
	{
		return ( SDL_WasInit(SDL_INIT_NOPARACHUTE) ) != 0;
	}
	bool Manager::isEventThreadEnabled(void) const
	{
		return ( SDL_WasInit(SDL_INIT_EVENTTHREAD) ) != 0;
	}

        Logger & operator << (Logger & log, const Manager & man)
        {
            log << nl << std::boolalpha << "Manager :" << nl <<
            "- Is Timer Enabled ? " << man.isTimerEnabled() << nl <<
            "- Is Audio Enabled ? " << man.isAudioEnabled() << nl <<
            "- Is Video Enabled ? " << man.isVideoEnabled() << nl <<
            "- Is CDROM Enabled ? " << man.isCdromEnabled() << nl <<
            "- Is Joystick Enabled ? " << man.isJoystickEnabled() << nl <<
            "- Is \"NoParachute\" Enabled ? " << man.isNoParachuteEnabled() << nl <<
            "- Is \"EventThread\" Enabled ? " << man.isEventThreadEnabled() ;
            return log;

        }
    }
}//namespace RAGE::SDL
<|endoftext|>


<commit_before>/*//////////////////////////////////////////////////////////////////
////       SKIRT -- an advanced radiative transfer code         ////
////       © Astronomical Observatory, Ghent University         ////
///////////////////////////////////////////////////////////////// */

#include <QDateTime>
#include <QMutex>
#include "FatalError.hpp"
#include "FITSInOut.hpp"
#include "fitsio.h"

using namespace std;

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

namespace
{
    // mutex to guard the FITS input/output operations
    QMutex _mutex;

    // function to report cfitsio errors
    void report_error(QString filepath, QString action, int status)
    {
        char message[FLEN_STATUS];
        ffgerr(status, message);
        throw FATALERROR("Error while " + action + " FITS file " + filepath + "\n" + QString(message));
    }
}

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

void FITSInOut::write(QString filepath, const Array& data, int nx, int ny, int nz,
                    double incx, double incy, QString dataUnits, QString xyUnits)
{
    // verify the data size
    int nelements = data.size();
    if (nelements != nx*ny*nz)
        throw FATALERROR("Inconsistent data size when creating FITS file " + filepath);
    long naxes[3] = {nx, ny, nz};

    // acquire a global lock since the cfitsio library is not guaranteed to be reentrant
    // (only when it is built with ./configure --enable-reentrant; make)
    QMutexLocker lock(&_mutex);

    // time stamp and temporaries
    std::string stamp = QDateTime::currentDateTime().toUTC().toString("yyyy-MM-ddThh:mm:ss").toStdString();
    std::string localpath = filepath.toLocal8Bit().constData();
    std::string dataunits = dataUnits.toStdString();
    std::string xyunits = xyUnits.toStdString();
    double zero = 0.;
    double one = 1.;
    double xref = (nx+1.0)/2.0;
    double yref = (ny+1.0)/2.0;

    // remove any existing file with the same name
    remove(localpath.c_str());

    // create the fits file
    int status = 0;
    fitsfile *fptr;
    ffdkinit(&fptr, localpath.c_str(), &status);
    if (status) report_error(filepath, "creating", status);

    // create the primary image (32-bit floating point pixels)
    ffcrim(fptr, FLOAT_IMG, (nz==1 ? 2 : 3), naxes, &status);
    if (status) report_error(filepath, "creating", status);

    // add the relevant keywords
    ffpky(fptr, TDOUBLE, "BSCALE", &one, "", &status);
    ffpky(fptr, TDOUBLE, "BZERO", &zero, "", &status);
    ffpkys(fptr, "DATE"  , const_cast<char*>(stamp.c_str()), "Date and time of creation (UTC)", &status);
    ffpkys(fptr, "ORIGIN", const_cast<char*>("SKIRT simulation"), "Astronomical Observatory, Ghent University", &status);
    ffpkys(fptr, "BUNIT" , const_cast<char*>(dataunits.c_str()), "Physical unit of the array values", &status);
    ffpky(fptr, TDOUBLE, "CRPIX1", &xref, "X-axis coordinate system reference pixel", &status);
    ffpky(fptr, TDOUBLE, "CRVAL1", &zero, "Coordinate system value at X-axis reference pixel", &status);
    ffpky(fptr, TDOUBLE, "CDELT1", &incx, "Coordinate increment along X-axis", &status);
    ffpkys(fptr, "CTYPE1", const_cast<char*>(xyunits.c_str()), "Physical units of the X-axis increment", &status);
    ffpky(fptr, TDOUBLE, "CRPIX2", &yref, "Y-axis coordinate system reference pixel", &status);
    ffpky(fptr, TDOUBLE, "CRVAL2", &zero, "Coordinate system value at Y-axis reference pixel", &status);
    ffpky(fptr, TDOUBLE, "CDELT2", &incy, "Coordinate increment along Y-axis", &status);
    ffpkys(fptr, "CTYPE2", const_cast<char*>(xyunits.c_str()), "Physical units of the Y-axis increment", &status);
    if (status) report_error(filepath, "writing", status);

    // write the array of pixels to the image
    ffpprd(fptr, 0, 1, nelements, const_cast<double*>(&data[0]), &status);
    if (status) report_error(filepath, "writing", status);

    // close the file
    ffclos(fptr, &status);
    if (status) report_error(filepath, "writing", status);
}

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

void FITSInOut::read(QString filepath, Array& data, int& nx, int& ny, int& nz)
{
    // acquire a global lock since the cfitsio library is not guaranteed to be reentrant
    QMutexLocker lock(&_mutex);

    // open the fits file
    int status = 0;
    fitsfile *fptr;
    ffdkopn(&fptr, filepath.toLocal8Bit().constData(), READONLY, &status);
    if (status) report_error(filepath, "opening", status);

    // get the dimensions of the primary image
    int naxis;
    long naxes[3];
    ffgidm(fptr, &naxis, &status);
    ffgisz(fptr, 3, naxes, &status);
    if (status) report_error(filepath, "reading", status);
    nx = naxis > 0 ? naxes[0] : 1;
    ny = naxis > 1 ? naxes[1] : 1;
    nz = naxis > 2 ? naxes[2] : 1;

    // resize the data container
    int nelements = nx*ny*nz;
    data.resize(nelements);

    // read the array of pixels from the image
    int dummy;
    ffgpvd(fptr, 0, 1, nelements, 0, &data[0], &dummy, &status);
    if (status) report_error(filepath, "reading", status);

    // close the file
    ffclos(fptr, &status);
    if (status) report_error(filepath, "reading", status);
}

////////////////////////////////////////////////////////////////////
<commit_msg>fix problem with writing FITS files larger than 16GB<commit_after>/*//////////////////////////////////////////////////////////////////
////       SKIRT -- an advanced radiative transfer code         ////
////       © Astronomical Observatory, Ghent University         ////
///////////////////////////////////////////////////////////////// */

#include <QDateTime>
#include <QMutex>
#include "FatalError.hpp"
#include "FITSInOut.hpp"
#include "fitsio.h"

using namespace std;

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

namespace
{
    // mutex to guard the FITS input/output operations
    QMutex _mutex;

    // function to report cfitsio errors
    void report_error(QString filepath, QString action, int status)
    {
        char message[FLEN_STATUS];
        ffgerr(status, message);
        throw FATALERROR("Error while " + action + " FITS file " + filepath + "\n" + QString(message));
    }
}

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

void FITSInOut::write(QString filepath, const Array& data, int nx, int ny, int nz,
                    double incx, double incy, QString dataUnits, QString xyUnits)
{
    // verify the data size
    size_t nelements = data.size();
    if (nelements != static_cast<size_t>(nx)*static_cast<size_t>(ny)*static_cast<size_t>(nz))
        throw FATALERROR("Inconsistent data size when creating FITS file " + filepath);
    long naxes[3] = {nx, ny, nz};

    // acquire a global lock since the cfitsio library is not guaranteed to be reentrant
    // (only when it is built with ./configure --enable-reentrant; make)
    QMutexLocker lock(&_mutex);

    // time stamp and temporaries
    std::string stamp = QDateTime::currentDateTime().toUTC().toString("yyyy-MM-ddThh:mm:ss").toStdString();
    std::string localpath = filepath.toLocal8Bit().constData();
    std::string dataunits = dataUnits.toStdString();
    std::string xyunits = xyUnits.toStdString();
    double zero = 0.;
    double one = 1.;
    double xref = (nx+1.0)/2.0;
    double yref = (ny+1.0)/2.0;

    // remove any existing file with the same name
    remove(localpath.c_str());

    // create the fits file
    int status = 0;
    fitsfile *fptr;
    ffdkinit(&fptr, localpath.c_str(), &status);
    if (status) report_error(filepath, "creating", status);

    // create the primary image (32-bit floating point pixels)
    ffcrim(fptr, FLOAT_IMG, (nz==1 ? 2 : 3), naxes, &status);
    if (status) report_error(filepath, "creating", status);

    // add the relevant keywords
    ffpky(fptr, TDOUBLE, "BSCALE", &one, "", &status);
    ffpky(fptr, TDOUBLE, "BZERO", &zero, "", &status);
    ffpkys(fptr, "DATE"  , const_cast<char*>(stamp.c_str()), "Date and time of creation (UTC)", &status);
    ffpkys(fptr, "ORIGIN", const_cast<char*>("SKIRT simulation"), "Astronomical Observatory, Ghent University", &status);
    ffpkys(fptr, "BUNIT" , const_cast<char*>(dataunits.c_str()), "Physical unit of the array values", &status);
    ffpky(fptr, TDOUBLE, "CRPIX1", &xref, "X-axis coordinate system reference pixel", &status);
    ffpky(fptr, TDOUBLE, "CRVAL1", &zero, "Coordinate system value at X-axis reference pixel", &status);
    ffpky(fptr, TDOUBLE, "CDELT1", &incx, "Coordinate increment along X-axis", &status);
    ffpkys(fptr, "CTYPE1", const_cast<char*>(xyunits.c_str()), "Physical units of the X-axis increment", &status);
    ffpky(fptr, TDOUBLE, "CRPIX2", &yref, "Y-axis coordinate system reference pixel", &status);
    ffpky(fptr, TDOUBLE, "CRVAL2", &zero, "Coordinate system value at Y-axis reference pixel", &status);
    ffpky(fptr, TDOUBLE, "CDELT2", &incy, "Coordinate increment along Y-axis", &status);
    ffpkys(fptr, "CTYPE2", const_cast<char*>(xyunits.c_str()), "Physical units of the Y-axis increment", &status);
    if (status) report_error(filepath, "writing", status);

    // write the array of pixels to the image
    ffpprd(fptr, 0, 1, nelements, const_cast<double*>(&data[0]), &status);
    if (status) report_error(filepath, "writing", status);

    // close the file
    ffclos(fptr, &status);
    if (status) report_error(filepath, "writing", status);
}

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

void FITSInOut::read(QString filepath, Array& data, int& nx, int& ny, int& nz)
{
    // acquire a global lock since the cfitsio library is not guaranteed to be reentrant
    QMutexLocker lock(&_mutex);

    // open the fits file
    int status = 0;
    fitsfile *fptr;
    ffdkopn(&fptr, filepath.toLocal8Bit().constData(), READONLY, &status);
    if (status) report_error(filepath, "opening", status);

    // get the dimensions of the primary image
    int naxis;
    long naxes[3];
    ffgidm(fptr, &naxis, &status);
    ffgisz(fptr, 3, naxes, &status);
    if (status) report_error(filepath, "reading", status);
    nx = naxis > 0 ? naxes[0] : 1;
    ny = naxis > 1 ? naxes[1] : 1;
    nz = naxis > 2 ? naxes[2] : 1;

    // resize the data container
    size_t nelements = static_cast<size_t>(nx)*static_cast<size_t>(ny)*static_cast<size_t>(nz);
    data.resize(nelements);

    // read the array of pixels from the image
    int dummy;
    ffgpvd(fptr, 0, 1, nelements, 0, &data[0], &dummy, &status);
    if (status) report_error(filepath, "reading", status);

    // close the file
    ffclos(fptr, &status);
    if (status) report_error(filepath, "reading", status);
}

////////////////////////////////////////////////////////////////////
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-2007, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

//-------------------------------------------------------------------------
//     AOD cluster base class
//     Author: Markus Oldenburg, CERN
//-------------------------------------------------------------------------

#include "AliAODCluster.h"

ClassImp(AliAODCluster)

//______________________________________________________________________________
AliAODCluster::AliAODCluster() :
  AliVCluster(),
  fEnergy(0),
  fChi2(-999.),
  fID(-999),
  fNLabel(0),
  fLabel(0x0),
  fFilterMap(0),
  fType(kUndef)
{
  // default constructor

  SetPosition(NULL);
  SetPID(NULL);
}

//______________________________________________________________________________
AliAODCluster::AliAODCluster(Int_t id,
			     UInt_t nLabel,
			     Int_t *label,
			     Double_t energy,
			     Double_t x[3],
			     Double_t pid[13],
			     Char_t ttype,
			     UInt_t selectInfo) :
  AliVCluster(),
  fEnergy(energy),
  fChi2(-999.),
  fID(id),
  fNLabel(0),
  fLabel(0x0),
  fFilterMap(selectInfo),
  fType(ttype)
{
  // constructor
  for (Int_t i = 0; i <  3; i++) fPosition[i] = 0.;
  for (Int_t i = 0; i < 13; i++) fPID[i]      = 0;

  if(x)   {for (Int_t i = 0; i < 3  ; i++) SetPositionAt(x[i]  ,i);}
  if(pid) {for (Int_t i = 0; i < 13 ; i++) SetPIDAt     (pid[i],i);}
  SetLabel(label, nLabel);
}

//______________________________________________________________________________
AliAODCluster::AliAODCluster(Int_t id,
			     UInt_t nLabel,
			     Int_t *label,
			     Float_t energy,
			     Float_t x[3],
			     Float_t pid[13],
			     Char_t ttype,
			     UInt_t selectInfo) :
  AliVCluster(),
  fEnergy(energy),
  fChi2(-999.),
  fID(id),
  fNLabel(0),
  fLabel(0x0),
  fFilterMap(selectInfo),
  fType(ttype)
{
  // constructor
  for (Int_t i = 0; i <  3; i++) fPosition[i] = 0.;
  for (Int_t i = 0; i < 13; i++) fPID[i]      = 0;

  if(x)   {for (Int_t i = 0; i < 3  ; i++) SetPositionAt(x[i]  ,i);}
  if(pid) {for (Int_t i = 0; i < 13 ; i++) SetPIDAt     (pid[i],i);}
  SetLabel(label, nLabel);
}

//______________________________________________________________________________
AliAODCluster::~AliAODCluster()
{
  // destructor

  RemoveLabel();
}

//______________________________________________________________________________
void AliAODCluster::Clear(const Option_t*)
{
  // Clear

  RemoveLabel();
}

//______________________________________________________________________________
AliAODCluster::AliAODCluster(const AliAODCluster& clus) :
  AliVCluster(clus),
  fEnergy(clus.fEnergy),
  fChi2(clus.fChi2),
  fID(clus.fID),
  fNLabel(0),
  fLabel(0x0),
  fFilterMap(clus.fFilterMap),
  fType(clus.fType)
{
  // Copy constructor

  if(fPosition) {for(Int_t i = 0; i < 3  ; i++) fPosition[i] = clus.fPosition[i];}
  for(Int_t i = 0; i < 13 ; i++) fPID[i]      = clus.fPID[i];

  SetLabel(clus.fLabel, clus.fNLabel);
}

//______________________________________________________________________________
AliAODCluster& AliAODCluster::operator=(const AliAODCluster& clus)
{
  // Assignment operator
  if(this!=&clus) {

	if(fPosition) {for(Int_t i = 0; i < 3 ;  i++) fPosition[i] = clus.fPosition[i];}
	for(Int_t i = 0; i < 13 ; i++) fPID[i]      = clus.fPID[i];

    fEnergy = clus.fEnergy;
    fChi2 = clus.fChi2;

    fID = clus.fID;
    SetLabel(clus.fLabel, clus.fNLabel);
    fFilterMap = clus.fFilterMap;

    fType = clus.fType;
  }

  return *this;
}

//______________________________________________________________________________
void AliAODCluster::SetPosition(Float_t *x)
{
  // set the position

  if (x) {
    fPosition[0] = x[0];
    fPosition[1] = x[1];
    fPosition[2] = x[2];
  } else {
    fPosition[0] = -999.;
    fPosition[1] = -999.;
    fPosition[2] = -999.;
  }
}

//______________________________________________________________________________
UShort_t AliAODCluster::GetMostProbablePID() const
{
  // Returns the most probable PID array element.

  Int_t nPID = 13;
  UShort_t unknown = AliVCluster::kUnknown;

  UShort_t loc = unknown;
  Double_t max = 0.;
  Bool_t allTheSame = kTRUE;

  for (Int_t iPID = 0; iPID < nPID; iPID++) {
    if (fPID[iPID] >= max) {
      if (fPID[iPID] > max) {
	allTheSame = kFALSE;
	max = fPID[iPID];
	loc = (UShort_t)iPID;
      } else {
	allTheSame = kTRUE;
      }
    }
  }
  return allTheSame ? unknown : loc;
}

//______________________________________________________________________________
void AliAODCluster::SetLabel(Int_t *label, UInt_t size)
{
  if (label && size>0) {
    if (size != (UInt_t)fNLabel) {
      RemoveLabel();
      fNLabel = size;
      fLabel = new Int_t[fNLabel];
    }

    for (Int_t i = 0; i < fNLabel; i++) {
      fLabel[i] = label[i];
    }
  } else {
    RemoveLabel();
  }

  return;
}

//______________________________________________________________________________
Int_t AliAODCluster::GetLabelAt(UInt_t i) const
{
  if (fLabel && i < (UInt_t)fNLabel) {
    return fLabel[i];
  } else {
    return -999;
  }
}

//______________________________________________________________________________
void AliAODCluster::RemoveLabel()
{
  delete[] fLabel;
  fLabel = 0x0;
  fNLabel = 0;

  return;
}

//______________________________________________________________________________
void AliAODCluster::Print(Option_t* /* option */) const
{
  // prints information about AliAODCluster

  printf("Cluster type: %d\n", GetType());
  printf("     energy = %f\n", E());
  printf("       chi2 = %f\n", Chi2());
  const Double_t *pid = GetPID();
  printf("PID weights: photon %0.2f, pi0 %0.2f, electron %0.2f, conversion electron %0.2f\n, hadrons: pion %0.2f, kaon %0.2f, proton %0.2f , neutron %0.2f, kaon %0.2f \n",
	 pid[AliVCluster::kPhoton],   pid[AliVCluster::kPi0],
	 pid[AliVCluster::kElectron], pid[AliVCluster::kEleCon],
	 pid[AliVCluster::kPion],     pid[AliVCluster::kKaon],   pid[AliVCluster::kProton],
	 pid[AliVCluster::kNeutron],  pid[AliVCluster::kKaon0]);
}
<commit_msg>Coverity fix.<commit_after>/**************************************************************************
 * Copyright(c) 1998-2007, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

//-------------------------------------------------------------------------
//     AOD cluster base class
//     Author: Markus Oldenburg, CERN
//-------------------------------------------------------------------------

#include "AliAODCluster.h"

ClassImp(AliAODCluster)

//______________________________________________________________________________
AliAODCluster::AliAODCluster() :
  AliVCluster(),
  fEnergy(0),
  fChi2(-999.),
  fID(-999),
  fNLabel(0),
  fLabel(0x0),
  fFilterMap(0),
  fType(kUndef)
{
  // default constructor

  SetPosition(NULL);
  SetPID(NULL);
}

//______________________________________________________________________________
AliAODCluster::AliAODCluster(Int_t id,
			     UInt_t nLabel,
			     Int_t *label,
			     Double_t energy,
			     Double_t x[3],
			     Double_t pid[13],
			     Char_t ttype,
			     UInt_t selectInfo) :
  AliVCluster(),
  fEnergy(energy),
  fChi2(-999.),
  fID(id),
  fNLabel(0),
  fLabel(0x0),
  fFilterMap(selectInfo),
  fType(ttype)
{
  // constructor
  for (Int_t i = 0; i <  3; i++) fPosition[i] = 0.;
  for (Int_t i = 0; i < 13; i++) fPID[i]      = 0;

  if(x)   {for (Int_t i = 0; i < 3  ; i++) SetPositionAt(x[i]  ,i);}
  if(pid) {for (Int_t i = 0; i < 13 ; i++) SetPIDAt     (pid[i],i);}
  SetLabel(label, nLabel);
}

//______________________________________________________________________________
AliAODCluster::AliAODCluster(Int_t id,
			     UInt_t nLabel,
			     Int_t *label,
			     Float_t energy,
			     Float_t x[3],
			     Float_t pid[13],
			     Char_t ttype,
			     UInt_t selectInfo) :
  AliVCluster(),
  fEnergy(energy),
  fChi2(-999.),
  fID(id),
  fNLabel(0),
  fLabel(0x0),
  fFilterMap(selectInfo),
  fType(ttype)
{
  // constructor
  for (Int_t i = 0; i <  3; i++) fPosition[i] = 0.;
  for (Int_t i = 0; i < 13; i++) fPID[i]      = 0;

  if(x)   {for (Int_t i = 0; i < 3  ; i++) SetPositionAt(x[i]  ,i);}
  if(pid) {for (Int_t i = 0; i < 13 ; i++) SetPIDAt     (pid[i],i);}
  SetLabel(label, nLabel);
}

//______________________________________________________________________________
AliAODCluster::~AliAODCluster()
{
  // destructor

  RemoveLabel();
}

//______________________________________________________________________________
void AliAODCluster::Clear(const Option_t*)
{
  // Clear

  RemoveLabel();
}

//______________________________________________________________________________
AliAODCluster::AliAODCluster(const AliAODCluster& clus) :
  AliVCluster(clus),
  fEnergy(clus.fEnergy),
  fChi2(clus.fChi2),
  fID(clus.fID),
  fNLabel(0),
  fLabel(0x0),
  fFilterMap(clus.fFilterMap),
  fType(clus.fType)
{
  // Copy constructor

  for(Int_t i = 0; i < 3  ; i++) fPosition[i]  = clus.fPosition[i];
  for(Int_t i = 0; i < 13 ; i++)  fPID[i]      = clus.fPID[i];

  SetLabel(clus.fLabel, clus.fNLabel);
}

//______________________________________________________________________________
AliAODCluster& AliAODCluster::operator=(const AliAODCluster& clus)
{
  // Assignment operator
  if(this!=&clus) {

	for(Int_t i = 0; i < 3 ;  i++) fPosition[i] = clus.fPosition[i];
	for(Int_t i = 0; i < 13 ; i++) fPID[i]      = clus.fPID[i];

    fEnergy = clus.fEnergy;
    fChi2 = clus.fChi2;

    fID = clus.fID;
    SetLabel(clus.fLabel, clus.fNLabel);
    fFilterMap = clus.fFilterMap;

    fType = clus.fType;
  }

  return *this;
}

//______________________________________________________________________________
void AliAODCluster::SetPosition(Float_t *x)
{
  // set the position

  if (x) {
    fPosition[0] = x[0];
    fPosition[1] = x[1];
    fPosition[2] = x[2];
  } else {
    fPosition[0] = -999.;
    fPosition[1] = -999.;
    fPosition[2] = -999.;
  }
}

//______________________________________________________________________________
UShort_t AliAODCluster::GetMostProbablePID() const
{
  // Returns the most probable PID array element.

  Int_t nPID = 13;
  UShort_t unknown = AliVCluster::kUnknown;

  UShort_t loc = unknown;
  Double_t max = 0.;
  Bool_t allTheSame = kTRUE;

  for (Int_t iPID = 0; iPID < nPID; iPID++) {
    if (fPID[iPID] >= max) {
      if (fPID[iPID] > max) {
	allTheSame = kFALSE;
	max = fPID[iPID];
	loc = (UShort_t)iPID;
      } else {
	allTheSame = kTRUE;
      }
    }
  }
  return allTheSame ? unknown : loc;
}

//______________________________________________________________________________
void AliAODCluster::SetLabel(Int_t *label, UInt_t size)
{
  if (label && size>0) {
    if (size != (UInt_t)fNLabel) {
      RemoveLabel();
      fNLabel = size;
      fLabel = new Int_t[fNLabel];
    }

    for (Int_t i = 0; i < fNLabel; i++) {
      fLabel[i] = label[i];
    }
  } else {
    RemoveLabel();
  }

  return;
}

//______________________________________________________________________________
Int_t AliAODCluster::GetLabelAt(UInt_t i) const
{
  if (fLabel && i < (UInt_t)fNLabel) {
    return fLabel[i];
  } else {
    return -999;
  }
}

//______________________________________________________________________________
void AliAODCluster::RemoveLabel()
{
  delete[] fLabel;
  fLabel = 0x0;
  fNLabel = 0;

  return;
}

//______________________________________________________________________________
void AliAODCluster::Print(Option_t* /* option */) const
{
  // prints information about AliAODCluster

  printf("Cluster type: %d\n", GetType());
  printf("     energy = %f\n", E());
  printf("       chi2 = %f\n", Chi2());
  const Double_t *pid = GetPID();
  printf("PID weights: photon %0.2f, pi0 %0.2f, electron %0.2f, conversion electron %0.2f\n, hadrons: pion %0.2f, kaon %0.2f, proton %0.2f , neutron %0.2f, kaon %0.2f \n",
	 pid[AliVCluster::kPhoton],   pid[AliVCluster::kPi0],
	 pid[AliVCluster::kElectron], pid[AliVCluster::kEleCon],
	 pid[AliVCluster::kPion],     pid[AliVCluster::kKaon],   pid[AliVCluster::kProton],
	 pid[AliVCluster::kNeutron],  pid[AliVCluster::kKaon0]);
}
<|endoftext|>


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

// CLASS HEADER
#include <style-monitor.h>

// INTERNAL INCLUDES
#include <style-monitor-impl.h>

namespace Dali
{

StyleMonitor::StyleMonitor()
{
}

StyleMonitor::StyleMonitor(const StyleMonitor& monitor)
: BaseHandle(monitor)
{
}

StyleMonitor StyleMonitor::StyleMonitor::Get()
{
  return Internal::Adaptor::StyleMonitor::Get();
}

StyleMonitor::~StyleMonitor()
{
}

StyleMonitor StyleMonitor::DownCast( BaseHandle handle )
{
  return StyleMonitor( dynamic_cast<Internal::Adaptor::StyleMonitor*>( handle.GetObjectPtr() ) );
}

std::string StyleMonitor::GetDefaultFontFamily() const
{
  return GetImplementation(*this).GetDefaultFontFamily();
}

int StyleMonitor::GetDefaultFontSize() const
{
  return GetImplementation(*this).GetDefaultFontSize();
}

const std::string& StyleMonitor::GetTheme() const
{
  return GetImplementation(*this).GetTheme();
}

void StyleMonitor::SetTheme(const std::string& themFilePath)
{
  return GetImplementation(*this).SetTheme(themFilePath);
}

bool StyleMonitor::LoadThemeFile( const std::string& filename, std::string& output )
{
  return GetImplementation(*this).LoadThemeFile( filename, output );
}

StyleMonitor::StyleChangeSignalType& StyleMonitor::StyleChangeSignal()
{
  return GetImplementation(*this).StyleChangeSignal();
}

StyleMonitor& StyleMonitor::operator=(const StyleMonitor& monitor)
{
  if( *this != monitor )
  {
    BaseHandle::operator=(monitor);
  }
  return *this;
}

StyleMonitor::StyleMonitor(Internal::Adaptor::StyleMonitor* internal)
: BaseHandle(internal)
{
}

} // namespace Dali
<commit_msg>Add missing StyleMonitor::GetDefaultFontStyle().<commit_after>/*
 * Copyright (c) 2015 Samsung Electronics Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

// CLASS HEADER
#include <style-monitor.h>

// INTERNAL INCLUDES
#include <style-monitor-impl.h>

namespace Dali
{

StyleMonitor::StyleMonitor()
{
}

StyleMonitor::StyleMonitor(const StyleMonitor& monitor)
: BaseHandle(monitor)
{
}

StyleMonitor StyleMonitor::StyleMonitor::Get()
{
  return Internal::Adaptor::StyleMonitor::Get();
}

StyleMonitor::~StyleMonitor()
{
}

StyleMonitor StyleMonitor::DownCast( BaseHandle handle )
{
  return StyleMonitor( dynamic_cast<Internal::Adaptor::StyleMonitor*>( handle.GetObjectPtr() ) );
}

std::string StyleMonitor::GetDefaultFontFamily() const
{
  return GetImplementation(*this).GetDefaultFontFamily();
}

std::string StyleMonitor::GetDefaultFontStyle() const
{
  return GetImplementation(*this).GetDefaultFontStyle();
}

int StyleMonitor::GetDefaultFontSize() const
{
  return GetImplementation(*this).GetDefaultFontSize();
}

const std::string& StyleMonitor::GetTheme() const
{
  return GetImplementation(*this).GetTheme();
}

void StyleMonitor::SetTheme(const std::string& themFilePath)
{
  return GetImplementation(*this).SetTheme(themFilePath);
}

bool StyleMonitor::LoadThemeFile( const std::string& filename, std::string& output )
{
  return GetImplementation(*this).LoadThemeFile( filename, output );
}

StyleMonitor::StyleChangeSignalType& StyleMonitor::StyleChangeSignal()
{
  return GetImplementation(*this).StyleChangeSignal();
}

StyleMonitor& StyleMonitor::operator=(const StyleMonitor& monitor)
{
  if( *this != monitor )
  {
    BaseHandle::operator=(monitor);
  }
  return *this;
}

StyleMonitor::StyleMonitor(Internal::Adaptor::StyleMonitor* internal)
: BaseHandle(internal)
{
}

} // namespace Dali
<|endoftext|>