<commit_before>#include "../../../shared/SystemImplBase.h"

#include "common/RhoConf.h"
#include "logging/RhoLog.h"
#include "../../platform/shared/qt/rhodes/impl/MainWindowImpl.h"
#include "../../platform/shared/qt/rhodes/RhoSimulator.h"

#undef null
#include <qwebkitglobal.h>
#if QT_VERSION >= 0x050000
#include <QtWebKit/qtwebkitversion.h>
#endif
#include <QLocale>
#include <QDesktopServices>
#include <QUrl>

#undef DEFAULT_LOGCATEGORY
#define DEFAULT_LOGCATEGORY "System"

namespace rho {

using namespace apiGenerator;

class CSystemImpl: public CSystemImplBase
{
public:
    CSystemImpl(): CSystemImplBase(){}

    virtual void getScreenWidth(CMethodResult& oResult);
    virtual void getScreenHeight(CMethodResult& oResult);
    virtual void getScreenOrientation(CMethodResult& oResult);
    virtual void getPpiX(CMethodResult& oResult);
    virtual void getPpiY(CMethodResult& oResult);
    virtual void getPhoneId(CMethodResult& oResult);
    virtual void getDeviceName(CMethodResult& oResult);
    virtual void getOsVersion(CMethodResult& oResult);
    virtual void getLocale(CMethodResult& oResult);
    virtual void getCountry(CMethodResult& oResult);
    virtual void getIsEmulator(CMethodResult& oResult);
    virtual void getHasCalendar(CMethodResult& oResult);
    virtual void getOemInfo(CMethodResult& oResult);
    virtual void getUuid(CMethodResult& oResult);
    virtual void getHttpProxyURI(CMethodResult& oResult);
    virtual void setHttpProxyURI( const rho::String& value, CMethodResult& oResult);
    virtual void getLockWindowSize(CMethodResult& oResult);
    virtual void setLockWindowSize( bool value, CMethodResult& oResult);
    //virtual void getKeyboardState(CMethodResult& oResult);
    //virtual void setKeyboardState( const rho::String& value, CMethodResult& oResult);
    virtual void getFullScreen(CMethodResult& oResult);
    virtual void setFullScreen( bool value, CMethodResult& oResult);
    virtual void getScreenAutoRotate(CMethodResult& oResult);
    virtual void setScreenAutoRotate( bool value, CMethodResult& oResult);
    virtual void getHasTouchscreen(rho::apiGenerator::CMethodResult& oResult);
    virtual void getScreenSleeping(rho::apiGenerator::CMethodResult& oResult);
    virtual void setScreenSleeping( bool value, rho::apiGenerator::CMethodResult& oResult);

    virtual void applicationInstall( const rho::String& applicationUrl, CMethodResult& oResult);
    virtual void isApplicationInstalled( const rho::String& applicationName, CMethodResult& oResult);
    virtual void applicationUninstall( const rho::String& applicationName, CMethodResult& oResult);
    virtual void openUrl( const rho::String& url, CMethodResult& oResult);
    //virtual void setRegistrySetting( int hive,  int type,  const rho::String& subKey,  const rho::String& setting,  const rho::String& value, rho::apiGenerator::CMethodResult& oResult);
    //virtual void getRegistrySetting( int hive,  const rho::String& subKey,  const rho::String& setting, rho::apiGenerator::CMethodResult& oResult);
    virtual void setWindowFrame( int x,  int y,  int width,  int height, CMethodResult& oResult);
    virtual void setWindowPosition( int x,  int y, CMethodResult& oResult);
    virtual void setWindowSize( int width,  int height, rho::apiGenerator::CMethodResult& oResult);
    virtual void getWebviewFramework(rho::apiGenerator::CMethodResult& oResult);
    virtual void bringToFront(rho::apiGenerator::CMethodResult& oResult);
    virtual void runApplication( const rho::String& appName,  const rho::String& params,  bool blockingCall, rho::apiGenerator::CMethodResult& oResult);
    virtual void getMain_window_closed(rho::apiGenerator::CMethodResult& oResult);

    virtual void set_http_proxy_url( const rho::String& proxyURI, rho::apiGenerator::CMethodResult& oResult);
    virtual void unset_http_proxy(rho::apiGenerator::CMethodResult& oResult);
};

void CSystemImpl::getOsVersion(CMethodResult& oResult)
{
    oResult.set(String(RHOSIMULATOR_NAME " v" RHOSIMULATOR_VERSION));
}

void CSystemImpl::getIsEmulator(CMethodResult& oResult)
{
    oResult.set(true);
}

void CSystemImpl::getScreenWidth(CMethodResult& oResult)
{
    oResult.set(CMainWindow::getScreenWidth());
}

void CSystemImpl::getScreenHeight(CMethodResult& oResult)
{
    oResult.set(CMainWindow::getScreenHeight());
}

void CSystemImpl::getScreenOrientation(CMethodResult& oResult)
{
    oResult.set(StringW(CMainWindow::getScreenWidth() <= CMainWindow::getScreenHeight() ? L"portrait" : L"landscape"));
}

void CSystemImpl::getPpiX(CMethodResult& oResult)
{
    oResult.set(CMainWindow::getInstance()->getLogicalDpiX());
}

void CSystemImpl::getPpiY(CMethodResult& oResult)
{
    oResult.set(CMainWindow::getInstance()->getLogicalDpiY());
}

void CSystemImpl::getPhoneId(CMethodResult& oResult)
{
    //oResult.set(...);
    getOsVersion(oResult);
}

void CSystemImpl::getDeviceName(CMethodResult& oResult)
{
#ifdef RHODES_EMULATOR
    oResult.set(String("RhoSimulator"));
#else
    oResult.set(String("Qt"));
#endif
}

void CSystemImpl::getLocale(CMethodResult& oResult)
{
    oResult.set(String(QLocale::system().name().left(2).toStdString().c_str()));
}

void CSystemImpl::getCountry(CMethodResult& oResult)
{
    oResult.set(String(QLocale::system().name().right(2).toStdString().c_str()));
}

void CSystemImpl::getHasCalendar(CMethodResult& oResult)
{
	oResult.set(true);
}

void CSystemImpl::getOemInfo(CMethodResult& oResult)
{
    //oResult.set(...);
}

void CSystemImpl::getUuid(CMethodResult& oResult)
{
    //oResult.set(...);
}

void CSystemImpl::getLockWindowSize(CMethodResult& oResult){}
void CSystemImpl::setLockWindowSize( bool value, CMethodResult& oResult){}
//void CSystemImpl::getKeyboardState(CMethodResult& oResult){}
//void CSystemImpl::setKeyboardState( const rho::String& value, CMethodResult& oResult){}
void CSystemImpl::getFullScreen(CMethodResult& oResult)
{
	//all apps working in full screen mode on WP8
    oResult.set(CMainWindow::getInstance()->getFullScreen());
}
void CSystemImpl::setFullScreen(bool value, CMethodResult& oResult)
{
    CMainWindow::getInstance()->fullscreenCommand(value);
}

void CSystemImpl::getScreenAutoRotate(CMethodResult& oResult)
{
    oResult.set(false);
}

void CSystemImpl::setScreenAutoRotate( bool value, CMethodResult& oResult)
{
    // TODO: impolement auto rotate
}

void CSystemImpl::applicationInstall( const rho::String& applicationUrl, CMethodResult& oResult)
{
}

void CSystemImpl::isApplicationInstalled( const rho::String& applicationName, CMethodResult& oResult)
{
	oResult.set(false);
}

void CSystemImpl::applicationUninstall( const rho::String& applicationName, CMethodResult& oResult)
{
}

void CSystemImpl::openUrl( const rho::String& url, CMethodResult& oResult)
{
    QString sUrl = QString::fromStdString(url);
    if (sUrl.startsWith("/"))
        sUrl.prepend("file://");
    QDesktopServices::openUrl(QUrl(sUrl));
}

void CSystemImpl::getMain_window_closed(rho::apiGenerator::CMethodResult& oResult)
{
    oResult.set(CMainWindow::mainWindowClosed);
}

void CSystemImpl::runApplication( const rho::String& appName,  const rho::String& params,  bool blockingCall, CMethodResult& oResult)
{
    //unsupported
}

/* use default implementation from SystemImplBase.cpp
void CSystemImpl::setRegistrySetting( int hive,  int type,  const rho::String& subKey,  const rho::String& setting,  const rho::String& value, rho::apiGenerator::CMethodResult& oResult)
{
	//unsupported
}

void CSystemImpl::getRegistrySetting( int hive,  const rho::String& subKey,  const rho::String& setting, rho::apiGenerator::CMethodResult& oResult)
{
	//unsupported
}
*/

void CSystemImpl::setWindowFrame(int x,  int y,  int width,  int height, CMethodResult& oResult)
{
    CMainWindow::getInstance()->setFrame(x, y, width, height);
}
void CSystemImpl::setWindowPosition( int x,  int y, CMethodResult& oResult)
{
    CMainWindow::getInstance()->setPosition(x, y);
}

extern "C" const char* rho_sys_qt_getWebviewFramework();
void CSystemImpl::getWebviewFramework(rho::apiGenerator::CMethodResult& oResult)
{
    oResult.set(String(rho_sys_qt_getWebviewFramework()));
}

void CSystemImpl::bringToFront(rho::apiGenerator::CMethodResult& oResult)
{
    CMainWindow::getInstance()->bringToFront();
}

extern "C" const char* rho_sys_get_http_proxy_url();
extern "C" void rho_sys_set_http_proxy_url(const char* url);
extern "C" void rho_sys_unset_http_proxy();
void CSystemImpl::getHttpProxyURI(CMethodResult& oResult)
{
	oResult.set(rho_sys_get_http_proxy_url());
}

void CSystemImpl::setHttpProxyURI( const rho::String& value, CMethodResult& oResult)
{
	if ( value.length() )
        rho_sys_set_http_proxy_url( value.c_str() );
    else
        rho_sys_unset_http_proxy();
}

void CSystemImpl::getHasTouchscreen(rho::apiGenerator::CMethodResult& oResult)
{
	oResult.set(true);
}

void CSystemImpl::getScreenSleeping(rho::apiGenerator::CMethodResult& oResult)
{
    oResult.set(false);
}

void CSystemImpl::setScreenSleeping( bool value, rho::apiGenerator::CMethodResult& oResult)
{
    //unsupported
}

void CSystemImpl::setWindowSize( int width,  int height, rho::apiGenerator::CMethodResult& oResult)
{
    CMainWindow::getInstance()->setSize(width, height);
}

void CSystemImpl::set_http_proxy_url( const rho::String& proxyURI, rho::apiGenerator::CMethodResult& oResult)
{
	rho_sys_set_http_proxy_url( proxyURI.c_str() );
}

void CSystemImpl::unset_http_proxy(rho::apiGenerator::CMethodResult& oResult)
{
	rho_sys_unset_http_proxy();
}

////////////////////////////////////////////////////////////////////////
class CSystemSingleton: public CModuleSingletonBase<ISystemSingleton>
{
public:
    ~CSystemSingleton(){}
    rho::StringW getInitialDefaultID(){return L"1";}
	rho::StringW getDefaultID(){return L"1";}
	void setDefaultID(const rho::StringW& strI){}
};

class CSystemFactory: public CSystemFactoryBase
{
public:
    ~CSystemFactory(){}

    ISystemSingleton* createModuleSingleton(){ return new CSystemImpl(); }
};

extern "C" void Init_System()
{
    CSystemFactory::setInstance( new CSystemFactory() );
    Init_System_API();

    RHODESAPP().getExtManager().requireRubyFile("RhoSystemApi");
}

}
<commit_msg>Update CSystemImpl.cpp<commit_after>#include "../../../shared/SystemImplBase.h"

#include "common/RhoConf.h"
#include "logging/RhoLog.h"
#include "../../platform/shared/qt/rhodes/impl/MainWindowImpl.h"
#include "../../platform/shared/qt/rhodes/RhoSimulator.h"

#undef null
#include <qwebkitglobal.h>
#if QT_VERSION >= 0x050000
#include <QtWebKit/qtwebkitversion.h>
#endif
#include <QLocale>
#include <QDesktopServices>
#include <QUrl>

#undef DEFAULT_LOGCATEGORY
#define DEFAULT_LOGCATEGORY "System"

namespace rho {

using namespace apiGenerator;

class CSystemImpl: public CSystemImplBase
{
public:
    CSystemImpl(): CSystemImplBase(){}

    virtual void getScreenWidth(CMethodResult& oResult);
    virtual void getScreenHeight(CMethodResult& oResult);
    virtual void getScreenOrientation(CMethodResult& oResult);
    virtual void getPpiX(CMethodResult& oResult);
    virtual void getPpiY(CMethodResult& oResult);
    virtual void getPhoneId(CMethodResult& oResult);
    virtual void getDeviceName(CMethodResult& oResult);
    virtual void getOsVersion(CMethodResult& oResult);
    virtual void getIsMotorolaDevice(CMethodResult& oResult);
    virtual void getLocale(CMethodResult& oResult);
    virtual void getCountry(CMethodResult& oResult);
    virtual void getIsEmulator(CMethodResult& oResult);
    virtual void getHasCalendar(CMethodResult& oResult);
    virtual void getOemInfo(CMethodResult& oResult);
    virtual void getUuid(CMethodResult& oResult);
    virtual void getHttpProxyURI(CMethodResult& oResult);
    virtual void setHttpProxyURI( const rho::String& value, CMethodResult& oResult);
    virtual void getLockWindowSize(CMethodResult& oResult);
    virtual void setLockWindowSize( bool value, CMethodResult& oResult);
    //virtual void getKeyboardState(CMethodResult& oResult);
    //virtual void setKeyboardState( const rho::String& value, CMethodResult& oResult);
    virtual void getFullScreen(CMethodResult& oResult);
    virtual void setFullScreen( bool value, CMethodResult& oResult);
    virtual void getScreenAutoRotate(CMethodResult& oResult);
    virtual void setScreenAutoRotate( bool value, CMethodResult& oResult);
    virtual void getHasTouchscreen(rho::apiGenerator::CMethodResult& oResult);
    virtual void getScreenSleeping(rho::apiGenerator::CMethodResult& oResult);
    virtual void setScreenSleeping( bool value, rho::apiGenerator::CMethodResult& oResult);

    virtual void applicationInstall( const rho::String& applicationUrl, CMethodResult& oResult);
    virtual void isApplicationInstalled( const rho::String& applicationName, CMethodResult& oResult);
    virtual void applicationUninstall( const rho::String& applicationName, CMethodResult& oResult);
    virtual void openUrl( const rho::String& url, CMethodResult& oResult);
    //virtual void setRegistrySetting( int hive,  int type,  const rho::String& subKey,  const rho::String& setting,  const rho::String& value, rho::apiGenerator::CMethodResult& oResult);
    //virtual void getRegistrySetting( int hive,  const rho::String& subKey,  const rho::String& setting, rho::apiGenerator::CMethodResult& oResult);
    virtual void setWindowFrame( int x,  int y,  int width,  int height, CMethodResult& oResult);
    virtual void setWindowPosition( int x,  int y, CMethodResult& oResult);
    virtual void setWindowSize( int width,  int height, rho::apiGenerator::CMethodResult& oResult);
    virtual void getWebviewFramework(rho::apiGenerator::CMethodResult& oResult);
    virtual void bringToFront(rho::apiGenerator::CMethodResult& oResult);
    virtual void runApplication( const rho::String& appName,  const rho::String& params,  bool blockingCall, rho::apiGenerator::CMethodResult& oResult);
    virtual void getMain_window_closed(rho::apiGenerator::CMethodResult& oResult);

    virtual void set_http_proxy_url( const rho::String& proxyURI, rho::apiGenerator::CMethodResult& oResult);
    virtual void unset_http_proxy(rho::apiGenerator::CMethodResult& oResult);
};

void CSystemImpl::getOsVersion(CMethodResult& oResult)
{
    oResult.set(String(RHOSIMULATOR_NAME " v" RHOSIMULATOR_VERSION));
}

void CSystemImpl::getIsEmulator(CMethodResult& oResult)
{
    oResult.set(true);
}

void CSystemImpl::getScreenWidth(CMethodResult& oResult)
{
    oResult.set(CMainWindow::getScreenWidth());
}

void CSystemImpl::getScreenHeight(CMethodResult& oResult)
{
    oResult.set(CMainWindow::getScreenHeight());
}

void CSystemImpl::getScreenOrientation(CMethodResult& oResult)
{
    oResult.set(StringW(CMainWindow::getScreenWidth() <= CMainWindow::getScreenHeight() ? L"portrait" : L"landscape"));
}

void CSystemImpl::getPpiX(CMethodResult& oResult)
{
    oResult.set(CMainWindow::getInstance()->getLogicalDpiX());
}

void CSystemImpl::getPpiY(CMethodResult& oResult)
{
    oResult.set(CMainWindow::getInstance()->getLogicalDpiY());
}

void CSystemImpl::getPhoneId(CMethodResult& oResult)
{
    //oResult.set(...);
    getOsVersion(oResult);
}

void CSystemImpl::getDeviceName(CMethodResult& oResult)
{
#ifdef RHODES_EMULATOR
    oResult.set(String("RhoSimulator"));
#else
    oResult.set(String("Qt"));
#endif
}

void CSystemImpl::getLocale(CMethodResult& oResult)
{
    oResult.set(String(QLocale::system().name().left(2).toStdString().c_str()));
}

void CSystemImpl::getCountry(CMethodResult& oResult)
{
    oResult.set(String(QLocale::system().name().right(2).toStdString().c_str()));
}

void CSystemImpl::getHasCalendar(CMethodResult& oResult)
{
	oResult.set(true);
}

void CSystemImpl::getIsMotorolaDevice(CMethodResult& oResult)
{
	oResult.set(false);
}

void CSystemImpl::getOemInfo(CMethodResult& oResult)
{
    //oResult.set(...);
}

void CSystemImpl::getUuid(CMethodResult& oResult)
{
    //oResult.set(...);
}

void CSystemImpl::getLockWindowSize(CMethodResult& oResult){}
void CSystemImpl::setLockWindowSize( bool value, CMethodResult& oResult){}
//void CSystemImpl::getKeyboardState(CMethodResult& oResult){}
//void CSystemImpl::setKeyboardState( const rho::String& value, CMethodResult& oResult){}
void CSystemImpl::getFullScreen(CMethodResult& oResult)
{
	//all apps working in full screen mode on WP8
    oResult.set(CMainWindow::getInstance()->getFullScreen());
}
void CSystemImpl::setFullScreen(bool value, CMethodResult& oResult)
{
    CMainWindow::getInstance()->fullscreenCommand(value);
}

void CSystemImpl::getScreenAutoRotate(CMethodResult& oResult)
{
    oResult.set(false);
}

void CSystemImpl::setScreenAutoRotate( bool value, CMethodResult& oResult)
{
    // TODO: impolement auto rotate
}

void CSystemImpl::applicationInstall( const rho::String& applicationUrl, CMethodResult& oResult)
{
}

void CSystemImpl::isApplicationInstalled( const rho::String& applicationName, CMethodResult& oResult)
{
	oResult.set(false);
}

void CSystemImpl::applicationUninstall( const rho::String& applicationName, CMethodResult& oResult)
{
}

void CSystemImpl::openUrl( const rho::String& url, CMethodResult& oResult)
{
    QString sUrl = QString::fromStdString(url);
    if (sUrl.startsWith("/"))
        sUrl.prepend("file://");
    QDesktopServices::openUrl(QUrl(sUrl));
}

void CSystemImpl::getMain_window_closed(rho::apiGenerator::CMethodResult& oResult)
{
    oResult.set(CMainWindow::mainWindowClosed);
}

void CSystemImpl::runApplication( const rho::String& appName,  const rho::String& params,  bool blockingCall, CMethodResult& oResult)
{
    //unsupported
}

/* use default implementation from SystemImplBase.cpp
void CSystemImpl::setRegistrySetting( int hive,  int type,  const rho::String& subKey,  const rho::String& setting,  const rho::String& value, rho::apiGenerator::CMethodResult& oResult)
{
	//unsupported
}

void CSystemImpl::getRegistrySetting( int hive,  const rho::String& subKey,  const rho::String& setting, rho::apiGenerator::CMethodResult& oResult)
{
	//unsupported
}
*/

void CSystemImpl::setWindowFrame(int x,  int y,  int width,  int height, CMethodResult& oResult)
{
    CMainWindow::getInstance()->setFrame(x, y, width, height);
}
void CSystemImpl::setWindowPosition( int x,  int y, CMethodResult& oResult)
{
    CMainWindow::getInstance()->setPosition(x, y);
}

extern "C" const char* rho_sys_qt_getWebviewFramework();
void CSystemImpl::getWebviewFramework(rho::apiGenerator::CMethodResult& oResult)
{
    oResult.set(String(rho_sys_qt_getWebviewFramework()));
}

void CSystemImpl::bringToFront(rho::apiGenerator::CMethodResult& oResult)
{
    CMainWindow::getInstance()->bringToFront();
}

extern "C" const char* rho_sys_get_http_proxy_url();
extern "C" void rho_sys_set_http_proxy_url(const char* url);
extern "C" void rho_sys_unset_http_proxy();
void CSystemImpl::getHttpProxyURI(CMethodResult& oResult)
{
	oResult.set(rho_sys_get_http_proxy_url());
}

void CSystemImpl::setHttpProxyURI( const rho::String& value, CMethodResult& oResult)
{
	if ( value.length() )
        rho_sys_set_http_proxy_url( value.c_str() );
    else
        rho_sys_unset_http_proxy();
}

void CSystemImpl::getHasTouchscreen(rho::apiGenerator::CMethodResult& oResult)
{
	oResult.set(true);
}

void CSystemImpl::getScreenSleeping(rho::apiGenerator::CMethodResult& oResult)
{
    oResult.set(false);
}

void CSystemImpl::setScreenSleeping( bool value, rho::apiGenerator::CMethodResult& oResult)
{
    //unsupported
}

void CSystemImpl::setWindowSize( int width,  int height, rho::apiGenerator::CMethodResult& oResult)
{
    CMainWindow::getInstance()->setSize(width, height);
}

void CSystemImpl::set_http_proxy_url( const rho::String& proxyURI, rho::apiGenerator::CMethodResult& oResult)
{
	rho_sys_set_http_proxy_url( proxyURI.c_str() );
}

void CSystemImpl::unset_http_proxy(rho::apiGenerator::CMethodResult& oResult)
{
	rho_sys_unset_http_proxy();
}

////////////////////////////////////////////////////////////////////////
class CSystemSingleton: public CModuleSingletonBase<ISystemSingleton>
{
public:
    ~CSystemSingleton(){}
    rho::StringW getInitialDefaultID(){return L"1";}
	rho::StringW getDefaultID(){return L"1";}
	void setDefaultID(const rho::StringW& strI){}
};

class CSystemFactory: public CSystemFactoryBase
{
public:
    ~CSystemFactory(){}

    ISystemSingleton* createModuleSingleton(){ return new CSystemImpl(); }
};

extern "C" void Init_System()
{
    CSystemFactory::setInstance( new CSystemFactory() );
    Init_System_API();

    RHODESAPP().getExtManager().requireRubyFile("RhoSystemApi");
}

}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkFEMLoadImplementationsRegister.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

// disable debug warnings in MS compiler
#ifdef _MSC_VER
#pragma warning(disable: 4786)
#endif

#include "itkVisitorDispatcher.h"
#include "itkFEMElements.h"
#include "itkFEMLoads.h"

namespace itk {
namespace fem {

/* This macro makes registering Load implementations easier. */
#ifndef FEM_USE_SMART_POINTERS
#define REGISTER_LOAD(ElementClass,LoadClass,FunctionName) \
  extern Element::LoadVectorType FunctionName(ElementClass::ConstPointer, LoadElement::Pointer); \
  VisitorDispatcher<ElementClass, LoadElement, Element::LoadVectorType>::RegisterVisitor((LoadClass*)0, &FunctionName);
#else
#define REGISTER_LOAD(ElementClass,LoadClass,FunctionName) \
  extern Element::LoadVectorType FunctionName(ElementClass::ConstPointer, FEMLightObject::Pointer); \
  VisitorDispatcher<ElementClass, FEMLightObject, Element::LoadVectorType>::RegisterVisitor((LoadClass*)0, &FunctionName);
#endif

/**
 * Registers all Load classes in the FEM library with VisitorDispatcher.
 * This function must be calles before the FEM library is functional!.
 */
void LoadImplementationsRegister(void)
{

  // Loads acting on Bar2D element
  REGISTER_LOAD( Bar2D,        LoadGrav,         LoadGravImplementation    );
  REGISTER_LOAD( Bar2D,        LoadGravConst,    LoadGravImplementation    );
  REGISTER_LOAD( Bar2D,        LoadPoint,        LoadPointImplementation   );

  // Loads acting on Beam2D element
  REGISTER_LOAD( Beam2D,       LoadGrav,         LoadGravImplementation    );
  REGISTER_LOAD( Beam2D,       LoadGravConst,    LoadGravImplementation    );
  REGISTER_LOAD( Beam2D,       LoadPoint,        LoadPointImplementation   );

  // Loads acting on TriC02D element
  REGISTER_LOAD( TriC02D,      LoadGrav,         LoadGravImplementation    );
  REGISTER_LOAD( TriC02D,      LoadGravConst,    LoadGravImplementation    );
  REGISTER_LOAD( TriC02D,      LoadEdge,         LoadEdgeImplementation    );

  // Loads acting on QuadC02D element
  REGISTER_LOAD( QuadC02D,     LoadGrav,         LoadGravImplementation    );
  REGISTER_LOAD( QuadC02D,     LoadGravConst,    LoadGravImplementation    );
  REGISTER_LOAD( QuadC02D,     LoadEdge,         LoadEdgeImplementation    );

  // Loads acting on C1IsoCurve2D element
  REGISTER_LOAD( C1IsoCurve2D, Load,             LoadImplementation        );

  // Add any additional loads here in a similar fashion...
  // Make sure that the pointer to visit function is the correct one!!!

}

}} // end namespace itk::fem
<commit_msg>ERR: compiler error in g++ on solaris.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkFEMLoadImplementationsRegister.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

// disable debug warnings in MS compiler
#ifdef _MSC_VER
#pragma warning(disable: 4786)
#endif

#include "itkVisitorDispatcher.h"
#include "itkFEMElements.h"
#include "itkFEMLoads.h"

namespace itk {
namespace fem {

/* This macro makes registering Load implementations easier. */
#ifndef FEM_USE_SMART_POINTERS
#define REGISTER_LOAD(ElementClass,LoadClass,FunctionName) \
  extern Element::LoadVectorType FunctionName(ElementClass::ConstPointer, LoadElement::Pointer); \
  VisitorDispatcher<ElementClass, LoadElement, Element::LoadVectorType>::RegisterVisitor((LoadClass*)0, &FunctionName);
#else
#define REGISTER_LOAD(ElementClass,LoadClass,FunctionName) \
  extern Element::LoadVectorType FunctionName(ElementClass::ConstPointer, FEMLightObject::Pointer); \
  VisitorDispatcher<ElementClass, FEMLightObject, Element::LoadVectorType>::RegisterVisitor((LoadClass*)0, &FunctionName);
#endif

/**
 * Registers all Load classes in the FEM library with VisitorDispatcher.
 * This function must be calles before the FEM library is functional!.
 */
void LoadImplementationsRegister(void)
{

  // Loads acting on Bar2D element
  REGISTER_LOAD( Bar2D,        LoadGrav,         LoadGravImplementation    );
  REGISTER_LOAD( Bar2D,        LoadGravConst,    LoadGravImplementation    );
  REGISTER_LOAD( Bar2D,        LoadPoint,        LoadPointImplementation   );

  // Loads acting on Beam2D element
  REGISTER_LOAD( Beam2D,       LoadGrav,         LoadGravImplementation    );
  REGISTER_LOAD( Beam2D,       LoadGravConst,    LoadGravImplementation    );
  REGISTER_LOAD( Beam2D,       LoadPoint,        LoadPointImplementation   );

  // Loads acting on TriC02D element
#if !(defined(__SVR4) && defined(sun))
  REGISTER_LOAD( TriC02D,      LoadGrav,         LoadGravImplementation    );
  REGISTER_LOAD( TriC02D,      LoadGravConst,    LoadGravImplementation    );
#endif
  REGISTER_LOAD( TriC02D,      LoadEdge,         LoadEdgeImplementation    );

  // Loads acting on QuadC02D element
#if !(defined(__SVR4) && defined(sun))
  REGISTER_LOAD( QuadC02D,     LoadGrav,         LoadGravImplementation    );
  REGISTER_LOAD( QuadC02D,     LoadGravConst,    LoadGravImplementation    );
#endif
  REGISTER_LOAD( QuadC02D,     LoadEdge,         LoadEdgeImplementation    );

  // Loads acting on C1IsoCurve2D element
  REGISTER_LOAD( C1IsoCurve2D, Load,             LoadImplementation        );

  // Add any additional loads here in a similar fashion...
  // Make sure that the pointer to visit function is the correct one!!!

}

}} // end namespace itk::fem
<|endoftext|>


<commit_before>
//@HEADER
// ***************************************************
//
// HPCG: High Performance Conjugate Gradient Benchmark
//
// Contact:
// Michael A. Heroux ( maherou@sandia.gov)
// Jack Dongarra     (dongarra@eecs.utk.edu)
// Piotr Luszczek    (luszczek@eecs.utk.edu)
//
// ***************************************************
//@HEADER

/*!
 @file ComputeResidual.cpp

 HPCG routine
 */
#ifndef HPCG_NO_MPI
#include <mpi.h>
#endif
#ifndef HPCG_NO_OPENMP
#include <omp.h>
#endif

#include "Vector.hpp"

#ifdef HPCG_DETAILED_DEBUG
#include <fstream>
#include "hpcg.hpp"
#endif

#include <cmath>  // needed for fabs
#include "ComputeResidual.hpp"
#ifdef HPCG_DETAILED_DEBUG
#include <iostream>
#endif

/*!
  Routine to compute the inf-norm difference between two vectors where:

  @param[in]  n        number of vector elements (local to this processor)
  @param[in]  v1, v2   input vectors
  @param[out] residual pointer to scalar value; on exit, will contain result: inf-norm difference

  @return Returns zero on success and a non-zero value otherwise.
*/
int ComputeResidual(const local_int_t n, const Vector & v1, const Vector & v2, double & residual) {

  double * v1v = v1.values;
  double * v2v = v2.values;
  double local_residual = 0.0;

#ifndef HPCG_NO_OPENMP
  #pragma omp parallel default(none) shared(local_residual, v1v, v2v)
  {
    double threadlocal_residual = 0.0;
    #pragma omp for
    for (local_int_t i=0; i<n; i++) {
      double diff = std::fabs(v1v[i] - v2v[i]);
      if (diff > threadlocal_residual) threadlocal_residual = diff;
    }
    #pragma omp critical
    {
      if (threadlocal_residual>local_residual) local_residual = threadlocal_residual;
    }
  }
#else // No threading
  for (local_int_t i=0; i<n; i++) {
    double diff = std::fabs(v1v[i] - v2v[i]);
    if (diff > local_residual) local_residual = diff;
#ifdef HPCG_DETAILED_DEBUG
    HPCG_fout << " Computed, exact, diff = " << v1v[i] << " " << v2v[i] << " " << diff << std::endl;
#endif
  }
#endif

#ifndef HPCG_NO_MPI
  // Use MPI's reduce function to collect all partial sums
  double global_residual = 0;
  MPI_Allreduce(&local_residual, &global_residual, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD);
  residual = global_residual;
#else
  residual = local_residual;
#endif

  return 0;
}
<commit_msg>Add missing variable designation, fixes issue #64<commit_after>
//@HEADER
// ***************************************************
//
// HPCG: High Performance Conjugate Gradient Benchmark
//
// Contact:
// Michael A. Heroux ( maherou@sandia.gov)
// Jack Dongarra     (dongarra@eecs.utk.edu)
// Piotr Luszczek    (luszczek@eecs.utk.edu)
//
// ***************************************************
//@HEADER

/*!
 @file ComputeResidual.cpp

 HPCG routine
 */
#ifndef HPCG_NO_MPI
#include <mpi.h>
#endif
#ifndef HPCG_NO_OPENMP
#include <omp.h>
#endif

#include "Vector.hpp"

#ifdef HPCG_DETAILED_DEBUG
#include <fstream>
#include "hpcg.hpp"
#endif

#include <cmath>  // needed for fabs
#include "ComputeResidual.hpp"
#ifdef HPCG_DETAILED_DEBUG
#include <iostream>
#endif

/*!
  Routine to compute the inf-norm difference between two vectors where:

  @param[in]  n        number of vector elements (local to this processor)
  @param[in]  v1, v2   input vectors
  @param[out] residual pointer to scalar value; on exit, will contain result: inf-norm difference

  @return Returns zero on success and a non-zero value otherwise.
*/
int ComputeResidual(const local_int_t n, const Vector & v1, const Vector & v2, double & residual) {

  double * v1v = v1.values;
  double * v2v = v2.values;
  double local_residual = 0.0;

#ifndef HPCG_NO_OPENMP
  #pragma omp parallel default(none) shared(n, local_residual, v1v, v2v)
  {
    double threadlocal_residual = 0.0;
    #pragma omp for
    for (local_int_t i=0; i<n; i++) {
      double diff = std::fabs(v1v[i] - v2v[i]);
      if (diff > threadlocal_residual) threadlocal_residual = diff;
    }
    #pragma omp critical
    {
      if (threadlocal_residual>local_residual) local_residual = threadlocal_residual;
    }
  }
#else // No threading
  for (local_int_t i=0; i<n; i++) {
    double diff = std::fabs(v1v[i] - v2v[i]);
    if (diff > local_residual) local_residual = diff;
#ifdef HPCG_DETAILED_DEBUG
    HPCG_fout << " Computed, exact, diff = " << v1v[i] << " " << v2v[i] << " " << diff << std::endl;
#endif
  }
#endif

#ifndef HPCG_NO_MPI
  // Use MPI's reduce function to collect all partial sums
  double global_residual = 0;
  MPI_Allreduce(&local_residual, &global_residual, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD);
  residual = global_residual;
#else
  residual = local_residual;
#endif

  return 0;
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/lib/p9_ppe_utils.H $       */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file  p9_ppe_utils.H
/// @brief PPE commonly used functions
///
/// *HWP HW Owner        : Ashish More <ashish.more.@in.ibm.com>
/// *HWP HW Backup Owner : Brian Vanderpool <vanderp@us.ibm.com>
/// *HWP FW Owner        : Sangeetha T S <sangeet2@in.ibm.com>
/// *HWP Team            : PM
/// *HWP Level           : 2
/// *HWP Consumed by     : CMEs, GPEs, SBE, Cronus
#include <map>
#ifndef __P9_PPE_UTILS_H__
#define __P9_PPE_UTILS_H__
typedef struct
{
    uint16_t    number;
    uint32_t    value;
} PPERegValue_t;

typedef struct
{
    PPERegValue_t     reg;
    std::string  name;
} PPEReg_t;

typedef struct
{
    uint16_t    number;
    uint64_t    value;
} SCOMRegValue_t;

typedef struct
{
    SCOMRegValue_t    reg;
    std::string  name;
} SCOMReg_t;
/**
 * @brief enumerates opcodes for few instructions.
 */
enum
{
    OPCODE_31         = 31,
    MTSPR_CONST1      = 467,
    MTSPR_BASE_OPCODE = (OPCODE_31 << (31 - 5)) | (MTSPR_CONST1 << (31 - 30)),
    MFSPR_CONST1      = 339,
    MFSPR_BASE_OPCODE = (OPCODE_31 << (31 - 5)) | (MFSPR_CONST1 << (31 - 30)),
    MFMSRD_CONST1     = 83,
    MFCR_CONST1       = 19,
    ANDIS_CONST       = 29,
    ORIS_CONST        = 25,
};

/**
 * @brief Offsets from base address for XIRs.
 */
const static uint64_t PPE_XIXCR    = 0x0; //XCR_NONE
const static uint64_t PPE_XIRAMRA  = 0x1; //XCR_SPRG0
const static uint64_t PPE_XIRAMGA  = 0x2; //IR_SPRG0
const static uint64_t PPE_XIRAMDBG = 0x3; //XSR_SPRG0
const static uint64_t PPE_XIRAMEDR = 0x4; //IR_EDR
const static uint64_t PPE_XIDBGPRO = 0x5; //XSR_IAR

enum PPE_DUMP_MODE
{
    NONE           = 0x0,
    XIRS           = 0x4,
    SNAPSHOT       = 0x1,
    HALT           = 0x2,
    FORCE_HALT     = 0x3
};
enum VERBOSE_MODE
{
    NOVERBOSE        = 0x0,
    VERBOSE          = 0x1,
    VERBOSEP         = 0x2,
    VERBOSE1         = 0x3,

};

enum INT_VEC_OFFSET
{
    MCHK_VEC = 0x000  ,  // 0,
    SRST_VEC = 0x040  ,  // 64,
    DSI_VEC  =  0x060 ,  // 96,
    ISI_VEC  =  0x080 ,  // 128,
    EXT_VEC  =  0x0A0 ,  // 160,
    ALIG_VEC = 0x0C0  ,  // 192,
    PRG_VEC  =  0x0E0 ,  // 224,
    DEC_VEC  =  0x100 ,  // 256,
    FIT_VEC  =  0x120 ,  // 288,
    WDT_VEC  =  0x140 ,  // 320,
} ;
enum PPE_XIRS
{
    XIR_XSR,
    XIR_IAR,
    XIR_IR,
    XIR_EDR,
    XIR_SPRG0,
};

//enum PPE_SPECIAL_ACCESS
//{
//    MSR,
//    CR,
//};
enum PPE_SPRS
{
    CTR     = 9,
    DACR    = 316,
    DBCR    = 308,
    DEC     = 22,
    EDR     = 61,
    IVPR    = 63,
    ISR     = 62,
    LR      = 8,
    PIR     = 286,
    PVR     = 287,
    SPRG0   = 272,
    SRR0    = 26,
    SRR1    = 27,
    TCR     = 340,
    TSR     = 336,
    XER     = 1,
    //Some unique identification no. FOR OTHER REGS(non sprn)
    XSR     = 4200,
    IAR     = 2,
    IR      = 3,
    MSR     = 42,
    CR      = 420,

};

// Note: EDR is available via XIR
enum PPE_GPRS
{
    R0  = 0,
    R1  = 1,
    R2  = 2,
    R3  = 3,
    R4  = 4,
    R5  = 5,
    R6  = 6,
    R7  = 7,
    R8  = 8,
    R9  = 9,
    R10 = 10,
    R13 = 13,
    R28 = 28,
    R29 = 29,
    R30 = 30,
    R31 = 31,
};
// Vector defining all spr acceess egisters
const std::map<uint16_t, std::string> v_ppe_sprs_num_name =
{
    { MSR,   "MSR"    },
    { CR,    "CR"     },
    { CTR,   "CTR"    },
    { LR,    "LR"     },
    { ISR,   "ISR"    },
    { SRR0,  "SRR0"   },
    { SRR1,  "SRR1"   },
    { TCR,   "TCR"    },
    { TSR,   "TSR"    },
    { DACR,  "DACR"   },
    { DBCR,  "DBCR"   },
    { DEC,   "DEC"    },
    { IVPR,  "IVPR"   },
    { PIR,   "PIR"    },
    { PVR,   "PVR"    },
    { XER,   "XER"    }
};

// Vector defining the GPRs
const std::map<uint16_t, std::string> v_ppe_gprs_num_name =
{
    { R0,    "R0"     },
    { R1,    "R1"     },
    { R2,    "R2"     },
    { R3,    "R3"     },
    { R4,    "R4"     },
    { R5,    "R5"     },
    { R6,    "R6"     },
    { R7,    "R7"     },
    { R8,    "R8"     },
    { R9,    "R9"     },
    { R10,   "R10"    },
    { R13,   "R13"    },
    { R28,   "R28"    },
    { R29,   "R29"    },
    { R30,   "R30"    },
    { R31,   "R31"    }
};
// Vector defining the other xsr regs
const std::map<uint16_t, std::string> v_ppe_xsr_num_name =
{
    { XSR,   "XSR"    },
    { IAR,   "IAR"    },
    { IR,    "IR"     },
    { EDR,   "EDR"    },
    { SPRG0, "SPRG0"  }
};

#endif  // __P9_PPE_UTILS_H__
<commit_msg>PM: PPE State tool fixes.<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/lib/p9_ppe_utils.H $       */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file  p9_ppe_utils.H
/// @brief PPE commonly used functions
///
/// *HWP HW Owner        : Ashish More <ashish.more.@in.ibm.com>
/// *HWP HW Backup Owner : Brian Vanderpool <vanderp@us.ibm.com>
/// *HWP FW Owner        : Sangeetha T S <sangeet2@in.ibm.com>
/// *HWP Team            : PM
/// *HWP Level           : 3
/// *HWP Consumed by     : Cronus, HB, FSP
#ifndef __P9_PPE_UTILS_H__
#define __P9_PPE_UTILS_H__
#include <map>
#include <fapi2.H>
typedef struct
{
    uint16_t    number;
    uint32_t    value;
} PPERegValue_t;

typedef struct
{
    uint16_t    number;
    uint64_t    value;
} SCOMRegValue_t;

/**
 * @brief enumerates opcodes for few instructions.
 */
enum
{
    OPCODE_31         = 31,
    MTSPR_CONST1      = 467,
    MTSPR_BASE_OPCODE = (OPCODE_31 << (31 - 5)) | (MTSPR_CONST1 << (31 - 30)),
    MFSPR_CONST1      = 339,
    MFSPR_BASE_OPCODE = (OPCODE_31 << (31 - 5)) | (MFSPR_CONST1 << (31 - 30)),
    MFMSRD_CONST1     = 83,
    MFCR_CONST1       = 19,
    ANDIS_CONST       = 29,
    ORIS_CONST        = 25,
};

/**
 * @brief Offsets from base address for XIRs.
 */
const static uint64_t PPE_XIXCR    = 0x0; //XCR_NONE
const static uint64_t PPE_XIRAMRA  = 0x1; //XCR_SPRG0
const static uint64_t PPE_XIRAMGA  = 0x2; //IR_SPRG0
const static uint64_t PPE_XIRAMDBG = 0x3; //XSR_SPRG0
const static uint64_t PPE_XIRAMEDR = 0x4; //IR_EDR
const static uint64_t PPE_XIDBGPRO = 0x5; //XSR_IAR

enum PPE_DUMP_MODE
{
    NONE           = 0x0,
    XIRS           = 0x4,
    SNAPSHOT       = 0x1,
    HALT           = 0x2,
    FORCE_HALT     = 0x3
};
enum VERBOSE_MODE
{
    NOVERBOSE        = 0x0,
    VERBOSE          = 0x1,
    VERBOSEP         = 0x2,
    VERBOSE1         = 0x3,

};

enum INT_VEC_OFFSET
{
    MCHK_VEC = 0x000  ,  // 0,
    SRST_VEC = 0x040  ,  // 64,
    DSI_VEC  =  0x060 ,  // 96,
    ISI_VEC  =  0x080 ,  // 128,
    EXT_VEC  =  0x0A0 ,  // 160,
    ALIG_VEC = 0x0C0  ,  // 192,
    PRG_VEC  =  0x0E0 ,  // 224,
    DEC_VEC  =  0x100 ,  // 256,
    FIT_VEC  =  0x120 ,  // 288,
    WDT_VEC  =  0x140 ,  // 320,
} ;
enum PPE_XIRS
{
    XIR_XSR,
    XIR_IAR,
    XIR_IR,
    XIR_EDR,
    XIR_SPRG0,
};

//enum PPE_SPECIAL_ACCESS
//{
//    MSR,
//    CR,
//};
enum PPE_SPRS
{
    CTR     = 9,
    DACR    = 316,
    DBCR    = 308,
    DEC     = 22,
    EDR     = 61,
    IVPR    = 63,
    ISR     = 62,
    LR      = 8,
    PIR     = 286,
    PVR     = 287,
    SPRG0   = 272,
    SRR0    = 26,
    SRR1    = 27,
    TCR     = 340,
    TSR     = 336,
    XER     = 1,
    //Some unique identification no. FOR OTHER REGS(non sprn)
    XSR     = 4200,
    IAR     = 2,
    IR      = 3,
    MSR     = 42,
    CR      = 420,

};

// Note: EDR is available via XIR
enum PPE_GPRS
{
    R0  = 0,
    R1  = 1,
    R2  = 2,
    R3  = 3,
    R4  = 4,
    R5  = 5,
    R6  = 6,
    R7  = 7,
    R8  = 8,
    R9  = 9,
    R10 = 10,
    R13 = 13,
    R28 = 28,
    R29 = 29,
    R30 = 30,
    R31 = 31,
};

#ifndef  __HOSTBOOT_MODULE
typedef struct
{
    SCOMRegValue_t    reg;
    std::string  name;
} SCOMReg_t;

typedef struct
{
    PPERegValue_t     reg;
    std::string  name;
} PPEReg_t;

// Vector defining all spr acceess egisters
const std::map<uint16_t, std::string> v_ppe_sprs_num_name =
{
    { MSR,   "MSR"    },
    { CR,    "CR"     },
    { CTR,   "CTR"    },
    { LR,    "LR"     },
    { ISR,   "ISR"    },
    { SRR0,  "SRR0"   },
    { SRR1,  "SRR1"   },
    { TCR,   "TCR"    },
    { TSR,   "TSR"    },
    { DACR,  "DACR"   },
    { DBCR,  "DBCR"   },
    { DEC,   "DEC"    },
    { IVPR,  "IVPR"   },
    { PIR,   "PIR"    },
    { PVR,   "PVR"    },
    { XER,   "XER"    }
};

// Vector defining the GPRs
const std::map<uint16_t, std::string> v_ppe_gprs_num_name =
{
    { R0,    "R0"     },
    { R1,    "R1"     },
    { R2,    "R2"     },
    { R3,    "R3"     },
    { R4,    "R4"     },
    { R5,    "R5"     },
    { R6,    "R6"     },
    { R7,    "R7"     },
    { R8,    "R8"     },
    { R9,    "R9"     },
    { R10,   "R10"    },
    { R13,   "R13"    },
    { R28,   "R28"    },
    { R29,   "R29"    },
    { R30,   "R30"    },
    { R31,   "R31"    }
};
// Vector defining the other xsr regs
const std::map<uint16_t, std::string> v_ppe_xsr_num_name =
{
    { XSR,   "XSR"    },
    { IAR,   "IAR"    },
    { IR,    "IR"     },
    { EDR,   "EDR"    },
    { SPRG0, "SPRG0"  }
};

#endif //__HOSTBOOT_MODULE

///--------------------------------------------------------------------------------------
/// @brief generates a PPE instruction for some formats
/// @param[in] i_Op      Opcode
/// @param[in] i_Rts     Source or Target Register
/// @param[in] i_RA      Address Register
/// @param[in] i_d       Instruction Data Field
/// @return returns 32 bit instruction representing the PPE instruction.
///--------------------------------------------------------------------------------------
uint32_t ppe_getInstruction( const uint16_t i_Op, const uint16_t i_Rts, const uint16_t i_Ra, const uint16_t i_d );

///--------------------------------------------------------------------------------------
/// @brief generates instruction for mtspr
/// @param[in] i_Rs      source register number
/// @param[in] i_Spr represents spr where data is to be moved.
/// @return returns 32 bit instruction representing mtspr instruction.
///--------------------------------------------------------------------------------------
uint32_t ppe_getMtsprInstruction( const uint16_t i_Rs, const uint16_t i_Spr );

///--------------------------------------------------------------------------------------
/// @brief generates instruction for mfspr
/// @param[in] i_Rt      target register number
/// @param[in] i_Spr represents spr where data is to sourced
/// @return returns 32 bit instruction representing mfspr instruction.
///--------------------------------------------------------------------------------------

uint32_t ppe_getMfsprInstruction( const uint16_t i_Rt, const uint16_t i_Spr );

///--------------------------------------------------------------------------------------
/// @brief generates instruction for mfmsr instruction.
/// @param[in]   i_Rt     target register number
/// @return  returns 32 bit instruction representing mfmsr instruction.
/// @note    moves contents of register MSR to i_Rt register.
///--------------------------------------------------------------------------------------
uint32_t ppe_getMfmsrInstruction( const uint16_t i_Rt );

///--------------------------------------------------------------------------------------
/// @brief generates instruction for mfcr instruction.
/// @param[in]   i_Rt     target register number
/// @return  returns 32 bit instruction representing mfcr instruction.
/// @note    moves contents of register CR to i_Rt register.
///--------------------------------------------------------------------------------------
uint32_t ppe_getMfcrInstruction( const uint16_t i_Rt );

///--------------------------------------------------------------------------------------
/// @brief poll for Halt state
/// @param[in]  i_target fapi2 target for proc chip
/// @param[in]  i_base_address  base SCOM address of the PPE
/// @return  fapi2::ReturnCode
/// @note    moves contents of register MSR to i_Rt register.
///--------------------------------------------------------------------------------------

fapi2::ReturnCode ppe_pollHaltState(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
    const uint64_t i_base_address) ;

///--------------------------------------------------------------------------------------
/// @brief halt the engine
/// @param[in]  i_target fapi2 target for proc chip
/// @param[in]  i_base_address  base SCOM address of the PPE
/// @return  fapi2::ReturnCode
/// @note    programs XCR with halt bit to halt the engine.
///--------------------------------------------------------------------------------------

fapi2::ReturnCode ppe_halt(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
    const uint64_t i_base_address );

///--------------------------------------------------------------------------------------
/// @brief force halt the engine
/// @param[in]  i_target fapi2 target for proc chip
/// @param[in]  i_base_address  base SCOM address of the PPE
/// @return  fapi2::ReturnCode
/// @note    programs XCR with force halt  to force halt the engine.
///--------------------------------------------------------------------------------------

fapi2::ReturnCode ppe_force_halt(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
    const uint64_t i_base_address );

///--------------------------------------------------------------------------------------
/// @brief resume the halted engine
/// @param[in]  i_target fapi2 target for proc chip
/// @param[in]  i_base_address  base SCOM address of the PPE
/// @return  fapi2::ReturnCode
/// @note    programs XCR with resume bit to resume the engine.
///--------------------------------------------------------------------------------------
fapi2::ReturnCode ppe_resume(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
    const uint64_t i_base_address );

///--------------------------------------------------------------------------------------
/// @brief update dbcr
/// @param[in]  i_target fapi2 target for proc chip
/// @param[in]  i_base_address  base SCOM address of the PPE
/// @param[in]  i_inst_op       instruction opcode
/// @param[in]  i_immed_16      16 bit constant
/// @param[in]  i_Rs            source GPR number
/// @return  fapi2::ReturnCode
/// @note    programs mtdbcr
///--------------------------------------------------------------------------------------

fapi2::ReturnCode ppe_update_dbcr(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
    const uint64_t i_base_address,
    const uint64_t i_inst_op,
    const uint16_t i_immed_16,
    const uint16_t i_Rs );

///--------------------------------------------------------------------------------------
/// @brief update dacr
/// @param[in]   i_target  target register number
/// @param[in]   i_base_address  base SCOM address of the PPE
/// @param[in]   i_address       address to be updated
/// @return      fapi2::ReturnCode
/// @note        programs mtdacr
///--------------------------------------------------------------------------------------
fapi2::ReturnCode ppe_update_dacr(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
    const uint64_t i_base_address,
    const uint64_t i_address,
    const uint16_t i_Rs );

///--------------------------------------------------------------------------------------
/// @brief Perform RAM "read" operation
/// @param[in]   i_target        Chip Target
/// @param[in]   i_base_address  base SCOM address of the PPE
/// @param[in]   i_instruction   RAM instruction to move a register
/// @param[out]  o_data          Returned data
/// @return  fapi2::ReturnCode
///--------------------------------------------------------------------------------------

fapi2::ReturnCode ppe_RAMRead(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
    const uint64_t i_base_address,
    const fapi2::buffer<uint64_t> i_instruction,
    fapi2::buffer<uint32_t>& o_data );

///--------------------------------------------------------------------------------------
/// @brief Perform RAM "read" operation
/// @param[in]   i_target        Chip Target
/// @param[in]   i_base_address  base SCOM address of the PPE
/// @param[in]   i_instruction   RAM instruction to move a register
/// @return  fapi2::ReturnCode
///--------------------------------------------------------------------------------------

fapi2::ReturnCode ppe_RAM(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
    const uint64_t i_base_address,
    const uint64_t i_instruction
);

///--------------------------------------------------------------------------------------
/// @brief single step the engine
/// @param[in]   i_target  target register number
/// @param[in]   i_base_address  base SCOM address of the PPE
/// @param[in]   i_Rs
/// @param[in]   i_step_count
/// @return  fapi2::ReturnCode
/// @note    programs XCR with single step  tosingle step the engine.
///--------------------------------------------------------------------------------------

fapi2::ReturnCode ppe_single_step(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
    const uint64_t i_base_address,
    const uint16_t i_Rs,
    uint64_t i_step_count );

///--------------------------------------------------------------------------------------
/// @brief clear the dbg status engine
/// @param[in]   i_target  target register number
/// @param[in]   i_base_address  base SCOM address of the PPE
/// @return  fapi2::ReturnCode
/// @note    programs XCR to clear dbg status.
///--------------------------------------------------------------------------------------

fapi2::ReturnCode ppe_clear_dbg(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
    const uint64_t i_base_address );

///--------------------------------------------------------------------------------------
/// @brief toggle TRH
/// @param[in]   i_target  target register number
/// @param[in]   i_base_address  base SCOM address of the PPE
/// @return  fapi2::ReturnCode
/// @note    programs XCR to toggle trh.
///--------------------------------------------------------------------------------------
fapi2::ReturnCode ppe_toggle_trh(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
    const uint64_t i_base_address );

///--------------------------------------------------------------------------------------
/// @brief xcr soft reset
/// @param[in]   i_target  target register number
/// @param[in]   i_base_address  base SCOM address of the PPE
/// @return  fapi2::ReturnCode
/// @note    programs XCR to give soft reset
///--------------------------------------------------------------------------------------

fapi2::ReturnCode ppe_soft_reset(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
    const uint64_t i_base_address );

///--------------------------------------------------------------------------------------
/// @brief xcr hard reset
/// @param[in]   i_target        target register number
/// @param[in]   i_base_address  base SCOM address of the PPE
/// @return  fapi2::ReturnCode
/// @note    programs XCR to give hard reset
///--------------------------------------------------------------------------------------

fapi2::ReturnCode ppe_hard_reset(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
    const uint64_t i_base_address );

///--------------------------------------------------------------------------------------
/// @brief xcr resume only
/// @param[in]   i_target  target register number
/// @param[in]   i_base_address  base SCOM address of the PPE
/// @return  fapi2::ReturnCode
/// @note    programs XCR to only resume
///--------------------------------------------------------------------------------------

fapi2::ReturnCode ppe_resume_only(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
    const uint64_t i_base_address );

///--------------------------------------------------------------------------------------
/// @brief only single step the engine
/// @param[in]   i_target  target register number
/// @param[in]   i_base_address  base SCOM address of the PPE
/// @param[in]   i_step_count
/// @return  fapi2::ReturnCode
/// @note    programs XCR with single step no clearing DBCR
///--------------------------------------------------------------------------------------

fapi2::ReturnCode ppe_ss_only(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
    const uint64_t i_base_address,
    uint64_t i_step_count );

///--------------------------------------------------------------------------------------
/// @brief populate IAR register with a given address
/// @param[in]   i_target        target register number
/// @param[in]   i_base_address  base SCOM address of the PPE
/// @param[in]   i_address       address to be populated
/// @return  fapi2::ReturnCode
/// @note    programs XCR with single step no clearing DBCR
///--------------------------------------------------------------------------------------

fapi2::ReturnCode ppe_write_iar(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
    const uint64_t i_base_address,
    const uint64_t i_address );

#ifndef  __HOSTBOOT_MODULE

///--------------------------------------------------------------------------------------
/// @brief   finds name of SCOM registers and populates a vector
/// @param[in]   i_ppe_regs_value    a vector of SCOMRegValue_t
/// @param[in]   i_ppe_regs_num_name a map of reg num and respective name
/// @param[in]   i_scom_regs         a vector of SCOMReg_t
/// @return  fapi2::ReturnCode
///--------------------------------------------------------------------------------------

fapi2::ReturnCode scom_regs_populate_name(
    std::vector<SCOMRegValue_t> i_ppe_regs_value,
    const std::map<uint16_t, std::string> i_ppe_regs_num_name,
    std::vector<SCOMReg_t>& i_scom_regs );

///--------------------------------------------------------------------------------------
/// @brief       populates register names
/// @param[in]   i_ppe_regs_value
/// @param[in]   i_ppe_regs_num_name
/// @param[in]   i_ppe_regs
/// @return      fapi2::ReturnCode
///--------------------------------------------------------------------------------------

fapi2::ReturnCode ppe_regs_populate_name(
    std::vector<PPERegValue_t> i_ppe_regs_value,
    const std::map<uint16_t, std::string> i_ppe_regs_num_name,
    std::vector<PPEReg_t>& i_ppe_regs );

#endif  //__HOSTBOOT_MODULE
#endif  // __P9_PPE_UTILS_H__
<|endoftext|>


<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014-2016 Francois Beaune, The appleseedhq Organization
//
// 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.
//

// Interface header.
#include "specularbtdf.h"

// appleseed.renderer headers.
#include "renderer/kernel/lighting/scatteringmode.h"
#include "renderer/modeling/bsdf/bsdf.h"
#include "renderer/modeling/bsdf/bsdfwrapper.h"

// appleseed.foundation headers.
#include "foundation/math/basis.h"
#include "foundation/math/fresnel.h"
#include "foundation/math/vector.h"
#include "foundation/utility/containers/dictionary.h"
#include "foundation/utility/containers/specializedarrays.h"

// Standard headers.
#include <algorithm>
#include <cmath>

using namespace foundation;
using namespace std;

namespace renderer
{

namespace
{
    //
    // Specular BTDF.
    //

    const char* Model = "specular_btdf";

    class SpecularBTDFImpl
      : public BSDF
    {
      public:
        SpecularBTDFImpl(
            const char*         name,
            const ParamArray&   params)
          : BSDF(name, Transmissive, ScatteringMode::Specular, params)
        {
            m_inputs.declare("reflectance", InputFormatSpectralReflectance);
            m_inputs.declare("reflectance_multiplier", InputFormatScalar, "1.0");
            m_inputs.declare("transmittance", InputFormatSpectralReflectance);
            m_inputs.declare("transmittance_multiplier", InputFormatScalar, "1.0");
            m_inputs.declare("fresnel_multiplier", InputFormatScalar, "1.0");
            m_inputs.declare("ior", InputFormatScalar);
            m_inputs.declare("density", InputFormatScalar, "0.0");
            m_inputs.declare("scale", InputFormatScalar, "1.0");
        }

        virtual void release() APPLESEED_OVERRIDE
        {
            delete this;
        }

        virtual const char* get_model() const APPLESEED_OVERRIDE
        {
            return Model;
        }

        virtual size_t compute_input_data_size(
            const Assembly&     assembly) const APPLESEED_OVERRIDE
        {
            return align(sizeof(InputValues), 16);
        }

        virtual void prepare_inputs(
            const ShadingPoint& shading_point,
            void*               data) const APPLESEED_OVERRIDE
        {
            InputValues* values = static_cast<InputValues*>(data);

            if (shading_point.is_entering())
            {
                values->m_from_ior =
                    shading_point.get_ray().get_current_ior();
                values->m_to_ior = values->m_ior;
            }
            else
            {
                values->m_to_ior =
                    shading_point.get_ray().get_previous_ior();
                values->m_from_ior = values->m_ior;
            }
        }

        APPLESEED_FORCE_INLINE virtual void sample(
            SamplingContext&    sampling_context,
            const void*         data,
            const bool          adjoint,
            const bool          cosine_mult,
            BSDFSample&         sample) const APPLESEED_OVERRIDE
        {
            const InputValues* values = static_cast<const InputValues*>(data);

            const Vector3d& shading_normal = sample.get_shading_normal();
            const double eta = values->m_from_ior / values->m_to_ior;
            const double cos_theta_i = dot(sample.m_outgoing.get_value(), shading_normal);
            const double sin_theta_i2 = 1.0 - square(cos_theta_i);
            const double sin_theta_t2 = sin_theta_i2 * square(eta);
            const double cos_theta_t2 = 1.0 - sin_theta_t2;

            Vector3d incoming;
            bool refract_differentials = true;

            if (cos_theta_t2 < 0.0)
            {
                // Total internal reflection: compute the reflected direction and radiance.
                incoming = reflect(sample.m_outgoing.get_value(), shading_normal);
                sample.m_value = values->m_transmittance;
                sample.m_value *= static_cast<float>(values->m_transmittance_multiplier);
                refract_differentials = false;
            }
            else
            {
                // Compute the Fresnel reflection factor.
                const double cos_theta_t = sqrt(cos_theta_t2);
                double fresnel_reflection;
                fresnel_reflectance_dielectric(
                    fresnel_reflection,
                    1.0 / eta,
                    abs(cos_theta_i),
                    cos_theta_t);
                fresnel_reflection *= values->m_fresnel_multiplier;

                sampling_context.split_in_place(1, 1);
                const double s = sampling_context.next_double2();

                if (s < fresnel_reflection)
                {
                    // Fresnel reflection: compute the reflected direction and radiance.
                    incoming = reflect(sample.m_outgoing.get_value(), shading_normal);
                    sample.m_value = values->m_reflectance;
                    sample.m_value *= static_cast<float>(values->m_reflectance_multiplier);
                    refract_differentials = false;
                }
                else
                {
                    // Compute the refracted direction.
                    incoming =
                        cos_theta_i > 0.0
                            ? (eta * cos_theta_i - cos_theta_t) * shading_normal - eta * sample.m_outgoing.get_value()
                            : (eta * cos_theta_i + cos_theta_t) * shading_normal - eta * sample.m_outgoing.get_value();

                    // Compute the refracted radiance.
                    sample.m_value = values->m_transmittance;
                    sample.m_value *=
                        adjoint
                            ? static_cast<float>(values->m_transmittance_multiplier)
                            : static_cast<float>(eta * eta * values->m_transmittance_multiplier);
                }
            }

            const double cos_in = abs(dot(incoming, shading_normal));
            sample.m_value /= static_cast<float>(cos_in);

            // The probability density of the sampled direction is the Dirac delta.
            sample.m_probability = DiracDelta;

            // Set the scattering mode.
            sample.m_mode = ScatteringMode::Specular;

            // Set the incoming direction.
            incoming = improve_normalization(incoming);
            sample.m_incoming = Dual3d(incoming);

            // Compute the ray differentials.
            if (refract_differentials)
                sample.compute_transmitted_differentials(eta);
            else sample.compute_reflected_differentials();
        }

        APPLESEED_FORCE_INLINE virtual double evaluate(
            const void*         data,
            const bool          adjoint,
            const bool          cosine_mult,
            const Vector3d&     geometric_normal,
            const Basis3d&      shading_basis,
            const Vector3d&     outgoing,
            const Vector3d&     incoming,
            const int           modes,
            Spectrum&           value) const APPLESEED_OVERRIDE
        {
            return 0.0;
        }

        APPLESEED_FORCE_INLINE virtual double evaluate_pdf(
            const void*         data,
            const Vector3d&     geometric_normal,
            const Basis3d&      shading_basis,
            const Vector3d&     outgoing,
            const Vector3d&     incoming,
            const int           modes) const APPLESEED_OVERRIDE
        {
            return 0.0;
        }

        double sample_ior(
            SamplingContext&    sampling_context,
            const void*         data) const APPLESEED_OVERRIDE
        {
            return static_cast<const InputValues*>(data)->m_ior;
        }

        void compute_absorption(
            const void*         data,
            const double        distance,
            Spectrum&           absorption) const APPLESEED_OVERRIDE
        {
            const InputValues* values = static_cast<const InputValues*>(data);
            const float d = static_cast<float>(values->m_density * values->m_scale * distance);

            absorption.resize(values->m_transmittance.size());

            for (size_t i = 0, e = absorption.size(); i < e; ++i)
            {
                //
                // Reference:
                //
                //   Beer-Lambert law:
                //   https://en.wikipedia.org/wiki/Beer%E2%80%93Lambert_law
                //

                const float a = 1.0f - static_cast<float>(values->m_transmittance[i] * values->m_transmittance_multiplier);
                const float optical_depth = a * d;
                absorption[i] = exp(-optical_depth);
            }
        }

      private:
        typedef SpecularBTDFInputValues InputValues;
    };

    typedef BSDFWrapper<SpecularBTDFImpl> SpecularBTDF;
}

//
// SpecularBTDFFactory class implementation.
//

const char* SpecularBTDFFactory::get_model() const
{
    return Model;
}

Dictionary SpecularBTDFFactory::get_model_metadata() const
{
    return
        Dictionary()
            .insert("name", Model)
            .insert("label", "Specular BTDF");
}

DictionaryArray SpecularBTDFFactory::get_input_metadata() const
{
    DictionaryArray metadata;

    metadata.push_back(
        Dictionary()
            .insert("name", "reflectance")
            .insert("label", "Reflectance")
            .insert("type", "colormap")
            .insert("entity_types",
                Dictionary()
                    .insert("color", "Colors")
                    .insert("texture_instance", "Textures"))
            .insert("use", "required")
            .insert("default", "0.5"));

    metadata.push_back(
        Dictionary()
            .insert("name", "reflectance_multiplier")
            .insert("label", "Reflectance Multiplier")
            .insert("type", "colormap")
            .insert("entity_types",
                Dictionary().insert("texture_instance", "Textures"))
            .insert("use", "optional")
            .insert("default", "1.0"));

    metadata.push_back(
        Dictionary()
            .insert("name", "transmittance")
            .insert("label", "Transmittance")
            .insert("type", "colormap")
            .insert("entity_types",
                Dictionary()
                    .insert("color", "Colors")
                    .insert("texture_instance", "Textures"))
            .insert("use", "required")
            .insert("default", "0.5"));

    metadata.push_back(
        Dictionary()
            .insert("name", "transmittance_multiplier")
            .insert("label", "Transmittance Multiplier")
            .insert("type", "colormap")
            .insert("entity_types",
                Dictionary().insert("texture_instance", "Textures"))
            .insert("use", "optional")
            .insert("default", "1.0"));

    metadata.push_back(
        Dictionary()
            .insert("name", "fresnel_multiplier")
            .insert("label", "Fresnel Multiplier")
            .insert("type", "colormap")
            .insert("entity_types",
                Dictionary().insert("texture_instance", "Textures"))
            .insert("use", "optional")
            .insert("default", "1.0"));

    metadata.push_back(
        Dictionary()
            .insert("name", "ior")
            .insert("label", "Index of Refraction")
            .insert("type", "numeric")
            .insert("min_value", "1.0")
            .insert("max_value", "2.5")
            .insert("use", "required")
            .insert("default", "1.5"));

    metadata.push_back(
        Dictionary()
            .insert("name", "density")
            .insert("label", "Density")
            .insert("type", "numeric")
            .insert("min_value", "0.0")
            .insert("max_value", "10.0")
            .insert("use", "optional")
            .insert("default", "0.0"));

    metadata.push_back(
        Dictionary()
            .insert("name", "scale")
            .insert("label", "Scale")
            .insert("type", "numeric")
            .insert("min_value", "0.0")
            .insert("max_value", "10.0")
            .insert("use", "optional")
            .insert("default", "1.0"));

    return metadata;
}

auto_release_ptr<BSDF> SpecularBTDFFactory::create(
    const char*         name,
    const ParamArray&   params) const
{
    return auto_release_ptr<BSDF>(new SpecularBTDF(name, params));
}

auto_release_ptr<BSDF> SpecularBTDFFactory::static_create(
    const char*         name,
    const ParamArray&   params)
{
    return auto_release_ptr<BSDF>(new SpecularBTDF(name, params));
}

}   // namespace renderer
<commit_msg>Code tweak<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014-2016 Francois Beaune, The appleseedhq Organization
//
// 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.
//

// Interface header.
#include "specularbtdf.h"

// appleseed.renderer headers.
#include "renderer/kernel/lighting/scatteringmode.h"
#include "renderer/modeling/bsdf/bsdf.h"
#include "renderer/modeling/bsdf/bsdfwrapper.h"

// appleseed.foundation headers.
#include "foundation/math/basis.h"
#include "foundation/math/fresnel.h"
#include "foundation/math/vector.h"
#include "foundation/utility/containers/dictionary.h"
#include "foundation/utility/containers/specializedarrays.h"

// Standard headers.
#include <algorithm>
#include <cmath>

using namespace foundation;
using namespace std;

namespace renderer
{

namespace
{
    //
    // Specular BTDF.
    //

    const char* Model = "specular_btdf";

    class SpecularBTDFImpl
      : public BSDF
    {
      public:
        SpecularBTDFImpl(
            const char*         name,
            const ParamArray&   params)
          : BSDF(name, Transmissive, ScatteringMode::Specular, params)
        {
            m_inputs.declare("reflectance", InputFormatSpectralReflectance);
            m_inputs.declare("reflectance_multiplier", InputFormatScalar, "1.0");
            m_inputs.declare("transmittance", InputFormatSpectralReflectance);
            m_inputs.declare("transmittance_multiplier", InputFormatScalar, "1.0");
            m_inputs.declare("fresnel_multiplier", InputFormatScalar, "1.0");
            m_inputs.declare("ior", InputFormatScalar);
            m_inputs.declare("density", InputFormatScalar, "0.0");
            m_inputs.declare("scale", InputFormatScalar, "1.0");
        }

        virtual void release() APPLESEED_OVERRIDE
        {
            delete this;
        }

        virtual const char* get_model() const APPLESEED_OVERRIDE
        {
            return Model;
        }

        virtual size_t compute_input_data_size(
            const Assembly&     assembly) const APPLESEED_OVERRIDE
        {
            return align(sizeof(InputValues), 16);
        }

        virtual void prepare_inputs(
            const ShadingPoint& shading_point,
            void*               data) const APPLESEED_OVERRIDE
        {
            InputValues* values = static_cast<InputValues*>(data);

            if (shading_point.is_entering())
            {
                values->m_from_ior =
                    shading_point.get_ray().get_current_ior();
                values->m_to_ior = values->m_ior;
            }
            else
            {
                values->m_from_ior = values->m_ior;
                values->m_to_ior =
                    shading_point.get_ray().get_previous_ior();
            }
        }

        APPLESEED_FORCE_INLINE virtual void sample(
            SamplingContext&    sampling_context,
            const void*         data,
            const bool          adjoint,
            const bool          cosine_mult,
            BSDFSample&         sample) const APPLESEED_OVERRIDE
        {
            const InputValues* values = static_cast<const InputValues*>(data);

            const Vector3d& shading_normal = sample.get_shading_normal();
            const double eta = values->m_from_ior / values->m_to_ior;
            const double cos_theta_i = dot(sample.m_outgoing.get_value(), shading_normal);
            const double sin_theta_i2 = 1.0 - square(cos_theta_i);
            const double sin_theta_t2 = sin_theta_i2 * square(eta);
            const double cos_theta_t2 = 1.0 - sin_theta_t2;

            Vector3d incoming;
            bool refract_differentials = true;

            if (cos_theta_t2 < 0.0)
            {
                // Total internal reflection: compute the reflected direction and radiance.
                incoming = reflect(sample.m_outgoing.get_value(), shading_normal);
                sample.m_value = values->m_transmittance;
                sample.m_value *= static_cast<float>(values->m_transmittance_multiplier);
                refract_differentials = false;
            }
            else
            {
                // Compute the Fresnel reflection factor.
                const double cos_theta_t = sqrt(cos_theta_t2);
                double fresnel_reflection;
                fresnel_reflectance_dielectric(
                    fresnel_reflection,
                    1.0 / eta,
                    abs(cos_theta_i),
                    cos_theta_t);
                fresnel_reflection *= values->m_fresnel_multiplier;

                sampling_context.split_in_place(1, 1);
                const double s = sampling_context.next_double2();

                if (s < fresnel_reflection)
                {
                    // Fresnel reflection: compute the reflected direction and radiance.
                    incoming = reflect(sample.m_outgoing.get_value(), shading_normal);
                    sample.m_value = values->m_reflectance;
                    sample.m_value *= static_cast<float>(values->m_reflectance_multiplier);
                    refract_differentials = false;
                }
                else
                {
                    // Compute the refracted direction.
                    incoming =
                        cos_theta_i > 0.0
                            ? (eta * cos_theta_i - cos_theta_t) * shading_normal - eta * sample.m_outgoing.get_value()
                            : (eta * cos_theta_i + cos_theta_t) * shading_normal - eta * sample.m_outgoing.get_value();

                    // Compute the refracted radiance.
                    sample.m_value = values->m_transmittance;
                    sample.m_value *=
                        adjoint
                            ? static_cast<float>(values->m_transmittance_multiplier)
                            : static_cast<float>(eta * eta * values->m_transmittance_multiplier);
                }
            }

            const double cos_in = abs(dot(incoming, shading_normal));
            sample.m_value /= static_cast<float>(cos_in);

            // The probability density of the sampled direction is the Dirac delta.
            sample.m_probability = DiracDelta;

            // Set the scattering mode.
            sample.m_mode = ScatteringMode::Specular;

            // Set the incoming direction.
            incoming = improve_normalization(incoming);
            sample.m_incoming = Dual3d(incoming);

            // Compute the ray differentials.
            if (refract_differentials)
                sample.compute_transmitted_differentials(eta);
            else sample.compute_reflected_differentials();
        }

        APPLESEED_FORCE_INLINE virtual double evaluate(
            const void*         data,
            const bool          adjoint,
            const bool          cosine_mult,
            const Vector3d&     geometric_normal,
            const Basis3d&      shading_basis,
            const Vector3d&     outgoing,
            const Vector3d&     incoming,
            const int           modes,
            Spectrum&           value) const APPLESEED_OVERRIDE
        {
            return 0.0;
        }

        APPLESEED_FORCE_INLINE virtual double evaluate_pdf(
            const void*         data,
            const Vector3d&     geometric_normal,
            const Basis3d&      shading_basis,
            const Vector3d&     outgoing,
            const Vector3d&     incoming,
            const int           modes) const APPLESEED_OVERRIDE
        {
            return 0.0;
        }

        double sample_ior(
            SamplingContext&    sampling_context,
            const void*         data) const APPLESEED_OVERRIDE
        {
            return static_cast<const InputValues*>(data)->m_ior;
        }

        void compute_absorption(
            const void*         data,
            const double        distance,
            Spectrum&           absorption) const APPLESEED_OVERRIDE
        {
            const InputValues* values = static_cast<const InputValues*>(data);
            const float d = static_cast<float>(values->m_density * values->m_scale * distance);

            absorption.resize(values->m_transmittance.size());

            for (size_t i = 0, e = absorption.size(); i < e; ++i)
            {
                //
                // Reference:
                //
                //   Beer-Lambert law:
                //   https://en.wikipedia.org/wiki/Beer%E2%80%93Lambert_law
                //

                const float a = 1.0f - static_cast<float>(values->m_transmittance[i] * values->m_transmittance_multiplier);
                const float optical_depth = a * d;
                absorption[i] = exp(-optical_depth);
            }
        }

      private:
        typedef SpecularBTDFInputValues InputValues;
    };

    typedef BSDFWrapper<SpecularBTDFImpl> SpecularBTDF;
}

//
// SpecularBTDFFactory class implementation.
//

const char* SpecularBTDFFactory::get_model() const
{
    return Model;
}

Dictionary SpecularBTDFFactory::get_model_metadata() const
{
    return
        Dictionary()
            .insert("name", Model)
            .insert("label", "Specular BTDF");
}

DictionaryArray SpecularBTDFFactory::get_input_metadata() const
{
    DictionaryArray metadata;

    metadata.push_back(
        Dictionary()
            .insert("name", "reflectance")
            .insert("label", "Reflectance")
            .insert("type", "colormap")
            .insert("entity_types",
                Dictionary()
                    .insert("color", "Colors")
                    .insert("texture_instance", "Textures"))
            .insert("use", "required")
            .insert("default", "0.5"));

    metadata.push_back(
        Dictionary()
            .insert("name", "reflectance_multiplier")
            .insert("label", "Reflectance Multiplier")
            .insert("type", "colormap")
            .insert("entity_types",
                Dictionary().insert("texture_instance", "Textures"))
            .insert("use", "optional")
            .insert("default", "1.0"));

    metadata.push_back(
        Dictionary()
            .insert("name", "transmittance")
            .insert("label", "Transmittance")
            .insert("type", "colormap")
            .insert("entity_types",
                Dictionary()
                    .insert("color", "Colors")
                    .insert("texture_instance", "Textures"))
            .insert("use", "required")
            .insert("default", "0.5"));

    metadata.push_back(
        Dictionary()
            .insert("name", "transmittance_multiplier")
            .insert("label", "Transmittance Multiplier")
            .insert("type", "colormap")
            .insert("entity_types",
                Dictionary().insert("texture_instance", "Textures"))
            .insert("use", "optional")
            .insert("default", "1.0"));

    metadata.push_back(
        Dictionary()
            .insert("name", "fresnel_multiplier")
            .insert("label", "Fresnel Multiplier")
            .insert("type", "colormap")
            .insert("entity_types",
                Dictionary().insert("texture_instance", "Textures"))
            .insert("use", "optional")
            .insert("default", "1.0"));

    metadata.push_back(
        Dictionary()
            .insert("name", "ior")
            .insert("label", "Index of Refraction")
            .insert("type", "numeric")
            .insert("min_value", "1.0")
            .insert("max_value", "2.5")
            .insert("use", "required")
            .insert("default", "1.5"));

    metadata.push_back(
        Dictionary()
            .insert("name", "density")
            .insert("label", "Density")
            .insert("type", "numeric")
            .insert("min_value", "0.0")
            .insert("max_value", "10.0")
            .insert("use", "optional")
            .insert("default", "0.0"));

    metadata.push_back(
        Dictionary()
            .insert("name", "scale")
            .insert("label", "Scale")
            .insert("type", "numeric")
            .insert("min_value", "0.0")
            .insert("max_value", "10.0")
            .insert("use", "optional")
            .insert("default", "1.0"));

    return metadata;
}

auto_release_ptr<BSDF> SpecularBTDFFactory::create(
    const char*         name,
    const ParamArray&   params) const
{
    return auto_release_ptr<BSDF>(new SpecularBTDF(name, params));
}

auto_release_ptr<BSDF> SpecularBTDFFactory::static_create(
    const char*         name,
    const ParamArray&   params)
{
    return auto_release_ptr<BSDF>(new SpecularBTDF(name, params));
}

}   // namespace renderer
<|endoftext|>


<commit_before>#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include "errno.h"
#include <string>
#include <vector>
#include <list>
#include "boost/tokenizer.hpp"

using namespace std;

int main (int argc, char const *argv[])
{
    char host[128];
    gethostname(host, sizeof(host));
    char * login = getlogin();

	string input;

    while(true)
	{
        //Terminal prompt display
        cout << login << "@" << host << " $ ";
        cout.flush();

        //Grab user input for bash prompt
        getline(cin,input);

        typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
        boost::char_separator<char> sep(" ");
        tokenizer tok(input, sep);

        string arg;
        list<string> ls;
        vector<char*> args;

        for(tokenizer::iterator it = tok.begin(); it != tok.end(); ++it) {
            ls.push_back(*it);
            args.push_back(const_cast<char*>(ls.back().c_str()));
        }
        args.push_back(0);

        //TODO: Filter Input
        //TODO: Grab arguments

        if(input == "exit") {
            exit(0);
        }

        //Main process thread
        pid_t i = fork();

        if(i < 0) { //Error
            perror("Failed to create child process");
            break;
        }
        else if(i == 0) { //Child process

            int com = execvp(args[0], &args[0]);
            if(com < 0)
                perror("Error executing command");
            else {
                exit(0);
            }
        }
        else { //Parent process
            int *status = nullptr;
            waitpid(i, status, 0); //Temp fix just to get child to run properly.
        }
	}
}
<commit_msg>Allow chaining commands now<commit_after>#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include "errno.h"
#include <string>
#include <vector>
#include <list>
#include "boost/tokenizer.hpp"

using namespace std;

int main (int argc, char const *argv[])
{
    char host[128];
    gethostname(host, sizeof(host));
    char * login = getlogin();

	string input;

    while(true)
	{
        //Terminal prompt display
        cout << login << "@" << host << " $ ";
        cout.flush();

        //Grab user input for bash prompt
        getline(cin,input);

        typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
        boost::char_separator<char> sep(" ", ";");
        tokenizer tok(input, sep);

        list<string> ls;
        vector<char*> args;
        vector<vector<char*> > commands;

        for(tokenizer::iterator it = tok.begin(); it != tok.end(); ++it) {
            if(*it == "#")
                break;
            if(*it == ";" || *it == "||" || *it == "&&") {
                args.push_back(0);
                commands.push_back(args);
                args.clear();
            }
            else {
                ls.push_back(*it);
                args.push_back(const_cast<char*>(ls.back().c_str()));
            }
        }
        args.push_back(0);
        commands.push_back(args);

        for(int x = 0; x < commands.size(); x++) {

            vector<char*> com = commands.at(x);

            if(strncmp(com[0], "exit", 4) == 0) {
                exit(0);
            }

            //Main process thread
            pid_t i = fork();

            if(i < 0) { //Error
                perror("Failed to create child process");
                break;
            }
            else if(i == 0) { //Child process

                int result = execvp(com[0], &com[0]);
                if(result < 0)
                    perror("Error executing command");
                else {
                    exit(0);
                }
            }
            else { //Parent process
                int *status = nullptr;
                waitpid(i, status, 0); //Temp fix just to get child to run properly.
            }
        }
	}
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_setup_evid.H $       */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file  p9_setup_evid.H
/// @brief Setup External Voltage IDs
///
/// *HW Owner    : Sudheendra K Srivathsa <sudheendraks@in.ibm.com>
/// *FW Owner    : Sangeetha T S <sangeet2@in.ibm.com>
/// *Team        : PM
/// *Consumed by : HB
/// *Level       : 2
///

#ifndef __P9_SETUP_EVID_H__
#define __P9_SETUP_EVID_H__

#include <fapi2.H>

extern "C"
{

/// @typedef p9_setup_evid_FP_t
/// function pointer typedef definition for HWP call support
    typedef fapi2::ReturnCode (*p9_setup_evid_FP_t) (
        const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&);

/// @brief Read attributes containing part's boot voltages(VDD,VCS and VDN)
/// and set these voltage using the AVSBUS interface (VDD, VDN and VCS).
///
/// @param [in] i_target TARGET_TYPE_PROC_CHIP
/// @attr
/// @attritem  ATTR_VCS_BOOT_VOLTAGE  - 1mV grandularity setting for VCS rail
/// @attritem  ATTR_VDD_BOOT_VOLTAGE  - 1mV grandularity setting for VDD rail
/// @attritem  ATTR_VDN_BOOT_VOLTAGE  - 1mV grandularity setting for VDN rail
/// @attritem  ATTR_VDD_AVSBUS_BUSNUM - AVSBus Number having the VDD VRM
/// @attritem  ATTR_VDD_AVSBUS_RAIL   - AVSBus Rail number for VDD VRM
/// @attritem  ATTR_VDN_AVSBUS_BUSNUM - AVSBus Number having the VDN VRM
/// @attritem  ATTR_VDN_AVSBUS_RAIL   - AVSBus Rail number for VDN VRM
/// @attritem  ATTR_VCS_AVSBUS_BUSNUM - AVSBus Number having the VCS VRM
/// @attritem  ATTR_VCS_AVSBUS_RAIL   - AVSBus Rail number for VCS VRM
///
/// @retval FAPI_RC_SUCCESS
    fapi2::ReturnCode
    p9_setup_evid(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target);

} // extern C

#endif  // __P9_SETUP_EVID_H__
<commit_msg>Add parameter to setup evid to define action for HWP<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_setup_evid.H $       */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file  p9_setup_evid.H
/// @brief Setup External Voltage IDs
///
/// *HW Owner    : Sudheendra K Srivathsa <sudheendraks@in.ibm.com>
/// *FW Owner    : Sangeetha T S <sangeet2@in.ibm.com>
/// *Team        : PM
/// *Consumed by : HB
/// *Level       : 2
///

#ifndef __P9_SETUP_EVID_H__
#define __P9_SETUP_EVID_H__

#include <fapi2.H>

extern "C"
{

/// @typedef VoltageConfigActions_t
/// enum of the two actions this hwp can perform
/// it can either compute default voltage settings
/// otherwise it can apply voltage setting to the system
    typedef enum
    {
        COMPUTE_VOLTAGE_SETTINGS,
        APPLY_VOLTAGE_SETTINGS
    } VoltageConfigActions_t;

/// @typedef p9_setup_evid_FP_t
/// function pointer typedef definition for HWP call support
    typedef fapi2::ReturnCode (*p9_setup_evid_FP_t) (
        const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&,
        const VoltageConfigActions_t);

/// @brief Read attributes containing part's boot voltages(VDD,VCS and VDN)
/// and set these voltage using the AVSBUS interface (VDD, VDN and VCS).
///
/// @param [in] i_target TARGET_TYPE_PROC_CHIP
/// @param [in] i_action Describes whether you wish to COMPUTE voltage settings
///                      during the step or if you would like to APPLY them.
/// @attr
/// @attritem  ATTR_VCS_BOOT_VOLTAGE  - 1mV grandularity setting for VCS rail
/// @attritem  ATTR_VDD_BOOT_VOLTAGE  - 1mV grandularity setting for VDD rail
/// @attritem  ATTR_VDN_BOOT_VOLTAGE  - 1mV grandularity setting for VDN rail
/// @attritem  ATTR_VDD_AVSBUS_BUSNUM - AVSBus Number having the VDD VRM
/// @attritem  ATTR_VDD_AVSBUS_RAIL   - AVSBus Rail number for VDD VRM
/// @attritem  ATTR_VDN_AVSBUS_BUSNUM - AVSBus Number having the VDN VRM
/// @attritem  ATTR_VDN_AVSBUS_RAIL   - AVSBus Rail number for VDN VRM
/// @attritem  ATTR_VCS_AVSBUS_BUSNUM - AVSBus Number having the VCS VRM
/// @attritem  ATTR_VCS_AVSBUS_RAIL   - AVSBus Rail number for VCS VRM
///
/// @retval FAPI_RC_SUCCESS
    fapi2::ReturnCode
    p9_setup_evid(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
                  const VoltageConfigActions_t i_action);

} // extern C

#endif  // __P9_SETUP_EVID_H__
<|endoftext|>