<commit_before>#if _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <objbase.h>
#endif

#include <clocale>
#include <memory>
#include <boo/boo.hpp>
#include <boo/graphicsdev/GL.hpp>
#include "CBasics.hpp"
#include "CMemoryCardSys.hpp"
#include "CResFactory.hpp"
#include "CSimplePool.hpp"
#include "Character/CAssetFactory.hpp"
#include "CAi.hpp"
#include "CGameState.hpp"
#include "CInGameTweakManager.hpp"
#include "Particle/CElementGen.hpp"
#include "Character/CAnimData.hpp"
#include "Particle/CDecalManager.hpp"
#include "Graphics/CBooRenderer.hpp"
#include "Audio/CAudioSys.hpp"
#include "Input/CInputGenerator.hpp"
#include "GuiSys/CGuiSys.hpp"
#include "CIOWinManager.hpp"
#include "GuiSys/CSplashScreen.hpp"
#include "CMainFlow.hpp"
#include "GuiSys/CConsoleOutputWindow.hpp"
#include "Audio/CAudioStateWin.hpp"
#include "GameGlobalObjects.hpp"
#include "CArchitectureQueue.hpp"
#include "CMain.hpp"
#include "CTimeProvider.hpp"

#include "DataSpec/DNAMP1/Tweaks/CTweakPlayer.hpp"
#include "DataSpec/DNAMP1/Tweaks/CTweakGame.hpp"

namespace pshag
{
CMemoryCardSys* g_MemoryCardSys = nullptr;
CResFactory*  g_ResFactory = nullptr;
CSimplePool* g_SimplePool = nullptr;
CCharacterFactoryBuilder* g_CharFactoryBuilder = nullptr;
CAiFuncMap* g_AiFuncMap = nullptr;
CGameState* g_GameState = nullptr;
CInGameTweakManagerBase* g_TweakManager = nullptr;
CBooRenderer* g_Renderer = nullptr;

namespace MP1
{
class CMain* g_main = nullptr;

class CGameGlobalObjects
{
    CMemoryCardSys x0_memoryCardSys;
    CResFactory x20_resFactory;
    CSimplePool x114_simplePool;
    CCharacterFactoryBuilder x14c_charFactoryBuilder;
    CAiFuncMap x188_aiFuncMap;
    CGameState x1a8_gameState;
    CInGameTweakManager x1c0_tweakManager;
    std::unique_ptr<CBooRenderer> m_renderer;

    void AddPaksAndFactories()
    {
    }
    void LoadStringTable()
    {
    }
    static CBooRenderer*
    AllocateRenderer(IObjectStore& store,
                     CMemorySys& memSys, CResFactory& resFactory)
    {
        g_Renderer = new CBooRenderer(store, memSys, resFactory);
        return g_Renderer;
    }

public:
    CGameGlobalObjects()
    : x114_simplePool(x20_resFactory)
    {
        g_MemoryCardSys = &x0_memoryCardSys;
        g_ResFactory = &x20_resFactory;
        g_SimplePool = &x114_simplePool;
        g_CharFactoryBuilder = &x14c_charFactoryBuilder;
        g_AiFuncMap = &x188_aiFuncMap;
        g_GameState = &x1a8_gameState;
        g_TweakManager = &x1c0_tweakManager;
    }

    void PostInitialize(CMemorySys& memSys)
    {
        AddPaksAndFactories();
        LoadStringTable();
        m_renderer.reset(AllocateRenderer(x114_simplePool, memSys, x20_resFactory));
    }
};

class CGameArchitectureSupport : public boo::IWindowCallback
{
    CArchitectureQueue m_archQueue;
    CAudioSys m_audioSys;
    CInputGenerator m_inputGenerator;
    CGuiSys m_guiSys;
    CIOWinManager m_ioWinManager;
    CSplashScreen m_splashScreen;
    CMainFlow m_mainFlow;
    CConsoleOutputWindow m_consoleWindow;
    CAudioStateWin m_audioStateWin;

    void mouseDown(const boo::SWindowCoord &coord, boo::EMouseButton button, boo::EModifierKey mods)
    { m_inputGenerator.mouseDown(coord, button, mods); }
    void mouseUp(const boo::SWindowCoord &coord, boo::EMouseButton button, boo::EModifierKey mods)
    { m_inputGenerator.mouseUp(coord, button, mods); }
    void mouseMove(const boo::SWindowCoord &coord)
    { m_inputGenerator.mouseMove(coord); }
    void scroll(const boo::SWindowCoord &coord, const boo::SScrollDelta &scroll)
    { m_inputGenerator.scroll(coord, scroll); }
    void charKeyDown(unsigned long charCode, boo::EModifierKey mods, bool isRepeat)
    { m_inputGenerator.charKeyDown(charCode, mods, isRepeat); }
    void charKeyUp(unsigned long charCode, boo::EModifierKey mods)
    { m_inputGenerator.charKeyUp(charCode, mods); }
    void specialKeyDown(boo::ESpecialKey key, boo::EModifierKey mods, bool isRepeat)
    { m_inputGenerator.specialKeyDown(key, mods, isRepeat); }
    void specialKeyUp(boo::ESpecialKey key, boo::EModifierKey mods)
    { m_inputGenerator.specialKeyUp(key, mods); }
    void modKeyDown(boo::EModifierKey mod, bool isRepeat)
    { m_inputGenerator.modKeyDown(mod, isRepeat);}
    void modKeyUp(boo::EModifierKey mod)
    { m_inputGenerator.modKeyUp(mod); }

    void destroyed() { m_archQueue.Push(std::move(MakeMsg::CreateApplicationExit(EArchMsgTarget::ArchitectureSupport))); }

public:
    CGameArchitectureSupport()
        : m_audioSys(0,0,0,0,0),
          m_inputGenerator(0.0f /*g_tweakPlayer->GetLeftLogicalThreshold()*/,
                           0.0f /*g_tweakPlayer->GetRightLogicalThreshold()*/)
    {
        m_inputGenerator.startScanning();
    }
    bool Update()
    {
        bool finished = false;
        m_inputGenerator.Update(1.0 / 60.0, m_archQueue);

        while(m_archQueue)
        {
            CArchitectureMessage msg = m_archQueue.Pop();
            if (msg.GetTarget() == EArchMsgTarget::ArchitectureSupport)
            {
                if (msg.GetType() == EArchMsgType::ApplicationExit)
                    finished = true;
            }

            if (msg.GetTarget() == EArchMsgTarget::Game && msg.GetType() == EArchMsgType::UserInput)
            {
                const CArchMsgParmUserInput* input = msg.GetParm<CArchMsgParmUserInput>();
                if (input->x4_parm.DStart())
                    m_archQueue.Push(std::move(MakeMsg::CreateApplicationExit(EArchMsgTarget::ArchitectureSupport)));
            }
        }
        return finished;
    }
};

CMain::CMain()
: x6c_memSys(CMemorySys::GetGameAllocator())
{
    g_main = this;
    xe4_gameplayResult = EGameplayResult::Playing;
}
void CMain::RegisterResourceTweaks()
{
}
void CMain::ResetGameState()
{
}

void CMain::InitializeSubsystems()
{
    CElementGen::Initialize();
    CAnimData::InitializeCache();
    CDecalManager::Initialize();
}
void CMain::AddWorldPaks()
{
#if 0
    u32 i = 0;
    while (i <= 255)
    {
        std::string pakName = CBasics::Stringize("%s%i.pak", g_tweakGame->GetWorldPrefix().c_str(), i);
        if (CDvdFile::FileExists(pakName.c_str()))
            g_ResFactory->GetLoader().AddPakFile(pakName, false);
        i++;
    }
#endif
}

void CMain::FillInAssetIDs()
{
}
void CMain::LoadAudio()
{
}

int CMain::appMain(boo::IApplication* app)
{
    Zeus::detectCPU();
    mainWindow = app->newWindow(_S("Metroid Prime 1 Reimplementation vZygote"));
    mainWindow->showWindow();
    TOneStatic<CGameGlobalObjects> globalObjs;
    InitializeSubsystems();
    globalObjs->PostInitialize(x6c_memSys);
    x70_tweaks.RegisterTweaks();
    AddWorldPaks();
    g_TweakManager->ReadFromMemoryCard("AudioTweaks");
    FillInAssetIDs();
    TOneStatic<CGameArchitectureSupport> archSupport;
    mainWindow->setCallback(archSupport.GetAllocSpace());

    boo::IGraphicsCommandQueue* gfxQ = mainWindow->getCommandQueue();
    float rgba[4] = { 0.2f, 0.2f, 0.2f, 1.0f};
    gfxQ->setClearColor(rgba);

    while (!xe8_b24_finished)
    {
        mainWindow->waitForRetrace();
        xe8_b24_finished = archSupport->Update();
        gfxQ->clearTarget();

        gfxQ->resolveDisplay(nullptr);
        gfxQ->execute();
    }
    return 0;
}

}
}

#ifdef _WIN32
int wmain(int argc, const wchar_t* argv[])
#else
int main(int argc, const char* argv[])
#endif
{
#if _WIN32
    CoInitializeEx(nullptr, COINIT_MULTITHREADED);
#else
    std::setlocale(LC_ALL, "en-US.UTF-8");
#endif

    LogVisor::RegisterConsoleLogger();
    pshag::TOneStatic<pshag::MP1::CMain> main;
    int ret = boo::ApplicationRun(boo::IApplication::EPlatformType::Auto, *main,
                                  _S("mp1"), _S("MP1"), argc, argv);
    return ret;
}
<commit_msg>Use rendertarget<commit_after>#if _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <objbase.h>
#endif

#include <clocale>
#include <memory>
#include <boo/boo.hpp>
#include <boo/graphicsdev/GL.hpp>
#include "CBasics.hpp"
#include "CMemoryCardSys.hpp"
#include "CResFactory.hpp"
#include "CSimplePool.hpp"
#include "Character/CAssetFactory.hpp"
#include "CAi.hpp"
#include "CGameState.hpp"
#include "CInGameTweakManager.hpp"
#include "Particle/CElementGen.hpp"
#include "Character/CAnimData.hpp"
#include "Particle/CDecalManager.hpp"
#include "Graphics/CBooRenderer.hpp"
#include "Audio/CAudioSys.hpp"
#include "Input/CInputGenerator.hpp"
#include "GuiSys/CGuiSys.hpp"
#include "CIOWinManager.hpp"
#include "GuiSys/CSplashScreen.hpp"
#include "CMainFlow.hpp"
#include "GuiSys/CConsoleOutputWindow.hpp"
#include "Audio/CAudioStateWin.hpp"
#include "GameGlobalObjects.hpp"
#include "CArchitectureQueue.hpp"
#include "CMain.hpp"
#include "CTimeProvider.hpp"

#include "DataSpec/DNAMP1/Tweaks/CTweakPlayer.hpp"
#include "DataSpec/DNAMP1/Tweaks/CTweakGame.hpp"

namespace pshag
{
CMemoryCardSys* g_MemoryCardSys = nullptr;
CResFactory*  g_ResFactory = nullptr;
CSimplePool* g_SimplePool = nullptr;
CCharacterFactoryBuilder* g_CharFactoryBuilder = nullptr;
CAiFuncMap* g_AiFuncMap = nullptr;
CGameState* g_GameState = nullptr;
CInGameTweakManagerBase* g_TweakManager = nullptr;
CBooRenderer* g_Renderer = nullptr;

namespace MP1
{
class CMain* g_main = nullptr;

class CGameGlobalObjects
{
    CMemoryCardSys x0_memoryCardSys;
    CResFactory x20_resFactory;
    CSimplePool x114_simplePool;
    CCharacterFactoryBuilder x14c_charFactoryBuilder;
    CAiFuncMap x188_aiFuncMap;
    CGameState x1a8_gameState;
    CInGameTweakManager x1c0_tweakManager;
    std::unique_ptr<CBooRenderer> m_renderer;

    void AddPaksAndFactories()
    {
    }
    void LoadStringTable()
    {
    }
    static CBooRenderer*
    AllocateRenderer(IObjectStore& store,
                     CMemorySys& memSys, CResFactory& resFactory)
    {
        g_Renderer = new CBooRenderer(store, memSys, resFactory);
        return g_Renderer;
    }

public:
    CGameGlobalObjects()
    : x114_simplePool(x20_resFactory)
    {
        g_MemoryCardSys = &x0_memoryCardSys;
        g_ResFactory = &x20_resFactory;
        g_SimplePool = &x114_simplePool;
        g_CharFactoryBuilder = &x14c_charFactoryBuilder;
        g_AiFuncMap = &x188_aiFuncMap;
        g_GameState = &x1a8_gameState;
        g_TweakManager = &x1c0_tweakManager;
    }

    void PostInitialize(CMemorySys& memSys)
    {
        AddPaksAndFactories();
        LoadStringTable();
        m_renderer.reset(AllocateRenderer(x114_simplePool, memSys, x20_resFactory));
    }
};

class CGameArchitectureSupport : public boo::IWindowCallback
{
    CArchitectureQueue m_archQueue;
    CAudioSys m_audioSys;
    CInputGenerator m_inputGenerator;
    CGuiSys m_guiSys;
    CIOWinManager m_ioWinManager;
    CSplashScreen m_splashScreen;
    CMainFlow m_mainFlow;
    CConsoleOutputWindow m_consoleWindow;
    CAudioStateWin m_audioStateWin;
    boo::SWindowRect m_windowRect;
    bool m_rectIsDirty;

    void mouseDown(const boo::SWindowCoord &coord, boo::EMouseButton button, boo::EModifierKey mods)
    { m_inputGenerator.mouseDown(coord, button, mods); }
    void mouseUp(const boo::SWindowCoord &coord, boo::EMouseButton button, boo::EModifierKey mods)
    { m_inputGenerator.mouseUp(coord, button, mods); }
    void mouseMove(const boo::SWindowCoord &coord)
    { m_inputGenerator.mouseMove(coord); }
    void scroll(const boo::SWindowCoord &coord, const boo::SScrollDelta &scroll)
    { m_inputGenerator.scroll(coord, scroll); }
    void charKeyDown(unsigned long charCode, boo::EModifierKey mods, bool isRepeat)
    { m_inputGenerator.charKeyDown(charCode, mods, isRepeat); }
    void charKeyUp(unsigned long charCode, boo::EModifierKey mods)
    { m_inputGenerator.charKeyUp(charCode, mods); }
    void specialKeyDown(boo::ESpecialKey key, boo::EModifierKey mods, bool isRepeat)
    { m_inputGenerator.specialKeyDown(key, mods, isRepeat); }
    void specialKeyUp(boo::ESpecialKey key, boo::EModifierKey mods)
    { m_inputGenerator.specialKeyUp(key, mods); }
    void modKeyDown(boo::EModifierKey mod, bool isRepeat)
    { m_inputGenerator.modKeyDown(mod, isRepeat);}
    void modKeyUp(boo::EModifierKey mod)
    { m_inputGenerator.modKeyUp(mod); }

    void destroyed() { m_archQueue.Push(std::move(MakeMsg::CreateApplicationExit(EArchMsgTarget::ArchitectureSupport))); }

    void resized(const boo::SWindowRect &rect)
    {
        m_windowRect = rect;
        m_rectIsDirty = true;
    }

public:
    CGameArchitectureSupport()
        : m_audioSys(0,0,0,0,0),
          m_inputGenerator(0.0f /*g_tweakPlayer->GetLeftLogicalThreshold()*/,
                           0.0f /*g_tweakPlayer->GetRightLogicalThreshold()*/)
    {
        m_inputGenerator.startScanning();
    }
    bool Update()
    {
        bool finished = false;
        m_inputGenerator.Update(1.0 / 60.0, m_archQueue);

        while(m_archQueue)
        {
            CArchitectureMessage msg = m_archQueue.Pop();
            if (msg.GetTarget() == EArchMsgTarget::ArchitectureSupport)
            {
                if (msg.GetType() == EArchMsgType::ApplicationExit)
                    finished = true;
            }

            if (msg.GetTarget() == EArchMsgTarget::Game && msg.GetType() == EArchMsgType::UserInput)
            {
                const CArchMsgParmUserInput* input = msg.GetParm<CArchMsgParmUserInput>();
                if (input->x4_parm.DStart())
                    m_archQueue.Push(std::move(MakeMsg::CreateApplicationExit(EArchMsgTarget::ArchitectureSupport)));
            }
        }
        return finished;
    }

    bool isRectDirty() { return m_rectIsDirty; }
    const boo::SWindowRect& getWindowRect()
    {
        m_rectIsDirty = false;
        return m_windowRect;
    }
};

CMain::CMain()
: x6c_memSys(CMemorySys::GetGameAllocator())
{
    g_main = this;
    xe4_gameplayResult = EGameplayResult::Playing;
}
void CMain::RegisterResourceTweaks()
{
}
void CMain::ResetGameState()
{
}

void CMain::InitializeSubsystems()
{
    CElementGen::Initialize();
    CAnimData::InitializeCache();
    CDecalManager::Initialize();
}
void CMain::AddWorldPaks()
{
#if 0
    u32 i = 0;
    while (i <= 255)
    {
        std::string pakName = CBasics::Stringize("%s%i.pak", g_tweakGame->GetWorldPrefix().c_str(), i);
        if (CDvdFile::FileExists(pakName.c_str()))
            g_ResFactory->GetLoader().AddPakFile(pakName, false);
        i++;
    }
#endif
}

void CMain::FillInAssetIDs()
{
}
void CMain::LoadAudio()
{
}

int CMain::appMain(boo::IApplication* app)
{
    Zeus::detectCPU();
    mainWindow = app->newWindow(_S("Metroid Prime 1 Reimplementation vZygote"));
    mainWindow->showWindow();
    TOneStatic<CGameGlobalObjects> globalObjs;
    InitializeSubsystems();
    globalObjs->PostInitialize(x6c_memSys);
    x70_tweaks.RegisterTweaks();
    AddWorldPaks();
    g_TweakManager->ReadFromMemoryCard("AudioTweaks");
    FillInAssetIDs();
    TOneStatic<CGameArchitectureSupport> archSupport;
    mainWindow->setCallback(archSupport.GetAllocSpace());

    boo::IGraphicsCommandQueue* gfxQ = mainWindow->getCommandQueue();
    boo::SWindowRect windowRect = mainWindow->getWindowFrame();
    boo::ITextureR* renderTex = mainWindow->getMainContextDataFactory()->newRenderTexture(windowRect.size[0], windowRect.size[1], 1);
    float rgba[4] = { 0.2f, 0.2f, 0.2f, 1.0f};
    gfxQ->setClearColor(rgba);

    while (!xe8_b24_finished)
    {
        mainWindow->waitForRetrace();
        xe8_b24_finished = archSupport->Update();

        if (archSupport->isRectDirty())
        {
            const boo::SWindowRect& windowRect = archSupport->getWindowRect();
            gfxQ->resizeRenderTexture(renderTex,
                                      windowRect.size[0],
                                      windowRect.size[1]);
        }

        gfxQ->setRenderTarget(renderTex);
        gfxQ->clearTarget();
        gfxQ->resolveDisplay(renderTex);
        gfxQ->execute();
    }
    return 0;
}

}
}

#ifdef _WIN32
int wmain(int argc, const wchar_t* argv[])
#else
int main(int argc, const char* argv[])
#endif
{
#if _WIN32
    CoInitializeEx(nullptr, COINIT_MULTITHREADED);
#else
    std::setlocale(LC_ALL, "en-US.UTF-8");
#endif

    LogVisor::RegisterConsoleLogger();
    pshag::TOneStatic<pshag::MP1::CMain> main;
    int ret = boo::ApplicationRun(boo::IApplication::EPlatformType::Auto, *main,
                                  _S("mp1"), _S("MP1"), argc, argv);
    return ret;
}
<|endoftext|>


<commit_before>#if !defined __GNUC__
#pragma warning( disable: 4571 4820 4514 4987 4710 4309 4986 4548)
// relative include path contains '..'
// (function) selected for automatic inline expansion
#pragma warning( disable: 4464 4711 )
#endif

#include <iostream>
#include "../SafeInt.hpp"

enum class Foo
{
	Foo1 = 0,
	Foo2
};

template <typename T, typename U>
void CompiledMixedType()
{
	// Mixed constructors
	U u = 0;
	SafeInt<T> st(u);
	SafeInt<U> su(u);
	SafeInt<T> st2(su);
}

template <typename T>
void CompileType()
{
	// Test constructors
	SafeInt<T> s;
	SafeInt<T> i(Foo::Foo1);
	T t = 0;
	SafeInt<T> st(t);
	SafeInt<T> b(false);

	// Mixed operations
	CompiledMixedType<T, char>();
	CompiledMixedType<T, signed char>();
	CompiledMixedType<T, unsigned char>();
	CompiledMixedType<T, short>();
	CompiledMixedType<T, unsigned short>();
	CompiledMixedType<T, int>();
	CompiledMixedType<T, unsigned int>();
	CompiledMixedType<T, long>();
	CompiledMixedType<T, unsigned long>();
	CompiledMixedType<T, long long>();
	CompiledMixedType<T, unsigned long long>();
}

void CompileMe()
{
	CompileType<char>();
	CompileType<unsigned char>();
	CompileType<signed char>();

	CompileType<unsigned short>();
	CompileType<signed short>();
	CompileType<unsigned int>();
	CompileType<signed int>();
	CompileType<unsigned long>();
	CompileType<signed long>();
	CompileType<unsigned long long>();
	CompileType<signed long long>();
}

int main(int, char**)
{
  std::cout << "It compiles!\n";
  return 0;
}
<commit_msg>Clang warning suppression.<commit_after>#if !defined __GNUC__
#pragma warning( disable: 4571 4820 4514 4987 4710 4309 4986 4548)
// relative include path contains '..'
// (function) selected for automatic inline expansion
#pragma warning( disable: 4464 4711 )
#else
#pragma GCC diagnostic ignored "-Wunused-variable"
#endif

#include <iostream>
#include "../SafeInt.hpp"

enum class Foo
{
	Foo1 = 0,
	Foo2
};

template <typename T, typename U>
void CompiledMixedType()
{
	// Mixed constructors
	U u = 0;
	SafeInt<T> st(u);
	SafeInt<U> su(u);
	SafeInt<T> st2(su);
}

template <typename T>
void CompileType()
{
	// Test constructors
	SafeInt<T> s;
	SafeInt<T> i(Foo::Foo1);
	T t = 0;
	SafeInt<T> st(t);
	SafeInt<T> b(false);

	// Mixed operations
	CompiledMixedType<T, char>();
	CompiledMixedType<T, signed char>();
	CompiledMixedType<T, unsigned char>();
	CompiledMixedType<T, short>();
	CompiledMixedType<T, unsigned short>();
	CompiledMixedType<T, int>();
	CompiledMixedType<T, unsigned int>();
	CompiledMixedType<T, long>();
	CompiledMixedType<T, unsigned long>();
	CompiledMixedType<T, long long>();
	CompiledMixedType<T, unsigned long long>();
}

void CompileMe()
{
	CompileType<char>();
	CompileType<unsigned char>();
	CompileType<signed char>();

	CompileType<unsigned short>();
	CompileType<signed short>();
	CompileType<unsigned int>();
	CompileType<signed int>();
	CompileType<unsigned long>();
	CompileType<signed long>();
	CompileType<unsigned long long>();
	CompileType<signed long long>();
}

int main(int, char**)
{
  std::cout << "It compiles!\n";
  return 0;
}
<|endoftext|>


<commit_before>#include <math.h>
#include <iostream>
#include <cassert>
#include <chrono>
#include <thread>
#include "RhIO.hpp"

int main()
{
    RhIO::Root.newChild("test");
    RhIO::Root.newChild("test2/pouet");
    RhIO::Root.newBool("test/paramBool");
    RhIO::Root.newFloat("test/freq");
    RhIO::Root.newFloat("test/sin")
        ->minimum(-1)
        ->maximum(1);
    RhIO::Root.newInt("test/test3/paramInt")
        ->minimum(-1)
        ->maximum(10);
    RhIO::Root.child("test").newFloat("paramFloat")
        ->comment("this is a test float")
        ->defaultValue(42.0)
        ->persisted(true);
    RhIO::Root.child("test/test3").newStr("paramStr");

    RhIO::Root.newChild("server");
    RhIO::Root.child("server").newStr("hostname")
        ->defaultValue("testServ")
        ->persisted(true)
        ;

    RhIO::Root.newChild("sensors");
    RhIO::Root.newChild("sensors/GyroY");
    RhIO::Root.newFloat("sensors/GyroYaw");

    RhIO::Root.newStream("test/stream1", "Some stream");

    RhIO::Root.newCommand("test/command1",
        "command1",
        [](const std::vector<std::string>& args) -> std::string
        {
            if (args.size()!=1) {
                return "Usage: command1 arg";
            } else {
                return "OK " + args[0];
            }
        });

    std::cout << "Waiting" << std::endl;

    float angle = 0.0;
    RhIO::Bind bind("lowlevel/servos/ChevilleG");
    bind.bindNew("angle", angle);

    auto &out = RhIO::Root.out("test/stream1");

    float t = 0.0;
    while (true) {
        std::this_thread::sleep_for(
            std::chrono::milliseconds(10));
        float f = RhIO::Root.getFloat("test/freq");
        t += 0.01*f;

        RhIO::Root.setFloat("test/sin", sin(t*2*M_PI));
        out << "Debug, t=" << t << ", sin(t) = " << sin(t*2*M_PI) << std::flush;

        angle = sin(t)*1.0;
        bind.push();
    }

    return 0;
}
<commit_msg>Adding buggy completion example<commit_after>#include <math.h>
#include <iostream>
#include <cassert>
#include <chrono>
#include <thread>
#include "RhIO.hpp"

int main()
{
    RhIO::Root.newChild("test");
    RhIO::Root.newChild("test2/pouet");
    RhIO::Root.newBool("test/paramBool");
    RhIO::Root.newFloat("test/freq");
    RhIO::Root.newFloat("test/sin")
        ->minimum(-1)
        ->maximum(1);
    RhIO::Root.newInt("test/test3/paramInt")
        ->minimum(-1)
        ->maximum(10);
    RhIO::Root.child("test").newFloat("paramFloat")
        ->comment("this is a test float")
        ->defaultValue(42.0)
        ->persisted(true);
    RhIO::Root.child("test/test3").newStr("paramStr");

    RhIO::Root.newChild("server");
    RhIO::Root.child("server").newStr("hostname")
        ->defaultValue("testServ")
        ->persisted(true)
        ;

    RhIO::Root.newChild("foo");
    RhIO::Root.newChild("foo/bar");
    RhIO::Root.newFloat("foo/bar/x");
    RhIO::Root.newChild("foo/barz");
    RhIO::Root.newFloat("foo/barz/x");

    RhIO::Root.newStream("test/stream1", "Some stream");

    RhIO::Root.newCommand("test/command1",
        "command1",
        [](const std::vector<std::string>& args) -> std::string
        {
            if (args.size()!=1) {
                return "Usage: command1 arg";
            } else {
                return "OK " + args[0];
            }
        });

    std::cout << "Waiting" << std::endl;

    float angle = 0.0;
    RhIO::Bind bind("lowlevel/servos/ChevilleG");
    bind.bindNew("angle", angle);

    auto &out = RhIO::Root.out("test/stream1");

    float t = 0.0;
    while (true) {
        std::this_thread::sleep_for(
            std::chrono::milliseconds(10));
        float f = RhIO::Root.getFloat("test/freq");
        t += 0.01*f;

        RhIO::Root.setFloat("test/sin", sin(t*2*M_PI));
        out << "Debug, t=" << t << ", sin(t) = " << sin(t*2*M_PI) << std::flush;

        angle = sin(t)*1.0;
        bind.push();
    }

    return 0;
}
<|endoftext|>


<commit_before>#include "EasyCL.h"
#include "util/stringhelper.h"
#include "util/StatefulTimer.h"
#include "templates/TemplatedKernel.h"

#include <sstream>
#include <iostream>
#include <string>

#include <clBLAS.h>

#include "BackwardIm2Col.h"

using namespace std;

#undef STATIC
#define STATIC

#undef VIRTUAL
#define VIRTUAL

#define PUBLIC

PUBLIC BackwardIm2Col::BackwardIm2Col(EasyCL *cl, LayerDimensions dim) :
            Backward(cl, dim)
        {
//    addBias = new AddBias(cl);

    int size = dim.inputSize;
    int padding = dim.padZeros ? dim.halfFilterSize : 0;
    int stride = 1;
    int channels = dim.inputPlanes;
    int size_col = (size + 2 * padding - dim.filterSize) / stride + 1;

    this->numKernels = channels * dim.inputSizeSquared;

    TemplatedKernel builder(cl);
    builder.set("padding", dim.padZeros ? dim.halfFilterSize : 0);
    builder.set("stride", 1);
    builder.set("colSize", size_col);
    builder.set("channels", dim.inputPlanes);
    builder.set("filterSize", dim.filterSize);
    builder.set("size", dim.inputSize);
    this->kernelCol2Im = builder.buildKernel(
        "col2im",
        "ForwardIm2Col.cl",
        getKernelTemplate(),
        "col2im",
        false);
}
PUBLIC VIRTUAL BackwardIm2Col::~BackwardIm2Col() {
    delete kernelCol2Im;
//    delete addBias;
}
PUBLIC VIRTUAL void BackwardIm2Col::backward( int batchSize,
        CLWrapper *inputDataWrapper, CLWrapper *gradOutputWrapper, CLWrapper *weightsWrapper,
        CLWrapper *gradInputWrapper ) {
    StatefulTimer::timeCheck("BackwardIm2Col::backward START");

    int gradColumnsSize = dim.inputPlanes * dim.filterSizeSquared * dim.outputSizeSquared;
    float *gradColumns = new float[gradColumnsSize];
    CLWrapper *gradColumnsWrapper = cl->wrap(gradColumnsSize, gradColumns);
    gradColumnsWrapper->createOnDevice();
//    cout << "gradColumnsSize: " << gradColumnsSize << endl;
//    cout << "weightsize: " << weightsWrapper->size() << endl;

    StatefulTimer::timeCheck("BackwardIm2Col::backward after alloc");

    if(!gradInputWrapper->isOnDevice()) {
        gradInputWrapper->createOnDevice();
    }
    for (int b = 0; b < batchSize; b ++) {
//        cout << "b=" << b << " numkernels=" << numKernels << endl;
        // Extract columns:

        // M,N,K are dims of matrix A and B
        // (see http://docs.nvidia.com/cuda/clblas/#clblas-lt-t-gt-gemm)

//    long m = weight->size[1];  = inputPlanes * filterSizeSquared
//    long n = gradColumns->size[1]; = outputSizeSquared
//    long k = weight->size[0]; = numFilters

        long m = dim.outputSizeSquared;
        long n = dim.inputPlanes * dim.filterSizeSquared;
        long k = dim.numFilters;
//        cout << "m=" << m << " k=" << k << " n=" << n << endl;

        clblasOrder order = clblasColumnMajor;
        clblasTranspose aTrans = clblasNoTrans;
        clblasTranspose bTrans = clblasTrans;
        size_t lda = ((order == clblasRowMajor) != (aTrans == clblasTrans)) ? k : m;
        size_t ldb = ((order == clblasRowMajor) != (bTrans == clblasTrans)) ? n : k;
        size_t ldc = order == clblasRowMajor ? n : m;
        cl_int err = clblasSgemm(
            order,
            aTrans, bTrans,
            m, n, k,
            1,
            gradOutputWrapper->getBuffer(), b * dim.outputCubeSize, lda,
            weightsWrapper->getBuffer(), 0, ldb,
            0,
            gradColumnsWrapper->getBuffer(), 0, ldc,
            1, cl->queue, 0, NULL, 0
       );
       if (err != CL_SUCCESS) {
           throw runtime_error("clblasSgemm() failed with " + toString(err));
       }

//    long m = weight->size[1];
//    long n = gradColumns->size[1];
//    long k = weight->size[0];

//    // Do GEMM (note: this is a bit confusing because gemm assumes column-major matrices)
//    THClBlas_gemm(
//        state,
//        'n', 't',
//        n, m, k,
//        1,
//        gradOutput_n, n,
//        weight, m,
//        0,
//        gradColumns, n
//    );

//       cl->finish();
//       gradOutputWrapper->copyToHost();
//       for( int i = 0; i < gradOutputWrapper->size(); i++ ) {
//           cout << "gradOutput[" << i << "]=" << reinterpret_cast<float *>(gradOutputWrapper->getHostArray())[i] << endl;
//       }
//       weightsWrapper->copyToHost();
//       for( int i = 0; i < weightsWrapper->size(); i++ ) {
//           cout << "weights[" << i << "]=" << reinterpret_cast<float *>(weightsWrapper->getHostArray())[i] << endl;
//       }
//       gradColumnsWrapper->copyToHost();
//       for( int i = 0; i < gradColumnsSize; i++ ) {
//           cout << "gradColumns[" << i << "]=" << reinterpret_cast<float *>(gradColumnsWrapper->getHostArray())[i] << endl;
//       }

//    THClBlas_gemm(
//        'n', 't',
//        n, m, k,
//        1,
//        gradOutput_n, n,
//        weight, m,
//        0,
//        gradColumns, n
//    );
        kernelCol2Im->in(numKernels);
        kernelCol2Im->in(gradColumnsWrapper);
        kernelCol2Im->out(gradInputWrapper);
        kernelCol2Im->in(b * dim.inputCubeSize);

        int workgroupSize = cl->getMaxWorkgroupSize();
        int numWorkgroups = this->numKernels;

//        cout << "numworkgroups=" << numWorkgroups << " workgorupSize=" << workgroupSize << endl;
        kernelCol2Im->run_1d(numWorkgroups * workgroupSize, workgroupSize);

//        cl->finish();
//        gradInputWrapper->copyToHost();
//        cl->finish();
//        for( int i = 0; i < gradInputWrapper->size(); i++ ) {
//            cout << "gradInput[" << i << "]=" << reinterpret_cast<float *>(gradInputWrapper->getHostArray())[i] << endl;
//        }
    }

    delete gradColumnsWrapper;
    delete gradColumns;

    StatefulTimer::timeCheck("BackwardIm2Col::backward after call backward");

    StatefulTimer::timeCheck("BackwardIm2Col::backward END");
}
STATIC std::string BackwardIm2Col::getKernelTemplate() {
    // [[[cog
    // import stringify
    // stringify.write_kernel("kernel", "cl/ForwardIm2Col.cl")
    // ]]]
    // generated using cog, from cl/ForwardIm2Col.cl:
    const char * kernelSource =
    "// from SpatialConvolutionMM.cu:\n"
    "\n"
    "// CL: grid stride looping\n"
    "#define CL_KERNEL_LOOP(i, n)                        \\\n"
    "  for (int i = get_group_id(0) * get_local_size(0) + get_local_id(0); \\\n"
    "      i < (n);                                       \\\n"
    "      i += get_local_size(0) * get_num_groups(0))\n"
    "\n"
    "//#define gPadding {{padding}}\n"
    "//#define gStride {{stride}}\n"
    "//#define gColSize {{colSize}}\n"
    "//#define gFilterSize {{filterSize}}\n"
    "//#define gSize {{size}}\n"
    "\n"
    "// Kernel for fast unfold+copy\n"
    "// (adapted from Caffe: https://github.com/BVLC/caffe/blob/master/src/caffe/layers/conv_layer.cu)\n"
    "kernel void im2col(\n"
    "    const int n,\n"
    "    global float const * im_data, int im_offset,\n"
    "    global float* data_col) {\n"
    "  global const float *data_im = im_data + im_offset;\n"
    "\n"
    "  CL_KERNEL_LOOP(index, n) {\n"
    "    int w_out = index % {{colSize}};\n"
    "    index /= {{colSize}};\n"
    "    int h_out = index % {{colSize}};\n"
    "    int channel_in = index / {{colSize}};\n"
    "    int channel_out = channel_in * {{filterSize}} * {{filterSize}};\n"
    "    int h_in = h_out * {{stride}} - {{padding}};\n"
    "    int w_in = w_out * {{stride}} - {{padding}};\n"
    "    data_col += (channel_out * {{colSize}} + h_out) * {{colSize}} + w_out;\n"
    "    data_im += (channel_in * {{size}} + h_in) * {{size}} + w_in;\n"
    "    for (int i = 0; i < {{filterSize}}; ++i) {\n"
    "      for (int j = 0; j < {{filterSize}}; ++j) {\n"
    "        int h = h_in + i;\n"
    "        int w = w_in + j;\n"
    "        *data_col = (h >= 0 && w >= 0 && h < {{size}} && w < {{size}}) ?\n"
    "          data_im[i * {{size}} + j] : 0;\n"
    "        data_col += {{colSize}} * {{colSize}};\n"
    "      }\n"
    "    }\n"
    "  }\n"
    "}\n"
    "\n"
    "kernel void col2im(\n"
    "    const int n,\n"
    "    global float const *data_col,\n"
    "    global float* im_data, int im_offset) {\n"
    "  global float *data_im = im_data + im_offset;\n"
    "\n"
    "  for (int index = get_group_id(0) * get_local_size(0) + get_local_id(0); index < (n); index += get_local_size(0) * get_num_groups(0)) {\n"
    "    float val = 0;\n"
    "    int w = index % {{size}} + {{padding}};\n"
    "    int h = (index / {{size}}) % {{size}} + {{padding}};\n"
    "    int c = index / ({{size}} * {{size}});\n"
    "    // compute the start and end of the output\n"
    "    int w_col_start = (w < {{filterSize}}) ? 0 : (w - {{filterSize}}) / {{stride}} + 1;\n"
    "    int w_col_end = min(w / {{stride}} + 1, {{colSize}});\n"
    "    int h_col_start = (h < {{filterSize}}) ? 0 : (h - {{filterSize}}) / {{stride}} + 1;\n"
    "    int h_col_end = min(h / {{stride}} + 1, {{colSize}});\n"
    "\n"
    "    int offset = (c * {{filterSize}} * {{filterSize}} + h * {{filterSize}} + w) * {{colSize}} * {{colSize}};\n"
    "    int coeff_h_col = (1 - {{stride}} * {{filterSize}} * {{colSize}}) * {{colSize}};\n"
    "    int coeff_w_col = (1 - {{stride}} * {{colSize}} * {{colSize}});\n"
    "    for (int h_col = h_col_start; h_col < h_col_end; ++h_col) {\n"
    "      for (int w_col = w_col_start; w_col < w_col_end; ++w_col) {\n"
    "        val += data_col[offset + h_col * coeff_h_col + w_col * coeff_w_col];\n"
    "      }\n"
    "    }\n"
    "    data_im[index] = val;\n"
    "  }\n"
    "}\n"
    "\n"
    "";
    // [[[end]]]
    return kernelSource;
}

<commit_msg>initialize clblas at start of backwardim2col<commit_after>#include "EasyCL.h"
#include "util/stringhelper.h"
#include "util/StatefulTimer.h"
#include "templates/TemplatedKernel.h"

#include <sstream>
#include <iostream>
#include <string>

#include <clBLAS.h>

#include "clblas/ClBlasInstance.h"
#include "BackwardIm2Col.h"

using namespace std;

#undef STATIC
#define STATIC

#undef VIRTUAL
#define VIRTUAL

#define PUBLIC

PUBLIC BackwardIm2Col::BackwardIm2Col(EasyCL *cl, LayerDimensions dim) :
            Backward(cl, dim)
        {
    ClBlasInstance::initializeIfNecessary();

//    addBias = new AddBias(cl);

    int size = dim.inputSize;
    int padding = dim.padZeros ? dim.halfFilterSize : 0;
    int stride = 1;
    int channels = dim.inputPlanes;
    int size_col = (size + 2 * padding - dim.filterSize) / stride + 1;

    this->numKernels = channels * dim.inputSizeSquared;

    TemplatedKernel builder(cl);
    builder.set("padding", dim.padZeros ? dim.halfFilterSize : 0);
    builder.set("stride", 1);
    builder.set("colSize", size_col);
    builder.set("channels", dim.inputPlanes);
    builder.set("filterSize", dim.filterSize);
    builder.set("size", dim.inputSize);
    this->kernelCol2Im = builder.buildKernel(
        "col2im",
        "ForwardIm2Col.cl",
        getKernelTemplate(),
        "col2im",
        false);
}
PUBLIC VIRTUAL BackwardIm2Col::~BackwardIm2Col() {
    delete kernelCol2Im;
//    delete addBias;
}
PUBLIC VIRTUAL void BackwardIm2Col::backward( int batchSize,
        CLWrapper *inputDataWrapper, CLWrapper *gradOutputWrapper, CLWrapper *weightsWrapper,
        CLWrapper *gradInputWrapper ) {
    StatefulTimer::timeCheck("BackwardIm2Col::backward START");

    int gradColumnsSize = dim.inputPlanes * dim.filterSizeSquared * dim.outputSizeSquared;
    float *gradColumns = new float[gradColumnsSize];
    CLWrapper *gradColumnsWrapper = cl->wrap(gradColumnsSize, gradColumns);
    gradColumnsWrapper->createOnDevice();
//    cout << "gradColumnsSize: " << gradColumnsSize << endl;
//    cout << "weightsize: " << weightsWrapper->size() << endl;

    StatefulTimer::timeCheck("BackwardIm2Col::backward after alloc");

    if(!gradInputWrapper->isOnDevice()) {
        gradInputWrapper->createOnDevice();
    }
    for (int b = 0; b < batchSize; b ++) {
//        cout << "b=" << b << " numkernels=" << numKernels << endl;
        // Extract columns:

        // M,N,K are dims of matrix A and B
        // (see http://docs.nvidia.com/cuda/clblas/#clblas-lt-t-gt-gemm)

//    long m = weight->size[1];  = inputPlanes * filterSizeSquared
//    long n = gradColumns->size[1]; = outputSizeSquared
//    long k = weight->size[0]; = numFilters

        long m = dim.outputSizeSquared;
        long n = dim.inputPlanes * dim.filterSizeSquared;
        long k = dim.numFilters;
//        cout << "m=" << m << " k=" << k << " n=" << n << endl;

        clblasOrder order = clblasColumnMajor;
        clblasTranspose aTrans = clblasNoTrans;
        clblasTranspose bTrans = clblasTrans;
        size_t lda = ((order == clblasRowMajor) != (aTrans == clblasTrans)) ? k : m;
        size_t ldb = ((order == clblasRowMajor) != (bTrans == clblasTrans)) ? n : k;
        size_t ldc = order == clblasRowMajor ? n : m;
        cl_int err = clblasSgemm(
            order,
            aTrans, bTrans,
            m, n, k,
            1,
            gradOutputWrapper->getBuffer(), b * dim.outputCubeSize, lda,
            weightsWrapper->getBuffer(), 0, ldb,
            0,
            gradColumnsWrapper->getBuffer(), 0, ldc,
            1, cl->queue, 0, NULL, 0
       );
       if (err != CL_SUCCESS) {
           throw runtime_error("clblasSgemm() failed with " + toString(err));
       }

//    long m = weight->size[1];
//    long n = gradColumns->size[1];
//    long k = weight->size[0];

//    // Do GEMM (note: this is a bit confusing because gemm assumes column-major matrices)
//    THClBlas_gemm(
//        state,
//        'n', 't',
//        n, m, k,
//        1,
//        gradOutput_n, n,
//        weight, m,
//        0,
//        gradColumns, n
//    );

//       cl->finish();
//       gradOutputWrapper->copyToHost();
//       for( int i = 0; i < gradOutputWrapper->size(); i++ ) {
//           cout << "gradOutput[" << i << "]=" << reinterpret_cast<float *>(gradOutputWrapper->getHostArray())[i] << endl;
//       }
//       weightsWrapper->copyToHost();
//       for( int i = 0; i < weightsWrapper->size(); i++ ) {
//           cout << "weights[" << i << "]=" << reinterpret_cast<float *>(weightsWrapper->getHostArray())[i] << endl;
//       }
//       gradColumnsWrapper->copyToHost();
//       for( int i = 0; i < gradColumnsSize; i++ ) {
//           cout << "gradColumns[" << i << "]=" << reinterpret_cast<float *>(gradColumnsWrapper->getHostArray())[i] << endl;
//       }

//    THClBlas_gemm(
//        'n', 't',
//        n, m, k,
//        1,
//        gradOutput_n, n,
//        weight, m,
//        0,
//        gradColumns, n
//    );
        kernelCol2Im->in(numKernels);
        kernelCol2Im->in(gradColumnsWrapper);
        kernelCol2Im->out(gradInputWrapper);
        kernelCol2Im->in(b * dim.inputCubeSize);

        int workgroupSize = cl->getMaxWorkgroupSize();
        int numWorkgroups = this->numKernels;

//        cout << "numworkgroups=" << numWorkgroups << " workgorupSize=" << workgroupSize << endl;
        kernelCol2Im->run_1d(numWorkgroups * workgroupSize, workgroupSize);

//        cl->finish();
//        gradInputWrapper->copyToHost();
//        cl->finish();
//        for( int i = 0; i < gradInputWrapper->size(); i++ ) {
//            cout << "gradInput[" << i << "]=" << reinterpret_cast<float *>(gradInputWrapper->getHostArray())[i] << endl;
//        }
    }

    delete gradColumnsWrapper;
    delete gradColumns;

    StatefulTimer::timeCheck("BackwardIm2Col::backward after call backward");

    StatefulTimer::timeCheck("BackwardIm2Col::backward END");
}
STATIC std::string BackwardIm2Col::getKernelTemplate() {
    // [[[cog
    // import stringify
    // stringify.write_kernel("kernel", "cl/ForwardIm2Col.cl")
    // ]]]
    // generated using cog, from cl/ForwardIm2Col.cl:
    const char * kernelSource =
    "// from SpatialConvolutionMM.cu:\n"
    "\n"
    "// CL: grid stride looping\n"
    "#define CL_KERNEL_LOOP(i, n)                        \\\n"
    "  for (int i = get_group_id(0) * get_local_size(0) + get_local_id(0); \\\n"
    "      i < (n);                                       \\\n"
    "      i += get_local_size(0) * get_num_groups(0))\n"
    "\n"
    "//#define gPadding {{padding}}\n"
    "//#define gStride {{stride}}\n"
    "//#define gColSize {{colSize}}\n"
    "//#define gFilterSize {{filterSize}}\n"
    "//#define gSize {{size}}\n"
    "\n"
    "// Kernel for fast unfold+copy\n"
    "// (adapted from Caffe: https://github.com/BVLC/caffe/blob/master/src/caffe/layers/conv_layer.cu)\n"
    "kernel void im2col(\n"
    "    const int n,\n"
    "    global float const * im_data, int im_offset,\n"
    "    global float* data_col) {\n"
    "  global const float *data_im = im_data + im_offset;\n"
    "\n"
    "  CL_KERNEL_LOOP(index, n) {\n"
    "    int w_out = index % {{colSize}};\n"
    "    index /= {{colSize}};\n"
    "    int h_out = index % {{colSize}};\n"
    "    int channel_in = index / {{colSize}};\n"
    "    int channel_out = channel_in * {{filterSize}} * {{filterSize}};\n"
    "    int h_in = h_out * {{stride}} - {{padding}};\n"
    "    int w_in = w_out * {{stride}} - {{padding}};\n"
    "    data_col += (channel_out * {{colSize}} + h_out) * {{colSize}} + w_out;\n"
    "    data_im += (channel_in * {{size}} + h_in) * {{size}} + w_in;\n"
    "    for (int i = 0; i < {{filterSize}}; ++i) {\n"
    "      for (int j = 0; j < {{filterSize}}; ++j) {\n"
    "        int h = h_in + i;\n"
    "        int w = w_in + j;\n"
    "        *data_col = (h >= 0 && w >= 0 && h < {{size}} && w < {{size}}) ?\n"
    "          data_im[i * {{size}} + j] : 0;\n"
    "        data_col += {{colSize}} * {{colSize}};\n"
    "      }\n"
    "    }\n"
    "  }\n"
    "}\n"
    "\n"
    "kernel void col2im(\n"
    "    const int n,\n"
    "    global float const *data_col,\n"
    "    global float* im_data, int im_offset) {\n"
    "  global float *data_im = im_data + im_offset;\n"
    "\n"
    "  for (int index = get_group_id(0) * get_local_size(0) + get_local_id(0); index < (n); index += get_local_size(0) * get_num_groups(0)) {\n"
    "    float val = 0;\n"
    "    int w = index % {{size}} + {{padding}};\n"
    "    int h = (index / {{size}}) % {{size}} + {{padding}};\n"
    "    int c = index / ({{size}} * {{size}});\n"
    "    // compute the start and end of the output\n"
    "    int w_col_start = (w < {{filterSize}}) ? 0 : (w - {{filterSize}}) / {{stride}} + 1;\n"
    "    int w_col_end = min(w / {{stride}} + 1, {{colSize}});\n"
    "    int h_col_start = (h < {{filterSize}}) ? 0 : (h - {{filterSize}}) / {{stride}} + 1;\n"
    "    int h_col_end = min(h / {{stride}} + 1, {{colSize}});\n"
    "\n"
    "    int offset = (c * {{filterSize}} * {{filterSize}} + h * {{filterSize}} + w) * {{colSize}} * {{colSize}};\n"
    "    int coeff_h_col = (1 - {{stride}} * {{filterSize}} * {{colSize}}) * {{colSize}};\n"
    "    int coeff_w_col = (1 - {{stride}} * {{colSize}} * {{colSize}});\n"
    "    for (int h_col = h_col_start; h_col < h_col_end; ++h_col) {\n"
    "      for (int w_col = w_col_start; w_col < w_col_end; ++w_col) {\n"
    "        val += data_col[offset + h_col * coeff_h_col + w_col * coeff_w_col];\n"
    "      }\n"
    "    }\n"
    "    data_im[index] = val;\n"
    "  }\n"
    "}\n"
    "\n"
    "";
    // [[[end]]]
    return kernelSource;
}

<|endoftext|>


<commit_before>#include "core/HierarchicalEA.hpp"
#include "exception/NodeAlreadyExistsException.hpp"
#include "exception/InvalidNodeException.hpp"
#include "exception/NoNodesException.hpp"
#include "exception/NoEvolutionOrderException.hpp"

#include <iostream>
#include <algorithm>

HierarchicalEA::HierarchicalEA(int maxEpochs) {
	this->maxEpochs = maxEpochs;
}

HierarchicalEA::~HierarchicalEA() {}

void HierarchicalEA::addNode(PopulationNode * node, string name, bool print) {
	for (int i = 0; i < nodeNames.size(); i++) {
		if (nodeNames[i] == name or nodes[i] == node) {
			throw NodeAlreadyExistsException();
		}
	}
	nodes.push_back(node);
	nodeNames.push_back(name);
	if (print) nodesToPrint.push_back(name);
}

void HierarchicalEA::removeNode(string name) {
	for (int i = 0; i < nodeNames.size(); i++) {
		string nodeName = nodeNames[i];
		if (nodeName == name) {
			nodeNames.erase(nodeNames.begin()+i);
			nodes.erase(nodes.begin()+i);
			break;
		}
	}

	for (int i = 0; i < nodesToPrint.size(); i++) {
		if ((nodesToPrint[i]) == name) {
			nodesToPrint.erase(nodesToPrint.begin()+i);
		}
	}
}

void HierarchicalEA::checkNodesExist(vector<string> names) {
	for (int i = 0; i < names.size(); i++) {
		bool exists = false;

		for (int k = 0; k < nodeNames.size(); k++) {
			if (nodeNames[k] == names[i]) exists = true;
		}

		if (!exists) throw InvalidNodeException();
	}
}

void HierarchicalEA::setNodesToPrint(vector<string> names) {
	checkNodesExist(names);
	nodesToPrint.clear();
	nodesToPrint = names;
}

void HierarchicalEA::setEvolutionOrder(vector<string> names) {
	checkNodesExist(names);
	evolutionOrder.clear();
	evolutionOrder = names;
}

void HierarchicalEA::buildNodeSet(
	vector<string> targetNames,
	vector<PopulationNode *> * targetSet
) {
	if (nodes.empty()) throw NoNodesException();
	checkNodesExist(targetNames);

	for (int i = 0; i < targetNames.size(); i++) {
		string name = targetNames[i];
		for (int k = 0; k < nodeNames.size(); k++) {
			string realName = nodeNames[k];
			if (name == realName) {
				targetSet->push_back(nodes[k]);
				break;
			}
		}
	}
}

void HierarchicalEA::buildEvolutionNodes() {
	if (evolutionOrder.empty()) throw NoEvolutionOrderException();
	evolutionNodes.clear();
	buildNodeSet(evolutionOrder, &evolutionNodes);
}

void HierarchicalEA::buildPrintNodes() {
	printNodes.clear();
	buildNodeSet(nodesToPrint, &printNodes);
}

bool HierarchicalEA::done(int currentEpoch) {
	bool done = true;
	if (currentEpoch >= maxEpochs - 1) {
		cout << "Hierarchical EA ended because maximum epoch count was reached.\n";
		return done;
	}

	for (int i = 0; i < evolutionNodes.size(); i++) {
		if (!evolutionNodes[i]->done()) {
			done = false;
			break;
		}
	}

	if (done) cout << "Hierarchical EA ended because all population nodes reported reaching their specified ending conditions.\n";

	return done;
}

void HierarchicalEA::run(bool verbose) {
	buildEvolutionNodes();
	buildPrintNodes();
	cout << "Before:\n";
	cout << string(80, '=') << "\n";
	for (int i = 0; i < printNodes.size(); i++) {
		cout << "Node " << nodesToPrint[i] << ":\n";
		cout << printNodes[i]->toString();
		cout << string(80, '-') << "\n";
	}

	for (int i = 0; i < maxEpochs; i++) {
		for (int k = 0; k < evolutionNodes.size(); k++) {
			if (!evolutionNodes[k]->done()) {
				evolutionNodes[k]->runGenerations();
			}
		}

		// Because humans count from 1, we add 1 to our epoch counter
		cout << "After epoch " << i+1 << ":\n";
		cout << string(80, '=') << "\n";
		for (int k = 0; k < printNodes.size(); k++) {
			cout << "Node " << nodesToPrint[k] << ":\n";
			cout << printNodes[k]->toString();
			cout << string(80, '-') << "\n";
		}

		if (done(i)) break;
	}
}
<commit_msg>[HierarchicalEA]: Added TODO<commit_after>#include "core/HierarchicalEA.hpp"
#include "exception/NodeAlreadyExistsException.hpp"
#include "exception/InvalidNodeException.hpp"
#include "exception/NoNodesException.hpp"
#include "exception/NoEvolutionOrderException.hpp"

#include <iostream>
#include <algorithm>

HierarchicalEA::HierarchicalEA(int maxEpochs) {
	this->maxEpochs = maxEpochs;
}

HierarchicalEA::~HierarchicalEA() {}

void HierarchicalEA::addNode(PopulationNode * node, string name, bool print) {
	for (int i = 0; i < nodeNames.size(); i++) {
		if (nodeNames[i] == name or nodes[i] == node) {
			throw NodeAlreadyExistsException();
		}
	}
	nodes.push_back(node);
	nodeNames.push_back(name);
	if (print) nodesToPrint.push_back(name);
}

void HierarchicalEA::removeNode(string name) {
	for (int i = 0; i < nodeNames.size(); i++) {
		string nodeName = nodeNames[i];
		if (nodeName == name) {
			nodeNames.erase(nodeNames.begin()+i);
			nodes.erase(nodes.begin()+i);
			break;
		}
	}

	for (int i = 0; i < nodesToPrint.size(); i++) {
		if ((nodesToPrint[i]) == name) {
			nodesToPrint.erase(nodesToPrint.begin()+i);
		}
	}
}

void HierarchicalEA::checkNodesExist(vector<string> names) {
	for (int i = 0; i < names.size(); i++) {
		bool exists = false;

		for (int k = 0; k < nodeNames.size(); k++) {
			if (nodeNames[k] == names[i]) exists = true;
		}

		if (!exists) throw InvalidNodeException();
	}
}

void HierarchicalEA::setNodesToPrint(vector<string> names) {
	checkNodesExist(names);
	nodesToPrint.clear();
	nodesToPrint = names;
}

void HierarchicalEA::setEvolutionOrder(vector<string> names) {
	checkNodesExist(names);
	evolutionOrder.clear();
	evolutionOrder = names;
}

void HierarchicalEA::buildNodeSet(
	vector<string> targetNames,
	vector<PopulationNode *> * targetSet
) {
	if (nodes.empty()) throw NoNodesException();
	checkNodesExist(targetNames);

	for (int i = 0; i < targetNames.size(); i++) {
		string name = targetNames[i];
		for (int k = 0; k < nodeNames.size(); k++) {
			string realName = nodeNames[k];
			if (name == realName) {
				targetSet->push_back(nodes[k]);
				break;
			}
		}
	}
}

void HierarchicalEA::buildEvolutionNodes() {
	if (evolutionOrder.empty()) throw NoEvolutionOrderException();
	evolutionNodes.clear();
	buildNodeSet(evolutionOrder, &evolutionNodes);
}

void HierarchicalEA::buildPrintNodes() {
	printNodes.clear();
	buildNodeSet(nodesToPrint, &printNodes);
}

bool HierarchicalEA::done(int currentEpoch) {
	bool done = true;
	if (currentEpoch >= maxEpochs - 1) {
		cout << "Hierarchical EA ended because maximum epoch count was reached.\n";
		return done;
	}

	for (int i = 0; i < evolutionNodes.size(); i++) {
		if (!evolutionNodes[i]->done()) {
			done = false;
			break;
		}
	}

	if (done) cout << "Hierarchical EA ended because all population nodes reported reaching their specified ending conditions.\n";

	return done;
}

// TODO: Make verbosity option actually mean something
void HierarchicalEA::run(bool verbose) {
	buildEvolutionNodes();
	buildPrintNodes();
	cout << "Before:\n";
	cout << string(80, '=') << "\n";
	for (int i = 0; i < printNodes.size(); i++) {
		cout << "Node " << nodesToPrint[i] << ":\n";
		cout << printNodes[i]->toString();
		cout << string(80, '-') << "\n";
	}

	for (int i = 0; i < maxEpochs; i++) {
		for (int k = 0; k < evolutionNodes.size(); k++) {
			if (!evolutionNodes[k]->done()) {
				evolutionNodes[k]->runGenerations();
			}
		}

		// Because humans count from 1, we add 1 to our epoch counter
		cout << "After epoch " << i+1 << ":\n";
		cout << string(80, '=') << "\n";
		for (int k = 0; k < printNodes.size(); k++) {
			cout << "Node " << nodesToPrint[k] << ":\n";
			cout << printNodes[k]->toString();
			cout << string(80, '-') << "\n";
		}

		if (done(i)) break;
	}
}
<|endoftext|>


<commit_before>#include <stdexcept>
#include <memory>
#include <cmath>
#include <cassert>
#include <iostream>

#include "gamestates/playstate.hh"
#include "gamestates/endstate.hh"
#include "settings.hh"
#include "map_reader.hh"
#include "player.hh"
#include "mouse.hh"
#include "map.hh"
#include "text_drawer.hh"
#include "turrets/basic.hh"
#include "turrets/sniper.hh"
#include "turrets/super.hh"
#include "mobs/foot_soldier.hh"
#include "mobs/horse_soldier.hh"
#include "mobs/tank_soldier.hh"
#include "pathfinding.hh"

PlayState::PlayState(std::string map)
         : turret_{nullptr}
{
    if (!MapReader::set_size(map))
        throw std::logic_error("Could not load map '" + map + "'.");
    Map::init();
    Map::init_draw(100, 100);
    Map::init_draw(0, 50);
    if (!MapReader::read_map(map))
        throw std::logic_error("Error reading map '" + map + "'.");
    Player::init(500, 10, std::chrono::system_clock::now());
    this->levels.push_back(Level("resources/levels/1.td42"));
    this->levels.push_back(Level("resources/levels/2.td42"));
    this->levels.push_back(Level("resources/levels/3.td42"));
    this->levels.push_back(Level("resources/levels/4.td42"));
    this->levels.push_back(Level("resources/levels/5.td42"));
    ms_before_next_level = 100;
    ms_before_next_mob = TIME_BETWEEN_MOBS;
}

void PlayState::insert_mode(std::shared_ptr<Turret> t)
{
    turret_ = t;
    t->set_opacity(100);
}

void PlayState::exit_insert_mode()
{
    turret_ = nullptr;
    ms_before_next_level = 100;
}

void PlayState::exit_insert_mode_and_create()
{
    if (turret_ != nullptr)
    {
        if (!Player::remove_money(turret_->get_cost()))
        {
            turret_ = nullptr;
            return;
        }
        auto pos = turret_->get_pos();
        if (pos.first < 0 || pos.first >= Map::width || pos.second < 0
                || pos.second >= Map::height
                || Map::cells[pos.first][pos.second].type != CellType::Empty)
        {
            turret_ = nullptr;
            return;
        }
        Map::cells[pos.first][pos.second].type = CellType::Tower;
        turret_->set_opacity(255);
        Map::turrets.push_front(turret_);
        turret_ = nullptr;
        for (auto& enemy : Map::ennemies)
            enemy->update_pathfinding();
    }
}

void PlayState::draw(sf::RenderWindow& w)
{
    if (turret_ != nullptr)
    {
        auto pos = Mouse::get_mouse_pos(w);
        unsigned px;
        unsigned py;
        Map::screen_to_map(pos.first, pos.second, px, py);
        turret_->set_pos(px, py);
    }
    Map::draw(w, turret_);
    TextDrawer::display_time(w);
    TextDrawer::display_lifes(w);
    TextDrawer::display_money(w);
    TextDrawer::display_mouse_coords(w);
    TextDrawer::display_mouse_coords_on_map(w);
}

void PlayState::update(unsigned elapsed_ms)
{
    if (this->levels.size() == 0)
    {
        GameState::stack.pop_back();
        auto ptr = std::make_shared<EndState>();
        GameState::stack.push_back(ptr);
    }
    else if (ms_before_next_level <= 0)
    {
        if (ms_before_next_mob <= 0)
        {
            if (!this->levels.front().make_mob())
            {
                std::cout << "NEW LEVEL" << std::endl;
                this->levels.pop_front();
                ms_before_next_level = TIME_BETWEEN_LEVELS;
            }
            else
                ms_before_next_mob = TIME_BETWEEN_MOBS;
        }
        else
            ms_before_next_mob -= elapsed_ms;
    }
    else
        ms_before_next_level -= elapsed_ms;
    for (std::list<std::shared_ptr<Mob>>::iterator i = Map::ennemies.begin();
            i != Map::ennemies.end();)
    {
        if ((*i)->dead())
            i = Map::ennemies.erase(i);
        else
        {
            (*i)->move();
            auto pos = (*i)->get_pos();
            float dx = fabs(pos.first - Map::finish_mobs.first);
            float dy = fabs(pos.second - Map::finish_mobs.second);
            if (dx < 0.02f && dy < 0.02f)
            {
                (*i)->harakiri();
                if (!Player::remove_a_life())
                {
                    std::cout << "U LOST!" << std::endl;
                    GameState::stack.pop_back();
                    auto ptr = std::make_shared<EndState>();
                    GameState::stack.push_back(ptr);
                }
                i = Map::ennemies.erase(i);
            }
            else
                ++i;
        }
    }
    for (std::shared_ptr<Turret> turret : Map::turrets)
        turret->attack(elapsed_ms);
    ++elapsed_ms;
}
<commit_msg>Now we can lost<commit_after>#include <stdexcept>
#include <memory>
#include <cmath>
#include <cassert>
#include <iostream>

#include "gamestates/playstate.hh"
#include "gamestates/endstate.hh"
#include "settings.hh"
#include "map_reader.hh"
#include "player.hh"
#include "mouse.hh"
#include "map.hh"
#include "text_drawer.hh"
#include "turrets/basic.hh"
#include "turrets/sniper.hh"
#include "turrets/super.hh"
#include "mobs/foot_soldier.hh"
#include "mobs/horse_soldier.hh"
#include "mobs/tank_soldier.hh"
#include "pathfinding.hh"

PlayState::PlayState(std::string map)
         : turret_{nullptr}
{
    if (!MapReader::set_size(map))
        throw std::logic_error("Could not load map '" + map + "'.");
    Map::init();
    Map::init_draw(100, 100);
    Map::init_draw(0, 50);
    if (!MapReader::read_map(map))
        throw std::logic_error("Error reading map '" + map + "'.");
    Player::init(500, 10, std::chrono::system_clock::now());
    this->levels.push_back(Level("resources/levels/1.td42"));
    this->levels.push_back(Level("resources/levels/2.td42"));
    this->levels.push_back(Level("resources/levels/3.td42"));
    this->levels.push_back(Level("resources/levels/4.td42"));
    this->levels.push_back(Level("resources/levels/5.td42"));
    ms_before_next_level = 100;
    ms_before_next_mob = TIME_BETWEEN_MOBS;
}

void PlayState::insert_mode(std::shared_ptr<Turret> t)
{
    turret_ = t;
    t->set_opacity(100);
}

void PlayState::exit_insert_mode()
{
    turret_ = nullptr;
    ms_before_next_level = 100;
}

void PlayState::exit_insert_mode_and_create()
{
    if (turret_ != nullptr)
    {
        if (!Player::remove_money(turret_->get_cost()))
        {
            turret_ = nullptr;
            return;
        }
        auto pos = turret_->get_pos();
        if (pos.first < 0 || pos.first >= Map::width || pos.second < 0
                || pos.second >= Map::height
                || Map::cells[pos.first][pos.second].type != CellType::Empty)
        {
            turret_ = nullptr;
            return;
        }
        Map::cells[pos.first][pos.second].type = CellType::Tower;
        turret_->set_opacity(255);
        Map::turrets.push_front(turret_);
        turret_ = nullptr;
        for (auto& enemy : Map::ennemies)
            enemy->update_pathfinding();
    }
}

void PlayState::draw(sf::RenderWindow& w)
{
    if (turret_ != nullptr)
    {
        auto pos = Mouse::get_mouse_pos(w);
        unsigned px;
        unsigned py;
        Map::screen_to_map(pos.first, pos.second, px, py);
        turret_->set_pos(px, py);
    }
    Map::draw(w, turret_);
    TextDrawer::display_time(w);
    TextDrawer::display_lifes(w);
    TextDrawer::display_money(w);
    TextDrawer::display_mouse_coords(w);
    TextDrawer::display_mouse_coords_on_map(w);
}

bool is_arrived(float x1, float x2, float y1, float y2)
{
    int ix1 = x1;
    int ix2 = x2;
    int iy1 = y1;
    int iy2 = y2;
    if (ix1 == ix2 && iy1 == iy2)
        return true;
    float dx = fabs(x1 - x2);
    float dy = fabs(y1 - y2);
    return dx < 0.2f && dy < 0.2f;
}

void PlayState::update(unsigned elapsed_ms)
{
    if (this->levels.size() == 0)
    {
        GameState::stack.pop_back();
        auto ptr = std::make_shared<EndState>();
        GameState::stack.push_back(ptr);
    }
    else if (ms_before_next_level <= 0)
    {
        if (ms_before_next_mob <= 0)
        {
            if (!this->levels.front().make_mob())
            {
                std::cout << "NEW LEVEL" << std::endl;
                this->levels.pop_front();
                ms_before_next_level = TIME_BETWEEN_LEVELS;
            }
            else
                ms_before_next_mob = TIME_BETWEEN_MOBS;
        }
        else
            ms_before_next_mob -= elapsed_ms;
    }
    else
        ms_before_next_level -= elapsed_ms;
    for (std::list<std::shared_ptr<Mob>>::iterator i = Map::ennemies.begin();
            i != Map::ennemies.end();)
    {
        if ((*i)->dead())
            i = Map::ennemies.erase(i);
        else
        {
            (*i)->move();
            auto pos = (*i)->get_pos();
            if (is_arrived(pos.first, Map::finish_mobs.first,
                           pos.second, Map::finish_mobs.second))
            {
                std::cout << "xd" << std::endl;
                (*i)->harakiri();
                if (!Player::remove_a_life())
                {
                    GameState::stack.pop_back();
                    auto ptr = std::make_shared<EndState>();
                    GameState::stack.push_back(ptr);
                }
                i = Map::ennemies.erase(i);
            }
            else
                ++i;
        }
    }
    for (std::shared_ptr<Turret> turret : Map::turrets)
        turret->attack(elapsed_ms);
    ++elapsed_ms;
}
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "webkit/plugins/ppapi/ppb_flash_impl.h"

#include <string>
#include <vector>

#include "base/message_loop.h"
#include "base/time.h"
#include "googleurl/src/gurl.h"
#include "ppapi/c/dev/ppb_font_dev.h"
#include "ppapi/c/private/ppb_flash.h"
#include "ppapi/shared_impl/time_conversion.h"
#include "ppapi/shared_impl/var.h"
#include "ppapi/thunk/enter.h"
#include "ppapi/thunk/ppb_image_data_api.h"
#include "skia/ext/platform_canvas.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkMatrix.h"
#include "third_party/skia/include/core/SkPaint.h"
#include "third_party/skia/include/core/SkPoint.h"
#include "third_party/skia/include/core/SkTemplates.h"
#include "third_party/skia/include/core/SkTypeface.h"
#include "webkit/plugins/ppapi/common.h"
#include "webkit/plugins/ppapi/host_globals.h"
#include "webkit/plugins/ppapi/plugin_delegate.h"
#include "webkit/plugins/ppapi/plugin_module.h"
#include "webkit/plugins/ppapi/ppapi_plugin_instance.h"
#include "webkit/plugins/ppapi/ppb_url_request_info_impl.h"
#include "webkit/plugins/ppapi/resource_helper.h"
#include "webkit/plugins/ppapi/ppb_image_data_impl.h"

using ppapi::PPTimeToTime;
using ppapi::StringVar;
using ppapi::thunk::EnterResource;
using ppapi::thunk::PPB_ImageData_API;
using ppapi::thunk::PPB_URLRequestInfo_API;

namespace webkit {
namespace ppapi {

namespace {

void SetInstanceAlwaysOnTop(PP_Instance pp_instance, PP_Bool on_top) {
  PluginInstance* instance = HostGlobals::Get()->GetInstance(pp_instance);
  if (!instance)
    return;
  instance->set_always_on_top(PPBoolToBool(on_top));
}

PP_Bool DrawGlyphs(PP_Instance,
                   PP_Resource pp_image_data,
                   const PP_FontDescription_Dev* font_desc,
                   uint32_t color,
                   const PP_Point* position,
                   const PP_Rect* clip,
                   const float transformation[3][3],
                   PP_Bool allow_subpixel_aa,
                   uint32_t glyph_count,
                   const uint16_t glyph_indices[],
                   const PP_Point glyph_advances[]) {
  EnterResource<PPB_ImageData_API> enter(pp_image_data, true);
  if (enter.failed())
    return PP_FALSE;
  PPB_ImageData_Impl* image_resource =
      static_cast<PPB_ImageData_Impl*>(enter.object());

  ImageDataAutoMapper mapper(image_resource);
  if (!mapper.is_valid())
    return PP_FALSE;

  // Set up the typeface.
  StringVar* face_name = StringVar::FromPPVar(font_desc->face);
  if (!face_name)
    return PP_FALSE;
  int style = SkTypeface::kNormal;
  if (font_desc->weight >= PP_FONTWEIGHT_BOLD)
    style |= SkTypeface::kBold;
  if (font_desc->italic)
    style |= SkTypeface::kItalic;
  SkTypeface* typeface =
      SkTypeface::CreateFromName(face_name->value().c_str(),
                                 static_cast<SkTypeface::Style>(style));
  if (!typeface)
    return PP_FALSE;

  // Set up the canvas.
  SkCanvas* canvas = image_resource->mapped_canvas();
  canvas->save();

  // Clip is applied in pixels before the transform.
  SkRect clip_rect = { clip->point.x, clip->point.y,
                       clip->point.x + clip->size.width,
                       clip->point.y + clip->size.height };
  canvas->clipRect(clip_rect);

  // -- Do not return early below this. The canvas needs restoring and the
  // typeface will leak if it's not assigned to the paint (it's refcounted and
  // the refcount is currently 0).

  // Convert & set the matrix.
  SkMatrix matrix;
  matrix.set(SkMatrix::kMScaleX, SkFloatToScalar(transformation[0][0]));
  matrix.set(SkMatrix::kMSkewX,  SkFloatToScalar(transformation[0][1]));
  matrix.set(SkMatrix::kMTransX, SkFloatToScalar(transformation[0][2]));
  matrix.set(SkMatrix::kMSkewY,  SkFloatToScalar(transformation[1][0]));
  matrix.set(SkMatrix::kMScaleY, SkFloatToScalar(transformation[1][1]));
  matrix.set(SkMatrix::kMTransY, SkFloatToScalar(transformation[1][2]));
  matrix.set(SkMatrix::kMPersp0, SkFloatToScalar(transformation[2][0]));
  matrix.set(SkMatrix::kMPersp1, SkFloatToScalar(transformation[2][1]));
  matrix.set(SkMatrix::kMPersp2, SkFloatToScalar(transformation[2][2]));
  canvas->concat(matrix);

  SkPaint paint;
  paint.setColor(color);
  paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
  paint.setAntiAlias(true);
  paint.setHinting(SkPaint::kFull_Hinting);
  paint.setTextSize(SkIntToScalar(font_desc->size));
  paint.setTypeface(typeface);  // Takes a ref and manages lifetime.
  if (allow_subpixel_aa) {
    paint.setSubpixelText(true);
    paint.setLCDRenderText(true);
  }

  SkScalar x = SkIntToScalar(position->x);
  SkScalar y = SkIntToScalar(position->y);

  // Build up the skia advances.
  if (glyph_count == 0)
    return PP_TRUE;
  std::vector<SkPoint> storage;
  storage.resize(glyph_count);
  SkPoint* sk_positions = &storage[0];
  for (uint32_t i = 0; i < glyph_count; i++) {
    sk_positions[i].set(x, y);
    x += SkFloatToScalar(glyph_advances[i].x);
    y += SkFloatToScalar(glyph_advances[i].y);
  }

  canvas->drawPosText(glyph_indices, glyph_count * 2, sk_positions, paint);

  canvas->restore();
  return PP_TRUE;
}

PP_Bool DrawGlyphs11(PP_Instance instance,
                     PP_Resource pp_image_data,
                     const PP_FontDescription_Dev* font_desc,
                     uint32_t color,
                     PP_Point position,
                     PP_Rect clip,
                     const float transformation[3][3],
                     uint32_t glyph_count,
                     const uint16_t glyph_indices[],
                     const PP_Point glyph_advances[]) {
  return DrawGlyphs(instance, pp_image_data, font_desc, color, &position,
                    &clip, transformation, PP_TRUE, glyph_count,
                    glyph_indices, glyph_advances);
}

PP_Var GetProxyForURL(PP_Instance pp_instance, const char* url) {
  PluginInstance* instance = HostGlobals::Get()->GetInstance(pp_instance);
  if (!instance)
    return PP_MakeUndefined();

  GURL gurl(url);
  if (!gurl.is_valid())
    return PP_MakeUndefined();

  std::string proxy_host = instance->delegate()->ResolveProxy(gurl);
  if (proxy_host.empty())
    return PP_MakeUndefined();  // No proxy.
  return StringVar::StringToPPVar(proxy_host);
}

int32_t Navigate(PP_Resource request_id,
                 const char* target,
                 PP_Bool from_user_action) {
  EnterResource<PPB_URLRequestInfo_API> enter(request_id, true);
  if (enter.failed())
    return PP_ERROR_BADRESOURCE;
  PPB_URLRequestInfo_Impl* request =
      static_cast<PPB_URLRequestInfo_Impl*>(enter.object());

  if (!target)
    return PP_ERROR_BADARGUMENT;

  PluginInstance* plugin_instance = ResourceHelper::GetPluginInstance(request);
  if (!plugin_instance)
    return PP_ERROR_FAILED;
  return plugin_instance->Navigate(request, target,
                                   PP_ToBool(from_user_action));
}

int32_t Navigate11(PP_Resource request_id,
                   const char* target,
                   bool from_user_action) {
  return Navigate(request_id, target, PP_FromBool(from_user_action));
}

void RunMessageLoop(PP_Instance instance) {
  bool old_state = MessageLoop::current()->NestableTasksAllowed();
  MessageLoop::current()->SetNestableTasksAllowed(true);
  MessageLoop::current()->Run();
  MessageLoop::current()->SetNestableTasksAllowed(old_state);
}

void QuitMessageLoop(PP_Instance instance) {
  MessageLoop::current()->QuitNow();
}

double GetLocalTimeZoneOffset(PP_Instance pp_instance, PP_Time t) {
  PluginInstance* instance = HostGlobals::Get()->GetInstance(pp_instance);
  if (!instance)
    return 0.0;

  // Evil hack. The time code handles exact "0" values as special, and produces
  // a "null" Time object. This will represent some date hundreds of years ago
  // and will give us funny results at 1970 (there are some tests where this
  // comes up, but it shouldn't happen in real life). To work around this
  // special handling, we just need to give it some nonzero value.
  if (t == 0.0)
    t = 0.0000000001;

  // We can't do the conversion here because on Linux, the localtime calls
  // require filesystem access prohibited by the sandbox.
  return instance->delegate()->GetLocalTimeZoneOffset(PPTimeToTime(t));
}

PP_Var GetCommandLineArgs(PP_Module pp_module) {
  PluginModule* module = HostGlobals::Get()->GetModule(pp_module);
  if (!module)
    return PP_MakeUndefined();

  PluginInstance* instance = module->GetSomeInstance();
  if (!instance)
    return PP_MakeUndefined();

  std::string args = instance->delegate()->GetFlashCommandLineArgs();
  return StringVar::StringToPPVar(args);
}

void PreLoadFontWin(const void* logfontw) {
  // Not implemented in-process.
}

const PPB_Flash_11 ppb_flash_11 = {
  &SetInstanceAlwaysOnTop,
  &DrawGlyphs11,
  &GetProxyForURL,
  &Navigate11,
  &RunMessageLoop,
  &QuitMessageLoop,
  &GetLocalTimeZoneOffset,
  &GetCommandLineArgs
};

const PPB_Flash ppb_flash_12 = {
  &SetInstanceAlwaysOnTop,
  &DrawGlyphs,
  &GetProxyForURL,
  &Navigate,
  &RunMessageLoop,
  &QuitMessageLoop,
  &GetLocalTimeZoneOffset,
  &GetCommandLineArgs,
  &PreLoadFontWin
};

}  // namespace

// static
const PPB_Flash_11* PPB_Flash_Impl::GetInterface11() {
  return &ppb_flash_11;
}

// static
const PPB_Flash* PPB_Flash_Impl::GetInterface12() {
  return &ppb_flash_12;
}

}  // namespace ppapi
}  // namespace webkit
<commit_msg>Fix leak of the typeface when doing DrawGlyphs for Flash.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "webkit/plugins/ppapi/ppb_flash_impl.h"

#include <string>
#include <vector>

#include "base/message_loop.h"
#include "base/time.h"
#include "googleurl/src/gurl.h"
#include "ppapi/c/dev/ppb_font_dev.h"
#include "ppapi/c/private/ppb_flash.h"
#include "ppapi/shared_impl/time_conversion.h"
#include "ppapi/shared_impl/var.h"
#include "ppapi/thunk/enter.h"
#include "ppapi/thunk/ppb_image_data_api.h"
#include "skia/ext/platform_canvas.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkMatrix.h"
#include "third_party/skia/include/core/SkPaint.h"
#include "third_party/skia/include/core/SkPoint.h"
#include "third_party/skia/include/core/SkTemplates.h"
#include "third_party/skia/include/core/SkTypeface.h"
#include "webkit/plugins/ppapi/common.h"
#include "webkit/plugins/ppapi/host_globals.h"
#include "webkit/plugins/ppapi/plugin_delegate.h"
#include "webkit/plugins/ppapi/plugin_module.h"
#include "webkit/plugins/ppapi/ppapi_plugin_instance.h"
#include "webkit/plugins/ppapi/ppb_url_request_info_impl.h"
#include "webkit/plugins/ppapi/resource_helper.h"
#include "webkit/plugins/ppapi/ppb_image_data_impl.h"

using ppapi::PPTimeToTime;
using ppapi::StringVar;
using ppapi::thunk::EnterResource;
using ppapi::thunk::PPB_ImageData_API;
using ppapi::thunk::PPB_URLRequestInfo_API;

namespace webkit {
namespace ppapi {

namespace {

void SetInstanceAlwaysOnTop(PP_Instance pp_instance, PP_Bool on_top) {
  PluginInstance* instance = HostGlobals::Get()->GetInstance(pp_instance);
  if (!instance)
    return;
  instance->set_always_on_top(PPBoolToBool(on_top));
}

PP_Bool DrawGlyphs(PP_Instance,
                   PP_Resource pp_image_data,
                   const PP_FontDescription_Dev* font_desc,
                   uint32_t color,
                   const PP_Point* position,
                   const PP_Rect* clip,
                   const float transformation[3][3],
                   PP_Bool allow_subpixel_aa,
                   uint32_t glyph_count,
                   const uint16_t glyph_indices[],
                   const PP_Point glyph_advances[]) {
  EnterResource<PPB_ImageData_API> enter(pp_image_data, true);
  if (enter.failed())
    return PP_FALSE;
  PPB_ImageData_Impl* image_resource =
      static_cast<PPB_ImageData_Impl*>(enter.object());

  ImageDataAutoMapper mapper(image_resource);
  if (!mapper.is_valid())
    return PP_FALSE;

  // Set up the typeface.
  StringVar* face_name = StringVar::FromPPVar(font_desc->face);
  if (!face_name)
    return PP_FALSE;
  int style = SkTypeface::kNormal;
  if (font_desc->weight >= PP_FONTWEIGHT_BOLD)
    style |= SkTypeface::kBold;
  if (font_desc->italic)
    style |= SkTypeface::kItalic;
  SkTypeface* typeface =
      SkTypeface::CreateFromName(face_name->value().c_str(),
                                 static_cast<SkTypeface::Style>(style));
  if (!typeface)
    return PP_FALSE;
  SkAutoUnref aur(typeface);

  // Set up the canvas.
  SkCanvas* canvas = image_resource->mapped_canvas();
  SkAutoCanvasRestore acr(canvas, true);

  // Clip is applied in pixels before the transform.
  SkRect clip_rect = { clip->point.x, clip->point.y,
                       clip->point.x + clip->size.width,
                       clip->point.y + clip->size.height };
  canvas->clipRect(clip_rect);

  // Convert & set the matrix.
  SkMatrix matrix;
  matrix.set(SkMatrix::kMScaleX, SkFloatToScalar(transformation[0][0]));
  matrix.set(SkMatrix::kMSkewX,  SkFloatToScalar(transformation[0][1]));
  matrix.set(SkMatrix::kMTransX, SkFloatToScalar(transformation[0][2]));
  matrix.set(SkMatrix::kMSkewY,  SkFloatToScalar(transformation[1][0]));
  matrix.set(SkMatrix::kMScaleY, SkFloatToScalar(transformation[1][1]));
  matrix.set(SkMatrix::kMTransY, SkFloatToScalar(transformation[1][2]));
  matrix.set(SkMatrix::kMPersp0, SkFloatToScalar(transformation[2][0]));
  matrix.set(SkMatrix::kMPersp1, SkFloatToScalar(transformation[2][1]));
  matrix.set(SkMatrix::kMPersp2, SkFloatToScalar(transformation[2][2]));
  canvas->concat(matrix);

  SkPaint paint;
  paint.setColor(color);
  paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
  paint.setAntiAlias(true);
  paint.setHinting(SkPaint::kFull_Hinting);
  paint.setTextSize(SkIntToScalar(font_desc->size));
  paint.setTypeface(typeface);  // Takes a ref and manages lifetime.
  if (allow_subpixel_aa) {
    paint.setSubpixelText(true);
    paint.setLCDRenderText(true);
  }

  SkScalar x = SkIntToScalar(position->x);
  SkScalar y = SkIntToScalar(position->y);

  // Build up the skia advances.
  if (glyph_count == 0)
    return PP_TRUE;
  std::vector<SkPoint> storage;
  storage.resize(glyph_count);
  SkPoint* sk_positions = &storage[0];
  for (uint32_t i = 0; i < glyph_count; i++) {
    sk_positions[i].set(x, y);
    x += SkFloatToScalar(glyph_advances[i].x);
    y += SkFloatToScalar(glyph_advances[i].y);
  }

  canvas->drawPosText(glyph_indices, glyph_count * 2, sk_positions, paint);

  return PP_TRUE;
}

PP_Bool DrawGlyphs11(PP_Instance instance,
                     PP_Resource pp_image_data,
                     const PP_FontDescription_Dev* font_desc,
                     uint32_t color,
                     PP_Point position,
                     PP_Rect clip,
                     const float transformation[3][3],
                     uint32_t glyph_count,
                     const uint16_t glyph_indices[],
                     const PP_Point glyph_advances[]) {
  return DrawGlyphs(instance, pp_image_data, font_desc, color, &position,
                    &clip, transformation, PP_TRUE, glyph_count,
                    glyph_indices, glyph_advances);
}

PP_Var GetProxyForURL(PP_Instance pp_instance, const char* url) {
  PluginInstance* instance = HostGlobals::Get()->GetInstance(pp_instance);
  if (!instance)
    return PP_MakeUndefined();

  GURL gurl(url);
  if (!gurl.is_valid())
    return PP_MakeUndefined();

  std::string proxy_host = instance->delegate()->ResolveProxy(gurl);
  if (proxy_host.empty())
    return PP_MakeUndefined();  // No proxy.
  return StringVar::StringToPPVar(proxy_host);
}

int32_t Navigate(PP_Resource request_id,
                 const char* target,
                 PP_Bool from_user_action) {
  EnterResource<PPB_URLRequestInfo_API> enter(request_id, true);
  if (enter.failed())
    return PP_ERROR_BADRESOURCE;
  PPB_URLRequestInfo_Impl* request =
      static_cast<PPB_URLRequestInfo_Impl*>(enter.object());

  if (!target)
    return PP_ERROR_BADARGUMENT;

  PluginInstance* plugin_instance = ResourceHelper::GetPluginInstance(request);
  if (!plugin_instance)
    return PP_ERROR_FAILED;
  return plugin_instance->Navigate(request, target,
                                   PP_ToBool(from_user_action));
}

int32_t Navigate11(PP_Resource request_id,
                   const char* target,
                   bool from_user_action) {
  return Navigate(request_id, target, PP_FromBool(from_user_action));
}

void RunMessageLoop(PP_Instance instance) {
  bool old_state = MessageLoop::current()->NestableTasksAllowed();
  MessageLoop::current()->SetNestableTasksAllowed(true);
  MessageLoop::current()->Run();
  MessageLoop::current()->SetNestableTasksAllowed(old_state);
}

void QuitMessageLoop(PP_Instance instance) {
  MessageLoop::current()->QuitNow();
}

double GetLocalTimeZoneOffset(PP_Instance pp_instance, PP_Time t) {
  PluginInstance* instance = HostGlobals::Get()->GetInstance(pp_instance);
  if (!instance)
    return 0.0;

  // Evil hack. The time code handles exact "0" values as special, and produces
  // a "null" Time object. This will represent some date hundreds of years ago
  // and will give us funny results at 1970 (there are some tests where this
  // comes up, but it shouldn't happen in real life). To work around this
  // special handling, we just need to give it some nonzero value.
  if (t == 0.0)
    t = 0.0000000001;

  // We can't do the conversion here because on Linux, the localtime calls
  // require filesystem access prohibited by the sandbox.
  return instance->delegate()->GetLocalTimeZoneOffset(PPTimeToTime(t));
}

PP_Var GetCommandLineArgs(PP_Module pp_module) {
  PluginModule* module = HostGlobals::Get()->GetModule(pp_module);
  if (!module)
    return PP_MakeUndefined();

  PluginInstance* instance = module->GetSomeInstance();
  if (!instance)
    return PP_MakeUndefined();

  std::string args = instance->delegate()->GetFlashCommandLineArgs();
  return StringVar::StringToPPVar(args);
}

void PreLoadFontWin(const void* logfontw) {
  // Not implemented in-process.
}

const PPB_Flash_11 ppb_flash_11 = {
  &SetInstanceAlwaysOnTop,
  &DrawGlyphs11,
  &GetProxyForURL,
  &Navigate11,
  &RunMessageLoop,
  &QuitMessageLoop,
  &GetLocalTimeZoneOffset,
  &GetCommandLineArgs
};

const PPB_Flash ppb_flash_12 = {
  &SetInstanceAlwaysOnTop,
  &DrawGlyphs,
  &GetProxyForURL,
  &Navigate,
  &RunMessageLoop,
  &QuitMessageLoop,
  &GetLocalTimeZoneOffset,
  &GetCommandLineArgs,
  &PreLoadFontWin
};

}  // namespace

// static
const PPB_Flash_11* PPB_Flash_Impl::GetInterface11() {
  return &ppb_flash_11;
}

// static
const PPB_Flash* PPB_Flash_Impl::GetInterface12() {
  return &ppb_flash_12;
}

}  // namespace ppapi
}  // namespace webkit
<|endoftext|>