<commit_before>// Copyright 2015-2017 Joy Machine, LLC. All rights reserved.

#include "steelhunters.h"

#include "ObjectPool.h"

#include "DateTime.h"

#include "IPooledObject.h"

// Console variable definition.
static TAutoConsoleVariable< int > CVarDebugObjectPooling( TEXT( "joy.DebugObjectPooling" ),
	0,
	TEXT( "Verbose output from the object pooling system for debugging." ),
	ECVF_Default );

// Static class definitions.
const int64 UObjectPool::kDefaultPruneStaleSeconds = 60;

uint32 UObjectPool::IDCounter = 0;
uint32 UObjectPool::PoolCount = 0;

//----------------------------------------------------------------------------------------------------
UObjectPool::UObjectPool( const class FObjectInitializer& ObjectInitializer )
: Name( *FString::Printf( TEXT( "Pool-%d" ), PoolCount ) )
, PoolID( PoolCount )
, PoolSizeOptimal( 256 )
, PoolSizeMaximum( 2048 )
, PruneStale( false )
, PruneLastTimestamp( FDateTime::Now( ).ToUnixTimestamp( ) )
, PruneStale_Seconds( kDefaultPruneStaleSeconds )
{
	Pool.Empty( );

	// Set this pool ID.
	PoolID = ++PoolCount;

	{
		const bool debug = CVarDebugObjectPooling.GetValueOnGameThread( );
		if( debug )
		{
			// Just toss out some debug information.
			UE_LOG( SteelHuntersLog, Log, TEXT( "[UObjectPool] Creating new pool (Pool Count: %d)." ), PoolCount );
		}
	}
}

//----------------------------------------------------------------------------------------------------
void UObjectPool::OnObjectReturn( IPooledObject* pObject )
{
	check( pObject != nullptr );

	// Reset the object (pure virtual method, so the logic is reliant on the child class).
	pObject->IsActive = false;
	pObject->Reset( );
}

//----------------------------------------------------------------------------------------------------
void UObjectPool::Prune( )
{
	const int64 currentTime = FDateTime::Now( ).ToUnixTimestamp( );
	int32 prunedObjectCount = Pool.RemoveAll( [&]( TWeakObjectPtr< UObject > pObject ) {
		if( !pObject.IsStale( ) && pObject.IsValid( ) )
		{
			// The object pointer is either stale or no longer valid.
			return false;
		}

		IPooledObject* pPooledObject = dynamic_cast< IPooledObject* >( pObject.Get( ) );
		if( !pPooledObject->GetIsActive( ) && !pPooledObject->Check( ) || ( PruneStale && ( ( currentTime - pPooledObject->LastActiveTimestamp ) > PruneStale_Seconds ) ) )
		{
			// This object is invalid or stale. Remove it.
			if( pPooledObject != nullptr )
			{
				// Just in case any logic in ::Deactivate is necessary, execute that, and then the ::Destroy method.
				pPooledObject->ReturnToPool.Unbind( );

				pPooledObject->DestroyInstance( );
				pPooledObject = nullptr;
			}

			return true;
		}

		return false;
	} );

	{
		const bool debug = CVarDebugObjectPooling.GetValueOnGameThread( );
		if( debug )
		{
			// Log the number of pruned objects.
			UE_LOG( SteelHuntersLog, Log, TEXT( "[UObjectPool] Pool pruning logic completed (Pool: %s, Object Count: %d, Pruned Count: %d." ), *Name.ToString( ), Pool.Num( ), prunedObjectCount );
		}
	}

	PruneLastTimestamp = currentTime;
}

//----------------------------------------------------------------------------------------------------
void UObjectPool::SetName( const FName& PoolName )
{
	// Just set the pool name; doesn't have to be unique.
	Name = GenerateName( PoolName );
}

//----------------------------------------------------------------------------------------------------
FName UObjectPool::GenerateName( const FName& BaseName )
{
	return( *FString::Printf( TEXT( "%s-%d" ), *BaseName.ToString( ), PoolCount ) );
}

//----------------------------------------------------------------------------------------------------
void UObjectPool::Empty( bool SeparateActiveInstances )
{
	const bool debug = CVarDebugObjectPooling.GetValueOnGameThread( );

	// Remove all objects from the pool and destroy them (unless SeparateActiveInstances is true, in which case leave them alone for now).
	int32 destroyedObjectCount = Pool.RemoveAll( [&]( TWeakObjectPtr< UObject > pObject ) {
		IPooledObject* pPooledObject = dynamic_cast< IPooledObject* >( pObject.Get( ) );
		if( !( SeparateActiveInstances && ( pPooledObject != nullptr ) && pPooledObject->GetIsActive( ) ) )
		{
			// Just in case any logic in ::Deactivate is necessary, execute that, and then the ::Destroy method.
			pPooledObject->ReturnToPool.Unbind( );

			pPooledObject->DestroyInstance( );
			pPooledObject = nullptr;
			return true;
		}

		return false;
	} );

	if( !SeparateActiveInstances )
	{
		if( debug )
		{
			// Log the object destroyed count and the destruction of the pool.
			UE_LOG( SteelHuntersLog, Log, TEXT( "[UObjectPool] Pool destroy completed (Pool: %s, Destroyed Object Count: %d)." ), *Name.ToString( ), destroyedObjectCount );
		}

		return;
	}

	// Now handle the separation of objects.
	int32 separatedObjectCount = Pool.RemoveAll( [&]( TWeakObjectPtr< UObject > pObject ) {
		IPooledObject* pPooledObject = dynamic_cast< IPooledObject* >( pObject.Get( ) );
		pPooledObject->ReturnToPool.Unbind( );

		pPooledObject->OnPoolRemovalWhileActive( );
		return true;
	} );

	if( debug )
	{
		// Log the object destroyed count and the destruction of the pool.
		UE_LOG( SteelHuntersLog, Log, TEXT( "[UObjectPool] Pool destroy completed with object separation (Pool: %s, Separated Object Count: %d, Destroyed Object Count: %d)." ), *Name.ToString( ), separatedObjectCount, destroyedObjectCount );
	}

#if !UE_BUILD_SHIPPING
	ensure( Pool.Num( ) == 0 );
#endif	// !UE_BUILD_SHIPPING.
}

//----------------------------------------------------------------------------------------------------
bool UObjectPool::Add( IPooledObject* ObjectIn, bool Active )
{
	check( ObjectIn != nullptr );

	// Check to ensure that IPooledObject is a derivative of UObject.
	UObject* pUObject = dynamic_cast< UObject* >( ObjectIn );

#if !UE_BUILD_SHIPPING
	ensure( IsValid( pUObject ) );
#endif	// !UE_BUILD_SHIPPING.

	// Predicate to check if this object is already in the pool.
	const uint32 objectID = ObjectIn->ID;
	if( Pool.ContainsByPredicate( [objectID]( TWeakObjectPtr< UObject > pObject ) {
		IPooledObject* pPooledObject = dynamic_cast< IPooledObject* >( pObject.Get( ) );
		return( objectID == pPooledObject->ID );
	} ) )
	{
		// Object is already in the pool.
		return false;
	}

	// Add this object to the pool.
	Pool.Add( pUObject );

	// Set whether or not the object is active (if being added, it usually is), and give it an ID.
	ObjectIn->IsActive = Active;
	ObjectIn->ID = IDCounter++;

	// Setup the object's pool return delegate (executed when the object is deactivated).
	ObjectIn->ReturnToPool.BindUObject( this, &UObjectPool::OnObjectReturn );

	{
		const bool debug = CVarDebugObjectPooling.GetValueOnGameThread( );
		if( debug )
		{
			// Debug logging.
			UE_LOG( SteelHuntersLog, Log, TEXT( "[UObjectPool] Adding object to pool (Pool: %s, Object Count: %d)." ), *Name.ToString( ), Pool.Num( ) );
		}
	}

	return true;
}

//----------------------------------------------------------------------------------------------------
template< typename T >
T* UObjectPool::GetPooledObject( )
{
	IPooledObject* pPooledObject = GetPooledObject( );
	if( pPooledObject == nullptr )
	{
		// No valid pooled objects.
		return nullptr;
	}

	T* pTemplateObject = Cast< T >( pPooledObject );
	check( IsValid( pTemplateObject ) );

	return pTemplateObject;
}

//----------------------------------------------------------------------------------------------------
IPooledObject* UObjectPool::GetPooledObject( )
{
	const int64 currentTime = FDateTime::Now( ).ToUnixTimestamp( );
	bool executePrune = PruneStale && ( ( currentTime - PruneLastTimestamp ) > PruneStale_Seconds );		// If this isn't true, then it may be time to prune anyway if the search finds an invalid object.

	// Find the first inactive and valid object.
	int32 idx = Pool.IndexOfByPredicate( [&]( TWeakObjectPtr< UObject > pObject ) {
		IPooledObject* pPooledObject = dynamic_cast< IPooledObject* >( pObject.Get( ) );
		if( !pPooledObject->GetIsActive( ) )
		{
			if( !pPooledObject->Check( ) )
			{
				// This object is invalid. Prune the pool after this search.
				executePrune = true;
				return false;
			}

			return true;
		}

		return false;
	} );

	if( idx == INDEX_NONE )
	{
		const bool debug = CVarDebugObjectPooling.GetValueOnGameThread( );
		if( debug )
		{
			// Debug logging.
			UE_LOG( SteelHuntersLog, Log, TEXT( "[UObjectPool] Unable to get a free object from the pool using ::GetPooledObject (Pool: %s, Object Count: %d)." ), *Name.ToString( ), Pool.Num( ) );
		}
	}

	// Get the found valid object, remove its place in the array, and add it to the back for a more efficient check later.
	//	NOTE (trent, 12/10/17): Ensure that this is actually an optimization.
	UObject* pUObject = Pool[idx].Get( );
	IPooledObject* pValidObject = dynamic_cast< IPooledObject* >( pUObject );
	Pool.RemoveAtSwap( idx, 1, false );
	Pool.Add( pUObject );

	// Activate the object.
	pValidObject->IsActive = true;
	pValidObject->LastActiveTimestamp = FDateTime::Now( ).ToUnixTimestamp( );

	if( executePrune )
	{
		// Prune the pool if need be (or if it's just time).
		//	NOTE: Since the object that was just found has already been reactivated and given an updated timestamp, it won't be pruned.
		Prune( );
	}

	return pValidObject;
}

//----------------------------------------------------------------------------------------------------
void UObjectPool::SetPruneStale( bool PruneStaleIn )
{
	PruneStale = PruneStaleIn;
}

//----------------------------------------------------------------------------------------------------
void UObjectPool::SetPruneInactiveTime( int64 PruneInactivitySeconds )
{
	PruneStale_Seconds = PruneInactivitySeconds;
}<commit_msg>Fixed an occasional first-run crash with the pooling system.<commit_after>// Copyright 2015-2017 Joy Machine, LLC. All rights reserved.

#include "steelhunters.h"

#include "ObjectPool.h"

#include "DateTime.h"

#include "IPooledObject.h"

// Console variable definition.
static TAutoConsoleVariable< int > CVarDebugObjectPooling( TEXT( "joy.DebugObjectPooling" ),
	0,
	TEXT( "Verbose output from the object pooling system for debugging." ),
	ECVF_Default );

// Static class definitions.
const int64 UObjectPool::kDefaultPruneStaleSeconds = 60;

uint32 UObjectPool::IDCounter = 0;
uint32 UObjectPool::PoolCount = 0;

//----------------------------------------------------------------------------------------------------
UObjectPool::UObjectPool( const class FObjectInitializer& ObjectInitializer )
: Name( *FString::Printf( TEXT( "Pool-%d" ), PoolCount ) )
, PoolID( PoolCount )
, PoolSizeOptimal( 256 )
, PoolSizeMaximum( 2048 )
, PruneStale( false )
, PruneLastTimestamp( FDateTime::Now( ).ToUnixTimestamp( ) )
, PruneStale_Seconds( kDefaultPruneStaleSeconds )
{
	Pool.Empty( );

	// Set this pool ID.
	PoolID = ++PoolCount;

	{
		const bool debug = CVarDebugObjectPooling.GetValueOnGameThread( );
		if( debug )
		{
			// Just toss out some debug information.
			UE_LOG( SteelHuntersLog, Log, TEXT( "[UObjectPool] Creating new pool (Pool Count: %d)." ), PoolCount );
		}
	}
}

//----------------------------------------------------------------------------------------------------
void UObjectPool::OnObjectReturn( IPooledObject* pObject )
{
	check( pObject != nullptr );

	// Reset the object (pure virtual method, so the logic is reliant on the child class).
	pObject->IsActive = false;
	pObject->Reset( );
}

//----------------------------------------------------------------------------------------------------
void UObjectPool::Prune( )
{
	const int64 currentTime = FDateTime::Now( ).ToUnixTimestamp( );
	int32 prunedObjectCount = Pool.RemoveAll( [&]( TWeakObjectPtr< UObject > pObject ) {
		if( !pObject.IsStale( ) && pObject.IsValid( ) )
		{
			// The object pointer is either stale or no longer valid.
			return false;
		}

		IPooledObject* pPooledObject = dynamic_cast< IPooledObject* >( pObject.Get( ) );
		if( !pPooledObject->GetIsActive( ) && !pPooledObject->Check( ) || ( PruneStale && ( ( currentTime - pPooledObject->LastActiveTimestamp ) > PruneStale_Seconds ) ) )
		{
			// This object is invalid or stale. Remove it.
			if( pPooledObject != nullptr )
			{
				// Just in case any logic in ::Deactivate is necessary, execute that, and then the ::Destroy method.
				pPooledObject->ReturnToPool.Unbind( );

				pPooledObject->DestroyInstance( );
				pPooledObject = nullptr;
			}

			return true;
		}

		return false;
	} );

	{
		const bool debug = CVarDebugObjectPooling.GetValueOnGameThread( );
		if( debug )
		{
			// Log the number of pruned objects.
			UE_LOG( SteelHuntersLog, Log, TEXT( "[UObjectPool] Pool pruning logic completed (Pool: %s, Object Count: %d, Pruned Count: %d." ), *Name.ToString( ), Pool.Num( ), prunedObjectCount );
		}
	}

	PruneLastTimestamp = currentTime;
}

//----------------------------------------------------------------------------------------------------
void UObjectPool::SetName( const FName& PoolName )
{
	// Just set the pool name; doesn't have to be unique.
	Name = GenerateName( PoolName );
}

//----------------------------------------------------------------------------------------------------
FName UObjectPool::GenerateName( const FName& BaseName )
{
	return( *FString::Printf( TEXT( "%s-%d" ), *BaseName.ToString( ), PoolCount ) );
}

//----------------------------------------------------------------------------------------------------
void UObjectPool::Empty( bool SeparateActiveInstances )
{
	const bool debug = CVarDebugObjectPooling.GetValueOnGameThread( );

	// Remove all objects from the pool and destroy them (unless SeparateActiveInstances is true, in which case leave them alone for now).
	int32 destroyedObjectCount = Pool.RemoveAll( [&]( TWeakObjectPtr< UObject > pObject ) {
		IPooledObject* pPooledObject = dynamic_cast< IPooledObject* >( pObject.Get( ) );
		if( !( SeparateActiveInstances && ( pPooledObject != nullptr ) && pPooledObject->GetIsActive( ) ) )
		{
			// Just in case any logic in ::Deactivate is necessary, execute that, and then the ::Destroy method.
			pPooledObject->ReturnToPool.Unbind( );

			pPooledObject->DestroyInstance( );
			pPooledObject = nullptr;
			return true;
		}

		return false;
	} );

	if( !SeparateActiveInstances )
	{
		if( debug )
		{
			// Log the object destroyed count and the destruction of the pool.
			UE_LOG( SteelHuntersLog, Log, TEXT( "[UObjectPool] Pool destroy completed (Pool: %s, Destroyed Object Count: %d)." ), *Name.ToString( ), destroyedObjectCount );
		}

		return;
	}

	// Now handle the separation of objects.
	int32 separatedObjectCount = Pool.RemoveAll( [&]( TWeakObjectPtr< UObject > pObject ) {
		IPooledObject* pPooledObject = dynamic_cast< IPooledObject* >( pObject.Get( ) );
		pPooledObject->ReturnToPool.Unbind( );

		pPooledObject->OnPoolRemovalWhileActive( );
		return true;
	} );

	if( debug )
	{
		// Log the object destroyed count and the destruction of the pool.
		UE_LOG( SteelHuntersLog, Log, TEXT( "[UObjectPool] Pool destroy completed with object separation (Pool: %s, Separated Object Count: %d, Destroyed Object Count: %d)." ), *Name.ToString( ), separatedObjectCount, destroyedObjectCount );
	}

#if !UE_BUILD_SHIPPING
	ensure( Pool.Num( ) == 0 );
#endif	// !UE_BUILD_SHIPPING.
}

//----------------------------------------------------------------------------------------------------
bool UObjectPool::Add( IPooledObject* ObjectIn, bool Active )
{
	check( ObjectIn != nullptr );

	// Check to ensure that IPooledObject is a derivative of UObject.
	UObject* pUObject = dynamic_cast< UObject* >( ObjectIn );

#if !UE_BUILD_SHIPPING
	ensure( IsValid( pUObject ) );
#endif	// !UE_BUILD_SHIPPING.

	// Predicate to check if this object is already in the pool.
	const uint32 objectID = ObjectIn->ID;
	if( Pool.ContainsByPredicate( [objectID]( TWeakObjectPtr< UObject > pObject ) {
		IPooledObject* pPooledObject = dynamic_cast< IPooledObject* >( pObject.Get( ) );
		return( objectID == pPooledObject->ID );
	} ) )
	{
		// Object is already in the pool.
		return false;
	}

	// Add this object to the pool.
	Pool.Add( pUObject );

	// Set whether or not the object is active (if being added, it usually is), and give it an ID.
	ObjectIn->IsActive = Active;
	ObjectIn->ID = IDCounter++;

	// Setup the object's pool return delegate (executed when the object is deactivated).
	ObjectIn->ReturnToPool.BindUObject( this, &UObjectPool::OnObjectReturn );

	{
		const bool debug = CVarDebugObjectPooling.GetValueOnGameThread( );
		if( debug )
		{
			// Debug logging.
			UE_LOG( SteelHuntersLog, Log, TEXT( "[UObjectPool] Adding object to pool (Pool: %s, Object Count: %d)." ), *Name.ToString( ), Pool.Num( ) );
		}
	}

	return true;
}

//----------------------------------------------------------------------------------------------------
template< typename T >
T* UObjectPool::GetPooledObject( )
{
	IPooledObject* pPooledObject = GetPooledObject( );
	if( pPooledObject == nullptr )
	{
		// No valid pooled objects.
		return nullptr;
	}

	T* pTemplateObject = Cast< T >( pPooledObject );
	check( IsValid( pTemplateObject ) );

	return pTemplateObject;
}

//----------------------------------------------------------------------------------------------------
IPooledObject* UObjectPool::GetPooledObject( )
{
	if( Pool.Num( ) <= 0 )
	{
		const bool debug = CVarDebugObjectPooling.GetValueOnGameThread( );
		if( debug )
		{
			// Debug logging.
			UE_LOG( SteelHuntersLog, Log, TEXT( "[UObjectPool] Pool size of 0 in ::GetPooledObject (Pool: %s, Object Count: %d)." ), *Name.ToString( ), Pool.Num( ) );
		}

		return nullptr;
	}

	const int64 currentTime = FDateTime::Now( ).ToUnixTimestamp( );
	bool executePrune = PruneStale && ( ( currentTime - PruneLastTimestamp ) > PruneStale_Seconds );		// If this isn't true, then it may be time to prune anyway if the search finds an invalid object.

	// Find the first inactive and valid object.
	int32 idx = Pool.IndexOfByPredicate( [&]( TWeakObjectPtr< UObject > pObject ) {
		IPooledObject* pPooledObject = dynamic_cast< IPooledObject* >( pObject.Get( ) );
		if( !pPooledObject->GetIsActive( ) )
		{
			if( !pPooledObject->Check( ) )
			{
				// This object is invalid. Prune the pool after this search.
				executePrune = true;
				return false;
			}

			return true;
		}

		return false;
	} );

	if( idx == INDEX_NONE )
	{
		const bool debug = CVarDebugObjectPooling.GetValueOnGameThread( );
		if( debug )
		{
			// Debug logging.
			UE_LOG( SteelHuntersLog, Log, TEXT( "[UObjectPool] Unable to get a free object from the pool using ::GetPooledObject (Pool: %s, Object Count: %d)." ), *Name.ToString( ), Pool.Num( ) );
		}
	}

	// Get the found valid object, remove its place in the array, and add it to the back for a more efficient check later.
	//	NOTE (trent, 12/10/17): Ensure that this is actually an optimization.
	UObject* pUObject = Pool[idx].Get( );
	IPooledObject* pValidObject = dynamic_cast< IPooledObject* >( pUObject );
	Pool.RemoveAtSwap( idx, 1, false );
	Pool.Add( pUObject );

	// Activate the object.
	pValidObject->IsActive = true;
	pValidObject->LastActiveTimestamp = FDateTime::Now( ).ToUnixTimestamp( );

	if( executePrune )
	{
		// Prune the pool if need be (or if it's just time).
		//	NOTE: Since the object that was just found has already been reactivated and given an updated timestamp, it won't be pruned.
		Prune( );
	}

	return pValidObject;
}

//----------------------------------------------------------------------------------------------------
void UObjectPool::SetPruneStale( bool PruneStaleIn )
{
	PruneStale = PruneStaleIn;
}

//----------------------------------------------------------------------------------------------------
void UObjectPool::SetPruneInactiveTime( int64 PruneInactivitySeconds )
{
	PruneStale_Seconds = PruneInactivitySeconds;
}<|endoftext|>


<commit_before>/*
 * Copyright (c) 2006 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Korey Sewell
 */

#ifndef __ARCH_MIPS_LINUX_LINUX_HH__
#define __ARCH_MIPS_LINUX_LINUX_HH__

#include "kern/linux/linux.hh"

class MipsLinux : public Linux
{
  public:

    /// This table maps the target open() flags to the corresponding
    /// host open() flags.
    static OpenFlagTransTable openFlagTable[];

    /// Number of entries in openFlagTable[].
    static const int NUM_OPEN_FLAGS;

    //@{
    /// open(2) flag values.
    static const int TGT_O_RDONLY       = 0x00000000;   //!< O_RDONLY
    static const int TGT_O_WRONLY       = 0x00000001;   //!< O_WRONLY
    static const int TGT_O_RDWR         = 0x00000002;   //!< O_RDWR
    static const int TGT_O_NONBLOCK     = 0x00000080;   //!< O_NONBLOCK
    static const int TGT_O_APPEND       = 0x00000008;   //!< O_APPEND
    static const int TGT_O_CREAT        = 0x00000100;   //!< O_CREAT
    static const int TGT_O_TRUNC        = 0x00000200;   //!< O_TRUNC
    static const int TGT_O_EXCL         = 0x00000400;   //!< O_EXCL
    static const int TGT_O_NOCTTY       = 0x00000800;   //!< O_NOCTTY
    static const int TGT_O_SYNC         = 0x00000010;   //!< O_SYNC
    static const int TGT_O_DRD          = 0x00010000;   //!< O_DRD
    static const int TGT_O_DIRECTIO     = 0x00020000;   //!< O_DIRECTIO
    static const int TGT_O_CACHE        = 0x00002000;   //!< O_CACHE
    static const int TGT_O_DSYNC        = 0x00008000;   //!< O_DSYNC
    static const int TGT_O_RSYNC        = 0x00040000;   //!< O_RSYNC
    //@}

    /// For mmap().
    static const unsigned TGT_MAP_ANONYMOUS = 0x800;
    static const unsigned TGT_MAP_FIXED     = 0x10;

    //@{
    /// For getsysinfo().
    static const unsigned GSI_PLATFORM_NAME = 103; //!< platform name as string
    static const unsigned GSI_CPU_INFO = 59;       //!< CPU information
    static const unsigned GSI_PROC_TYPE = 60;      //!< get proc_type
    static const unsigned GSI_MAX_CPU = 30;        //!< max # cpu's on this machine
    static const unsigned GSI_CPUS_IN_BOX = 55;    //!< number of CPUs in system
    static const unsigned GSI_PHYSMEM = 19;        //!< Physical memory in KB
    static const unsigned GSI_CLK_TCK = 42;        //!< clock freq in Hz
    //@}

    //@{
    /// For setsysinfo().
    static const unsigned SSI_IEEE_FP_CONTROL = 14; //!< ieee_set_fp_control()
    //@}

    //@{
    /// ioctl() command codes.
    static const unsigned TGT_TCGETA     = 0x5401;
    static const unsigned TGT_TCSETAW    = 0x5403;
    static const unsigned TGT_TCGETS     = 0x540d;
    static const unsigned TGT_FIONREAD   = 0x467f;
    static const unsigned TGT_TIOCGETP   = 0x7408;
    static const unsigned TGT_TIOCSETP   = 0x7409;
    static const unsigned TGT_TIOCSETN   = 0x740a;
    //@}

    static bool
    isTtyReq(unsigned req)
    {
        switch (req) {
          case TGT_TIOCGETP:
          case TGT_TIOCSETP:
          case TGT_TIOCSETN:
          case TGT_FIONREAD:
          case TGT_TCGETS:
          case TGT_TCGETA:
          case TGT_TCSETAW:
            return true;
          default:
            return false;
        }
    }

    /// For table().
    static const int TBL_SYSINFO = 12;

    /// Resource constants for getrlimit() (overide some generics).
    static const unsigned TGT_RLIMIT_NPROC = 8;
    static const unsigned TGT_RLIMIT_AS = 6;
    static const unsigned RLIMIT_RSS = 7;
    static const unsigned TGT_RLIMIT_NOFILE = 5;
    static const unsigned TGT_RLIMIT_MEMLOCK = 9;

    /// Offset used to make sure that processes don't
    /// assign themselves to process IDs reserved for
    /// the root users.
    static const int NUM_ROOT_PROCS = 2;

    typedef struct {
       int32_t  uptime;    /* Seconds since boot */
       uint32_t loads[3];  /* 1, 5, and 15 minute load averages */
       uint32_t totalram;  /* Total usable main memory size */
       uint32_t freeram;   /* Available memory size */
       uint32_t sharedram; /* Amount of shared memory */
       uint32_t bufferram; /* Memory used by buffers */
       uint32_t totalswap; /* Total swap space size */
       uint32_t freeswap;  /* swap space still available */
       uint16_t procs;     /* Number of current processes */
       uint32_t totalhigh; /* Total high memory size */
       uint32_t freehigh;  /* Available high memory size */
       uint32_t mem_unit;  /* Memory unit size in bytes */
    } tgt_sysinfo;

};

#endif
<commit_msg>mips: Fix RLIMIT_RSS naming<commit_after>/*
 * Copyright (c) 2006 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Korey Sewell
 */

#ifndef __ARCH_MIPS_LINUX_LINUX_HH__
#define __ARCH_MIPS_LINUX_LINUX_HH__

#include "kern/linux/linux.hh"

class MipsLinux : public Linux
{
  public:

    /// This table maps the target open() flags to the corresponding
    /// host open() flags.
    static OpenFlagTransTable openFlagTable[];

    /// Number of entries in openFlagTable[].
    static const int NUM_OPEN_FLAGS;

    //@{
    /// open(2) flag values.
    static const int TGT_O_RDONLY       = 0x00000000;   //!< O_RDONLY
    static const int TGT_O_WRONLY       = 0x00000001;   //!< O_WRONLY
    static const int TGT_O_RDWR         = 0x00000002;   //!< O_RDWR
    static const int TGT_O_NONBLOCK     = 0x00000080;   //!< O_NONBLOCK
    static const int TGT_O_APPEND       = 0x00000008;   //!< O_APPEND
    static const int TGT_O_CREAT        = 0x00000100;   //!< O_CREAT
    static const int TGT_O_TRUNC        = 0x00000200;   //!< O_TRUNC
    static const int TGT_O_EXCL         = 0x00000400;   //!< O_EXCL
    static const int TGT_O_NOCTTY       = 0x00000800;   //!< O_NOCTTY
    static const int TGT_O_SYNC         = 0x00000010;   //!< O_SYNC
    static const int TGT_O_DRD          = 0x00010000;   //!< O_DRD
    static const int TGT_O_DIRECTIO     = 0x00020000;   //!< O_DIRECTIO
    static const int TGT_O_CACHE        = 0x00002000;   //!< O_CACHE
    static const int TGT_O_DSYNC        = 0x00008000;   //!< O_DSYNC
    static const int TGT_O_RSYNC        = 0x00040000;   //!< O_RSYNC
    //@}

    /// For mmap().
    static const unsigned TGT_MAP_ANONYMOUS = 0x800;
    static const unsigned TGT_MAP_FIXED     = 0x10;

    //@{
    /// For getsysinfo().
    static const unsigned GSI_PLATFORM_NAME = 103; //!< platform name as string
    static const unsigned GSI_CPU_INFO = 59;       //!< CPU information
    static const unsigned GSI_PROC_TYPE = 60;      //!< get proc_type
    static const unsigned GSI_MAX_CPU = 30;        //!< max # cpu's on this machine
    static const unsigned GSI_CPUS_IN_BOX = 55;    //!< number of CPUs in system
    static const unsigned GSI_PHYSMEM = 19;        //!< Physical memory in KB
    static const unsigned GSI_CLK_TCK = 42;        //!< clock freq in Hz
    //@}

    //@{
    /// For setsysinfo().
    static const unsigned SSI_IEEE_FP_CONTROL = 14; //!< ieee_set_fp_control()
    //@}

    //@{
    /// ioctl() command codes.
    static const unsigned TGT_TCGETA     = 0x5401;
    static const unsigned TGT_TCSETAW    = 0x5403;
    static const unsigned TGT_TCGETS     = 0x540d;
    static const unsigned TGT_FIONREAD   = 0x467f;
    static const unsigned TGT_TIOCGETP   = 0x7408;
    static const unsigned TGT_TIOCSETP   = 0x7409;
    static const unsigned TGT_TIOCSETN   = 0x740a;
    //@}

    static bool
    isTtyReq(unsigned req)
    {
        switch (req) {
          case TGT_TIOCGETP:
          case TGT_TIOCSETP:
          case TGT_TIOCSETN:
          case TGT_FIONREAD:
          case TGT_TCGETS:
          case TGT_TCGETA:
          case TGT_TCSETAW:
            return true;
          default:
            return false;
        }
    }

    /// For table().
    static const int TBL_SYSINFO = 12;

    /// Resource constants for getrlimit() (overide some generics).
    static const unsigned TGT_RLIMIT_NPROC = 8;
    static const unsigned TGT_RLIMIT_AS = 6;
    static const unsigned TGT_RLIMIT_RSS = 7;
    static const unsigned TGT_RLIMIT_NOFILE = 5;
    static const unsigned TGT_RLIMIT_MEMLOCK = 9;

    /// Offset used to make sure that processes don't
    /// assign themselves to process IDs reserved for
    /// the root users.
    static const int NUM_ROOT_PROCS = 2;

    typedef struct {
       int32_t  uptime;    /* Seconds since boot */
       uint32_t loads[3];  /* 1, 5, and 15 minute load averages */
       uint32_t totalram;  /* Total usable main memory size */
       uint32_t freeram;   /* Available memory size */
       uint32_t sharedram; /* Amount of shared memory */
       uint32_t bufferram; /* Memory used by buffers */
       uint32_t totalswap; /* Total swap space size */
       uint32_t freeswap;  /* swap space still available */
       uint16_t procs;     /* Number of current processes */
       uint32_t totalhigh; /* Total high memory size */
       uint32_t freehigh;  /* Available high memory size */
       uint32_t mem_unit;  /* Memory unit size in bytes */
    } tgt_sysinfo;

};

#endif
<|endoftext|>


<commit_before>//%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements.  Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// 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.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////

#include <sys/stat.h>

UNIX_LogEntry::UNIX_LogEntry(void)
{
}

UNIX_LogEntry::~UNIX_LogEntry(void)
{
}

Boolean UNIX_LogEntry::getInstanceID(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_INSTANCE_ID, getInstanceID());
	return true;
}

String UNIX_LogEntry::getInstanceID() const
{
	String s;
	s.append(getLogName());
	s.append("_");
	s.append("A");
	return s;
}

Boolean UNIX_LogEntry::getCaption(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_CAPTION, getCaption());
	return true;
}

String UNIX_LogEntry::getCaption() const
{
	return msg;
}

Boolean UNIX_LogEntry::getDescription(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_DESCRIPTION, getDescription());
	return true;
}

String UNIX_LogEntry::getDescription() const
{
	return String ("");
}

Boolean UNIX_LogEntry::getElementName(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_ELEMENT_NAME, getElementName());
	return true;
}

String UNIX_LogEntry::getElementName() const
{
	return String("LogEntry");
}

Boolean UNIX_LogEntry::getRecordFormat(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_RECORD_FORMAT, getRecordFormat());
	return true;
}

String UNIX_LogEntry::getRecordFormat() const
{
	return String ("[DATE] [MESSAGE]");
}

Boolean UNIX_LogEntry::getRecordData(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_RECORD_DATA, getRecordData());
	return true;
}

String UNIX_LogEntry::getRecordData() const
{
	return data;
}

Boolean UNIX_LogEntry::getLocale(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_LOCALE, getLocale());
	return true;
}

String UNIX_LogEntry::getLocale() const
{
	return String ("en-US");
}

Boolean UNIX_LogEntry::getPerceivedSeverity(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_PERCEIVED_SEVERITY, getPerceivedSeverity());
	return true;
}

Uint16 UNIX_LogEntry::getPerceivedSeverity() const
{
	return Uint16(0);
}

Boolean UNIX_LogEntry::getLogInstanceID(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_LOG_INSTANCE_ID, getLogInstanceID());
	return true;
}

String UNIX_LogEntry::getLogInstanceID() const
{
	return logs.getInstanceID();
}

Boolean UNIX_LogEntry::getLogName(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_LOG_NAME, getLogName());
	return true;
}

String UNIX_LogEntry::getLogName() const
{
	return logs.getName();
}

Boolean UNIX_LogEntry::getRecordID(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_RECORD_ID, getRecordID());
	return true;
}

String UNIX_LogEntry::getRecordID() const
{
	return String ("");
}

Boolean UNIX_LogEntry::getCreationTimeStamp(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_CREATION_TIME_STAMP, getCreationTimeStamp());
	return true;
}

CIMDateTime UNIX_LogEntry::getCreationTimeStamp() const
{
	return logDate;
}

Boolean UNIX_LogEntry::getMessageID(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_MESSAGE_ID, getMessageID());
	return true;
}

String UNIX_LogEntry::getMessageID() const
{
	return String ("");
}

Boolean UNIX_LogEntry::getMessage(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_MESSAGE, getMessage());
	return true;
}

String UNIX_LogEntry::getMessage() const
{
	return msg;
}

Boolean UNIX_LogEntry::getMessageArguments(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_MESSAGE_ARGUMENTS, getMessageArguments());
	return true;
}

Array<String> UNIX_LogEntry::getMessageArguments() const
{
	Array<String> as;

	return as;

}

Boolean UNIX_LogEntry::getOwningEntity(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_OWNING_ENTITY, getOwningEntity());
	return true;
}

String UNIX_LogEntry::getOwningEntity() const
{
	return String ("");
}

Boolean UNIX_LogEntry::initialize()
{
	fp = NULL;
	logs.initialize();
	logIndex = 0;
	return false;
}

Boolean UNIX_LogEntry::load(int &pIndex)
{
	if (fp == NULL)
	{
		if (logs.load(logIndex))
		{
			logIndex++;
		}
		else {
			return false;
		}
	}
	if (fp == NULL)
	{
		if (logs.getFileName(fileName))
		{
			if ((fp = fopen(fileName.getCString(), "r")) == NULL)
			{
				fileName.assign("");
				fp = NULL;
				return load(++pIndex);
			}
			else {
				/* Since syslog doesn't store year in logs will use the year of the file */
				/* Hopfully syslog change the file when it changes year */
				struct tm* clock;			// create a time structure
				struct stat attrib;			// create a file attribute structure
				stat(fileName.getCString(), &attrib);		// get the attributes mnt
				clock = gmtime(&(attrib.st_mtime));	// Get the last modified time and put it into the time structure
				currentYear = clock->tm_year + 1900;
			}
		}
		else {
			fp == NULL;
			return load(++pIndex);
		}
	}
	char val[512];
	if (fgets(val, sizeof(val), fp) != NULL)
	{
		//Parse Date from syslog
		struct tm clock;
		char *retc = strptime(val, "%b %d %H:%M:%S", &clock);
		logDate = CIMDateTime(
		currentYear,
		clock.tm_mon + 1,
		clock.tm_mday,
		clock.tm_hour,
		clock.tm_min,
		clock.tm_sec,
		0,0,
		0);
		data = String(val);
		msg.assign(CIMHelper::trim(retc));
		return true;
	}
	else
	{
		fclose(fp);
		fp = NULL;
		return load(++pIndex);
	}
}

Boolean UNIX_LogEntry::finalize()
{
	logIndex = 0;
	logs.finalize();
	return false;
}

Boolean UNIX_LogEntry::find(Array<CIMKeyBinding> &kbArray)
{
	CIMKeyBinding kb;
	String instanceIDKey;

	for(Uint32 i = 0; i < kbArray.size(); i++)
	{
		kb = kbArray[i];
		CIMName keyName = kb.getName();
		if (keyName.equal(PROPERTY_INSTANCE_ID)) instanceIDKey = kb.getValue();
	}

/* EXecute find with extracted keys */

	return false;
}
<commit_msg>Fixing CIM_LogEntry Implementation<commit_after>//%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements.  Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// 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.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////

#include <sys/stat.h>

UNIX_LogEntry::UNIX_LogEntry(void)
{
}

UNIX_LogEntry::~UNIX_LogEntry(void)
{
}

Boolean UNIX_LogEntry::getInstanceID(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_INSTANCE_ID, getInstanceID());
	return true;
}

String UNIX_LogEntry::getInstanceID() const
{
	String s;
	s.append(getLogName());
	s.append("_");
	s.append("A");
	return s;
}

Boolean UNIX_LogEntry::getCaption(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_CAPTION, getCaption());
	return true;
}

String UNIX_LogEntry::getCaption() const
{
	return msg;
}

Boolean UNIX_LogEntry::getDescription(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_DESCRIPTION, getDescription());
	return true;
}

String UNIX_LogEntry::getDescription() const
{
	return String ("");
}

Boolean UNIX_LogEntry::getElementName(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_ELEMENT_NAME, getElementName());
	return true;
}

String UNIX_LogEntry::getElementName() const
{
	return String("LogEntry");
}

Boolean UNIX_LogEntry::getRecordFormat(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_RECORD_FORMAT, getRecordFormat());
	return true;
}

String UNIX_LogEntry::getRecordFormat() const
{
	return String ("[DATE] [MESSAGE]");
}

Boolean UNIX_LogEntry::getRecordData(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_RECORD_DATA, getRecordData());
	return true;
}

String UNIX_LogEntry::getRecordData() const
{
	return data;
}

Boolean UNIX_LogEntry::getLocale(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_LOCALE, getLocale());
	return true;
}

String UNIX_LogEntry::getLocale() const
{
	return String ("en-US");
}

Boolean UNIX_LogEntry::getPerceivedSeverity(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_PERCEIVED_SEVERITY, getPerceivedSeverity());
	return true;
}

Uint16 UNIX_LogEntry::getPerceivedSeverity() const
{
	return Uint16(0);
}

Boolean UNIX_LogEntry::getLogInstanceID(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_LOG_INSTANCE_ID, getLogInstanceID());
	return true;
}

String UNIX_LogEntry::getLogInstanceID() const
{
	return logs.getInstanceID();
}

Boolean UNIX_LogEntry::getLogName(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_LOG_NAME, getLogName());
	return true;
}

String UNIX_LogEntry::getLogName() const
{
	return logs.getName();
}

Boolean UNIX_LogEntry::getRecordID(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_RECORD_ID, getRecordID());
	return true;
}

String UNIX_LogEntry::getRecordID() const
{
	return String ("");
}

Boolean UNIX_LogEntry::getCreationTimeStamp(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_CREATION_TIME_STAMP, getCreationTimeStamp());
	return true;
}

CIMDateTime UNIX_LogEntry::getCreationTimeStamp() const
{
	return logDate;
}

Boolean UNIX_LogEntry::getMessageID(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_MESSAGE_ID, getMessageID());
	return true;
}

String UNIX_LogEntry::getMessageID() const
{
	return String ("");
}

Boolean UNIX_LogEntry::getMessage(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_MESSAGE, getMessage());
	return true;
}

String UNIX_LogEntry::getMessage() const
{
	return msg;
}

Boolean UNIX_LogEntry::getMessageArguments(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_MESSAGE_ARGUMENTS, getMessageArguments());
	return true;
}

Array<String> UNIX_LogEntry::getMessageArguments() const
{
	Array<String> as;

	return as;

}

Boolean UNIX_LogEntry::getOwningEntity(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_OWNING_ENTITY, getOwningEntity());
	return true;
}

String UNIX_LogEntry::getOwningEntity() const
{
	return String ("");
}

Boolean UNIX_LogEntry::initialize()
{
	fp = NULL;
	logs.initialize();
	logIndex = 0;
	return true;
}

Boolean UNIX_LogEntry::load(int &pIndex)
{
	if (fp == NULL)
	{
		if (logs.load(logIndex))
		{
			logIndex++;
		}
		else {
			return false;
		}
	}
	if (fp == NULL)
	{
		if (logs.getFileName(fileName))
		{
			if ((fp = fopen(fileName.getCString(), "r")) == NULL)
			{
				fileName.assign("");
				fp = NULL;
				return load(++pIndex);
			}
			else {
				/* Since syslog doesn't store year in logs will use the year of the file */
				/* Hopfully syslog change the file when it changes year */
				struct tm* clock;			// create a time structure
				struct stat attrib;			// create a file attribute structure
				stat(fileName.getCString(), &attrib);		// get the attributes mnt
				clock = gmtime(&(attrib.st_mtime));	// Get the last modified time and put it into the time structure
				currentYear = clock->tm_year + 1900;
			}
		}
		else {
			fp == NULL;
			return load(++pIndex);
		}
	}
	char val[512];
	if (fgets(val, sizeof(val), fp) != NULL)
	{
		//Parse Date from syslog
		struct tm clock;
		char *retc = strptime(val, "%b %d %H:%M:%S", &clock);
		logDate = CIMDateTime(
		currentYear,
		clock.tm_mon + 1,
		clock.tm_mday,
		clock.tm_hour,
		clock.tm_min,
		clock.tm_sec,
		0,0,
		0);
		data = String(val);
		msg.assign(CIMHelper::trim(retc));
		return true;
	}
	else
	{
		fclose(fp);
		fp = NULL;
		return load(++pIndex);
	}
}

Boolean UNIX_LogEntry::finalize()
{
	logIndex = 0;
	logs.finalize();
	return true;
}

Boolean UNIX_LogEntry::find(Array<CIMKeyBinding> &kbArray)
{
	CIMKeyBinding kb;
	String instanceIDKey;

	for(Uint32 i = 0; i < kbArray.size(); i++)
	{
		kb = kbArray[i];
		CIMName keyName = kb.getName();
		if (keyName.equal(PROPERTY_INSTANCE_ID)) instanceIDKey = kb.getValue();
	}

/* EXecute find with extracted keys */

	return false;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2016 neurodata (http://neurodata.io/)
 * Written by Disa Mhembere (disa@jhu.edu)
 *
 * This file is part of k-par-means
 *
 * 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 CURRENT_KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef __KPM_DIST_MATRIX_HPP__
#define __KPM_DIST_MATRIX_HPP__

#include <memory>
#include <limits>
#include <vector>

#include <El.hpp>
#include "util.hpp"

#if 0
namespace kpmeans { namespace prune {
    class prune_clusters;
} } // End namespace kpmeans, prune
#endif

namespace kpmeans { namespace prune {
// NOTE: Creates a matrix like this e.g for K = 5
/* - Don't store full matrix, don't store dist to myself -> space: (k*k-1)/2
   0 ==> 1 2 3 4
   1 ==> 2 3 4
   2 ==> 3 4
   3 ==> 4
   (4 ==> not needed)
   */
class dist_matrix {
private:
    std::vector<std::vector<double>> mat;
    unsigned rows;

    dist_matrix(const unsigned rows);
    void translate(unsigned& row, unsigned& col);

public:
    typedef typename std::shared_ptr<dist_matrix> ptr;

    static ptr create(const unsigned rows) {
        return ptr(new dist_matrix(rows));
    }

    const unsigned get_num_rows() { return rows; }

    /* Do a translation from raw id's to indexes in the distance matrix */
    double get(unsigned row, unsigned col);
    // Testing purposes only
    double get_min_dist(const unsigned row);
    void set(unsigned row, unsigned col, double val);

    void print();
#if 0
    void compute_dist(kpmeans::base::prune_clusters::ptr cl,
            const unsigned ncol);
#endif
    // Note cls is col-wise unlike dist_matrix
    template<typename T>
    void compute_dist(El::Matrix<T>& cls,
            std::vector<T>& s_val_v) {
    if (cls.Width() <= 1) return (T)0;

    assert(get_num_rows() == cls.Width());
    std::fill(s_val_v.begin(), s_val_v.end(),
            std::numeric_limits<double>::max());

    for (unsigned i = 0; i < cls.Width(); i++) {
        for (unsigned j = i+1; j < cls.Width(); j++) {
            // FIXME
            double dist = kpmeans::base::eucl_dist(cls.LockedBuffer(0,i),
                    cls.LockedBuffer(0,j), cls.Height()) / 2.0;

            set(i,j, dist);

            // Set s(x) for each cluster
            if (dist < s_val_v[i])
                s_val_v[i] = dist;

            if (dist < s_val_v[j])
                s_val_v[j] = dist;
        }
    }
#if VERBOSE
    for (unsigned cl = 0; cl < cls.Width(); cl++) {
        assert(s_val_v[cl] == get_min_dist(cl));
        if (El::mpi::Rank(El::mpi::COMM_WORLD) == 0)
            El::Output("cl: ", cl," get_s_val: ", s_val_v[cl]);
    }
#endif
}
};
} } // End namespace kpmeans, prune
#endif
<commit_msg>bug: return should be void<commit_after>/*
 * Copyright 2016 neurodata (http://neurodata.io/)
 * Written by Disa Mhembere (disa@jhu.edu)
 *
 * This file is part of k-par-means
 *
 * 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 CURRENT_KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef __KPM_DIST_MATRIX_HPP__
#define __KPM_DIST_MATRIX_HPP__

#include <memory>
#include <limits>
#include <vector>

#include <El.hpp>
#include "util.hpp"

#if 0
namespace kpmeans { namespace prune {
    class prune_clusters;
} } // End namespace kpmeans, prune
#endif

namespace kpmeans { namespace prune {
// NOTE: Creates a matrix like this e.g for K = 5
/* - Don't store full matrix, don't store dist to myself -> space: (k*k-1)/2
   0 ==> 1 2 3 4
   1 ==> 2 3 4
   2 ==> 3 4
   3 ==> 4
   (4 ==> not needed)
   */
class dist_matrix {
private:
    std::vector<std::vector<double>> mat;
    unsigned rows;

    dist_matrix(const unsigned rows);
    void translate(unsigned& row, unsigned& col);

public:
    typedef typename std::shared_ptr<dist_matrix> ptr;

    static ptr create(const unsigned rows) {
        return ptr(new dist_matrix(rows));
    }

    const unsigned get_num_rows() { return rows; }

    /* Do a translation from raw id's to indexes in the distance matrix */
    double get(unsigned row, unsigned col);
    // Testing purposes only
    double get_min_dist(const unsigned row);
    void set(unsigned row, unsigned col, double val);

    void print();
#if 0
    void compute_dist(kpmeans::base::prune_clusters::ptr cl,
            const unsigned ncol);
#endif
    // Note cls is col-wise unlike dist_matrix
    template<typename T>
    void compute_dist(El::Matrix<T>& cls,
            std::vector<T>& s_val_v) {
    if (cls.Width() == 1) {
        s_val_v.push_back((T)0);
        return;
    }

    assert(get_num_rows() == cls.Width());
    std::fill(s_val_v.begin(), s_val_v.end(),
            std::numeric_limits<double>::max());

    for (unsigned i = 0; i < cls.Width(); i++) {
        for (unsigned j = i+1; j < cls.Width(); j++) {
            // FIXME
            double dist = kpmeans::base::eucl_dist(cls.LockedBuffer(0,i),
                    cls.LockedBuffer(0,j), cls.Height()) / 2.0;

            set(i,j, dist);

            // Set s(x) for each cluster
            if (dist < s_val_v[i])
                s_val_v[i] = dist;

            if (dist < s_val_v[j])
                s_val_v[j] = dist;
        }
    }
#if VERBOSE
    for (unsigned cl = 0; cl < cls.Width(); cl++) {
        assert(s_val_v[cl] == get_min_dist(cl));
        if (El::mpi::Rank(El::mpi::COMM_WORLD) == 0)
            El::Output("cl: ", cl," get_s_val: ", s_val_v[cl]);
    }
#endif
}
};
} } // End namespace kpmeans, prune
#endif
<|endoftext|>


<commit_before>#include "CGUITerrainControlWidget.h"

#include "CProgramContext.h"
#include "CMainState.h"
#include "CTerrainNodeManager.h"
#include "CGUIContext.h"

#include <Gwen/Controls.h>
#include <Gwen/Controls/ComboBox.h>

CGUITerrainControlWidget::CGUITerrainControlWidget()
	: Terrain(CProgramContext::Get().Scene.Terrain), Water(CProgramContext::Get().Scene.Water), MainState(CMainState::Get())
{
	Window = new Gwen::Controls::WindowControl(GUIManager->GetCanvas());
	Window->SetDeleteOnClose(false);
	Window->SetBounds(1200, 500, 330, 235);
	Window->SetTitle("Terrain Controls");
	Window->SetHidden(true);

	TerrainButton = new Gwen::Controls::Button(Window);
	TerrainButton->SetBounds(15, 10, 290, 25);
	TerrainButton->SetText(Terrain->GetNode()->IsVisible() ? "Disable Terrain" : "Enable Terrain");
	TerrainButton->onPress.Add(this, & CGUITerrainControlWidget::OnToggleTerrain);

	WaterButton = new Gwen::Controls::Button(Window);
	WaterButton->SetBounds(15, 10 + 35, 290, 25);
	WaterButton->SetText("Enable Water");
	//WaterButton->SetText(Water->isVisible() ? "Disable Water" : "Enable Water");
	WaterButton->onPress.Add(this, & CGUITerrainControlWidget::OnToggleWater);

	// Panel
	{
		Gwen::Controls::Label * SliderLabel = new Gwen::Controls::Label(Window);
		SliderLabel->SetFont(GUIManager->GetRegularFont());
		SliderLabel->SetText(L"Texture:");
		SliderLabel->SetBounds(10, 10 + 30 + 45, 300, 40);
		SliderLabel->SetTextColor(Gwen::Color(50, 20, 20, 215));

		Gwen::Controls::Button * ElevationButton = new Gwen::Controls::Button(Window);
		ElevationButton->SetBounds(15, 10 + 30 + 45 + 20, 140, 25);
		ElevationButton->SetText("Elevation");
		ElevationButton->onPress.Add(this, & CGUITerrainControlWidget::OnSelectElevation);

		Gwen::Controls::Button * ColorButton = new Gwen::Controls::Button(Window);
		ColorButton->SetBounds(140 + 15 + 10, 10 + 30 + 45 + 20, 140, 25);
		ColorButton->SetText("GoogleMaps");
		ColorButton->onPress.Add(this, & CGUITerrainControlWidget::OnSelectColor);

		Gwen::Controls::Label * ModeLabel = new Gwen::Controls::Label(Window);
		ModeLabel->SetFont(GUIManager->GetRegularFont());
		ModeLabel->SetText(L"Mode:");
		ModeLabel->SetBounds(10, 10 + 15 + 45 + 75, 300, 40);
		ModeLabel->SetTextColor(Gwen::Color(50, 20, 20, 215));

		Gwen::Controls::ComboBox * ModeBox = new Gwen::Controls::ComboBox(Window);
		ModeBox->SetBounds(15, 10 + 15 + 45 + 20 + 75, 200, 25);
		ModeBox->AddItem(L"Solid");
		ModeBox->AddItem(L"Wireframe");
		ModeBox->AddItem(L"AO1");
		ModeBox->AddItem(L"AO2");
		ModeBox->AddItem(L"AO3");
		ModeBox->AddItem(L"AO4");
		ModeBox->AddItem(L"AO5");
		ModeBox->AddItem(L"AO6");
		ModeBox->AddItem(L"AO7");
		ModeBox->AddItem(L"AO8");
		ModeBox->AddItem(L"AO9");
		ModeBox->onSelection.Add(this, & CGUITerrainControlWidget::OnModeSelect);
	}
}

void CGUITerrainControlWidget::OnToggleTerrain(Gwen::Controls::Base * Control)
{
	CProgramContext * Context = & CProgramContext::Get();

	if (Context->Scene.Terrain->GetNode()->IsVisible())
	{
		Context->Scene.Terrain->GetNode()->SetVisible(false);
		GUIContext->GetConsole()->AddMessage("Terrain View Disabled");
		TerrainButton->SetText("Enable Terrain");
	}
	else
	{
		Context->Scene.Terrain->GetNode()->SetVisible(true);
		GUIContext->GetConsole()->AddMessage("Terrain View Enabled");
		TerrainButton->SetText("Disable Terrain");
	}
}

void CGUITerrainControlWidget::OnToggleWater(Gwen::Controls::Base * Control)
{
	CProgramContext * Context = & CProgramContext::Get();

	//if (Context->Scene.Water->isVisible())
	//{
	//	Context->Scene.Water->setVisible(false);
	//	GUIContext->GetConsole()->AddMessage("Water View Disabled");
	//	WaterButton->SetText("Enable Water");
	//}
	//else
	//{
	//	Context->Scene.Water->setVisible(true);
	//	GUIContext->GetConsole()->AddMessage("Water View Enabled");
	//	WaterButton->SetText("Disable Water");
	//}
}

void CGUITerrainControlWidget::OnSelectElevation(Gwen::Controls::Base * Control)
{
	CProgramContext * Context = & CProgramContext::Get();
	Context->Scene.Terrain->SetDebugHeightEnabled(true);
}

void CGUITerrainControlWidget::OnSelectColor(Gwen::Controls::Base * Control)
{
	CProgramContext * Context = & CProgramContext::Get();
	Context->Scene.Terrain->SetDebugHeightEnabled(false);
}

void CGUITerrainControlWidget::OnModeSelect(Gwen::Controls::Base * Control)
{
	CProgramContext * Context = & CProgramContext::Get();
	Gwen::Controls::ComboBox * Box = (Gwen::Controls::ComboBox *) Control;

	if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L"Solid"))
	{
		Context->Scene.Terrain->DebugMode = 0;
		Context->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);
	}
	else if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L"Wireframe"))
	{
		Context->Scene.Terrain->DebugMode = 0;
		Context->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, true);
	}
	else if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L"AO1"))
	{
		Context->Scene.Terrain->DebugMode = 1;
		Context->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);
	}
	else if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L"AO2"))
	{
		Context->Scene.Terrain->DebugMode = 2;
		Context->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);
	}
	else if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L"AO3"))
	{
		Context->Scene.Terrain->DebugMode = 3;
		Context->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);
	}
	else if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L"AO4"))
	{
		Context->Scene.Terrain->DebugMode = 4;
		Context->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);
	}
	else if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L"AO5"))
	{
		Context->Scene.Terrain->DebugMode = 5;
		Context->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);
	}
	else if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L"AO6"))
	{
		Context->Scene.Terrain->DebugMode = 6;
		Context->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);
	}
	else if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L"AO7"))
	{
		Context->Scene.Terrain->DebugMode = 7;
		Context->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);
	}
	else if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L"AO8"))
	{
		Context->Scene.Terrain->DebugMode = 8;
		Context->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);
	}
	else if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L"AO9"))
	{
		Context->Scene.Terrain->DebugMode = 9;
		Context->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);
	}
}

void CGUITerrainControlWidget::toggle()
{
	Window->SetHidden(Window->Visible());
}
<commit_msg>Re-enable water controls in gui<commit_after>#include "CGUITerrainControlWidget.h"

#include "CProgramContext.h"
#include "CMainState.h"
#include "CTerrainNodeManager.h"
#include "CGUIContext.h"

#include <Gwen/Controls.h>
#include <Gwen/Controls/ComboBox.h>

CGUITerrainControlWidget::CGUITerrainControlWidget()
	: Terrain(CProgramContext::Get().Scene.Terrain), Water(CProgramContext::Get().Scene.Water), MainState(CMainState::Get())
{
	Window = new Gwen::Controls::WindowControl(GUIManager->GetCanvas());
	Window->SetDeleteOnClose(false);
	Window->SetBounds(1200, 500, 330, 235);
	Window->SetTitle("Terrain Controls");
	Window->SetHidden(true);

	TerrainButton = new Gwen::Controls::Button(Window);
	TerrainButton->SetBounds(15, 10, 290, 25);
	TerrainButton->SetText(Terrain->GetNode()->IsVisible() ? "Disable Terrain" : "Enable Terrain");
	TerrainButton->onPress.Add(this, & CGUITerrainControlWidget::OnToggleTerrain);

	WaterButton = new Gwen::Controls::Button(Window);
	WaterButton->SetBounds(15, 10 + 35, 290, 25);
	WaterButton->SetText("Enable Water");
	WaterButton->SetText(Water->IsVisible() ? "Disable Water" : "Enable Water");
	WaterButton->onPress.Add(this, & CGUITerrainControlWidget::OnToggleWater);

	// Panel
	{
		Gwen::Controls::Label * SliderLabel = new Gwen::Controls::Label(Window);
		SliderLabel->SetFont(GUIManager->GetRegularFont());
		SliderLabel->SetText(L"Texture:");
		SliderLabel->SetBounds(10, 10 + 30 + 45, 300, 40);
		SliderLabel->SetTextColor(Gwen::Color(50, 20, 20, 215));

		Gwen::Controls::Button * ElevationButton = new Gwen::Controls::Button(Window);
		ElevationButton->SetBounds(15, 10 + 30 + 45 + 20, 140, 25);
		ElevationButton->SetText("Elevation");
		ElevationButton->onPress.Add(this, & CGUITerrainControlWidget::OnSelectElevation);

		Gwen::Controls::Button * ColorButton = new Gwen::Controls::Button(Window);
		ColorButton->SetBounds(140 + 15 + 10, 10 + 30 + 45 + 20, 140, 25);
		ColorButton->SetText("GoogleMaps");
		ColorButton->onPress.Add(this, & CGUITerrainControlWidget::OnSelectColor);

		Gwen::Controls::Label * ModeLabel = new Gwen::Controls::Label(Window);
		ModeLabel->SetFont(GUIManager->GetRegularFont());
		ModeLabel->SetText(L"Mode:");
		ModeLabel->SetBounds(10, 10 + 15 + 45 + 75, 300, 40);
		ModeLabel->SetTextColor(Gwen::Color(50, 20, 20, 215));

		Gwen::Controls::ComboBox * ModeBox = new Gwen::Controls::ComboBox(Window);
		ModeBox->SetBounds(15, 10 + 15 + 45 + 20 + 75, 200, 25);
		ModeBox->AddItem(L"Solid");
		ModeBox->AddItem(L"Wireframe");
		ModeBox->AddItem(L"AO1");
		ModeBox->AddItem(L"AO2");
		ModeBox->AddItem(L"AO3");
		ModeBox->AddItem(L"AO4");
		ModeBox->AddItem(L"AO5");
		ModeBox->AddItem(L"AO6");
		ModeBox->AddItem(L"AO7");
		ModeBox->AddItem(L"AO8");
		ModeBox->AddItem(L"AO9");
		ModeBox->onSelection.Add(this, & CGUITerrainControlWidget::OnModeSelect);
	}
}

void CGUITerrainControlWidget::OnToggleTerrain(Gwen::Controls::Base * Control)
{
	CProgramContext * Context = & CProgramContext::Get();

	if (Context->Scene.Terrain->GetNode()->IsVisible())
	{
		Context->Scene.Terrain->GetNode()->SetVisible(false);
		GUIContext->GetConsole()->AddMessage("Terrain View Disabled");
		TerrainButton->SetText("Enable Terrain");
	}
	else
	{
		Context->Scene.Terrain->GetNode()->SetVisible(true);
		GUIContext->GetConsole()->AddMessage("Terrain View Enabled");
		TerrainButton->SetText("Disable Terrain");
	}
}

void CGUITerrainControlWidget::OnToggleWater(Gwen::Controls::Base * Control)
{
	CProgramContext * Context = & CProgramContext::Get();

	if (Context->Scene.Water->IsVisible())
	{
		Context->Scene.Water->SetVisible(false);
		GUIContext->GetConsole()->AddMessage("Water View Disabled");
		WaterButton->SetText("Enable Water");
	}
	else
	{
		Context->Scene.Water->SetVisible(true);
		GUIContext->GetConsole()->AddMessage("Water View Enabled");
		WaterButton->SetText("Disable Water");
	}
}

void CGUITerrainControlWidget::OnSelectElevation(Gwen::Controls::Base * Control)
{
	CProgramContext * Context = & CProgramContext::Get();
	Context->Scene.Terrain->SetDebugHeightEnabled(true);
}

void CGUITerrainControlWidget::OnSelectColor(Gwen::Controls::Base * Control)
{
	CProgramContext * Context = & CProgramContext::Get();
	Context->Scene.Terrain->SetDebugHeightEnabled(false);
}

void CGUITerrainControlWidget::OnModeSelect(Gwen::Controls::Base * Control)
{
	CProgramContext * Context = & CProgramContext::Get();
	Gwen::Controls::ComboBox * Box = (Gwen::Controls::ComboBox *) Control;

	if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L"Solid"))
	{
		Context->Scene.Terrain->DebugMode = 0;
		Context->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);
	}
	else if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L"Wireframe"))
	{
		Context->Scene.Terrain->DebugMode = 0;
		Context->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, true);
	}
	else if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L"AO1"))
	{
		Context->Scene.Terrain->DebugMode = 1;
		Context->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);
	}
	else if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L"AO2"))
	{
		Context->Scene.Terrain->DebugMode = 2;
		Context->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);
	}
	else if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L"AO3"))
	{
		Context->Scene.Terrain->DebugMode = 3;
		Context->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);
	}
	else if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L"AO4"))
	{
		Context->Scene.Terrain->DebugMode = 4;
		Context->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);
	}
	else if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L"AO5"))
	{
		Context->Scene.Terrain->DebugMode = 5;
		Context->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);
	}
	else if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L"AO6"))
	{
		Context->Scene.Terrain->DebugMode = 6;
		Context->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);
	}
	else if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L"AO7"))
	{
		Context->Scene.Terrain->DebugMode = 7;
		Context->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);
	}
	else if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L"AO8"))
	{
		Context->Scene.Terrain->DebugMode = 8;
		Context->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);
	}
	else if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L"AO9"))
	{
		Context->Scene.Terrain->DebugMode = 9;
		Context->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);
	}
}

void CGUITerrainControlWidget::toggle()
{
	Window->SetHidden(Window->Visible());
}
<|endoftext|>


<commit_before>/* -------------------------------------------------------------------------- *
 *                       Simbody(tm): SimTKcommon                             *
 * -------------------------------------------------------------------------- *
 * This is part of the SimTK biosimulation toolkit originating from           *
 * Simbios, the NIH National Center for Physics-Based Simulation of           *
 * Biological Structures at Stanford, funded under the NIH Roadmap for        *
 * Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody.  *
 *                                                                            *
 * Portions copyright (c) 2008-12 Stanford University and the Authors.        *
 * Authors: Peter Eastman                                                     *
 * Contributors:                                                              *
 *                                                                            *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may    *
 * not use this file except in compliance with the License. You may obtain a  *
 * copy of the License at http://www.apache.org/licenses/LICENSE-2.0.         *
 *                                                                            *
 * Unless required by applicable law or agreed to in writing, software        *
 * distributed under the License is distributed on an "AS IS" BASIS,          *
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   *
 * See the License for the specific language governing permissions and        *
 * limitations under the License.                                             *
 * -------------------------------------------------------------------------- */

#include "ParallelExecutorImpl.h"
#include "SimTKcommon/internal/ParallelExecutor.h"

#include <iostream>
#include <string>
#include <algorithm>
#include <mutex>

using namespace std;

namespace SimTK {

static void threadBody(ThreadInfo& info);

ParallelExecutorImpl::ParallelExecutorImpl() : finished(false) {

    //By default, we use the total number of processors available of the
    //computer (including hyperthreads)
    numMaxThreads = ParallelExecutor::getNumProcessors();
    if(numMaxThreads <= 0)
      numMaxThreads = 1;
}
ParallelExecutorImpl::ParallelExecutorImpl(int numThreads) : finished(false) {

    // Set the maximum number of threads that we can use
    SimTK_APIARGCHECK_ALWAYS(numThreads > 0, "ParallelExecutorImpl",
                 "ParallelExecutorImpl", "Number of threads must be positive.");
    numMaxThreads = numThreads;
}
ParallelExecutorImpl::~ParallelExecutorImpl() {

    // Notify the threads that they should exit.

    std::unique_lock<std::mutex> lock(runMutex);
    finished = true;
    for (int i = 0; i < (int) threads.size(); ++i)
        threadInfo[i].running = true;
    runCondition.notify_all();
    lock.unlock();

    // Wait until all the threads have finished.

    for (int i = 0; i < (int) threads.size(); ++i)
        threads[i].join();
}
ParallelExecutorImpl* ParallelExecutorImpl::clone() const {
    return new ParallelExecutorImpl(numMaxThreads);
}
void ParallelExecutorImpl::execute(ParallelExecutor::Task& task, int times) {
  if (numMaxThreads < 2) {
      //(1) NON-PARALLEL CASE:
      // Nothing is actually going to get done in parallel, so we might as well
      // just execute the task directly and save the threading overhead.
      task.initialize();
      for (int i = 0; i < times; ++i)
          task.execute(i);
      task.finish();
      return;
    }

    //(2) PARALLEL CASE:
    // We launch the maximum number of threads and save them for later use
    if(threads.size() < (size_t)numMaxThreads)
    {
      // We do not support numMaxThreads changing for a given instance of
      // ParallelExecutor.
      assert(threads.size() == 0);
      threadInfo.reserve(numMaxThreads);
      threads.resize(numMaxThreads);
      for (int i = 0; i < numMaxThreads; ++i) {
          threadInfo.emplace_back(i, this);
          threads[i] = std::thread(threadBody, std::ref(threadInfo[i]));
      }
    }

    // Initialize fields to execute the new task.
    std::unique_lock<std::mutex> lock(runMutex);
    currentTask = &task;
    currentTaskCount = times;
    waitingThreadCount = 0;
    for (int i = 0; i < (int)threadInfo.size(); ++i) {
        threadInfo[i].running = true;
    }

    // Wake up the worker threads and wait until they finish.
    runCondition.notify_all();
    waitCondition.wait(lock,
        [&] { return waitingThreadCount == (int)threads.size(); });
    lock.unlock();
}
void ParallelExecutorImpl::incrementWaitingThreads() {
    std::lock_guard<std::mutex> lock(runMutex);
    getCurrentTask().finish();
    waitingThreadCount++;
    if (waitingThreadCount == (int)threads.size()) {
        waitCondition.notify_one();
    }
}

thread_local bool ParallelExecutorImpl::isWorker(false);

/**
 * This function contains the code executed by the worker threads.
 */

void threadBody(ThreadInfo& info) {
    ParallelExecutorImpl::isWorker = true;
    ParallelExecutorImpl& executor = *info.executor;
    int threadCount = executor.getThreadCount();
    while (!executor.isFinished()) {

        // Wait for a Task to come in.

        std::unique_lock<std::mutex> lock(executor.getMutex());
        executor.getCondition().wait(lock, [&] { return info.running; });
        lock.unlock();
        if (!executor.isFinished()) {

            // Execute the task for all the indices belonging to this thread.

            int count = executor.getCurrentTaskCount();
            ParallelExecutor::Task& task = executor.getCurrentTask();
            task.initialize();
            int index = info.index;

            try {
                while (index < count) {
                    task.execute(index);
                    index += threadCount;
                }
            }
            catch (const std::exception& ex) {
                std::cerr <<"The parallel task threw an unhandled exception:"<< std::endl;
                std::cerr <<ex.what()<< std::endl;
            }
            catch (...) {
                std::cerr <<"The parallel task threw an error."<< std::endl;
            }
            info.running = false;
            executor.incrementWaitingThreads();
        }
    }
}

ParallelExecutor::ParallelExecutor() : HandleBase(new ParallelExecutorImpl()) {
}

ParallelExecutor::ParallelExecutor(int numThreads) : HandleBase(new ParallelExecutorImpl(numThreads)) {
}

ParallelExecutor* ParallelExecutor::clone() const{
    return new ParallelExecutor(getMaxThreads());
}

void ParallelExecutor::execute(Task& task, int times) {
    updImpl().execute(task, times);
}

#ifdef __APPLE__
   #include <sys/sysctl.h>
   #include <dlfcn.h>
#elif _WIN32
   #include <windows.h>
#elif __linux__
   #include <dlfcn.h>
   #include <unistd.h>
#else
  #error "Architecture unsupported"
#endif

int ParallelExecutor::getNumProcessors() {
#ifdef __APPLE__
    int ncpu,retval;
    size_t len = 4;

    retval = sysctlbyname( "hw.physicalcpu", &ncpu, &len, NULL, 0 );
    if( retval == 0 ) {
       return (ncpu );
    } else {
       return(1);
    }
#else
#ifdef __linux__
    long nProcessorsOnline     = sysconf(_SC_NPROCESSORS_ONLN);
    if( nProcessorsOnline == -1 )  {
        return(1);
    } else {
        return( (int)nProcessorsOnline );
    }
#else
    // Windows

    SYSTEM_INFO siSysInfo;
    int ncpu;

    // Copy the hardware information to the SYSTEM_INFO structure.

    GetSystemInfo(&siSysInfo);

    // Display the contents of the SYSTEM_INFO structure.

    ncpu =  siSysInfo.dwNumberOfProcessors;
    if( ncpu < 1 ) ncpu = 1;
    return(ncpu);
#endif
#endif
}

bool ParallelExecutor::isWorkerThread() {
    return ParallelExecutorImpl::isWorker;
}
int ParallelExecutor::getMaxThreads() const{
    return getImpl().getMaxThreads();
}

} // namespace SimTK
<commit_msg>Fix build on FreeBSD (#726)<commit_after>/* -------------------------------------------------------------------------- *
 *                       Simbody(tm): SimTKcommon                             *
 * -------------------------------------------------------------------------- *
 * This is part of the SimTK biosimulation toolkit originating from           *
 * Simbios, the NIH National Center for Physics-Based Simulation of           *
 * Biological Structures at Stanford, funded under the NIH Roadmap for        *
 * Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody.  *
 *                                                                            *
 * Portions copyright (c) 2008-12 Stanford University and the Authors.        *
 * Authors: Peter Eastman                                                     *
 * Contributors:                                                              *
 *                                                                            *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may    *
 * not use this file except in compliance with the License. You may obtain a  *
 * copy of the License at http://www.apache.org/licenses/LICENSE-2.0.         *
 *                                                                            *
 * Unless required by applicable law or agreed to in writing, software        *
 * distributed under the License is distributed on an "AS IS" BASIS,          *
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   *
 * See the License for the specific language governing permissions and        *
 * limitations under the License.                                             *
 * -------------------------------------------------------------------------- */

#include "ParallelExecutorImpl.h"
#include "SimTKcommon/internal/ParallelExecutor.h"

#include <iostream>
#include <string>
#include <algorithm>
#include <mutex>

using namespace std;

namespace SimTK {

static void threadBody(ThreadInfo& info);

ParallelExecutorImpl::ParallelExecutorImpl() : finished(false) {

    //By default, we use the total number of processors available of the
    //computer (including hyperthreads)
    numMaxThreads = ParallelExecutor::getNumProcessors();
    if(numMaxThreads <= 0)
      numMaxThreads = 1;
}
ParallelExecutorImpl::ParallelExecutorImpl(int numThreads) : finished(false) {

    // Set the maximum number of threads that we can use
    SimTK_APIARGCHECK_ALWAYS(numThreads > 0, "ParallelExecutorImpl",
                 "ParallelExecutorImpl", "Number of threads must be positive.");
    numMaxThreads = numThreads;
}
ParallelExecutorImpl::~ParallelExecutorImpl() {

    // Notify the threads that they should exit.

    std::unique_lock<std::mutex> lock(runMutex);
    finished = true;
    for (int i = 0; i < (int) threads.size(); ++i)
        threadInfo[i].running = true;
    runCondition.notify_all();
    lock.unlock();

    // Wait until all the threads have finished.

    for (int i = 0; i < (int) threads.size(); ++i)
        threads[i].join();
}
ParallelExecutorImpl* ParallelExecutorImpl::clone() const {
    return new ParallelExecutorImpl(numMaxThreads);
}
void ParallelExecutorImpl::execute(ParallelExecutor::Task& task, int times) {
  if (numMaxThreads < 2) {
      //(1) NON-PARALLEL CASE:
      // Nothing is actually going to get done in parallel, so we might as well
      // just execute the task directly and save the threading overhead.
      task.initialize();
      for (int i = 0; i < times; ++i)
          task.execute(i);
      task.finish();
      return;
    }

    //(2) PARALLEL CASE:
    // We launch the maximum number of threads and save them for later use
    if(threads.size() < (size_t)numMaxThreads)
    {
      // We do not support numMaxThreads changing for a given instance of
      // ParallelExecutor.
      assert(threads.size() == 0);
      threadInfo.reserve(numMaxThreads);
      threads.resize(numMaxThreads);
      for (int i = 0; i < numMaxThreads; ++i) {
          threadInfo.emplace_back(i, this);
          threads[i] = std::thread(threadBody, std::ref(threadInfo[i]));
      }
    }

    // Initialize fields to execute the new task.
    std::unique_lock<std::mutex> lock(runMutex);
    currentTask = &task;
    currentTaskCount = times;
    waitingThreadCount = 0;
    for (int i = 0; i < (int)threadInfo.size(); ++i) {
        threadInfo[i].running = true;
    }

    // Wake up the worker threads and wait until they finish.
    runCondition.notify_all();
    waitCondition.wait(lock,
        [&] { return waitingThreadCount == (int)threads.size(); });
    lock.unlock();
}
void ParallelExecutorImpl::incrementWaitingThreads() {
    std::lock_guard<std::mutex> lock(runMutex);
    getCurrentTask().finish();
    waitingThreadCount++;
    if (waitingThreadCount == (int)threads.size()) {
        waitCondition.notify_one();
    }
}

thread_local bool ParallelExecutorImpl::isWorker(false);

/**
 * This function contains the code executed by the worker threads.
 */

void threadBody(ThreadInfo& info) {
    ParallelExecutorImpl::isWorker = true;
    ParallelExecutorImpl& executor = *info.executor;
    int threadCount = executor.getThreadCount();
    while (!executor.isFinished()) {

        // Wait for a Task to come in.

        std::unique_lock<std::mutex> lock(executor.getMutex());
        executor.getCondition().wait(lock, [&] { return info.running; });
        lock.unlock();
        if (!executor.isFinished()) {

            // Execute the task for all the indices belonging to this thread.

            int count = executor.getCurrentTaskCount();
            ParallelExecutor::Task& task = executor.getCurrentTask();
            task.initialize();
            int index = info.index;

            try {
                while (index < count) {
                    task.execute(index);
                    index += threadCount;
                }
            }
            catch (const std::exception& ex) {
                std::cerr <<"The parallel task threw an unhandled exception:"<< std::endl;
                std::cerr <<ex.what()<< std::endl;
            }
            catch (...) {
                std::cerr <<"The parallel task threw an error."<< std::endl;
            }
            info.running = false;
            executor.incrementWaitingThreads();
        }
    }
}

ParallelExecutor::ParallelExecutor() : HandleBase(new ParallelExecutorImpl()) {
}

ParallelExecutor::ParallelExecutor(int numThreads) : HandleBase(new ParallelExecutorImpl(numThreads)) {
}

ParallelExecutor* ParallelExecutor::clone() const{
    return new ParallelExecutor(getMaxThreads());
}

void ParallelExecutor::execute(Task& task, int times) {
    updImpl().execute(task, times);
}

#ifdef __APPLE__
   #include <sys/sysctl.h>
   #include <dlfcn.h>
#elif __FreeBSD__
    #include <sys/types.h>
    #include <sys/sysctl.h>
#elif _WIN32
   #include <windows.h>
#elif __linux__
   #include <dlfcn.h>
   #include <unistd.h>
#else
  #error "Architecture unsupported"
#endif

int ParallelExecutor::getNumProcessors() {
#ifdef __APPLE__
    int ncpu,retval;
    size_t len = 4;

    retval = sysctlbyname( "hw.physicalcpu", &ncpu, &len, NULL, 0 );
    if( retval == 0 ) {
       return (ncpu );
    } else {
       return(1);
    }
#elif defined(__FreeBSD__)
    int mib[2];
    int ncpu;
    size_t szNcpu = sizeof(ncpu);

    mib[0] = CTL_HW;
    mib[1] = HW_NCPU;
    int ret = sysctl(mib, 2, &ncpu, &szNcpu, NULL, 0);
    return ret == 0 ? ncpu : 1;
#elif defined(__linux__)
    long nProcessorsOnline     = sysconf(_SC_NPROCESSORS_ONLN);
    if( nProcessorsOnline == -1 )  {
        return(1);
    } else {
        return( (int)nProcessorsOnline );
    }
#elif defined(_WIN32)
    // Windows

    SYSTEM_INFO siSysInfo;
    int ncpu;

    // Copy the hardware information to the SYSTEM_INFO structure.

    GetSystemInfo(&siSysInfo);

    // Display the contents of the SYSTEM_INFO structure.

    ncpu =  siSysInfo.dwNumberOfProcessors;
    if( ncpu < 1 ) ncpu = 1;
    return(ncpu);
#else
  #error "Architecture unsupported"
#endif
}

bool ParallelExecutor::isWorkerThread() {
    return ParallelExecutorImpl::isWorker;
}
int ParallelExecutor::getMaxThreads() const{
    return getImpl().getMaxThreads();
}

} // namespace SimTK
<|endoftext|>


<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1        *
*                (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This program is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU General Public License as published by the Free  *
* Software Foundation; either version 2 of the License, or (at your option)   *
* any later version.                                                          *
*                                                                             *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for    *
* more details.                                                               *
*                                                                             *
* You should have received a copy of the GNU General Public License along     *
* with this program; if not, write to the Free Software Foundation, Inc., 51  *
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.                   *
*******************************************************************************
*                            SOFA :: Applications                             *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#define MY_PARAM_TYPE(name, DType, MType) \
    struct name { \
        typedef DType DataType; \
        typedef MType MassType; \
    }; \

#include "Sofa_test.h"

#include <SofaBaseMechanics/DiagonalMass.h>

namespace sofa {

template <class T>
class SOFA_TestPlugin_API DiagonalMass_test : public ::testing::Test
{
public :

    typedef typename T::DataType dt;
    typedef typename T::MassType mt;
    typedef sofa::component::mass::DiagonalMass<dt,mt> DiagonalMassType;
    typename DiagonalMassType::SPtr m;

    /**
     * Constructor call for each test
     */
    virtual void SetUp(){}
};

TYPED_TEST_CASE_P(DiagonalMass_test);

TYPED_TEST_P(DiagonalMass_test, fakeTest1)
{
    EXPECT_EQ(0,0);
    std::cout << this->m->templateName() << std::endl;
}

TYPED_TEST_P(DiagonalMass_test, fakeTest2)
{
    EXPECT_EQ(0,1);
    std::cout << this->m->templateName() << std::endl;
}

REGISTER_TYPED_TEST_CASE_P(DiagonalMass_test, fakeTest1, fakeTest2);

MY_PARAM_TYPE(Vec3dd, sofa::defaulttype::Vec3dTypes, double)
MY_PARAM_TYPE(Vec2dd, sofa::defaulttype::Vec2dTypes, double)
MY_PARAM_TYPE(Vec1dd, sofa::defaulttype::Vec1dTypes, double)

INSTANTIATE_TYPED_TEST_CASE_P(DiagonalMass_test_case1, DiagonalMass_test, Vec3dd);
INSTANTIATE_TYPED_TEST_CASE_P(DiagonalMass_test_case2, DiagonalMass_test, Vec2dd);
INSTANTIATE_TYPED_TEST_CASE_P(DiagonalMass_test_case3, DiagonalMass_test, Vec1dd);

} // namespace sofa
<commit_msg>Fix test in DiagonalMass<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1        *
*                (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This program is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU General Public License as published by the Free  *
* Software Foundation; either version 2 of the License, or (at your option)   *
* any later version.                                                          *
*                                                                             *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for    *
* more details.                                                               *
*                                                                             *
* You should have received a copy of the GNU General Public License along     *
* with this program; if not, write to the Free Software Foundation, Inc., 51  *
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.                   *
*******************************************************************************
*                            SOFA :: Applications                             *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#define MY_PARAM_TYPE(name, DType, MType) \
    struct name { \
        typedef DType DataType; \
        typedef MType MassType; \
    }; \

#include "Sofa_test.h"

#include <SofaBaseMechanics/DiagonalMass.h>

//TODO : Perform smart tests :) Infrastructure for multi templated tests is ok.

namespace sofa {

template <class T>
class SOFA_TestPlugin_API DiagonalMass_test : public ::testing::Test
{
public :

    typedef typename T::DataType dt;
    typedef typename T::MassType mt;
    typedef sofa::component::mass::DiagonalMass<dt,mt> DiagonalMassType;
    typename DiagonalMassType::SPtr m;

    /**
     * Constructor call for each test
     */
    virtual void SetUp(){}
};

TYPED_TEST_CASE_P(DiagonalMass_test);

TYPED_TEST_P(DiagonalMass_test, fakeTest1)
{
    EXPECT_EQ(0,0);
}

TYPED_TEST_P(DiagonalMass_test, fakeTest2)
{
    EXPECT_EQ(1,1);
}

REGISTER_TYPED_TEST_CASE_P(DiagonalMass_test, fakeTest1, fakeTest2);

MY_PARAM_TYPE(Vec3dd, sofa::defaulttype::Vec3dTypes, double)
MY_PARAM_TYPE(Vec2dd, sofa::defaulttype::Vec2dTypes, double)
MY_PARAM_TYPE(Vec1dd, sofa::defaulttype::Vec1dTypes, double)

INSTANTIATE_TYPED_TEST_CASE_P(DiagonalMass_test_case1, DiagonalMass_test, Vec3dd);
INSTANTIATE_TYPED_TEST_CASE_P(DiagonalMass_test_case2, DiagonalMass_test, Vec2dd);
INSTANTIATE_TYPED_TEST_CASE_P(DiagonalMass_test_case3, DiagonalMass_test, Vec1dd);

} // namespace sofa
<|endoftext|>