<commit_before>#include "mitkOpenGLRenderer.h"
#include "Mapper.h"
#include "ImageMapper2D.h"
#include "BaseVtkMapper2D.h"
#include "BaseVtkMapper3D.h"
#include "LevelWindow.h"
#include "mitkVtkInteractorCameraController.h"
#include "mitkVtkRenderWindow.h"

#include <vtkRenderer.h>
#include <vtkLight.h>
#include <vtkRenderWindow.h>

#include "PlaneGeometry.h"

//##ModelId=3E33ECF301AD
mitk::OpenGLRenderer::OpenGLRenderer() : m_IilImage(0),
    first(true) //FIXME provisorium
{
    m_CameraController=NULL;
    m_CameraController = VtkInteractorCameraController::New();
    m_CameraController->AddRenderer(this);
}

//##ModelId=3E3D28AB0018
void mitk::OpenGLRenderer::SetData(mitk::DataTreeIterator* iterator)
{
    BaseRenderer::SetData(iterator);

    m_MitkVtkRenderWindow->RemoveRenderer(m_VtkRenderer);
    m_VtkRenderer->Delete();

    m_VtkRenderer = vtkRenderer::New();
    m_VtkRenderer->SetLayer(0);
    m_MitkVtkRenderWindow->AddRenderer( this->m_VtkRenderer );

    m_Light->Delete();
    m_Light = vtkLight::New();
    m_VtkRenderer->AddLight( m_Light );

    //    try
    mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
    {
        while(it->hasNext())
        {
            it->next();
            if(first) //FIXME: provisorium
            {
                BaseData::Pointer data=it->get()->GetData();
                if(data!=NULL)
                {
                    Image::Pointer image = dynamic_cast<Image*>(data.GetPointer());
                    if(image!=NULL)
                    {
                        SetWorldGeometry(image->GetGeometry2D(0, 0));
                        first=false;
                    }
                }
            }
            //            mitk::LevelWindow lw;
            unsigned int dummy[] = {10,10,10};
            //Geometry3D geometry(3,dummy);
            mitk::Mapper::Pointer mapper = it->get()->GetMapper(m_MapperID);
            if(mapper!=NULL)
            {
                //                mapper->Update();
                BaseVtkMapper2D* anVtkMapper2D;
                anVtkMapper2D=dynamic_cast<BaseVtkMapper2D*>(mapper.GetPointer());
                if(anVtkMapper2D!=NULL)
                {
                    anVtkMapper2D->Update();
                    m_VtkRenderer->AddProp(anVtkMapper2D->GetProp());
                }
                else
                {
                    BaseVtkMapper3D* anVtkMapper3D;
                    anVtkMapper3D=dynamic_cast<BaseVtkMapper3D*>(mapper.GetPointer());
                    if(anVtkMapper3D!=NULL)
                    {
                        anVtkMapper3D->Update();
                        m_VtkRenderer->AddProp(anVtkMapper3D->GetProp());
                    }
                }
            }
        }
    }
    //    catch( ::itk::ExceptionObject ee)
    //    {
    //        printf("%s\n",ee.what());
    ////        itkGenericOutputMacro(ee->what());
    //    }
    //    catch( ...)
    //    {
    //            printf("test\n");
    //    }
    delete it;

    Modified();
}

//##ModelId=3E330D260255
void mitk::OpenGLRenderer::Update()
{
    if(m_DataTreeIterator==NULL) return;
    mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
    while(it->hasNext())
    {
        it->next();
        //      mitk::LevelWindow lw;
        unsigned int dummy[] = {10,10,10};
        //Geometry3D geometry(3,dummy);
        mitk::Mapper::Pointer mapper = it->get()->GetMapper(m_MapperID);
        if(mapper!=NULL)
        {
            Mapper2D* mapper2d=dynamic_cast<Mapper2D*>(mapper.GetPointer());
            if(mapper2d!=NULL)
            {
                ImageMapper2D* imagemapper2d=dynamic_cast<ImageMapper2D*>(mapper.GetPointer());
                //								imagemapper2d->m_IilImage = &m_IilImage;
                //								mapper2d->SetDisplayGeometry(GetDisplayGeometry());
                mapper2d->Update();
            }
            else
                if(dynamic_cast<BaseVtkMapper3D*>(mapper.GetPointer()))
                    mapper->Update();
        }
    }

    delete it;
    Modified();
    m_LastUpdateTime=GetMTime();
}
//##ModelId=3E330D2903CC
void mitk::OpenGLRenderer::Render()
{
    // TODO: nderung des Baums beachten!!!
    if (m_LastUpdateTime<GetMTime() ||
        m_LastUpdateTime<GetDisplayGeometry()->GetMTime() ||
        m_LastUpdateTime<GetDisplayGeometry()->GetWorldGeometry()->GetMTime() )
    {
        std::cout << "OpenGLRenderer calling its update..." << std::endl;
        Update();
    }
    else
    if(m_MapperID==2) //FIXME: in 3D mode wird sonst nix geupdated, da z.Z. weder camera noch nderung des Baums beachtet wird!!!
        Update();

    glClear(GL_COLOR_BUFFER_BIT);

    if(m_DataTreeIterator==NULL) return;

    PlaneGeometry* myPlaneGeom =
        dynamic_cast<PlaneGeometry *>((mitk::Geometry2D*)(GetWorldGeometry()));

    glViewport (0, 0, m_Size[0], m_Size[1]);
    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    gluOrtho2D( 0.0, m_Size[0], 0.0, m_Size[1] );
    glMatrixMode( GL_MODELVIEW );

    bool m_VtkMapperPresent=false;

    mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
    while(it->hasNext())
    {
        it->next();
        mitk::Mapper::Pointer mapper = it->get()->GetMapper(m_MapperID);
        if(mapper!=NULL)
        {
            GLMapper2D* mapper2d=dynamic_cast<GLMapper2D*>(mapper.GetPointer());
            if(mapper2d!=NULL) {
                mapper2d->Paint(this);
            }
            else
                if(dynamic_cast<BaseVtkMapper2D*>(mapper.GetPointer()) || dynamic_cast<BaseVtkMapper3D*>(mapper.GetPointer()))
                    m_VtkMapperPresent=true;
        }
    }

    delete it;

    if(m_VtkMapperPresent)
        m_MitkVtkRenderWindow->MitkRender();
}

/*!
\brief Initialize the OpenGLRenderer

This method is called from the two Constructors
*/
void mitk::OpenGLRenderer::InitRenderer(mitk::RenderWindow* renderwindow)
{
    BaseRenderer::InitRenderer(renderwindow);

    m_InitNeeded = true;
    m_ResizeNeeded = true;

    m_MitkVtkRenderWindow = mitk::VtkRenderWindow::New();
    m_MitkVtkRenderWindow->SetMitkRenderer(this);
    m_MitkVtkRenderWindow->SetNumberOfLayers(2);

    m_VtkRenderer = vtkRenderer::New();
    m_MitkVtkRenderWindow->AddRenderer( m_VtkRenderer );

    m_Light = vtkLight::New();
    m_VtkRenderer->AddLight( m_Light );

    if(m_CameraController)
        ((VtkInteractorCameraController*)m_CameraController.GetPointer())->SetRenderWindow(m_MitkVtkRenderWindow);

    //we should disable vtk doublebuffering, but then it doesn't work
    //m_MitkVtkRenderWindow->SwapBuffersOff();
}

/*!
\brief Destructs the OpenGLRenderer.
*/
//##ModelId=3E33ECF301B7
mitk::OpenGLRenderer::~OpenGLRenderer() {
    m_VtkRenderer->Delete();
    m_MitkVtkRenderWindow->Delete();
}

/*!
\brief Initialize the OpenGL Window
*/
//##ModelId=3E33145B0096
void mitk::OpenGLRenderer::Initialize( ) {
    glClearColor(0.0, 0.0, 0.0, 1.0);
    glColor3f(1.0, 0.0, 0.0);
}

/*!
\brief Resize the OpenGL Window
*/
//##ModelId=3E33145B00D2
void mitk::OpenGLRenderer::Resize(int w, int h)
{
    BaseRenderer::Resize(w, h);

    glViewport (0, 0, w, h);
    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    gluOrtho2D( 0.0, w, 0.0, h );
    glMatrixMode( GL_MODELVIEW );

    GetDisplayGeometry()->SetSizeInDisplayUnits(w, h);
    GetDisplayGeometry()->Fit();

    Update();
    //    m_MitkVtkRenderWindow->SetSize(w,h); //FIXME?
}

/*!
\brief Render the scene
*/
//##ModelId=3E33145B005A
void mitk::OpenGLRenderer::Paint( )
{
    Render();
    glFlush();
}

//##ModelId=3E3314B0005C
void mitk::OpenGLRenderer::SetWindowId(void * id)
{
    m_MitkVtkRenderWindow->SetWindowId( id );
}

//##ModelId=3E3799420227
void mitk::OpenGLRenderer::InitSize(int w, int h)
{
    m_MitkVtkRenderWindow->SetSize(w,h);
    GetDisplayGeometry()->Fit();
    Modified();
    Update();
}
<commit_msg>old debug output to console now commented<commit_after>#include "mitkOpenGLRenderer.h"
#include "Mapper.h"
#include "ImageMapper2D.h"
#include "BaseVtkMapper2D.h"
#include "BaseVtkMapper3D.h"
#include "LevelWindow.h"
#include "mitkVtkInteractorCameraController.h"
#include "mitkVtkRenderWindow.h"

#include <vtkRenderer.h>
#include <vtkLight.h>
#include <vtkRenderWindow.h>

#include "PlaneGeometry.h"

//##ModelId=3E33ECF301AD
mitk::OpenGLRenderer::OpenGLRenderer() : m_IilImage(0),
    first(true) //FIXME provisorium
{
    m_CameraController=NULL;
    m_CameraController = VtkInteractorCameraController::New();
    m_CameraController->AddRenderer(this);
}

//##ModelId=3E3D28AB0018
void mitk::OpenGLRenderer::SetData(mitk::DataTreeIterator* iterator)
{
    BaseRenderer::SetData(iterator);

    m_MitkVtkRenderWindow->RemoveRenderer(m_VtkRenderer);
    m_VtkRenderer->Delete();

    m_VtkRenderer = vtkRenderer::New();
    m_VtkRenderer->SetLayer(0);
    m_MitkVtkRenderWindow->AddRenderer( this->m_VtkRenderer );

    m_Light->Delete();
    m_Light = vtkLight::New();
    m_VtkRenderer->AddLight( m_Light );

    //    try
    mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
    {
        while(it->hasNext())
        {
            it->next();
            if(first) //FIXME: provisorium
            {
                BaseData::Pointer data=it->get()->GetData();
                if(data!=NULL)
                {
                    Image::Pointer image = dynamic_cast<Image*>(data.GetPointer());
                    if(image!=NULL)
                    {
                        SetWorldGeometry(image->GetGeometry2D(0, 0));
                        first=false;
                    }
                }
            }
            //            mitk::LevelWindow lw;
            unsigned int dummy[] = {10,10,10};
            //Geometry3D geometry(3,dummy);
            mitk::Mapper::Pointer mapper = it->get()->GetMapper(m_MapperID);
            if(mapper!=NULL)
            {
                //                mapper->Update();
                BaseVtkMapper2D* anVtkMapper2D;
                anVtkMapper2D=dynamic_cast<BaseVtkMapper2D*>(mapper.GetPointer());
                if(anVtkMapper2D!=NULL)
                {
                    anVtkMapper2D->Update();
                    m_VtkRenderer->AddProp(anVtkMapper2D->GetProp());
                }
                else
                {
                    BaseVtkMapper3D* anVtkMapper3D;
                    anVtkMapper3D=dynamic_cast<BaseVtkMapper3D*>(mapper.GetPointer());
                    if(anVtkMapper3D!=NULL)
                    {
                        anVtkMapper3D->Update();
                        m_VtkRenderer->AddProp(anVtkMapper3D->GetProp());
                    }
                }
            }
        }
    }
    //    catch( ::itk::ExceptionObject ee)
    //    {
    //        printf("%s\n",ee.what());
    ////        itkGenericOutputMacro(ee->what());
    //    }
    //    catch( ...)
    //    {
    //            printf("test\n");
    //    }
    delete it;

    Modified();
}

//##ModelId=3E330D260255
void mitk::OpenGLRenderer::Update()
{
    if(m_DataTreeIterator==NULL) return;
    mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
    while(it->hasNext())
    {
        it->next();
        //      mitk::LevelWindow lw;
        unsigned int dummy[] = {10,10,10};
        //Geometry3D geometry(3,dummy);
        mitk::Mapper::Pointer mapper = it->get()->GetMapper(m_MapperID);
        if(mapper!=NULL)
        {
            Mapper2D* mapper2d=dynamic_cast<Mapper2D*>(mapper.GetPointer());
            if(mapper2d!=NULL)
            {
                ImageMapper2D* imagemapper2d=dynamic_cast<ImageMapper2D*>(mapper.GetPointer());
                //								imagemapper2d->m_IilImage = &m_IilImage;
                //								mapper2d->SetDisplayGeometry(GetDisplayGeometry());
                mapper2d->Update();
            }
            else
                if(dynamic_cast<BaseVtkMapper3D*>(mapper.GetPointer()))
                    mapper->Update();
        }
    }

    delete it;
    Modified();
    m_LastUpdateTime=GetMTime();
}
//##ModelId=3E330D2903CC
void mitk::OpenGLRenderer::Render()
{
    // TODO: nderung des Baums beachten!!!
    if (m_LastUpdateTime<GetMTime() ||
        m_LastUpdateTime<GetDisplayGeometry()->GetMTime() ||
        m_LastUpdateTime<GetDisplayGeometry()->GetWorldGeometry()->GetMTime() )
    {
        //std::cout << "OpenGLRenderer calling its update..." << std::endl;
        Update();
    }
    else
    if(m_MapperID==2) //FIXME: in 3D mode wird sonst nix geupdated, da z.Z. weder camera noch nderung des Baums beachtet wird!!!
        Update();

    glClear(GL_COLOR_BUFFER_BIT);

    if(m_DataTreeIterator==NULL) return;

    PlaneGeometry* myPlaneGeom =
        dynamic_cast<PlaneGeometry *>((mitk::Geometry2D*)(GetWorldGeometry()));

    glViewport (0, 0, m_Size[0], m_Size[1]);
    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    gluOrtho2D( 0.0, m_Size[0], 0.0, m_Size[1] );
    glMatrixMode( GL_MODELVIEW );

    bool m_VtkMapperPresent=false;

    mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
    while(it->hasNext())
    {
        it->next();
        mitk::Mapper::Pointer mapper = it->get()->GetMapper(m_MapperID);
        if(mapper!=NULL)
        {
            GLMapper2D* mapper2d=dynamic_cast<GLMapper2D*>(mapper.GetPointer());
            if(mapper2d!=NULL) {
                mapper2d->Paint(this);
            }
            else
                if(dynamic_cast<BaseVtkMapper2D*>(mapper.GetPointer()) || dynamic_cast<BaseVtkMapper3D*>(mapper.GetPointer()))
                    m_VtkMapperPresent=true;
        }
    }

    delete it;

    if(m_VtkMapperPresent)
        m_MitkVtkRenderWindow->MitkRender();
}

/*!
\brief Initialize the OpenGLRenderer

This method is called from the two Constructors
*/
void mitk::OpenGLRenderer::InitRenderer(mitk::RenderWindow* renderwindow)
{
    BaseRenderer::InitRenderer(renderwindow);

    m_InitNeeded = true;
    m_ResizeNeeded = true;

    m_MitkVtkRenderWindow = mitk::VtkRenderWindow::New();
    m_MitkVtkRenderWindow->SetMitkRenderer(this);
    m_MitkVtkRenderWindow->SetNumberOfLayers(2);

    m_VtkRenderer = vtkRenderer::New();
    m_MitkVtkRenderWindow->AddRenderer( m_VtkRenderer );

    m_Light = vtkLight::New();
    m_VtkRenderer->AddLight( m_Light );

    if(m_CameraController)
        ((VtkInteractorCameraController*)m_CameraController.GetPointer())->SetRenderWindow(m_MitkVtkRenderWindow);

    //we should disable vtk doublebuffering, but then it doesn't work
    //m_MitkVtkRenderWindow->SwapBuffersOff();
}

/*!
\brief Destructs the OpenGLRenderer.
*/
//##ModelId=3E33ECF301B7
mitk::OpenGLRenderer::~OpenGLRenderer() {
    m_VtkRenderer->Delete();
    m_MitkVtkRenderWindow->Delete();
}

/*!
\brief Initialize the OpenGL Window
*/
//##ModelId=3E33145B0096
void mitk::OpenGLRenderer::Initialize( ) {
    glClearColor(0.0, 0.0, 0.0, 1.0);
    glColor3f(1.0, 0.0, 0.0);
}

/*!
\brief Resize the OpenGL Window
*/
//##ModelId=3E33145B00D2
void mitk::OpenGLRenderer::Resize(int w, int h)
{
    BaseRenderer::Resize(w, h);

    glViewport (0, 0, w, h);
    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    gluOrtho2D( 0.0, w, 0.0, h );
    glMatrixMode( GL_MODELVIEW );

    GetDisplayGeometry()->SetSizeInDisplayUnits(w, h);
    GetDisplayGeometry()->Fit();

    Update();
    //    m_MitkVtkRenderWindow->SetSize(w,h); //FIXME?
}

/*!
\brief Render the scene
*/
//##ModelId=3E33145B005A
void mitk::OpenGLRenderer::Paint( )
{
    Render();
    glFlush();
}

//##ModelId=3E3314B0005C
void mitk::OpenGLRenderer::SetWindowId(void * id)
{
    m_MitkVtkRenderWindow->SetWindowId( id );
}

//##ModelId=3E3799420227
void mitk::OpenGLRenderer::InitSize(int w, int h)
{
    m_MitkVtkRenderWindow->SetSize(w,h);
    GetDisplayGeometry()->Fit();
    Modified();
    Update();
}
<|endoftext|>


<commit_before>#include "image_mgr_lua.h"

#include <lua\lua.hpp>

#include "image_mgr.h"

luaL_Reg kImgMgrLib[] =
{
  {"LoadImage", LoadImage},
  {"GetImage", GetImage},
  {NULL, NULL}
};

int LoadImage(lua_State* L)
{
  std::string path = lua_tostring(L, 1);
  std::string key = lua_tostring(L, 2);
  bool result = ImageManager::GetInstance().LoadImage(path, key);
  lua_pushboolean(L, result);
  return 1;
}

int GetImage(lua_State* L)
{
  std::string key = lua_tostring(L, 1);

#if 1
  Image** boxptr = static_cast<Image**>(lua_newuserdata(L, sizeof(Image*)));
  *boxptr = &ImageManager::GetInstance().GetImage(key);
#else // lua_boxpointer
  Image* image = &ImageManager::GetInstance().GetImage(key);
  *(void**)(lua_newuserdata(L, sizeof(void*))) = image;
#endif

  luaL_getmetatable(L, LuaImage::className_);
  lua_setmetatable(L, -2);

  return 1;
}

#define METHOD(class, name) { #name, class::name }

const char* LuaImage::className_ = "Image";
const luaL_reg LuaImage::methods_[] =
{
  METHOD(LuaImage, SetSmooth),
  {0, 0},
};

int LuaImage::SetSmooth(lua_State* L)
{
  assert(lua_gettop(L) == 2);

#if 1
  Image* image = *static_cast<Image**>(luaL_checkudata(L, 1, LuaImage::className_));
#else // lua_unboxpointer
  Image* image = (Image*)(*(void **)(lua_touserdata(L, 1)));
#endif

  bool smooth = lua_toboolean(L, 2);
  image->SetSmooth(smooth);

  return 0;
}

void LuaImage::Register(lua_State* L)
{
  lua_newtable(L);
  int methodTable = lua_gettop(L);

  luaL_newmetatable(L, className_);
  int metaTable = lua_gettop(L);

  lua_pushstring(L, "__metatable");
  lua_pushvalue(L, methodTable);
  lua_settable(L, metaTable);

  lua_pushstring(L, "__index");
  lua_pushvalue(L, methodTable);
  lua_settable(L, metaTable);

  lua_pushstring(L, "__gc");
  lua_pushcfunction(L, LuaImage::GC);
  lua_settable(L, metaTable);

  lua_pop(L, 1); // drop metatable
  luaL_register(L, NULL, LuaImage::methods_); // fill methodtable
  lua_pop(L, 1); // drop methodtable
}

int LuaImage::GC(lua_State* L)
{
  return 0;
}
<commit_msg>Cleanup LuaImage.<commit_after>#include "image_mgr_lua.h"

#include <lua\lua.hpp>

#include "image_mgr.h"

luaL_Reg kImgMgrLib[] =
{
  {"LoadImage", LoadImage},
  {"GetImage", GetImage},
  {NULL, NULL}
};

int LoadImage(lua_State* L)
{
  std::string path = lua_tostring(L, 1);
  std::string key = lua_tostring(L, 2);
  bool result = ImageManager::GetInstance().LoadImage(path, key);
  lua_pushboolean(L, result);
  return 1;
}

int GetImage(lua_State* L)
{
  std::string key = lua_tostring(L, 1);

#if 1
  Image** boxptr = static_cast<Image**>(lua_newuserdata(L, sizeof(void*)));
  *boxptr = &ImageManager::GetInstance().GetImage(key);
#else // lua_boxpointer
  Image* image = &ImageManager::GetInstance().GetImage(key);
  *(void**)(lua_newuserdata(L, sizeof(void*))) = image;
#endif

  luaL_getmetatable(L, LuaImage::className_);
  lua_setmetatable(L, -2);

  return 1;
}

#define METHOD(class, name) { #name, class::name }

const char* LuaImage::className_ = "Image";
const luaL_reg LuaImage::methods_[] =
{
  METHOD(LuaImage, SetSmooth),
  {0, 0},
};

int LuaImage::SetSmooth(lua_State* L)
{
  assert(lua_gettop(L) == 2);

#if 1
  Image* image = *static_cast<Image**>(luaL_checkudata(L, 1, LuaImage::className_));
#else // lua_unboxpointer
  Image* image = (Image*)(*(void **)(lua_touserdata(L, 1)));
#endif

  bool smooth = lua_toboolean(L, 2);
  image->SetSmooth(smooth);

  return 0;
}

void LuaImage::Register(lua_State* L)
{
  lua_newtable(L);
  int methodTable = lua_gettop(L);

  luaL_newmetatable(L, className_);
  int metaTable = lua_gettop(L);

#if 0
  lua_pushstring(L, "__metatable");
  lua_pushvalue(L, methodTable);
  lua_settable(L, metaTable);
#endif

  lua_pushstring(L, "__index");
  lua_pushvalue(L, methodTable);
  lua_settable(L, metaTable);

#if 0
  lua_pushstring(L, "__gc");
  lua_pushcfunction(L, LuaImage::GC);
  lua_settable(L, metaTable);
#endif

  lua_pop(L, 1); // drop metatable
  luaL_register(L, NULL, LuaImage::methods_); // fill methodtable
  lua_pop(L, 1); // drop methodtable
}

int LuaImage::GC(lua_State* L)
{
  return 0;
}
<|endoftext|>


<commit_before><commit_msg>cppcheck: redundantAssignment<commit_after><|endoftext|>


<commit_before>/*
* Copyright (C) 2008-2011 J-P Nurmi <jpnurmi@gmail.com>
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
* License for more details.
*/

#include <QtDeclarative>
#include <IrcSession>
#include <IrcMessage>
#include <Irc>

QML_DECLARE_TYPE(IrcSession)
QML_DECLARE_TYPE(IrcMessage)
QML_DECLARE_TYPE(IrcInviteMessage)
QML_DECLARE_TYPE(IrcJoinMessage)
QML_DECLARE_TYPE(IrcKickMessage)
QML_DECLARE_TYPE(IrcModeMessage)
QML_DECLARE_TYPE(IrcNickMessage)
QML_DECLARE_TYPE(IrcNoticeMessage)
QML_DECLARE_TYPE(IrcNumericMessage)
QML_DECLARE_TYPE(IrcPartMessage)
QML_DECLARE_TYPE(IrcPrivateMessage)
QML_DECLARE_TYPE(IrcQuitMessage)
QML_DECLARE_TYPE(IrcTopicMessage)

class DeclarativeIrc : public Irc
{
    Q_OBJECT

public:
    explicit DeclarativeIrc(QObject* parent = 0) : Irc(parent) { }

    Q_INVOKABLE IrcMessage* createMessage(const QString& command, QObject* parent = 0)
    {
        return IrcMessage::create(command, parent);
    }
};

QML_DECLARE_TYPE(DeclarativeIrc)

class IrcPlugin : public QDeclarativeExtensionPlugin
{
    Q_OBJECT

public:
    virtual void initializeEngine(QDeclarativeEngine* engine, const char* uri)
    {
        QDeclarativeExtensionPlugin::initializeEngine(engine, uri);
        QDeclarativeContext *context = engine->rootContext();
        DeclarativeIrc* irc = new DeclarativeIrc(context);
        context->setContextProperty("Irc", irc);
    }

    void registerTypes(const char *uri)
    {
        qmlRegisterType<IrcSession>(uri, 1, 0, "IrcSession");
        qmlRegisterType<IrcMessage>(uri, 1, 0, "IrcMessage");
        qmlRegisterType<IrcJoinMessage>(uri, 1, 0, "IrcJoinMessage");
    }
};

#include "ircplugin.moc"

Q_EXPORT_PLUGIN2(ircplugin, IrcPlugin);
<commit_msg>Declarative: added Irc.nickFromPrefix() helper<commit_after>/*
* Copyright (C) 2008-2011 J-P Nurmi <jpnurmi@gmail.com>
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
* License for more details.
*/

#include <QtDeclarative>
#include <IrcSession>
#include <IrcMessage>
#include <IrcUtil>
#include <Irc>

QML_DECLARE_TYPE(IrcSession)
QML_DECLARE_TYPE(IrcMessage)
QML_DECLARE_TYPE(IrcInviteMessage)
QML_DECLARE_TYPE(IrcJoinMessage)
QML_DECLARE_TYPE(IrcKickMessage)
QML_DECLARE_TYPE(IrcModeMessage)
QML_DECLARE_TYPE(IrcNickMessage)
QML_DECLARE_TYPE(IrcNoticeMessage)
QML_DECLARE_TYPE(IrcNumericMessage)
QML_DECLARE_TYPE(IrcPartMessage)
QML_DECLARE_TYPE(IrcPrivateMessage)
QML_DECLARE_TYPE(IrcQuitMessage)
QML_DECLARE_TYPE(IrcTopicMessage)

class DeclarativeIrc : public Irc
{
    Q_OBJECT

public:
    explicit DeclarativeIrc(QObject* parent = 0) : Irc(parent) { }

    Q_INVOKABLE IrcMessage* createMessage(const QString& command, QObject* parent = 0)
    {
        return IrcMessage::create(command, parent);
    }

    Q_INVOKABLE QString nickFromPrefix(const QString& prefix)
    {
        return IrcUtil::nickFromTarget(prefix);
    }
};

QML_DECLARE_TYPE(DeclarativeIrc)

class IrcPlugin : public QDeclarativeExtensionPlugin
{
    Q_OBJECT

public:
    virtual void initializeEngine(QDeclarativeEngine* engine, const char* uri)
    {
        QDeclarativeExtensionPlugin::initializeEngine(engine, uri);
        QDeclarativeContext *context = engine->rootContext();
        DeclarativeIrc* irc = new DeclarativeIrc(context);
        context->setContextProperty("Irc", irc);
    }

    void registerTypes(const char *uri)
    {
        qmlRegisterType<IrcSession>(uri, 1, 0, "IrcSession");
        qmlRegisterType<IrcMessage>(uri, 1, 0, "IrcMessage");
        qmlRegisterType<IrcJoinMessage>(uri, 1, 0, "IrcJoinMessage");
    }
};

#include "ircplugin.moc"

Q_EXPORT_PLUGIN2(ircplugin, IrcPlugin);
<|endoftext|>


<commit_before>#include "AuthOperationFactory.hpp"

#include "RpcOperationFactory_p.hpp"

// TODO: Instead of this include, add a generated cpp with all needed template instances
#include "ServerRpcOperation_p.hpp"

#include "AuthorizationProvider.hpp"

#include "ServerApi.hpp"
#include "ServerRpcLayer.hpp"
#include "Session.hpp"
#include "TelegramServerUser.hpp"

#include "Debug_p.hpp"
#include "RpcError.hpp"
#include "RpcProcessingContext.hpp"
#include "Utils.hpp"

#include "CTelegramStreamExtraOperators.hpp"
#include "FunctionStreamOperators.hpp"

#include <QLoggingCategory>

Q_LOGGING_CATEGORY(c_serverAuthRpcCategory, "telegram.server.rpc.auth", QtWarningMsg)

namespace Telegram {

namespace Server {

// Generated process methods
bool AuthRpcOperation::processBindTempAuthKey(RpcProcessingContext &context)
{
    setRunMethod(&AuthRpcOperation::runBindTempAuthKey);
    context.inputStream() >> m_bindTempAuthKey;
    return !context.inputStream().error();
}

bool AuthRpcOperation::processCancelCode(RpcProcessingContext &context)
{
    setRunMethod(&AuthRpcOperation::runCancelCode);
    context.inputStream() >> m_cancelCode;
    return !context.inputStream().error();
}

bool AuthRpcOperation::processCheckPassword(RpcProcessingContext &context)
{
    setRunMethod(&AuthRpcOperation::runCheckPassword);
    context.inputStream() >> m_checkPassword;
    return !context.inputStream().error();
}

bool AuthRpcOperation::processCheckPhone(RpcProcessingContext &context)
{
    setRunMethod(&AuthRpcOperation::runCheckPhone);
    context.inputStream() >> m_checkPhone;
    return !context.inputStream().error();
}

bool AuthRpcOperation::processDropTempAuthKeys(RpcProcessingContext &context)
{
    setRunMethod(&AuthRpcOperation::runDropTempAuthKeys);
    context.inputStream() >> m_dropTempAuthKeys;
    return !context.inputStream().error();
}

bool AuthRpcOperation::processExportAuthorization(RpcProcessingContext &context)
{
    setRunMethod(&AuthRpcOperation::runExportAuthorization);
    context.inputStream() >> m_exportAuthorization;
    return !context.inputStream().error();
}

bool AuthRpcOperation::processImportAuthorization(RpcProcessingContext &context)
{
    setRunMethod(&AuthRpcOperation::runImportAuthorization);
    context.inputStream() >> m_importAuthorization;
    return !context.inputStream().error();
}

bool AuthRpcOperation::processImportBotAuthorization(RpcProcessingContext &context)
{
    setRunMethod(&AuthRpcOperation::runImportBotAuthorization);
    context.inputStream() >> m_importBotAuthorization;
    return !context.inputStream().error();
}

bool AuthRpcOperation::processLogOut(RpcProcessingContext &context)
{
    setRunMethod(&AuthRpcOperation::runLogOut);
    context.inputStream() >> m_logOut;
    return !context.inputStream().error();
}

bool AuthRpcOperation::processRecoverPassword(RpcProcessingContext &context)
{
    setRunMethod(&AuthRpcOperation::runRecoverPassword);
    context.inputStream() >> m_recoverPassword;
    return !context.inputStream().error();
}

bool AuthRpcOperation::processRequestPasswordRecovery(RpcProcessingContext &context)
{
    setRunMethod(&AuthRpcOperation::runRequestPasswordRecovery);
    context.inputStream() >> m_requestPasswordRecovery;
    return !context.inputStream().error();
}

bool AuthRpcOperation::processResendCode(RpcProcessingContext &context)
{
    setRunMethod(&AuthRpcOperation::runResendCode);
    context.inputStream() >> m_resendCode;
    return !context.inputStream().error();
}

bool AuthRpcOperation::processResetAuthorizations(RpcProcessingContext &context)
{
    setRunMethod(&AuthRpcOperation::runResetAuthorizations);
    context.inputStream() >> m_resetAuthorizations;
    return !context.inputStream().error();
}

bool AuthRpcOperation::processSendCode(RpcProcessingContext &context)
{
    setRunMethod(&AuthRpcOperation::runSendCode);
    context.inputStream() >> m_sendCode;
    return !context.inputStream().error();
}

bool AuthRpcOperation::processSendInvites(RpcProcessingContext &context)
{
    setRunMethod(&AuthRpcOperation::runSendInvites);
    context.inputStream() >> m_sendInvites;
    return !context.inputStream().error();
}

bool AuthRpcOperation::processSignIn(RpcProcessingContext &context)
{
    setRunMethod(&AuthRpcOperation::runSignIn);
    context.inputStream() >> m_signIn;
    return !context.inputStream().error();
}

bool AuthRpcOperation::processSignUp(RpcProcessingContext &context)
{
    setRunMethod(&AuthRpcOperation::runSignUp);
    context.inputStream() >> m_signUp;
    return !context.inputStream().error();
}
// End of generated process methods

// Generated run methods
void AuthRpcOperation::runBindTempAuthKey()
{
    if (processNotImplementedMethod(TLValue::AuthBindTempAuthKey)) {
        return;
    }
    bool result;
    sendRpcReply(result);
}

void AuthRpcOperation::runCancelCode()
{
    if (processNotImplementedMethod(TLValue::AuthCancelCode)) {
        return;
    }
    bool result;
    sendRpcReply(result);
}

void AuthRpcOperation::runCheckPassword()
{
    qCDebug(c_serverAuthRpcCategory) << Q_FUNC_INFO;
    Session *session = layer()->session();
    if (!session) {
        sendRpcError(RpcError::AuthKeyUnregistered);
        return;
    }
    LocalUser *user = session->wanterUser();
    const bool passwordIsCorrect = api()->checkPassword(user->phoneNumber(), m_checkPassword.passwordHash);
    if (!passwordIsCorrect) {
        sendRpcError(RpcError::PasswordHashInvalid);
        return;
    }
    user->addSession(session);

    TLAuthAuthorization result;
    qCDebug(c_serverAuthRpcCategory) << "Result type:" << result.tlType;
    api()->setupTLUser(&result.user, user, user);
    sendRpcReply(result);
}

void AuthRpcOperation::runCheckPhone()
{
    PhoneStatus status = api()->getPhoneStatus(m_checkPhone.phoneNumber);
    TLAuthCheckedPhone result;
    result.phoneRegistered = status.exists();
    sendRpcReply(result);
}

void AuthRpcOperation::runDropTempAuthKeys()
{
    if (processNotImplementedMethod(TLValue::AuthDropTempAuthKeys)) {
        return;
    }
    bool result;
    sendRpcReply(result);
}

void AuthRpcOperation::runExportAuthorization()
{
    if (processNotImplementedMethod(TLValue::AuthExportAuthorization)) {
        return;
    }
    TLAuthExportedAuthorization result;
    sendRpcReply(result);
}

void AuthRpcOperation::runImportAuthorization()
{
    if (processNotImplementedMethod(TLValue::AuthImportAuthorization)) {
        return;
    }
    TLAuthAuthorization result;
    sendRpcReply(result);
}

void AuthRpcOperation::runImportBotAuthorization()
{
    if (processNotImplementedMethod(TLValue::AuthImportBotAuthorization)) {
        return;
    }
    TLAuthAuthorization result;
    sendRpcReply(result);
}

void AuthRpcOperation::runLogOut()
{
    if (processNotImplementedMethod(TLValue::AuthLogOut)) {
        return;
    }
    bool result;
    sendRpcReply(result);
}

void AuthRpcOperation::runRecoverPassword()
{
    if (processNotImplementedMethod(TLValue::AuthRecoverPassword)) {
        return;
    }
    TLAuthAuthorization result;
    sendRpcReply(result);
}

void AuthRpcOperation::runRequestPasswordRecovery()
{
    if (processNotImplementedMethod(TLValue::AuthRequestPasswordRecovery)) {
        return;
    }
    TLAuthPasswordRecovery result;
    sendRpcReply(result);
}

void AuthRpcOperation::runResendCode()
{
    if (processNotImplementedMethod(TLValue::AuthResendCode)) {
        return;
    }
    TLAuthSentCode result;
    sendRpcReply(result);
}

void AuthRpcOperation::runResetAuthorizations()
{
    if (processNotImplementedMethod(TLValue::AuthResetAuthorizations)) {
        return;
    }
    bool result;
    sendRpcReply(result);
}

void AuthRpcOperation::runSendCode()
{
    qCDebug(c_serverAuthRpcCategory) << Q_FUNC_INFO;

    if (!api()->identifierIsValid(m_sendCode.phoneNumber)) {
        sendRpcError(RpcError::PhoneNumberInvalid);
        return;
    }
    PhoneStatus status = api()->getPhoneStatus(m_sendCode.phoneNumber);
    if (status.exists() && (status.dcId != api()->dcId())) {
        RpcError error(RpcError::PhoneMigrateX, status.dcId);
        sendRpcError(error);
        return;
    }

    Authorization::Provider *provider = api()->getAuthorizationProvider();
    const Authorization::SentCodeInfo code = provider->sendCode(layer()->session(), m_sendCode.phoneNumber);

    TLAuthSentCode result;
    {
        TLAuthSentCodeType codeType;
        switch (code.type) {
        case Authorization::Code::Type::App:
            codeType.tlType = TLValue::AuthSentCodeTypeApp;
            codeType.length = code.length;
            break;
        case Authorization::Code::Type::Default:
        case Authorization::Code::Type::Sms:
            codeType.tlType = TLValue::AuthSentCodeTypeSms;
            codeType.length = code.length;
            break;
        case Authorization::Code::Type::Call:
            codeType.tlType = TLValue::AuthSentCodeTypeCall;
            codeType.length = code.length;
            break;
        case Authorization::Code::Type::FlashCall:
            codeType.tlType = TLValue::AuthSentCodeTypeFlashCall;
            codeType.pattern = code.pattern;
            break;
#ifdef MTPROTO_FORK
        case Authorization::Code::Type::NotNeeded:
        case Authorization::Code::Type::Denied:
            qCritical() << Q_FUNC_INFO << "Not implemented";
            break;
#endif
        }
        result.type = codeType;
    }

    result.phoneCodeHash = QString::fromLatin1(code.hash);
    if (status.exists()) {
        result.flags |= TLAuthSentCode::PhoneRegistered;
    }
    sendRpcReply(result);
}

void AuthRpcOperation::runSendInvites()
{
    if (processNotImplementedMethod(TLValue::AuthSendInvites)) {
        return;
    }
    bool result;
    sendRpcReply(result);
}

void AuthRpcOperation::runSignIn()
{
    qCDebug(c_serverAuthRpcCategory) << Q_FUNC_INFO;
    if (!api()->identifierIsValid(m_signIn.phoneNumber)) {
        sendRpcError(RpcError::PhoneNumberInvalid);
        return;
    }
    if (!verifyAuthCode(m_signIn.phoneNumber, m_signIn.phoneCodeHash, m_signIn.phoneCode)) {
        return;
    }

    PhoneStatus status = api()->getPhoneStatus(m_signIn.phoneNumber);
    if (status.exists() && (status.dcId != api()->dcId())) {
        RpcError error(RpcError::PhoneMigrateX, status.dcId);
        sendRpcError(error);
        return;
    }

    LocalUser *user = api()->getUser(m_signIn.phoneNumber);
    if (!user) {
        sendRpcError(RpcError::PhoneNumberUnoccupied);
        return;
    }
    if (!user->passwordHash().isEmpty()) {
        layer()->session()->setWantedUser(user);
        sendRpcError(RpcError::SessionPasswordNeeded);
        return;
    }
    user->addSession(layer()->session());

    TLAuthAuthorization result;
    api()->setupTLUser(&result.user, user, user);
    sendRpcReply(result);
}

void AuthRpcOperation::runSignUp()
{
    qCDebug(c_serverAuthRpcCategory) << Q_FUNC_INFO;
    if (!api()->identifierIsValid(m_signUp.phoneNumber)) {
        sendRpcError(RpcError::PhoneNumberInvalid);
        return;
    }

    if (m_signUp.firstName.isEmpty()) {
        sendRpcError(RpcError::FirstnameInvalid);
        return;
    }
    if (m_signUp.lastName.isEmpty()) {
        sendRpcError(RpcError::LastnameInvalid);
        return;
    }

    if (!verifyAuthCode(m_signUp.phoneNumber, m_signUp.phoneCodeHash, m_signUp.phoneCode)) {
        return;
    }
    LocalUser *user = api()->addUser(m_signUp.phoneNumber);
    user->setFirstName(m_signUp.firstName);
    user->setLastName(m_signUp.lastName);
    user->addSession(layer()->session());

    TLAuthAuthorization result;
    api()->setupTLUser(&result.user, user, user);
    sendRpcReply(result);
}
// End of generated run methods

bool AuthRpcOperation::verifyAuthCode(const QString &phoneNumber, const QString &hash, const QString &code)
{
    Authorization::Provider *provider = api()->getAuthorizationProvider();
    Authorization::CodeStatus status = provider->getCodeStatus(phoneNumber, hash.toLatin1(), code);
    if (status == Authorization::CodeStatus::CodeValid) {
        return true;
    }
    switch (status) {
    case Authorization::CodeStatus::PhoneInvalid:
        sendRpcError(RpcError::PhoneNumberInvalid);
        break;
    case Authorization::CodeStatus::CodeEmpty:
        sendRpcError(RpcError::PhoneCodeEmpty);
        break;
    case Authorization::CodeStatus::HashEmpty:
        sendRpcError(RpcError::PhoneCodeHashEmpty);
        break;
    case Authorization::CodeStatus::HashInvalid:
        sendRpcError(RpcError::PhoneCodeInvalid); // TODO: Check the behavior of the official server on invalid hash submission
        break;
    case Authorization::CodeStatus::CodeExpired:
        sendRpcError(RpcError::PhoneCodeExpired);
        break;
    case Authorization::CodeStatus::CodeInvalid:
        sendRpcError(RpcError::PhoneCodeInvalid);
        break;
    case Authorization::CodeStatus::CodeValid:
        Q_UNREACHABLE();
        break;
    }
    return false;
}

void AuthRpcOperation::setRunMethod(AuthRpcOperation::RunMethod method)
{
    m_runMethod = method;
}

AuthRpcOperation::ProcessingMethod AuthRpcOperation::getMethodForRpcFunction(TLValue function)
{
    switch (function) {
    // Generated methodForRpcFunction cases
    case TLValue::AuthBindTempAuthKey:
        return &AuthRpcOperation::processBindTempAuthKey;
    case TLValue::AuthCancelCode:
        return &AuthRpcOperation::processCancelCode;
    case TLValue::AuthCheckPassword:
        return &AuthRpcOperation::processCheckPassword;
    case TLValue::AuthCheckPhone:
        return &AuthRpcOperation::processCheckPhone;
    case TLValue::AuthDropTempAuthKeys:
        return &AuthRpcOperation::processDropTempAuthKeys;
    case TLValue::AuthExportAuthorization:
        return &AuthRpcOperation::processExportAuthorization;
    case TLValue::AuthImportAuthorization:
        return &AuthRpcOperation::processImportAuthorization;
    case TLValue::AuthImportBotAuthorization:
        return &AuthRpcOperation::processImportBotAuthorization;
    case TLValue::AuthLogOut:
        return &AuthRpcOperation::processLogOut;
    case TLValue::AuthRecoverPassword:
        return &AuthRpcOperation::processRecoverPassword;
    case TLValue::AuthRequestPasswordRecovery:
        return &AuthRpcOperation::processRequestPasswordRecovery;
    case TLValue::AuthResendCode:
        return &AuthRpcOperation::processResendCode;
    case TLValue::AuthResetAuthorizations:
        return &AuthRpcOperation::processResetAuthorizations;
    case TLValue::AuthSendCode:
        return &AuthRpcOperation::processSendCode;
    case TLValue::AuthSendInvites:
        return &AuthRpcOperation::processSendInvites;
    case TLValue::AuthSignIn:
        return &AuthRpcOperation::processSignIn;
    case TLValue::AuthSignUp:
        return &AuthRpcOperation::processSignUp;
    // End of generated methodForRpcFunction cases
    default:
        return nullptr;
    }
}

RpcOperation *AuthOperationFactory::processRpcCall(RpcLayer *layer, RpcProcessingContext &context)
{
    return processRpcCallImpl<AuthRpcOperation>(layer, context);
}

} // Server namespace

} // Telegram namespace
<commit_msg>Server: Fix possible crash on CheckPassword run on a free session<commit_after>#include "AuthOperationFactory.hpp"

#include "RpcOperationFactory_p.hpp"

// TODO: Instead of this include, add a generated cpp with all needed template instances
#include "ServerRpcOperation_p.hpp"

#include "AuthorizationProvider.hpp"

#include "ServerApi.hpp"
#include "ServerRpcLayer.hpp"
#include "Session.hpp"
#include "TelegramServerUser.hpp"

#include "Debug_p.hpp"
#include "RpcError.hpp"
#include "RpcProcessingContext.hpp"
#include "Utils.hpp"

#include "CTelegramStreamExtraOperators.hpp"
#include "FunctionStreamOperators.hpp"

#include <QLoggingCategory>

Q_LOGGING_CATEGORY(c_serverAuthRpcCategory, "telegram.server.rpc.auth", QtWarningMsg)

namespace Telegram {

namespace Server {

// Generated process methods
bool AuthRpcOperation::processBindTempAuthKey(RpcProcessingContext &context)
{
    setRunMethod(&AuthRpcOperation::runBindTempAuthKey);
    context.inputStream() >> m_bindTempAuthKey;
    return !context.inputStream().error();
}

bool AuthRpcOperation::processCancelCode(RpcProcessingContext &context)
{
    setRunMethod(&AuthRpcOperation::runCancelCode);
    context.inputStream() >> m_cancelCode;
    return !context.inputStream().error();
}

bool AuthRpcOperation::processCheckPassword(RpcProcessingContext &context)
{
    setRunMethod(&AuthRpcOperation::runCheckPassword);
    context.inputStream() >> m_checkPassword;
    return !context.inputStream().error();
}

bool AuthRpcOperation::processCheckPhone(RpcProcessingContext &context)
{
    setRunMethod(&AuthRpcOperation::runCheckPhone);
    context.inputStream() >> m_checkPhone;
    return !context.inputStream().error();
}

bool AuthRpcOperation::processDropTempAuthKeys(RpcProcessingContext &context)
{
    setRunMethod(&AuthRpcOperation::runDropTempAuthKeys);
    context.inputStream() >> m_dropTempAuthKeys;
    return !context.inputStream().error();
}

bool AuthRpcOperation::processExportAuthorization(RpcProcessingContext &context)
{
    setRunMethod(&AuthRpcOperation::runExportAuthorization);
    context.inputStream() >> m_exportAuthorization;
    return !context.inputStream().error();
}

bool AuthRpcOperation::processImportAuthorization(RpcProcessingContext &context)
{
    setRunMethod(&AuthRpcOperation::runImportAuthorization);
    context.inputStream() >> m_importAuthorization;
    return !context.inputStream().error();
}

bool AuthRpcOperation::processImportBotAuthorization(RpcProcessingContext &context)
{
    setRunMethod(&AuthRpcOperation::runImportBotAuthorization);
    context.inputStream() >> m_importBotAuthorization;
    return !context.inputStream().error();
}

bool AuthRpcOperation::processLogOut(RpcProcessingContext &context)
{
    setRunMethod(&AuthRpcOperation::runLogOut);
    context.inputStream() >> m_logOut;
    return !context.inputStream().error();
}

bool AuthRpcOperation::processRecoverPassword(RpcProcessingContext &context)
{
    setRunMethod(&AuthRpcOperation::runRecoverPassword);
    context.inputStream() >> m_recoverPassword;
    return !context.inputStream().error();
}

bool AuthRpcOperation::processRequestPasswordRecovery(RpcProcessingContext &context)
{
    setRunMethod(&AuthRpcOperation::runRequestPasswordRecovery);
    context.inputStream() >> m_requestPasswordRecovery;
    return !context.inputStream().error();
}

bool AuthRpcOperation::processResendCode(RpcProcessingContext &context)
{
    setRunMethod(&AuthRpcOperation::runResendCode);
    context.inputStream() >> m_resendCode;
    return !context.inputStream().error();
}

bool AuthRpcOperation::processResetAuthorizations(RpcProcessingContext &context)
{
    setRunMethod(&AuthRpcOperation::runResetAuthorizations);
    context.inputStream() >> m_resetAuthorizations;
    return !context.inputStream().error();
}

bool AuthRpcOperation::processSendCode(RpcProcessingContext &context)
{
    setRunMethod(&AuthRpcOperation::runSendCode);
    context.inputStream() >> m_sendCode;
    return !context.inputStream().error();
}

bool AuthRpcOperation::processSendInvites(RpcProcessingContext &context)
{
    setRunMethod(&AuthRpcOperation::runSendInvites);
    context.inputStream() >> m_sendInvites;
    return !context.inputStream().error();
}

bool AuthRpcOperation::processSignIn(RpcProcessingContext &context)
{
    setRunMethod(&AuthRpcOperation::runSignIn);
    context.inputStream() >> m_signIn;
    return !context.inputStream().error();
}

bool AuthRpcOperation::processSignUp(RpcProcessingContext &context)
{
    setRunMethod(&AuthRpcOperation::runSignUp);
    context.inputStream() >> m_signUp;
    return !context.inputStream().error();
}
// End of generated process methods

// Generated run methods
void AuthRpcOperation::runBindTempAuthKey()
{
    if (processNotImplementedMethod(TLValue::AuthBindTempAuthKey)) {
        return;
    }
    bool result;
    sendRpcReply(result);
}

void AuthRpcOperation::runCancelCode()
{
    if (processNotImplementedMethod(TLValue::AuthCancelCode)) {
        return;
    }
    bool result;
    sendRpcReply(result);
}

void AuthRpcOperation::runCheckPassword()
{
    qCDebug(c_serverAuthRpcCategory) << Q_FUNC_INFO;
    Session *session = layer()->session();
    if (!session || !session->wanterUser()) {
        sendRpcError(RpcError::AuthKeyUnregistered);
        return;
    }
    LocalUser *user = session->wanterUser();
    const bool passwordIsCorrect = api()->checkPassword(user->phoneNumber(), m_checkPassword.passwordHash);
    if (!passwordIsCorrect) {
        sendRpcError(RpcError::PasswordHashInvalid);
        return;
    }
    user->addSession(session);

    TLAuthAuthorization result;
    qCDebug(c_serverAuthRpcCategory) << "Result type:" << result.tlType;
    api()->setupTLUser(&result.user, user, user);
    sendRpcReply(result);
}

void AuthRpcOperation::runCheckPhone()
{
    PhoneStatus status = api()->getPhoneStatus(m_checkPhone.phoneNumber);
    TLAuthCheckedPhone result;
    result.phoneRegistered = status.exists();
    sendRpcReply(result);
}

void AuthRpcOperation::runDropTempAuthKeys()
{
    if (processNotImplementedMethod(TLValue::AuthDropTempAuthKeys)) {
        return;
    }
    bool result;
    sendRpcReply(result);
}

void AuthRpcOperation::runExportAuthorization()
{
    if (processNotImplementedMethod(TLValue::AuthExportAuthorization)) {
        return;
    }
    TLAuthExportedAuthorization result;
    sendRpcReply(result);
}

void AuthRpcOperation::runImportAuthorization()
{
    if (processNotImplementedMethod(TLValue::AuthImportAuthorization)) {
        return;
    }
    TLAuthAuthorization result;
    sendRpcReply(result);
}

void AuthRpcOperation::runImportBotAuthorization()
{
    if (processNotImplementedMethod(TLValue::AuthImportBotAuthorization)) {
        return;
    }
    TLAuthAuthorization result;
    sendRpcReply(result);
}

void AuthRpcOperation::runLogOut()
{
    if (processNotImplementedMethod(TLValue::AuthLogOut)) {
        return;
    }
    bool result;
    sendRpcReply(result);
}

void AuthRpcOperation::runRecoverPassword()
{
    if (processNotImplementedMethod(TLValue::AuthRecoverPassword)) {
        return;
    }
    TLAuthAuthorization result;
    sendRpcReply(result);
}

void AuthRpcOperation::runRequestPasswordRecovery()
{
    if (processNotImplementedMethod(TLValue::AuthRequestPasswordRecovery)) {
        return;
    }
    TLAuthPasswordRecovery result;
    sendRpcReply(result);
}

void AuthRpcOperation::runResendCode()
{
    if (processNotImplementedMethod(TLValue::AuthResendCode)) {
        return;
    }
    TLAuthSentCode result;
    sendRpcReply(result);
}

void AuthRpcOperation::runResetAuthorizations()
{
    if (processNotImplementedMethod(TLValue::AuthResetAuthorizations)) {
        return;
    }
    bool result;
    sendRpcReply(result);
}

void AuthRpcOperation::runSendCode()
{
    qCDebug(c_serverAuthRpcCategory) << Q_FUNC_INFO;

    if (!api()->identifierIsValid(m_sendCode.phoneNumber)) {
        sendRpcError(RpcError::PhoneNumberInvalid);
        return;
    }
    PhoneStatus status = api()->getPhoneStatus(m_sendCode.phoneNumber);
    if (status.exists() && (status.dcId != api()->dcId())) {
        RpcError error(RpcError::PhoneMigrateX, status.dcId);
        sendRpcError(error);
        return;
    }

    Authorization::Provider *provider = api()->getAuthorizationProvider();
    const Authorization::SentCodeInfo code = provider->sendCode(layer()->session(), m_sendCode.phoneNumber);

    TLAuthSentCode result;
    {
        TLAuthSentCodeType codeType;
        switch (code.type) {
        case Authorization::Code::Type::App:
            codeType.tlType = TLValue::AuthSentCodeTypeApp;
            codeType.length = code.length;
            break;
        case Authorization::Code::Type::Default:
        case Authorization::Code::Type::Sms:
            codeType.tlType = TLValue::AuthSentCodeTypeSms;
            codeType.length = code.length;
            break;
        case Authorization::Code::Type::Call:
            codeType.tlType = TLValue::AuthSentCodeTypeCall;
            codeType.length = code.length;
            break;
        case Authorization::Code::Type::FlashCall:
            codeType.tlType = TLValue::AuthSentCodeTypeFlashCall;
            codeType.pattern = code.pattern;
            break;
#ifdef MTPROTO_FORK
        case Authorization::Code::Type::NotNeeded:
        case Authorization::Code::Type::Denied:
            qCritical() << Q_FUNC_INFO << "Not implemented";
            break;
#endif
        }
        result.type = codeType;
    }

    result.phoneCodeHash = QString::fromLatin1(code.hash);
    if (status.exists()) {
        result.flags |= TLAuthSentCode::PhoneRegistered;
    }
    sendRpcReply(result);
}

void AuthRpcOperation::runSendInvites()
{
    if (processNotImplementedMethod(TLValue::AuthSendInvites)) {
        return;
    }
    bool result;
    sendRpcReply(result);
}

void AuthRpcOperation::runSignIn()
{
    qCDebug(c_serverAuthRpcCategory) << Q_FUNC_INFO;
    if (!api()->identifierIsValid(m_signIn.phoneNumber)) {
        sendRpcError(RpcError::PhoneNumberInvalid);
        return;
    }
    if (!verifyAuthCode(m_signIn.phoneNumber, m_signIn.phoneCodeHash, m_signIn.phoneCode)) {
        return;
    }

    PhoneStatus status = api()->getPhoneStatus(m_signIn.phoneNumber);
    if (status.exists() && (status.dcId != api()->dcId())) {
        RpcError error(RpcError::PhoneMigrateX, status.dcId);
        sendRpcError(error);
        return;
    }

    LocalUser *user = api()->getUser(m_signIn.phoneNumber);
    if (!user) {
        sendRpcError(RpcError::PhoneNumberUnoccupied);
        return;
    }
    if (!user->passwordHash().isEmpty()) {
        layer()->session()->setWantedUser(user);
        sendRpcError(RpcError::SessionPasswordNeeded);
        return;
    }
    user->addSession(layer()->session());

    TLAuthAuthorization result;
    api()->setupTLUser(&result.user, user, user);
    sendRpcReply(result);
}

void AuthRpcOperation::runSignUp()
{
    qCDebug(c_serverAuthRpcCategory) << Q_FUNC_INFO;
    if (!api()->identifierIsValid(m_signUp.phoneNumber)) {
        sendRpcError(RpcError::PhoneNumberInvalid);
        return;
    }

    if (m_signUp.firstName.isEmpty()) {
        sendRpcError(RpcError::FirstnameInvalid);
        return;
    }
    if (m_signUp.lastName.isEmpty()) {
        sendRpcError(RpcError::LastnameInvalid);
        return;
    }

    if (!verifyAuthCode(m_signUp.phoneNumber, m_signUp.phoneCodeHash, m_signUp.phoneCode)) {
        return;
    }
    LocalUser *user = api()->addUser(m_signUp.phoneNumber);
    user->setFirstName(m_signUp.firstName);
    user->setLastName(m_signUp.lastName);
    user->addSession(layer()->session());

    TLAuthAuthorization result;
    api()->setupTLUser(&result.user, user, user);
    sendRpcReply(result);
}
// End of generated run methods

bool AuthRpcOperation::verifyAuthCode(const QString &phoneNumber, const QString &hash, const QString &code)
{
    Authorization::Provider *provider = api()->getAuthorizationProvider();
    Authorization::CodeStatus status = provider->getCodeStatus(phoneNumber, hash.toLatin1(), code);
    if (status == Authorization::CodeStatus::CodeValid) {
        return true;
    }
    switch (status) {
    case Authorization::CodeStatus::PhoneInvalid:
        sendRpcError(RpcError::PhoneNumberInvalid);
        break;
    case Authorization::CodeStatus::CodeEmpty:
        sendRpcError(RpcError::PhoneCodeEmpty);
        break;
    case Authorization::CodeStatus::HashEmpty:
        sendRpcError(RpcError::PhoneCodeHashEmpty);
        break;
    case Authorization::CodeStatus::HashInvalid:
        sendRpcError(RpcError::PhoneCodeInvalid); // TODO: Check the behavior of the official server on invalid hash submission
        break;
    case Authorization::CodeStatus::CodeExpired:
        sendRpcError(RpcError::PhoneCodeExpired);
        break;
    case Authorization::CodeStatus::CodeInvalid:
        sendRpcError(RpcError::PhoneCodeInvalid);
        break;
    case Authorization::CodeStatus::CodeValid:
        Q_UNREACHABLE();
        break;
    }
    return false;
}

void AuthRpcOperation::setRunMethod(AuthRpcOperation::RunMethod method)
{
    m_runMethod = method;
}

AuthRpcOperation::ProcessingMethod AuthRpcOperation::getMethodForRpcFunction(TLValue function)
{
    switch (function) {
    // Generated methodForRpcFunction cases
    case TLValue::AuthBindTempAuthKey:
        return &AuthRpcOperation::processBindTempAuthKey;
    case TLValue::AuthCancelCode:
        return &AuthRpcOperation::processCancelCode;
    case TLValue::AuthCheckPassword:
        return &AuthRpcOperation::processCheckPassword;
    case TLValue::AuthCheckPhone:
        return &AuthRpcOperation::processCheckPhone;
    case TLValue::AuthDropTempAuthKeys:
        return &AuthRpcOperation::processDropTempAuthKeys;
    case TLValue::AuthExportAuthorization:
        return &AuthRpcOperation::processExportAuthorization;
    case TLValue::AuthImportAuthorization:
        return &AuthRpcOperation::processImportAuthorization;
    case TLValue::AuthImportBotAuthorization:
        return &AuthRpcOperation::processImportBotAuthorization;
    case TLValue::AuthLogOut:
        return &AuthRpcOperation::processLogOut;
    case TLValue::AuthRecoverPassword:
        return &AuthRpcOperation::processRecoverPassword;
    case TLValue::AuthRequestPasswordRecovery:
        return &AuthRpcOperation::processRequestPasswordRecovery;
    case TLValue::AuthResendCode:
        return &AuthRpcOperation::processResendCode;
    case TLValue::AuthResetAuthorizations:
        return &AuthRpcOperation::processResetAuthorizations;
    case TLValue::AuthSendCode:
        return &AuthRpcOperation::processSendCode;
    case TLValue::AuthSendInvites:
        return &AuthRpcOperation::processSendInvites;
    case TLValue::AuthSignIn:
        return &AuthRpcOperation::processSignIn;
    case TLValue::AuthSignUp:
        return &AuthRpcOperation::processSignUp;
    // End of generated methodForRpcFunction cases
    default:
        return nullptr;
    }
}

RpcOperation *AuthOperationFactory::processRpcCall(RpcLayer *layer, RpcProcessingContext &context)
{
    return processRpcCallImpl<AuthRpcOperation>(layer, context);
}

} // Server namespace

} // Telegram namespace
<|endoftext|>


<commit_before>#include "NetworkManagerClient.h"
#include <string.h>
#include <sys/types.h>
#include <stdlib.h>

#ifndef WIN32
#include <unistd.h>
#include <sys/time.h>

#else
#include <windows.h>
#include <time.h>

#endif

NetworkManagerClient::NetworkManagerClient(void) : connected(false), scores()
{
    if(SDL_Init(0) != 0){
        printf("SDL_Init done goofed: %s\n", SDL_GetError());
        exit(1);
    }

    if(SDLNet_Init() != 0){
        printf("SDLNet_Init done goofed: %s\n",SDLNet_GetError());
    }
}

NetworkManagerClient::~NetworkManagerClient(void)
{
    SDLNet_Quit();
    SDL_Quit();
}

//main method from tcpmulticlient.c in the SDLNet demos
int NetworkManagerClient::TCPConnect(char *host, long portNo, char *name)
{
    IPaddress ip;
    //	TCPsocket sock;
    char message[MAXLEN];
    int numready;
    SDLNet_SocketSet set;
    fd_set fdset;
    int result;
    char *str;
    struct timeval tv;
    Uint16 port = (Uint16)portNo;

    Packet pack;

    set = SDLNet_AllocSocketSet(1);
    if(!set)
    {
        printf("SDLNet_AllocSocketSet done goofed: %s\n", SDLNet_GetError());
        SDLNet_Quit();
        SDL_Quit();
        exit(4); /*most of the time this is a major error, but do what you want. */
    }

    /* Resolve the argument into an IPaddress type */
    printf("Connecting to %s port %d\n", host, port);
    if(SDLNet_ResolveHost(&ip, host, port)==-1)
    {
        printf("SDLNet_ResolveHost done goofed: %s\n",SDLNet_GetError());
        std::string exception = "fail_to_connect";
        throw exception;
    }

    printf("Opening server socket.\n");
    /* open the server socket */
    serverSock = SDLNet_TCP_Open(&ip);
    if(!serverSock)
    {
        printf("SDLNet_TCP_Open done goofed: %s\n",SDLNet_GetError());
        SDLNet_Quit();
        SDL_Quit();
        std::string exception = "fail_to_connect";
        throw exception;
    }

    if(SDLNet_TCP_AddSocket(set,serverSock) == -1)
    {
        printf("SDLNet_TCP_AddSocket done goofed: %s\n",SDLNet_GetError());
        SDLNet_Quit();
        SDL_Quit();
        exit(7);
    }

    pack.type = CONNECTION;
    pack.message = name;
    /* login with a name */
    char* out = PacketToCharArray(pack);
    printf("Sent %s\n", out);
    if(!TCPSend(serverSock, out))
    {
        SDLNet_TCP_Close(serverSock);
        exit(8);
    }

    printf("Logged in as %s\n",name);
    connected = true;
}

void NetworkManagerClient::sendPlayerScore(double score)
{
    Packet outgoing;
    std::stringstream ss;
    std::string s;
    ss << score;
    s = ss.str();
    outgoing.type = SCORE;
    outgoing.message = const_cast<char*>(s.c_str());

    char *incoming = NULL;
    char *out = PacketToCharArray(outgoing);
    //printf("Sending: %s\n", out);
    if(TCPSend(serverSock, out) && TCPReceive(serverSock, &incoming)) {
        printf("Receving: %s\n", incoming);
        Packet pack = charArrayToPacket(incoming);
        if(pack.type != SCORE)
        {
            printf("Error in sendPlayerScore() in NetworkManagerClient.cpp. Score not received from server.\n");
            scores = "";
        }
        else{
            printf("Received message: %s\n", pack.message);
            scores = pack.message;
        }
    }
    else {
        connected = false;
        scores = "";
    }
}

std::string NetworkManagerClient::getPlayerScores()
{
    return scores; //"name,score;"
}

void NetworkManagerClient::resetReadyState()
{
    Packet outgoing;
    outgoing.type = READY;
    outgoing.message = const_cast<char*>("RESET");
    TCPSend(serverSock, PacketToCharArray(outgoing));
}

void NetworkManagerClient::sendPlayerInput(ISpaceShipController* controller)
{
    Packet outgoing;

    bool left = controller->left();
    bool right = controller->right();
    bool up = controller->up();
    bool down = controller->down();
    bool forward = controller->forward();
    bool back = controller->back();
    bool shoot = controller->shoot();

    char result = left;
    result = (result << 1) + right;
    result = (result << 1) + up;
    result = (result << 1) + down;
    result = (result << 1) + forward;
    result = (result << 1) + back;
    result = (result << 1) + shoot;

    outgoing.type = PLAYERINPUT;
    outgoing.message = &result;

    char *out = PacketToCharArray(outgoing);
    if(!TCPSend(serverSock, out))
        connected = false;
}

bool NetworkManagerClient::isOnline()
{
    return connected;
}

void NetworkManagerClient::quit()
{
    Packet outgoing;
    outgoing.type = CONNECTION;
    outgoing.message = const_cast<char*>("QUIT");
    while(!TCPSend(serverSock, PacketToCharArray(outgoing))); // FIXME: what if server crashed?
    connected = false;
}

void NetworkManagerClient::receiveData(Ogre::SceneManager* sceneManager, SoundManager* sound, std::vector<Mineral*>& minerals, std::vector<SpaceShip*>& spaceships, std::vector<GameObject*>& walls)
{
    Packet outgoing;
    outgoing.type = STATE;
    outgoing.message = "NONE";
    char *out = PacketToCharArray(outgoing);
    std::cout << "We are sending state request" << std::endl;
    if(!TCPSend(serverSock, out))
    {
        connected = false;
        return;
    }
    std::cout << "Request Sent" << std::endl;

    char* incoming;
    std::cout << "Waiting for response." << std::endl;
    if(!TCPReceive(serverSock, &incoming))
    {
        connected = false;
        return;
    }
    std::cout << "Received initial response." << std::endl;
    Packet numPackets = charArrayToPacket(incoming);
    int packs = atoi(numPackets.message);
    std::cout << "We are expecting to receive " << packs << " number of packets" << std::endl;

    for(int i = 0; i < packs; ++i)
    {
        std::cout << "We are processing packet number " << i << "." << std::endl;
        if(!TCPReceive(serverSock, &incoming)) {
            connected = false; break;}
        Packet in = charArrayToPacket(incoming);
        if(in.type == MINERAL)
        {
            std::string message(in.message);
            std::string name = message.substr(0, message.find(","));
            message = message.substr(message.find(",") + 1);
            double pos_x = atof(message.substr(0, message.find(",")).c_str());
            message = message.substr(message.find(",") + 1);
            double pos_y = atof(message.substr(0, message.find(",")).c_str());
            message = message.substr(message.find(",") + 1);
            double pos_z = atof(message.substr(0, message.find(",")).c_str());
            message = message.substr(message.find(",") + 1);
            double vel_x = atof(message.substr(0, message.find(",")).c_str());
            message = message.substr(message.find(",") + 1);
            double vel_y = atof(message.substr(0, message.find(",")).c_str());
            message = message.substr(message.find(",") + 1);
            double vel_z = atof(message.substr(0, message.find(",")).c_str());
            message = message.substr(message.find(",") + 1);
            double rot_w = atof(message.substr(0, message.find(",")).c_str());
            message = message.substr(message.find(",") + 1);
            double rot_x = atof(message.substr(0, message.find(",")).c_str());
            message = message.substr(message.find(",") + 1);
            double rot_y = atof(message.substr(0, message.find(",")).c_str());
            message = message.substr(message.find(",") + 1);
            double rot_z = atof(message.substr(0, message.find(",")).c_str());
            message = message.substr(message.find(",") + 1);
            double radius = atof(message.substr(0, message.find(",")).c_str());

            // FIXME: THIS IS BAD, oh well
            bool found = false;
            for(int j = 0; j < minerals.size(); ++i)
            {
                if(minerals[j]->getName() == name)
                {
                    found = true;
                    minerals[j]->getSceneNode()->setPosition(pos_x, pos_y, pos_z);
                    minerals[j]->getSceneNode()->setOrientation(rot_w, rot_x, rot_y, rot_z);
                    break;
                }
            }
            if(!found)
            {
                minerals.push_back(new Mineral(name, sound, sceneManager->getRootSceneNode(), pos_x, pos_y, pos_z, radius));
                minerals.back()->getSceneNode()->setOrientation(rot_w, rot_x, rot_y, rot_z);
            }
        }
        else if(in.type == SPACESHIP)
        {

        }
        else if(in.type == WALL)
        {

        }
    }
}

<commit_msg>edited receiveData<commit_after>#include "NetworkManagerClient.h"
#include <string.h>
#include <sys/types.h>
#include <stdlib.h>

#ifndef WIN32
#include <unistd.h>
#include <sys/time.h>

#else
#include <windows.h>
#include <time.h>

#endif

NetworkManagerClient::NetworkManagerClient(void) : connected(false), scores()
{
    if(SDL_Init(0) != 0){
        printf("SDL_Init done goofed: %s\n", SDL_GetError());
        exit(1);
    }

    if(SDLNet_Init() != 0){
        printf("SDLNet_Init done goofed: %s\n",SDLNet_GetError());
    }
}

NetworkManagerClient::~NetworkManagerClient(void)
{
    SDLNet_Quit();
    SDL_Quit();
}

//main method from tcpmulticlient.c in the SDLNet demos
int NetworkManagerClient::TCPConnect(char *host, long portNo, char *name)
{
    IPaddress ip;
    //	TCPsocket sock;
    char message[MAXLEN];
    int numready;
    SDLNet_SocketSet set;
    fd_set fdset;
    int result;
    char *str;
    struct timeval tv;
    Uint16 port = (Uint16)portNo;

    Packet pack;

    set = SDLNet_AllocSocketSet(1);
    if(!set)
    {
        printf("SDLNet_AllocSocketSet done goofed: %s\n", SDLNet_GetError());
        SDLNet_Quit();
        SDL_Quit();
        exit(4); /*most of the time this is a major error, but do what you want. */
    }

    /* Resolve the argument into an IPaddress type */
    printf("Connecting to %s port %d\n", host, port);
    if(SDLNet_ResolveHost(&ip, host, port)==-1)
    {
        printf("SDLNet_ResolveHost done goofed: %s\n",SDLNet_GetError());
        std::string exception = "fail_to_connect";
        throw exception;
    }

    printf("Opening server socket.\n");
    /* open the server socket */
    serverSock = SDLNet_TCP_Open(&ip);
    if(!serverSock)
    {
        printf("SDLNet_TCP_Open done goofed: %s\n",SDLNet_GetError());
        SDLNet_Quit();
        SDL_Quit();
        std::string exception = "fail_to_connect";
        throw exception;
    }

    if(SDLNet_TCP_AddSocket(set,serverSock) == -1)
    {
        printf("SDLNet_TCP_AddSocket done goofed: %s\n",SDLNet_GetError());
        SDLNet_Quit();
        SDL_Quit();
        exit(7);
    }

    pack.type = CONNECTION;
    pack.message = name;
    /* login with a name */
    char* out = PacketToCharArray(pack);
    printf("Sent %s\n", out);
    if(!TCPSend(serverSock, out))
    {
        SDLNet_TCP_Close(serverSock);
        exit(8);
    }

    printf("Logged in as %s\n",name);
    connected = true;
}

std::string NetworkManagerClient::getPlayerScores()
{
    return scores; //"name,score;"
}

void NetworkManagerClient::resetReadyState()
{
    Packet outgoing;
    outgoing.type = READY;
    outgoing.message = const_cast<char*>("RESET");
    TCPSend(serverSock, PacketToCharArray(outgoing));
}

void NetworkManagerClient::sendPlayerInput(ISpaceShipController* controller)
{
    Packet outgoing;

    bool left = controller->left();
    bool right = controller->right();
    bool up = controller->up();
    bool down = controller->down();
    bool forward = controller->forward();
    bool back = controller->back();
    bool shoot = controller->shoot();

    char result = left;
    result = (result << 1) + right;
    result = (result << 1) + up;
    result = (result << 1) + down;
    result = (result << 1) + forward;
    result = (result << 1) + back;
    result = (result << 1) + shoot;

    outgoing.type = PLAYERINPUT;
    outgoing.message = &result;

    char *out = PacketToCharArray(outgoing);
    if(!TCPSend(serverSock, out))
        connected = false;
}

bool NetworkManagerClient::isOnline()
{
    return connected;
}

void NetworkManagerClient::quit()
{
    Packet outgoing;
    outgoing.type = CONNECTION;
    outgoing.message = const_cast<char*>("QUIT");
    while(!TCPSend(serverSock, PacketToCharArray(outgoing))); // FIXME: what if server crashed?
    connected = false;
}

void NetworkManagerClient::sendPlayerScore(double score)
{
    std::stringstream ss;
    std::string s;
    ss << score;
    s = ss.str();

    Packet outgoing;
    outgoing.type = SCORE;
    outgoing.message = const_cast<char*>(s.c_str());
    char *incoming = NULL;
    char *out = PacketToCharArray(outgoing);
    if(TCPSend(serverSock, out) && TCPReceive(serverSock, &incoming)) {
        printf("Receving: %s\n", incoming);
        Packet pack = charArrayToPacket(incoming);
        if(pack.type != SCORE)
        {
            printf("Error in sendPlayerScore() in NetworkManagerClient.cpp. Score not received from server.\n");
            scores = "";
        }
        else{
            printf("Received message: %s\n", pack.message);
            scores = pack.message;
        }
    }
    else {
        connected = false;
        scores = "";
    }
}

void NetworkManagerClient::receiveData(Ogre::SceneManager* sceneManager, SoundManager* sound, std::vector<Mineral*>& minerals, std::vector<SpaceShip*>& spaceships, std::vector<GameObject*>& walls)
{
    Packet outgoing;
    outgoing.type = STATE;
    outgoing.message = "NONE";
    char* incoming = NULL;
    char *out = PacketToCharArray(outgoing);
    std::cout << "We are sending state request and trying to receive initial response." << std::endl;
    if(TCPSend(serverSock, out) && TCPReceive(serverSock, &incoming)) {
        std::cout << "Received initial response." << std::endl;
        Packet numPackets = charArrayToPacket(incoming);
        int packs = atoi(numPackets.message);
        std::cout << "We are expecting to receive " << packs << " number of packets" << std::endl;
    }
    else {
        connected = false;
        return;
    }

    for(int i = 0; i < packs; ++i)
    {
        std::cout << "We are processing packet number " << i << "." << std::endl;
        if(!TCPReceive(serverSock, &incoming)) {
            connected = false; break;}
        Packet in = charArrayToPacket(incoming);
        if(in.type == MINERAL)
        {
            std::string message(in.message);
            std::string name = message.substr(0, message.find(","));
            message = message.substr(message.find(",") + 1);
            double pos_x = atof(message.substr(0, message.find(",")).c_str());
            message = message.substr(message.find(",") + 1);
            double pos_y = atof(message.substr(0, message.find(",")).c_str());
            message = message.substr(message.find(",") + 1);
            double pos_z = atof(message.substr(0, message.find(",")).c_str());
            message = message.substr(message.find(",") + 1);
            double vel_x = atof(message.substr(0, message.find(",")).c_str());
            message = message.substr(message.find(",") + 1);
            double vel_y = atof(message.substr(0, message.find(",")).c_str());
            message = message.substr(message.find(",") + 1);
            double vel_z = atof(message.substr(0, message.find(",")).c_str());
            message = message.substr(message.find(",") + 1);
            double rot_w = atof(message.substr(0, message.find(",")).c_str());
            message = message.substr(message.find(",") + 1);
            double rot_x = atof(message.substr(0, message.find(",")).c_str());
            message = message.substr(message.find(",") + 1);
            double rot_y = atof(message.substr(0, message.find(",")).c_str());
            message = message.substr(message.find(",") + 1);
            double rot_z = atof(message.substr(0, message.find(",")).c_str());
            message = message.substr(message.find(",") + 1);
            double radius = atof(message.substr(0, message.find(",")).c_str());

            // FIXME: THIS IS BAD, oh well
            bool found = false;
            for(int j = 0; j < minerals.size(); ++i)
            {
                if(minerals[j]->getName() == name)
                {
                    found = true;
                    minerals[j]->getSceneNode()->setPosition(pos_x, pos_y, pos_z);
                    minerals[j]->getSceneNode()->setOrientation(rot_w, rot_x, rot_y, rot_z);
                    break;
                }
            }
            if(!found)
            {
                minerals.push_back(new Mineral(name, sound, sceneManager->getRootSceneNode(), pos_x, pos_y, pos_z, radius));
                minerals.back()->getSceneNode()->setOrientation(rot_w, rot_x, rot_y, rot_z);
            }
        }
        else if(in.type == SPACESHIP)
        {

        }
        else if(in.type == WALL)
        {

        }
    }
}

<|endoftext|>


<commit_before>/*
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Library General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 * RobeWidgetTest.cpp
 * Test fixture for the DmxterWidget class
 * Copyright (C) 2010 Simon Newton
 */

#include <string.h>
#include <cppunit/extensions/HelperMacros.h>
#include <queue>
#include <string>
#include <vector>

#include "ola/BaseTypes.h"
#include "ola/DmxBuffer.h"
#include "ola/Callback.h"
#include "ola/Logging.h"
#include "plugins/usbpro/RobeWidget.h"
#include "plugins/usbpro/CommonWidgetTest.h"

using ola::DmxBuffer;
using ola::plugin::usbpro::RobeWidget;
using std::auto_ptr;
using std::string;

class RobeWidgetTest: public CommonWidgetTest {
  CPPUNIT_TEST_SUITE(RobeWidgetTest);
  CPPUNIT_TEST(testSendDMX);
  CPPUNIT_TEST_SUITE_END();

  public:
    void setUp();

    void testSendDMX();

  private:
    auto_ptr<ola::plugin::usbpro::RobeWidget> m_widget;

    void Terminate() {
      m_ss.Terminate();
    }

    static const unsigned int FOOTER_SIZE = 1;
    static const unsigned int HEADER_SIZE = 5;
    static const uint8_t DMX_FRAME_LABEL = 0x06;
};

CPPUNIT_TEST_SUITE_REGISTRATION(RobeWidgetTest);

void RobeWidgetTest::setUp() {
  CommonWidgetTest::setUp();
  m_widget.reset(new ola::plugin::usbpro::RobeWidget(&m_descriptor, &m_ss));
}

/*
 * Check that we can send DMX
 */
void RobeWidgetTest::testSendDMX() {
  // dmx data
  DmxBuffer buffer;
  buffer.SetFromString("0,1,2,3,4");

  // expected message
  uint8_t dmx_frame_data[] = {0, 1, 2, 3, 4, 0, 0, 0, 0};
  // add the expected data, run and verify.
  m_endpoint->AddExpectedRobeMessage(
      DMX_FRAME_LABEL,
      dmx_frame_data,
      sizeof(dmx_frame_data),
      ola::NewSingleCallback(this, &RobeWidgetTest::Terminate));
  m_widget->SendDMX(buffer);
  m_ss.Run();
  m_endpoint->Verify();

  // now test an empty frame
  DmxBuffer buffer2;
  uint8_t empty_frame_data[] = {0, 0, 0, 0};  // null frames still have 4 bytes

  // add the expected data, run and verify.
  m_endpoint->AddExpectedRobeMessage(
      DMX_FRAME_LABEL,
      empty_frame_data,
      sizeof(empty_frame_data),
      ola::NewSingleCallback(this, &RobeWidgetTest::Terminate));
  m_widget->SendDMX(buffer2);
  m_ss.Run();
  m_endpoint->Verify();
}

<commit_msg> * usbpro: fix a robe test<commit_after>/*
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Library General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 * RobeWidgetTest.cpp
 * Test fixture for the DmxterWidget class
 * Copyright (C) 2010 Simon Newton
 */

#include <string.h>
#include <cppunit/extensions/HelperMacros.h>
#include <queue>
#include <string>
#include <vector>

#include "ola/BaseTypes.h"
#include "ola/Callback.h"
#include "ola/DmxBuffer.h"
#include "ola/Logging.h"
#include "ola/rdm/UID.h"
#include "plugins/usbpro/RobeWidget.h"
#include "plugins/usbpro/CommonWidgetTest.h"

using ola::DmxBuffer;
using ola::plugin::usbpro::RobeWidget;
using std::auto_ptr;
using std::string;

class RobeWidgetTest: public CommonWidgetTest {
  CPPUNIT_TEST_SUITE(RobeWidgetTest);
  CPPUNIT_TEST(testSendDMX);
  CPPUNIT_TEST_SUITE_END();

  public:
    void setUp();

    void testSendDMX();

  private:
    auto_ptr<ola::plugin::usbpro::RobeWidget> m_widget;

    void Terminate() {
      m_ss.Terminate();
    }

    static const unsigned int FOOTER_SIZE = 1;
    static const unsigned int HEADER_SIZE = 5;
    static const uint8_t DMX_FRAME_LABEL = 0x06;
};

CPPUNIT_TEST_SUITE_REGISTRATION(RobeWidgetTest);

void RobeWidgetTest::setUp() {
  CommonWidgetTest::setUp();
  ola::rdm::UID uid(0, 1);
  m_widget.reset(
      new ola::plugin::usbpro::RobeWidget(&m_descriptor, &m_ss, uid));
}

/*
 * Check that we can send DMX
 */
void RobeWidgetTest::testSendDMX() {
  // dmx data
  DmxBuffer buffer;
  buffer.SetFromString("0,1,2,3,4");

  // expected message
  uint8_t dmx_frame_data[] = {0, 1, 2, 3, 4, 0, 0, 0, 0};
  // add the expected data, run and verify.
  m_endpoint->AddExpectedRobeMessage(
      DMX_FRAME_LABEL,
      dmx_frame_data,
      sizeof(dmx_frame_data),
      ola::NewSingleCallback(this, &RobeWidgetTest::Terminate));
  m_widget->SendDMX(buffer);
  m_ss.Run();
  m_endpoint->Verify();

  // now test an empty frame
  DmxBuffer buffer2;
  uint8_t empty_frame_data[] = {0, 0, 0, 0};  // null frames still have 4 bytes

  // add the expected data, run and verify.
  m_endpoint->AddExpectedRobeMessage(
      DMX_FRAME_LABEL,
      empty_frame_data,
      sizeof(empty_frame_data),
      ola::NewSingleCallback(this, &RobeWidgetTest::Terminate));
  m_widget->SendDMX(buffer2);
  m_ss.Run();
  m_endpoint->Verify();
}

<|endoftext|>


<commit_before>#include <CLHEP/Units/PhysicalConstants.h>
#include <CLHEP/Random/RandFlat.h>
#include <CLHEP/Random/RandGeneral.h>

#include <RAT/ReacIBDgen.hh>
#include <RAT/DB.hh>
#include <fstream>
#include <iostream>

using namespace CLHEP;

namespace RAT {

#define DEBUG

// Additional constants
const double DELTA = neutron_mass_c2 - proton_mass_c2;
const double GFERMI = 1.16639e-11 / MeV / MeV;

ReacIBDgen::ReacIBDgen()
{
  // Get parameters from database
  DBLinkPtr libd = DB::Get()->GetLink("IBD");

	//WATCH THIS: MAY NEED TO CHANGE TO MATCH THE ENERGY SPECTRUMS OR JUST REMOVE

  Emin = 1.806;  //CHANGED TO MATCH THE ENERGY RANGES IN MARC'S FILE FOR NOW
  Emax = 14.000;

  // Flux function
  // FIXME: For now, I just pull the energy and cross-section randomly from the
  // spectrums given by Marc.  Flux not used anymore in calculating energy.

  //rmpflux.Set(libd->GetDArray("spec_e"), libd->GetDArray("spec_flux"));

  // Other useful numbers
  //XCmax = CrossSection(Emax,-1);
  //FluxMax = rmpflux(Emin);

}

void ReacIBDgen::GenEvent(const Hep3Vector &nu_dir,
		      HepLorentzVector &neutrino,
		      HepLorentzVector &positron,
		      HepLorentzVector &neutron)
{
  float Enu, CosThetaLab;

  // Pick energy of neutrino and relative direction of positron
  GenInteraction(Enu, CosThetaLab);

  // Zero'th order approximation of positron quantities (infinite nucleon mass)
  double E0 = Enu - DELTA;
  double p0 = sqrt(E0*E0 - electron_mass_c2*electron_mass_c2);
  //double v0 = p0/E0;

  // First order correction for finite nucleon mass
  //double Ysquared = (DELTA*DELTA - electron_mass_c2*electron_mass_c2)/2;
  //double E1 = E0*(1 - Enu/proton_mass_c2*(1 - v0*CosThetaLab))
  //             - Ysquared/proton_mass_c2;
  //double p1 = sqrt(E1*E1 - electron_mass_c2*electron_mass_c2);

  // Compute nu 4-momentum
  neutrino.setVect(nu_dir * Enu); // MeV (divide by c if need real units)
  neutrino.setE(Enu);

  // Compute positron 4-momentum
  Hep3Vector pos_momentum(p0*nu_dir);

  // Rotation from nu direction to pos direction.
  double theta = acos(CosThetaLab);
  double phi = 2*pi*HepUniformRand();  // Random phi
  Hep3Vector rotation_axis = nu_dir.orthogonal();
  rotation_axis.rotate(phi, nu_dir);
  pos_momentum.rotate(theta, rotation_axis);

  positron.setVect(pos_momentum);
  positron.setE(E0);

  // Compute neutron 4-momentum
  neutron.setVect(neutrino.vect() - positron.vect());
  neutron.setE(sqrt(neutron.vect().mag2() + neutron_mass_c2*neutron_mass_c2));
}

void ReacIBDgen::GenInteraction(float &E, float &CosThetaLab)
{
    // Pick E from the reactor spectrum and cos(theta) uniformly
    //FIXME: Need to correct cos(theta) with the differential cross-section
    //eventually

    E = GetNuEnergy();
    CosThetaLab = -1.0+2.0*HepUniformRand();

}

float ReacIBDgen::GetNuEnergy()
{
      // This method of setting up probability densities as a function of
      // Energy is taken from the CfSource.cc file.  We use it to generate
      // neutrino energies from the energy spectrums provided by Marc Bergevin.

      // setup the probability density as a function of energy

      // Random generators according to probability densities.
      static CLHEP::RandGeneral* fGenerate = 0;

      static const float flow = Emin; static const float fhigh = Emax;

      static bool first = true;
      if (first)
	{
	  first = false;

	  // In the original code, the probability densities used the
	  // funlxp and funlux routines in CERNLIB to generate random
	  // numbers.  The following code uses CLHEP to generate the
	  // same "histograms" for the RandGeneral random-number
	  // generator.

	  const int probDensSize = 200;
	  double fspace[probDensSize];

	  // Find function values at bin centers.
	  for ( int i=0; i != probDensSize; i++ )
	    {
	      float value = (float(i) + 0.5) * (fhigh - flow) / (float) probDensSize;
	      fspace[i] = IBDESpectrum(flow + value);
#ifdef DEBUG
	      std::cout << "   i=" << i << " f="
			<< fspace[i] << ","
		        << std::endl;

#endif

#ifdef DEBUG
	  //Let's write the fspace prob. density function to a text file.
	  std::ofstream fout("TheProbFunc.txt");
	  if(fout.is_open())
	  {
		std::cout << "Your file is open.  Let's put the probability density function into it..." << std::endl;
		for(int i = 0; i < probDensSize; i++)
		{
			fout << i << " " << fspace[i] << std::endl;
		}
	  fout.close();
	  }
#endif

	  //printf("PDF: i=%d x:%5.2f y:%5.2f\n",i, value, fspace[i]);
	    }

	  // Define random-number generators.  First argument has your
	  // Array of probablility density values, second input has the
	  // number of array elements.
	  fGenerate = new CLHEP::RandGeneral(fspace,probDensSize);

#ifdef DEBUG
	  std::cout << " Random generator test (f):" << std::endl;
	  for ( int i=0; i != 20; i++ )
	    {
	      std::cout << i << ": "
			<< fGenerate->shoot() * (fhigh - flow) + flow << ", "
		        << std::endl;
	    }

#endif
	}

	  float nuE = fGenerate->shoot() * (fhigh - flow) + flow;
#ifdef DEBUG
	  std::cout << "Your generated neutrino energy is..."
		    << nuE
		    << std::endl;
#endif
	  return nuE;
}

double ReacIBDgen::IBDESpectrum(float x)
{
  //I have replaced the CrossSection function that lives in the original IBDgen
  //With the cross section function given in the original source file from
  //Marc Bergevin.
  //double mProton=938.27;
  //double mNeutron=939.565378;
  double mElectron=0.511;
  double XC=CrossSection(x);
  double EnergyVal = NuReacSpectrum(x)*XC*sqrt(XC*XC - mElectron*mElectron);
  //EnergyVal= EnergyVal - (mNeutron - mProton); THIS IS DONE LATER, DUH
  std::cout << EnergyVal << " and " << XC << std::endl;
  return EnergyVal;
  //According to Marc Bergevin's file, the final units output are in GeV and valid from 10 MeV
}

double ReacIBDgen::CrossSection(float x)
{
  //I have replaced the CrossSection function that lives in the original IBDgen
  //With the parameterized IBD neutrino cross section function given in
  // the original source file from Marc Bergevin.

  double mNeutron = 939.565378;
  double mProton = 938.27;
  double mElectron = 0.511;
  double delta = mNeutron - mProton;
  double A = 0.5;
  double B = mNeutron*mNeutron;
  double C = 4.0*mProton;
  double D = delta+(delta*delta - mElectron*mElectron)/(2*mProton);
  double E = mNeutron;

  double XC = A*(sqrt(B - C*(D-x)) - E);

   return XC;
}

float ReacIBDgen::U235ReacSpectrum(const float& x){

    // return the the reactor U235 neutrino flux contribution U235(x)
    float N = 0.;

    double C0=0.496;
    double C1=0.870;
    double C2=0.160;
    double C3=0.091;
    //double C4=201.92;  //Defined in Marc's file; not sure of function

    N = C0 * exp(C1 - C2*x - C3*x*x);

    std::cout << "N " << N << std::endl;
    return N;
  }

float ReacIBDgen::Pu239ReacSpectrum(const float& x){

    // return the reactor Pu239 neutrino flux contribution Pu239(x)
    float N = 0.;

    double C0=0.351;
    double C1=0.896;
    double C2=0.239;
    double C3=0.0981;
    //double C4=209.99;  //Defined in Marc's file; not sure of function

    N = C0 * exp(C1 - C2*x - C3*x*x);

    std::cout << "N " << N << std::endl;
    return N;
  }

float ReacIBDgen::U238ReacSpectrum(const float& x){

    // return the reactor U238 neutrino flux contribution U238(x)
    float N = 0.;

    double C0=0.087;
    double C1=0.976;
    double C2=0.162;
    double C3=0.079;
    //double C4=205.52;  //Defined in Marc's file; not sure of function

    N = C0 * exp(C1 - C2*x - C3*x*x);

    std::cout << "N " << N << std::endl;
    return N;
  }

float ReacIBDgen::Pu241ReacSpectrum(const float& x){

    // return the the reactor Pu241 Neutrino flux contribution Pu241(x)
    float N = 0.;

    double C0=0.066;
    double C1=0.793;
    double C2=0.080;
    double C3=0.1085;
    //double C4=213.60;  //Defined in Marc's file; not sure of function

    N = C0 * exp(C1 - C2*x - C3*x*x);

    std::cout << "N " << N << std::endl;
    return N;
  }

float ReacIBDgen::NuReacSpectrum(const float& x){

  // return the sum of the neutrino flux contributions from each reactor isotope
  // for a given value x (energy in MeV)

  float tot = U235ReacSpectrum(x) + Pu239ReacSpectrum(x) + U238ReacSpectrum(x) + Pu241ReacSpectrum(x);

  return tot;
  }

} // namespace RAT
<commit_msg>Removed some deprecated comments.<commit_after>#include <CLHEP/Units/PhysicalConstants.h>
#include <CLHEP/Random/RandFlat.h>
#include <CLHEP/Random/RandGeneral.h>

#include <RAT/ReacIBDgen.hh>
#include <RAT/DB.hh>
#include <fstream>
#include <iostream>

using namespace CLHEP;

namespace RAT {

#define DEBUG

// Additional constants
const double DELTA = neutron_mass_c2 - proton_mass_c2;
const double GFERMI = 1.16639e-11 / MeV / MeV;

ReacIBDgen::ReacIBDgen()
{
  // Get parameters from database
  DBLinkPtr libd = DB::Get()->GetLink("IBD");

  Emin = 1.806;  //CHANGED TO MATCH THE ENERGY RANGES IN MARC'S FILE FOR NOW
  Emax = 14.000;

}

void ReacIBDgen::GenEvent(const Hep3Vector &nu_dir,
		      HepLorentzVector &neutrino,
		      HepLorentzVector &positron,
		      HepLorentzVector &neutron)
{
  float Enu, CosThetaLab;

  // Pick energy of neutrino and relative direction of positron
  GenInteraction(Enu, CosThetaLab);

  // Zero'th order approximation of positron quantities (infinite nucleon mass)
  double E0 = Enu - DELTA;
  double p0 = sqrt(E0*E0 - electron_mass_c2*electron_mass_c2);
  //double v0 = p0/E0;

  // First order correction for finite nucleon mass
  //double Ysquared = (DELTA*DELTA - electron_mass_c2*electron_mass_c2)/2;
  //double E1 = E0*(1 - Enu/proton_mass_c2*(1 - v0*CosThetaLab))
  //             - Ysquared/proton_mass_c2;
  //double p1 = sqrt(E1*E1 - electron_mass_c2*electron_mass_c2);

  // Compute nu 4-momentum
  neutrino.setVect(nu_dir * Enu); // MeV (divide by c if need real units)
  neutrino.setE(Enu);

  // Compute positron 4-momentum
  Hep3Vector pos_momentum(p0*nu_dir);

  // Rotation from nu direction to pos direction.
  double theta = acos(CosThetaLab);
  double phi = 2*pi*HepUniformRand();  // Random phi
  Hep3Vector rotation_axis = nu_dir.orthogonal();
  rotation_axis.rotate(phi, nu_dir);
  pos_momentum.rotate(theta, rotation_axis);

  positron.setVect(pos_momentum);
  positron.setE(E0);

  // Compute neutron 4-momentum
  neutron.setVect(neutrino.vect() - positron.vect());
  neutron.setE(sqrt(neutron.vect().mag2() + neutron_mass_c2*neutron_mass_c2));
}

void ReacIBDgen::GenInteraction(float &E, float &CosThetaLab)
{
    // Pick E from the reactor spectrum and cos(theta) uniformly
    //FIXME: Need to correct cos(theta) with the differential cross-section
    //eventually

    E = GetNuEnergy();
    CosThetaLab = -1.0+2.0*HepUniformRand();

}

float ReacIBDgen::GetNuEnergy()
{
      // This method of setting up probability densities as a function of
      // Energy is taken from the CfSource.cc file.  We use it to generate
      // neutrino energies from the energy spectrums provided by Marc Bergevin.

      // setup the probability density as a function of energy

      // Random generators according to probability densities.
      static CLHEP::RandGeneral* fGenerate = 0;

      static const float flow = Emin; static const float fhigh = Emax;

      static bool first = true;
      if (first)
	{
	  first = false;

	  // In the original code, the probability densities used the
	  // funlxp and funlux routines in CERNLIB to generate random
	  // numbers.  The following code uses CLHEP to generate the
	  // same "histograms" for the RandGeneral random-number
	  // generator.

	  const int probDensSize = 200;
	  double fspace[probDensSize];

	  // Find function values at bin centers.
	  for ( int i=0; i != probDensSize; i++ )
	    {
	      float value = (float(i) + 0.5) * (fhigh - flow) / (float) probDensSize;
	      fspace[i] = IBDESpectrum(flow + value);
#ifdef DEBUG
	      std::cout << "   i=" << i << " f="
			<< fspace[i] << ","
		        << std::endl;

#endif

#ifdef DEBUG
	  //Let's write the fspace prob. density function to a text file.
	  std::ofstream fout("TheProbFunc.txt");
	  if(fout.is_open())
	  {
		std::cout << "Your file is open.  Let's put the probability density function into it..." << std::endl;
		for(int i = 0; i < probDensSize; i++)
		{
			fout << i << " " << fspace[i] << std::endl;
		}
	  fout.close();
	  }
#endif

	  //printf("PDF: i=%d x:%5.2f y:%5.2f\n",i, value, fspace[i]);
	    }

	  // Define random-number generators.  First argument has your
	  // Array of probablility density values, second input has the
	  // number of array elements.
	  fGenerate = new CLHEP::RandGeneral(fspace,probDensSize);

#ifdef DEBUG
	  std::cout << " Random generator test (f):" << std::endl;
	  for ( int i=0; i != 20; i++ )
	    {
	      std::cout << i << ": "
			<< fGenerate->shoot() * (fhigh - flow) + flow << ", "
		        << std::endl;
	    }

#endif
	}

	  float nuE = fGenerate->shoot() * (fhigh - flow) + flow;
#ifdef DEBUG
	  std::cout << "Your generated neutrino energy is..."
		    << nuE
		    << std::endl;
#endif
	  return nuE;
}

double ReacIBDgen::IBDESpectrum(float x)
{
  //I have replaced the CrossSection function that lives in the original IBDgen
  //With the cross section function given in the original source file from
  //Marc Bergevin.
  //double mProton=938.27;
  //double mNeutron=939.565378;
  double mElectron=0.511;
  double XC=CrossSection(x);
  double EnergyVal = NuReacSpectrum(x)*XC*sqrt(XC*XC - mElectron*mElectron);
  std::cout << EnergyVal << " and " << XC << std::endl;
  return EnergyVal;
  //The final units output are in MeV and valid from 10 MeV
}

double ReacIBDgen::CrossSection(float x)
{
  //I have replaced the CrossSection function that lives in the original IBDgen
  //With the parameterized IBD neutrino cross section function given in
  // the original source file from Marc Bergevin.

  double mNeutron = 939.565378;
  double mProton = 938.27;
  double mElectron = 0.511;
  double delta = mNeutron - mProton;
  double A = 0.5;
  double B = mNeutron*mNeutron;
  double C = 4.0*mProton;
  double D = delta+(delta*delta - mElectron*mElectron)/(2*mProton);
  double E = mNeutron;

  double XC = A*(sqrt(B - C*(D-x)) - E);

   return XC;
}

float ReacIBDgen::U235ReacSpectrum(const float& x){

    // return the the reactor U235 neutrino flux contribution U235(x)
    float N = 0.;

    double C0=0.496;
    double C1=0.870;
    double C2=0.160;
    double C3=0.091;
    //double C4=201.92;  //Defined in Marc's file; not sure of function

    N = C0 * exp(C1 - C2*x - C3*x*x);

    std::cout << "N " << N << std::endl;
    return N;
  }

float ReacIBDgen::Pu239ReacSpectrum(const float& x){

    // return the reactor Pu239 neutrino flux contribution Pu239(x)
    float N = 0.;

    double C0=0.351;
    double C1=0.896;
    double C2=0.239;
    double C3=0.0981;
    //double C4=209.99;  //Defined in Marc's file; not sure of function

    N = C0 * exp(C1 - C2*x - C3*x*x);

    std::cout << "N " << N << std::endl;
    return N;
  }

float ReacIBDgen::U238ReacSpectrum(const float& x){

    // return the reactor U238 neutrino flux contribution U238(x)
    float N = 0.;

    double C0=0.087;
    double C1=0.976;
    double C2=0.162;
    double C3=0.079;
    //double C4=205.52;  //Defined in Marc's file; not sure of function

    N = C0 * exp(C1 - C2*x - C3*x*x);

    std::cout << "N " << N << std::endl;
    return N;
  }

float ReacIBDgen::Pu241ReacSpectrum(const float& x){

    // return the the reactor Pu241 Neutrino flux contribution Pu241(x)
    float N = 0.;

    double C0=0.066;
    double C1=0.793;
    double C2=0.080;
    double C3=0.1085;
    //double C4=213.60;  //Defined in Marc's file; not sure of function

    N = C0 * exp(C1 - C2*x - C3*x*x);

    std::cout << "N " << N << std::endl;
    return N;
  }

float ReacIBDgen::NuReacSpectrum(const float& x){

  // return the sum of the neutrino flux contributions from each reactor isotope
  // for a given value x (energy in MeV)

  float tot = U235ReacSpectrum(x) + Pu239ReacSpectrum(x) + U238ReacSpectrum(x) + Pu241ReacSpectrum(x);

  return tot;
  }

} // namespace RAT
<|endoftext|>