<commit_before>#include <osg/UnitTestFramework>
#include <osg/ArgumentParser>
#include <osg/ApplicationUsage>

#include <osg/Matrix>

void testFrustum(double left,double right,double bottom,double top,double zNear,double zFar)
{
    osg::Matrix f;
    f.makeFrustum(left,right,bottom,top,zNear,zFar);

    double c_zNear = f(3,2) / (f(2,2)-1.0f);
    double c_zFar = f(3,2) / (1.0f+f(2,2));

    double c_left = c_zNear * (f(2,0)-1.0f) / f(0,0);
    double c_right = c_zNear * (1.0f+f(2,0)) / f(0,0);

    double c_top = c_zNear * (1+f(2,1)) / f(1,1);
    double c_bottom = c_zNear * (f(2,1)-1.0f) / f(1,1);

    f.getFrustum(c_left,c_right,c_bottom,c_top,c_zNear,c_zFar);

    std::cout << "testFrustum"<<std::endl;
    std::cout << "  left = "<<left<<" compute "<<c_left<<std::endl;
    std::cout << "  right = "<<right<<" compute "<<c_right<<std::endl;

    std::cout << "  bottom = "<<bottom<<" compute "<<c_bottom<<std::endl;
    std::cout << "  top = "<<top<<" compute "<<c_top<<std::endl;

    std::cout << "  zNear = "<<zNear<<" compute "<<c_zNear<<std::endl;
    std::cout << "  zFar = "<<zFar<<" compute "<<c_zFar<<std::endl;

    std::cout << std::endl;
}

void testOrtho(double left,double right,double bottom,double top,double zNear,double zFar)
{
    osg::Matrix f;
    f.makeOrtho(left,right,bottom,top,zNear,zFar);

    double c_zNear = (f(3,2)+1.0f) / f(2,2);
    double c_zFar = (f(3,2)-1.0f) / f(2,2);

    double c_left = -(1.0f+f(3,0)) / f(0,0);
    double c_right = (1.0f-f(3,0)) / f(0,0);

    double c_bottom = -(1.0f+f(3,1)) / f(1,1);
    double c_top = (1.0f-f(3,1)) / f(1,1);

    f.getOrtho(c_left,c_right,c_bottom,c_top,c_zNear,c_zFar);

    std::cout << "testOrtho"<<std::endl;
    std::cout << "  left = "<<left<<" compute "<<c_left<<std::endl;
    std::cout << "  right = "<<right<<" compute "<<c_right<<std::endl;

    std::cout << "  bottom = "<<bottom<<" compute "<<c_bottom<<std::endl;
    std::cout << "  top = "<<top<<" compute "<<c_top<<std::endl;

    std::cout << "  zNear = "<<zNear<<" compute "<<c_zNear<<std::endl;
    std::cout << "  zFar = "<<zFar<<" compute "<<c_zFar<<std::endl;

    std::cout << std::endl;
}

void testLookAt(const osg::Vec3& eye,const osg::Vec3& center,const osg::Vec3& up)
{
    osg::Matrix mv;
    mv.makeLookAt(eye,center,up);

    osg::Vec3 c_eye,c_center,c_up;
    mv.getLookAt(c_eye,c_center,c_up);

    std::cout << "testLookAt"<<std::endl;
    std::cout << "  eye "<<eye<< " compute "<<c_eye<<std::endl;
    std::cout << "  eye "<<center<< " compute "<<c_center<<std::endl;
    std::cout << "  eye "<<up<< " compute "<<c_up<<std::endl;

    std::cout << std::endl;

}

int main( int argc, char** argv )
{
    osg::ArgumentParser arguments(&argc,argv);

    // set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which runs units tests.");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options]");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
    arguments.getApplicationUsage()->addCommandLineOption("qt","Display qualified tests.");
    arguments.getApplicationUsage()->addCommandLineOption("matrix","Display qualified tests.");

    if (arguments.argc()<=1)
    {
        arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
        return 1;
    }

    bool printQualifiedTest = false;
    while (arguments.read("qt")) printQualifiedTest = true;

    bool displayMatrixTest = false;
    while (arguments.read("matrix")) displayMatrixTest = true;

    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        std::cout<<arguments.getApplicationUsage()->getCommandLineUsage()<<std::endl;
        arguments.getApplicationUsage()->write(std::cout,arguments.getApplicationUsage()->getCommandLineOptions());
        return 1;
    }

    // any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized();

    // report any errors if they have occured when parsing the program aguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    if (displayMatrixTest)
    {
        std::cout<<"******   Running matrix tests   ******"<<std::endl;

        testFrustum(-1,1,-1,1,1,1000);
        testFrustum(0,1,1,2,2.5,100000);

        testOrtho(0,1,1,2,2.1,1000);
        testOrtho(-1,10,1,20,2.5,100000);

        testLookAt(osg::Vec3(10.0,4.0,2.0),osg::Vec3(10.0,4.0,2.0)+osg::Vec3(0.0,1.0,0.0),osg::Vec3(0.0,0.0,1.0));
        testLookAt(osg::Vec3(10.0,4.0,2.0),osg::Vec3(10.0,4.0,2.0)+osg::Vec3(1.0,1.0,0.0),osg::Vec3(0.0,0.0,1.0));

    }

    if (printQualifiedTest)
    {
         std::cout<<"*****   Qualified Tests  ******"<<std::endl;

         osgUtx::QualifiedTestPrinter printer;
         osgUtx::TestGraph::instance().root()->accept( printer );
         std::cout<<std::endl;
    }

    std::cout<<"******   Running tests   ******"<<std::endl;

    // Global Data or Context
    osgUtx::TestContext ctx;
    osgUtx::TestRunner runner( ctx );
    runner.specify("root");

    osgUtx::TestGraph::instance().root()->accept( runner );

    return 0;
}
<commit_msg>Added test of sizeof(types) - run osgunittests sizeof.<commit_after>#include <osg/UnitTestFramework>
#include <osg/ArgumentParser>
#include <osg/ApplicationUsage>

#include <osg/Matrix>

void testFrustum(double left,double right,double bottom,double top,double zNear,double zFar)
{
    osg::Matrix f;
    f.makeFrustum(left,right,bottom,top,zNear,zFar);

    double c_zNear = f(3,2) / (f(2,2)-1.0f);
    double c_zFar = f(3,2) / (1.0f+f(2,2));

    double c_left = c_zNear * (f(2,0)-1.0f) / f(0,0);
    double c_right = c_zNear * (1.0f+f(2,0)) / f(0,0);

    double c_top = c_zNear * (1+f(2,1)) / f(1,1);
    double c_bottom = c_zNear * (f(2,1)-1.0f) / f(1,1);

    f.getFrustum(c_left,c_right,c_bottom,c_top,c_zNear,c_zFar);

    std::cout << "testFrustum"<<std::endl;
    std::cout << "  left = "<<left<<" compute "<<c_left<<std::endl;
    std::cout << "  right = "<<right<<" compute "<<c_right<<std::endl;

    std::cout << "  bottom = "<<bottom<<" compute "<<c_bottom<<std::endl;
    std::cout << "  top = "<<top<<" compute "<<c_top<<std::endl;

    std::cout << "  zNear = "<<zNear<<" compute "<<c_zNear<<std::endl;
    std::cout << "  zFar = "<<zFar<<" compute "<<c_zFar<<std::endl;

    std::cout << std::endl;
}

void testOrtho(double left,double right,double bottom,double top,double zNear,double zFar)
{
    osg::Matrix f;
    f.makeOrtho(left,right,bottom,top,zNear,zFar);

    double c_zNear = (f(3,2)+1.0f) / f(2,2);
    double c_zFar = (f(3,2)-1.0f) / f(2,2);

    double c_left = -(1.0f+f(3,0)) / f(0,0);
    double c_right = (1.0f-f(3,0)) / f(0,0);

    double c_bottom = -(1.0f+f(3,1)) / f(1,1);
    double c_top = (1.0f-f(3,1)) / f(1,1);

    f.getOrtho(c_left,c_right,c_bottom,c_top,c_zNear,c_zFar);

    std::cout << "testOrtho"<<std::endl;
    std::cout << "  left = "<<left<<" compute "<<c_left<<std::endl;
    std::cout << "  right = "<<right<<" compute "<<c_right<<std::endl;

    std::cout << "  bottom = "<<bottom<<" compute "<<c_bottom<<std::endl;
    std::cout << "  top = "<<top<<" compute "<<c_top<<std::endl;

    std::cout << "  zNear = "<<zNear<<" compute "<<c_zNear<<std::endl;
    std::cout << "  zFar = "<<zFar<<" compute "<<c_zFar<<std::endl;

    std::cout << std::endl;
}

void testLookAt(const osg::Vec3& eye,const osg::Vec3& center,const osg::Vec3& up)
{
    osg::Matrix mv;
    mv.makeLookAt(eye,center,up);

    osg::Vec3 c_eye,c_center,c_up;
    mv.getLookAt(c_eye,c_center,c_up);

    std::cout << "testLookAt"<<std::endl;
    std::cout << "  eye "<<eye<< " compute "<<c_eye<<std::endl;
    std::cout << "  eye "<<center<< " compute "<<c_center<<std::endl;
    std::cout << "  eye "<<up<< " compute "<<c_up<<std::endl;

    std::cout << std::endl;

}

void sizeOfTest()
{
  std::cout<<"sizeof(bool)=="<<sizeof(bool)<<std::endl;
  std::cout<<"sizeof(char)=="<<sizeof(char)<<std::endl;
  std::cout<<"sizeof(short)=="<<sizeof(short)<<std::endl;
  std::cout<<"sizeof(int)=="<<sizeof(int)<<std::endl;
  std::cout<<"sizeof(long)=="<<sizeof(long)<<std::endl;
  std::cout<<"sizeof(long int)=="<<sizeof(long int)<<std::endl;

#if defined(_MSC_VER)
  // long long isn't supported on VS6.0...
  std::cout<<"sizeof(__int64)=="<<sizeof(__int64)<<std::endl;
#else
  std::cout<<"sizeof(long long)=="<<sizeof(long long)<<std::endl;
#endif
  std::cout<<"sizeof(float)=="<<sizeof(float)<<std::endl;
  std::cout<<"sizeof(double)=="<<sizeof(double)<<std::endl;
}

int main( int argc, char** argv )
{
    osg::ArgumentParser arguments(&argc,argv);

    // set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which runs units tests.");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options]");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
    arguments.getApplicationUsage()->addCommandLineOption("qt","Display qualified tests.");
    arguments.getApplicationUsage()->addCommandLineOption("sizeof","Display sizeof tests.");
    arguments.getApplicationUsage()->addCommandLineOption("matrix","Display qualified tests.");

    if (arguments.argc()<=1)
    {
        arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
        return 1;
    }

    bool printQualifiedTest = false;
    while (arguments.read("qt")) printQualifiedTest = true;

    bool printMatrixTest = false;
    while (arguments.read("matrix")) printMatrixTest = true;

    bool printSizeOfTest = false;
    while (arguments.read("sizeof")) printSizeOfTest = true;

    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        std::cout<<arguments.getApplicationUsage()->getCommandLineUsage()<<std::endl;
        arguments.getApplicationUsage()->write(std::cout,arguments.getApplicationUsage()->getCommandLineOptions());
        return 1;
    }

    // any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized();

    // report any errors if they have occured when parsing the program aguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    if (printMatrixTest)
    {
        std::cout<<"******   Running matrix tests   ******"<<std::endl;

        testFrustum(-1,1,-1,1,1,1000);
        testFrustum(0,1,1,2,2.5,100000);

        testOrtho(0,1,1,2,2.1,1000);
        testOrtho(-1,10,1,20,2.5,100000);

        testLookAt(osg::Vec3(10.0,4.0,2.0),osg::Vec3(10.0,4.0,2.0)+osg::Vec3(0.0,1.0,0.0),osg::Vec3(0.0,0.0,1.0));
        testLookAt(osg::Vec3(10.0,4.0,2.0),osg::Vec3(10.0,4.0,2.0)+osg::Vec3(1.0,1.0,0.0),osg::Vec3(0.0,0.0,1.0));

    }

    if (printSizeOfTest)
    {
        std::cout<<"**** sizeof() tests  ******"<<std::endl;

        sizeOfTest();

        std::cout<<std::endl;
    }

    if (printQualifiedTest)
    {
         std::cout<<"*****   Qualified Tests  ******"<<std::endl;

         osgUtx::QualifiedTestPrinter printer;
         osgUtx::TestGraph::instance().root()->accept( printer );
         std::cout<<std::endl;
    }

    std::cout<<"******   Running tests   ******"<<std::endl;

    // Global Data or Context
    osgUtx::TestContext ctx;
    osgUtx::TestRunner runner( ctx );
    runner.specify("root");

    osgUtx::TestGraph::instance().root()->accept( runner );

    return 0;
}
<|endoftext|>


<commit_before>#include "testing/testing.hpp"

#include "indexer/feature_data.hpp"
#include "indexer/feature_visibility.hpp"
#include "indexer/classificator.hpp"
#include "indexer/classificator_loader.hpp"
#include "indexer/scales.hpp"

#include "base/logging.hpp"

UNIT_TEST(VisibleScales_Smoke)
{
  classificator::Load();

  {
    char const * arr[] = { "place", "city", "capital" };
    uint32_t const type = classif().GetTypeByPath(vector<string>(arr, arr + 3));

    pair<int, int> const r = feature::GetDrawableScaleRange(type);
    TEST_NOT_EQUAL(r.first, -1, ());
    TEST_LESS_OR_EQUAL(r.first, r.second, ());

    TEST(my::between_s(r.first, r.second, 10), (r));
    TEST(!my::between_s(r.first, r.second, 1), (r));
    TEST(!my::between_s(r.first, r.second, scales::GetUpperScale()), (r));
  }
}

namespace
{

class DoGetMaxLowMinHighZoom
{
  pair<int, int> m_res;
  string m_low;

  set<uint32_t> m_skip;

public:
  DoGetMaxLowMinHighZoom(Classificator const & c) : m_res(-1, 1000)
  {
    char const * arr[][2] = {
      { "highway", "proposed" },
      { "highway", "bus_stop" },
    };

    for (size_t i = 0; i < ARRAY_SIZE(arr); ++i)
      m_skip.insert(c.GetTypeByPath(vector<string>(arr[i], arr[i] + 2)));
  }

  void operator() (ClassifObject const * p, uint32_t type)
  {
    if (m_skip.count(type) > 0)
      return;

    pair<int, int> const r = feature::GetDrawableScaleRange(type);
    ASSERT(r.first != -1 && r.second != -1, (r));

    if (m_res.first < r.first)
    {
      m_res.first = r.first;
      m_low = p->GetName();
    }
    if (m_res.second > r.second)
      m_res.second = r.second;
  }

  void Print()
  {
    TEST_EQUAL(m_res.second, scales::GetUpperStyleScale(), (m_res));
    LOG(LINFO, ("Max low highway zoom:", m_res, "for type:", m_low));
  }
};

}

UNIT_TEST(VisibleScales_Highway)
{
  Classificator const & c = classif();

  char const * arr[] = { "highway" };
  uint32_t const type = c.GetTypeByPath(vector<string>(arr, arr + 1));

  ClassifObject const * pObj = c.GetObject(type);

  DoGetMaxLowMinHighZoom doGet(c);
  pObj->ForEachObjectInTree(doGet, type);

  doGet.Print();
}
<commit_msg>Indexer test fix.<commit_after>#include "testing/testing.hpp"

#include "indexer/feature_data.hpp"
#include "indexer/feature_visibility.hpp"
#include "indexer/classificator.hpp"
#include "indexer/classificator_loader.hpp"
#include "indexer/scales.hpp"

#include "base/logging.hpp"

UNIT_TEST(VisibleScales_Smoke)
{
  classificator::Load();

  {
    char const * arr[] = { "place", "city", "capital" };
    uint32_t const type = classif().GetTypeByPath(vector<string>(arr, arr + 3));

    pair<int, int> const r = feature::GetDrawableScaleRange(type);
    TEST_NOT_EQUAL(r.first, -1, ());
    TEST_LESS_OR_EQUAL(r.first, r.second, ());

    TEST(my::between_s(r.first, r.second, 10), (r));
    TEST(!my::between_s(r.first, r.second, 1), (r));
    TEST(!my::between_s(r.first, r.second, scales::GetUpperScale()), (r));
  }
}

namespace
{

class DoGetMaxLowMinHighZoom
{
  pair<int, int> m_res;
  string m_low;

  set<uint32_t> m_skip;

public:
  DoGetMaxLowMinHighZoom(Classificator const & c) : m_res(-1, 1000)
  {
    char const * arr[][2] = {
      { "highway", "proposed" },
      { "highway", "bus_stop" },
      { "highway", "world_level" },
      { "highway", "world_towns_level" }
    };

    for (size_t i = 0; i < ARRAY_SIZE(arr); ++i)
      m_skip.insert(c.GetTypeByPath(vector<string>(arr[i], arr[i] + 2)));
  }

  void operator() (ClassifObject const * p, uint32_t type)
  {
    if (m_skip.count(type) > 0)
      return;

    pair<int, int> const r = feature::GetDrawableScaleRange(type);
    ASSERT(r.first != -1 && r.second != -1, (r));

    if (m_res.first < r.first)
    {
      m_res.first = r.first;
      m_low = p->GetName();
    }
    if (m_res.second > r.second)
      m_res.second = r.second;
  }

  void Print()
  {
    TEST_EQUAL(m_res.second, scales::GetUpperStyleScale(), (m_res));
    LOG(LINFO, ("Max low highway zoom:", m_res, "for type:", m_low));
  }
};

}

UNIT_TEST(VisibleScales_Highway)
{
  Classificator const & c = classif();

  char const * arr[] = { "highway" };
  uint32_t const type = c.GetTypeByPath(vector<string>(arr, arr + 1));

  ClassifObject const * pObj = c.GetObject(type);

  DoGetMaxLowMinHighZoom doGet(c);
  pObj->ForEachObjectInTree(doGet, type);

  doGet.Print();
}
<|endoftext|>


<commit_before>#include "3RVX.h"
#include "Controllers\Volume\IVolume.h"
#include "Controllers\Volume\CoreAudio.h"
#include "LayeredWnd\LayeredWnd.h"
#include "MeterWnd\Meters\HorizontalBar.h"
#include "MeterWnd\Meters\HorizontalEndcap.h"
#include "MeterWnd\MeterWnd.h"
#include "MeterWnd\Meter.h"
#include "VolumeOSD.h"
#include <Wtsapi32.h>
#include "Logger.h"

int APIENTRY
wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPTSTR lpCmdLine, int nCmdShow) {
    hInst = hInstance;

    using namespace Gdiplus;
    GdiplusStartupInput gdiplusStartupInput;
    GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

    Logger::OpenConsole();

    QCLOG(L"  _____ ______     ____  _______ ");
    QCLOG(L" |___ /|  _ \\ \\   / /\\ \\/ /___ / ");
    QCLOG(L"   |_ \\| |_) \\ \\ / /  \\  /  |_ \\ ");
    QCLOG(L"  ___) |  _ < \\ V /   /  \\ ___) |");
    QCLOG(L" |____/|_| \\_\\ \\_/   /_/\\_\\____/ ");
    QCLOG(L"");

    QCLOG(L"Starting up...");

    mainWnd = CreateMainWnd(hInstance);
    if (mainWnd == NULL) {
        CLOG(L"Could not create main window");
        return EXIT_FAILURE;
    }

    HRESULT hr = CoInitializeEx(NULL,
        COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
    if (hr != S_OK) {
        CLOG(L"Failed to initialize the COM library.");
        return EXIT_FAILURE;
    }

    /* Tell the program to initialize */
    PostMessage(mainWnd, WM_3RVX_CONTROL, MSG_LOAD, NULL);

    /* Start the event loop */
    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    GdiplusShutdown(gdiplusToken);
    return (int)msg.wParam;
}

void Init() {
    CLOG(L"Starting initialization.");
    ca = new CoreAudio(mainWnd);
    ca->Init();
    float v = ca->Volume();

    Meter *m = new HorizontalEndcap(L"meter.png", 71, 29, 28);
    mW = new MeterWnd(hInst, L"testtest", L"what what");
    mW->AddMeter(m);
    std::wstring bgbmp(L"bg.png");
    mW->SetBackgroundImage(Gdiplus::Bitmap::FromFile(bgbmp.c_str(), true));
    mW->MeterLevels(v);
    mW->Update();
    mW->Show();

    VolumeOSD *vosd = new VolumeOSD(hInst);
    vosd->LoadSkin();

    WTSRegisterSessionNotification(mainWnd, NOTIFY_FOR_THIS_SESSION);

    HotkeyManager *hkManager = HotkeyManager::Instance();
    hkManager->Register(mainWnd, HKM_MOD_WIN + VK_BACK);
    hkManager->Register(mainWnd, HKM_MOD_WIN + HKM_MOUSE_WHUP);
}

HWND CreateMainWnd(HINSTANCE hInstance) {
    WNDCLASSEX wcex;

    wcex.cbSize = sizeof(WNDCLASSEX);
    wcex.style = NULL;
    wcex.lpfnWndProc = WndProc;
    wcex.cbClsExtra = NULL;
    wcex.cbWndExtra = NULL;
    wcex.hInstance = hInstance;
    wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
    wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
    wcex.lpszMenuName = NULL;
    wcex.lpszClassName = L"3RVX";
    wcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION);

    if (!RegisterClassEx(&wcex)) {
        return NULL;
    }

    HWND hWnd = CreateWindowEx(
        NULL,
        L"3RVX", L"3RVX",
        NULL, NULL, NULL, //your boat, gently down the stream
        NULL, NULL, HWND_MESSAGE, NULL, hInstance, NULL);

    return hWnd;
}

LRESULT CALLBACK WndProc(
    HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {

    if (message == MSG_VOLCHNG) {
        float v = ca->Volume();
        QCLOG(L"Volume level: %.0f", v * 100.0f);
        mW->MeterLevels(v);
        mW->Update();
    }

    if (message == MSG_DEVCHNG) {
        printf("Device change detected.\n");
        ca->ReattachDefaultDevice();
    }

    if (message == WM_3RVX_CONTROL) {
        switch (wParam) {
        case MSG_LOAD:
            Init();
            break;

        case 101:
            printf("%x\n", lParam);
            break;
        }
    }

    if (message == WM_HOTKEY) {
        printf("Hotkey: %d\n", (int) wParam);
    }

    if (message == WM_WTSSESSION_CHANGE) {
        printf("session change\n");
    }

    return DefWindowProc(hWnd, message, wParam, lParam);
}<commit_msg>Only open console in debug mode<commit_after>#include "3RVX.h"
#include "Controllers\Volume\IVolume.h"
#include "Controllers\Volume\CoreAudio.h"
#include "LayeredWnd\LayeredWnd.h"
#include "MeterWnd\Meters\HorizontalBar.h"
#include "MeterWnd\Meters\HorizontalEndcap.h"
#include "MeterWnd\MeterWnd.h"
#include "MeterWnd\Meter.h"
#include "VolumeOSD.h"
#include <Wtsapi32.h>
#include "Logger.h"

int APIENTRY
wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPTSTR lpCmdLine, int nCmdShow) {
    hInst = hInstance;

    using namespace Gdiplus;
    GdiplusStartupInput gdiplusStartupInput;
    GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

#ifdef _DEBUG
    Logger::OpenConsole();
#endif

    QCLOG(L"  _____ ______     ____  _______ ");
    QCLOG(L" |___ /|  _ \\ \\   / /\\ \\/ /___ / ");
    QCLOG(L"   |_ \\| |_) \\ \\ / /  \\  /  |_ \\ ");
    QCLOG(L"  ___) |  _ < \\ V /   /  \\ ___) |");
    QCLOG(L" |____/|_| \\_\\ \\_/   /_/\\_\\____/ ");
    QCLOG(L"");

    QCLOG(L"Starting up...");

    mainWnd = CreateMainWnd(hInstance);
    if (mainWnd == NULL) {
        CLOG(L"Could not create main window");
        return EXIT_FAILURE;
    }

    HRESULT hr = CoInitializeEx(NULL,
        COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
    if (hr != S_OK) {
        CLOG(L"Failed to initialize the COM library.");
        return EXIT_FAILURE;
    }

    /* Tell the program to initialize */
    PostMessage(mainWnd, WM_3RVX_CONTROL, MSG_LOAD, NULL);

    /* Start the event loop */
    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    GdiplusShutdown(gdiplusToken);
    return (int)msg.wParam;
}

void Init() {
    CLOG(L"Starting initialization.");
    ca = new CoreAudio(mainWnd);
    ca->Init();
    float v = ca->Volume();

    Meter *m = new HorizontalEndcap(L"meter.png", 71, 29, 28);
    mW = new MeterWnd(hInst, L"testtest", L"what what");
    mW->AddMeter(m);
    std::wstring bgbmp(L"bg.png");
    mW->SetBackgroundImage(Gdiplus::Bitmap::FromFile(bgbmp.c_str(), true));
    mW->MeterLevels(v);
    mW->Update();
    mW->Show();

    VolumeOSD *vosd = new VolumeOSD(hInst);
    vosd->LoadSkin();

    WTSRegisterSessionNotification(mainWnd, NOTIFY_FOR_THIS_SESSION);

    HotkeyManager *hkManager = HotkeyManager::Instance();
    hkManager->Register(mainWnd, HKM_MOD_WIN + VK_BACK);
    hkManager->Register(mainWnd, HKM_MOD_WIN + HKM_MOUSE_WHUP);
}

HWND CreateMainWnd(HINSTANCE hInstance) {
    WNDCLASSEX wcex;

    wcex.cbSize = sizeof(WNDCLASSEX);
    wcex.style = NULL;
    wcex.lpfnWndProc = WndProc;
    wcex.cbClsExtra = NULL;
    wcex.cbWndExtra = NULL;
    wcex.hInstance = hInstance;
    wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
    wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
    wcex.lpszMenuName = NULL;
    wcex.lpszClassName = L"3RVX";
    wcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION);

    if (!RegisterClassEx(&wcex)) {
        return NULL;
    }

    HWND hWnd = CreateWindowEx(
        NULL,
        L"3RVX", L"3RVX",
        NULL, NULL, NULL, //your boat, gently down the stream
        NULL, NULL, HWND_MESSAGE, NULL, hInstance, NULL);

    return hWnd;
}

LRESULT CALLBACK WndProc(
    HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {

    if (message == MSG_VOLCHNG) {
        float v = ca->Volume();
        QCLOG(L"Volume level: %.0f", v * 100.0f);
        mW->MeterLevels(v);
        mW->Update();
    }

    if (message == MSG_DEVCHNG) {
        printf("Device change detected.\n");
        ca->ReattachDefaultDevice();
    }

    if (message == WM_3RVX_CONTROL) {
        switch (wParam) {
        case MSG_LOAD:
            Init();
            break;

        case 101:
            printf("%x\n", lParam);
            break;
        }
    }

    if (message == WM_HOTKEY) {
        printf("Hotkey: %d\n", (int) wParam);
    }

    if (message == WM_WTSSESSION_CHANGE) {
        printf("session change\n");
    }

    return DefWindowProc(hWnd, message, wParam, lParam);
}<|endoftext|>


<commit_before>/*
Copyright (c) 2009 Yahoo! Inc.  All rights reserved.  The copyrights
embodied in the content of this file are licensed under the BSD
(revised) open source license
 */
#include <stdio.h>
#include <float.h>

#include "cache.h"
#include "io.h"
#include "parse_regressor.h"
#include "parser.h"
#include "parse_args.h"
#include "sender.h"
#include "network.h"
#include "global_data.h"

const float default_decay = 1.;

po::variables_map parse_args(int argc, char *argv[], boost::program_options::options_description& desc,
			     gd_vars& vars,
			     regressor &r, parser* par,
			     string& final_regressor_name)
{
  vars.init();
  global.program_name = argv[0];
  // Declare the supported options.
  desc.add_options()
    ("active_learning", "active learning mode")
    ("active_simulation", "active learning simulation mode")
    ("active_mellowness", po::value<float>(&global.active_c0)->default_value(8.f), "active learning mellowness parameter c_0. Default 8")
    ("adaptive", "use adaptive, individual learning rates.")
    ("audit,a", "print weights of features")
    ("bit_precision,b", po::value<size_t>(),
     "number of bits in the feature table")
    ("backprop", "turn on delayed backprop")
    ("cache,c", "Use a cache.  The default is <data>.cache")
    ("cache_file", po::value< vector<string> >(), "The location(s) of cache_file.")
    ("compressed", "use gzip format whenever appropriate. If a cache file is being created, this option creates a compressed cache file. A mixture of raw-text & compressed inputs are supported if this option is on")
    ("conjugate_gradient", "use conjugate gradient based optimization")
    ("regularization", po::value<float>(&global.regularization)->default_value(0.), "minimize weight magnitude")
    ("corrective", "turn on corrective updates")
    ("data,d", po::value< string >()->default_value(""), "Example Set")
    ("daemon", "read data from port 39523")
    ("decay_learning_rate",    po::value<float>(&global.eta_decay_rate)->default_value(default_decay),
     "Set Decay factor for learning_rate between passes")
    ("final_regressor,f", po::value< string >(), "Final regressor")
    ("global_multiplier", po::value<float>(&global.global_multiplier)->default_value(1.0), "Global update multiplier")
    ("delayed_global", "Do delayed global updates")
    ("hash", po::value< string > (), "how to hash the features. Available options: strings, all")
    ("help,h","Output Arguments")
    ("version","Version information")
    ("initial_weight", po::value<float>(&global.initial_weight)->default_value(0.), "Set all weights to an initial value of 1.")
    ("initial_regressor,i", po::value< vector<string> >(), "Initial regressor(s)")
    ("initial_t", po::value<float>(&(par->t))->default_value(1.), "initial t value")
    ("min_prediction", po::value<double>(&global.min_label), "Smallest prediction to output")
    ("max_prediction", po::value<double>(&global.max_label), "Largest prediction to output")
    ("multisource", po::value<size_t>(), "multiple sources for daemon input")
    ("noop","do no learning")
    ("port", po::value<size_t>(),"port to listen on")
    ("power_t", po::value<float>(&vars.power_t)->default_value(0.5), "t power value")
    ("predictto", po::value< string > (), "host to send predictions to")
    ("learning_rate,l", po::value<float>(&global.eta)->default_value(10),
     "Set Learning Rate")
    ("passes", po::value<size_t>(&global.numpasses)->default_value(1),
     "Number of Training Passes")
    ("predictions,p", po::value< string >(), "File to output predictions to")
    ("quadratic,q", po::value< vector<string> > (),
     "Create and use quadratic features")
    ("quiet", "Don't output diagnostics")
    ("raw_predictions,r", po::value< string >(),
     "File to output unnormalized predictions to")
    ("sendto", po::value< vector<string> >(), "send example to <hosts>")
    ("testonly,t", "Ignore label information and just test")
    ("thread_bits", po::value<size_t>(&global.thread_bits)->default_value(0), "log_2 threads")
    ("loss_function", po::value<string>()->default_value("squared"), "Specify the loss function to be used, uses squared by default. Currently available ones are squared, hinge, logistic and quantile.")
    ("quantile_tau", po::value<double>()->default_value(0.5), "Parameter \\tau associated with Quantile loss. Defaults to 0.5")
    ("unique_id", po::value<size_t>(&global.unique_id)->default_value(0),"unique id used for cluster parallel")
    ("sort_features", "turn this on to disregard order in which features have been defined. This will lead to smaller cache sizes")
    ("ngram", po::value<size_t>(), "Generate N grams")
    ("skips", po::value<size_t>(), "Generate skips in N grams. This in conjunction with the ngram tag can be used to generate generalized n-skip-k-gram.");

  global.queries = 0;
  global.example_number = 0;
  global.weighted_examples = 0.;
  global.old_weighted_examples = 0.;
  global.backprop = false;
  global.corrective = false;
  global.delayed_global = false;
  global.conjugate_gradient = false;
  global.stride = 1;
  global.weighted_labels = 0.;
  global.total_features = 0;
  global.sum_loss = 0.0;
  global.sum_loss_since_last_dump = 0.0;
  global.dump_interval = exp(1.);
  global.num_bits = 18;
  global.default_bits = true;
  global.final_prediction_sink.begin = global.final_prediction_sink.end=global.final_prediction_sink.end_array = NULL;
  global.raw_prediction = -1;
  global.local_prediction = -1;
  global.print = print_result;
  global.min_label = 0.;
  global.max_label = 1.;

  global.adaptive = false;
  global.audit = false;
  global.active = false;
  global.active_simulation =false;
  global.reg = &r;

  po::positional_options_description p;

  po::variables_map vm;

  po::store(po::command_line_parser(argc, argv).
	    options(desc).positional(p).run(), vm);
  po::notify(vm);

  global.weighted_unlabeled_examples = par->t;
  global.initial_t = par->t;
  global.partition_bits = global.thread_bits;

  if (vm.count("help") || argc == 1) {
    /* upon direct query for help -- spit it out to stdout */
    cout << "\n" << desc << "\n";
    exit(0);
  }

  if (vm.count("active_simulation"))
      global.active_simulation = true;

  if (vm.count("active_learning") && !global.active_simulation)
    global.active = true;

  if (vm.count("adaptive")) {
      global.adaptive = true;
      global.stride = 2;
      vars.power_t = 0.0;
  }

  if (vm.count("backprop")) {
      global.backprop = true;
      cout << "enabling backprop updates" << endl;
  }

  if (vm.count("corrective")) {
      global.corrective = true;
      cout << "enabling corrective updates" << endl;
  }

  if (vm.count("delayed_global")) {
      global.delayed_global = true;
      cout << "enabling delayed_global updates" << endl;
  }

  if (vm.count("conjugate_gradient")) {
    global.conjugate_gradient = true;
    global.stride = 4;
    cout << "enabling conjugate gradient based optimization" << endl;
  }

  if (vm.count("version") || argc == 1) {
    /* upon direct query for version -- spit it out to stdout */
    cout << version << "\n";
    exit(0);
  }

  if(vm.count("ngram")){
    global.ngram = vm["ngram"].as<size_t>();
    if(!vm.count("skip_gram")) cout << "You have chosen to generate " << global.ngram << "-grams" << endl;
  }
  if(vm.count("skips"))
    {
    global.skips = vm["skips"].as<size_t>();
    if(!vm.count("ngram"))
      {
	cout << "You can not skip unless ngram is > 1" << endl;
	exit(1);
      }
    cout << "You have chosen to generate " << global.skips << "-skip-" << global.ngram << "-grams" << endl;
    if(global.skips > 4)
      {
      cout << "*********************************" << endl;
      cout << "Generating these features might take quite some time" << endl;
      cout << "*********************************" << endl;
      }
    }
  if (vm.count("bit_precision"))
    {
      global.default_bits = false;
      global.num_bits = vm["bit_precision"].as< size_t>();
    }

  if(vm.count("compressed")){
    set_compressed(par);
  }

  if(vm.count("sort_features"))
    par->sort_features = true;

  if (global.num_bits > 30) {
    cerr << "The system limits at 30 bits of precision!\n" << endl;
    exit(1);
  }
  if (vm.count("quiet"))
    global.quiet = true;
  else
    global.quiet = false;

  if (vm.count("quadratic"))
    {
      global.pairs = vm["quadratic"].as< vector<string> >();
      if (!global.quiet)
	{
	  cerr << "creating quadratic features for pairs: ";
	  for (vector<string>::iterator i = global.pairs.begin(); i != global.pairs.end();i++) {
	    cerr << *i << " ";
	    if (i->length() > 2)
	      cerr << endl << "warning, ignoring characters after the 2nd.\n";
	    if (i->length() < 2) {
	      cerr << endl << "error, quadratic features must involve two sets.\n";
	      exit(0);
	    }
	  }
	  cerr << endl;
	}
    }

  parse_regressor_args(vm, r, final_regressor_name, global.quiet);

  if (vm.count("active_c0"))
    global.active_c0 = vm["active_c0"].as<float>();

  if (vm.count("min_prediction"))
    global.min_label = vm["min_prediction"].as<double>();
  if (vm.count("max_prediction"))
    global.max_label = vm["max_prediction"].as<double>();
  if (vm.count("min_prediction") || vm.count("max_prediction") || vm.count("testonly"))
    set_minmax = noop_mm;

  string loss_function;
  if(vm.count("loss_function"))
	  loss_function = vm["loss_function"].as<string>();
  else
	  loss_function = "squaredloss";

  double loss_parameter = 0.0;
  if(vm.count("quantile_tau"))
    loss_parameter = vm["quantile_tau"].as<double>();
  r.loss = getLossFunction(loss_function, loss_parameter);
  global.loss = r.loss;

  global.eta *= pow(par->t, vars.power_t);

  if (global.eta_decay_rate != default_decay && global.numpasses == 1)
    cerr << "Warning: decay_learning_rate has no effect when there is only one pass" << endl;

  if (pow(global.eta_decay_rate, global.numpasses) < 0.0001 )
    cerr << "Warning: the learning rate for the last pass is multiplied by: " << pow(global.eta_decay_rate, global.numpasses)
	 << " adjust to --decay_learning_rate larger to avoid this." << endl;

  parse_source_args(vm,par,global.quiet,global.numpasses);

  if (!global.quiet)
    {
      cerr << "Num weight bits = " << global.num_bits << endl;
      cerr << "learning rate = " << global.eta << endl;
      cerr << "initial_t = " << par->t << endl;
      cerr << "power_t = " << vars.power_t << endl;
      if (global.numpasses > 1)
	cerr << "decay_learning_rate = " << global.eta_decay_rate << endl;
    }

  if (vm.count("predictions")) {
    if (!global.quiet)
      cerr << "predictions = " <<  vm["predictions"].as< string >() << endl;
    if (strcmp(vm["predictions"].as< string >().c_str(), "stdout") == 0)
      {
	int_pair pf = {1,0};
	push(global.final_prediction_sink,pf);//stdout
      }
    else
      {
	const char* fstr = (vm["predictions"].as< string >().c_str());
	int_pair pf = {fileno(fopen(fstr,"w")),0};
	if (pf.fd < 0)
	  cerr << "Error opening the predictions file: " << fstr << endl;
	push(global.final_prediction_sink,pf);
      }
  }

  if (vm.count("raw_predictions")) {
    if (!global.quiet)
      cerr << "raw predictions = " <<  vm["raw_predictions"].as< string >() << endl;
    if (strcmp(vm["raw_predictions"].as< string >().c_str(), "stdout") == 0)
      global.raw_prediction = 1;//stdout
    else
      global.raw_prediction = fileno(fopen(vm["raw_predictions"].as< string >().c_str(), "w"));
  }

  if (vm.count("audit"))
    global.audit = true;

  parse_send_args(vm, global.pairs);

  if (vm.count("testonly"))
    {
      if (!global.quiet)
	cerr << "only testing" << endl;
      global.training = false;
    }
  else
    {
      global.training = true;
      if (!global.quiet)
	cerr << "learning_rate set to " << global.eta << endl;
    }

  if (vm.count("predictto"))
    {
      if (!global.quiet)
	cerr << "predictto = " << vm["predictto"].as< string >() << endl;
      global.local_prediction = open_socket(vm["predictto"].as< string > ().c_str(), global.unique_id);
    }

  return vm;
}

<commit_msg>- Make vw friendlier: if -d is left-out, treat positional parameter   as data-file rather than throwing a cryptic program_options exception.<commit_after>/*
Copyright (c) 2009 Yahoo! Inc.  All rights reserved.  The copyrights
embodied in the content of this file are licensed under the BSD
(revised) open source license
 */
#include <stdio.h>
#include <float.h>

#include "cache.h"
#include "io.h"
#include "parse_regressor.h"
#include "parser.h"
#include "parse_args.h"
#include "sender.h"
#include "network.h"
#include "global_data.h"

const float default_decay = 1.;

po::variables_map parse_args(int argc, char *argv[], boost::program_options::options_description& desc,
			     gd_vars& vars,
			     regressor &r, parser* par,
			     string& final_regressor_name)
{
  vars.init();
  global.program_name = argv[0];
  // Declare the supported options.
  desc.add_options()
    ("active_learning", "active learning mode")
    ("active_simulation", "active learning simulation mode")
    ("active_mellowness", po::value<float>(&global.active_c0)->default_value(8.f), "active learning mellowness parameter c_0. Default 8")
    ("adaptive", "use adaptive, individual learning rates.")
    ("audit,a", "print weights of features")
    ("bit_precision,b", po::value<size_t>(),
     "number of bits in the feature table")
    ("backprop", "turn on delayed backprop")
    ("cache,c", "Use a cache.  The default is <data>.cache")
    ("cache_file", po::value< vector<string> >(), "The location(s) of cache_file.")
    ("compressed", "use gzip format whenever appropriate. If a cache file is being created, this option creates a compressed cache file. A mixture of raw-text & compressed inputs are supported if this option is on")
    ("conjugate_gradient", "use conjugate gradient based optimization")
    ("regularization", po::value<float>(&global.regularization)->default_value(0.), "minimize weight magnitude")
    ("corrective", "turn on corrective updates")
    ("data,d", po::value< string >()->default_value(""), "Example Set")
    ("daemon", "read data from port 39523")
    ("decay_learning_rate",    po::value<float>(&global.eta_decay_rate)->default_value(default_decay),
     "Set Decay factor for learning_rate between passes")
    ("final_regressor,f", po::value< string >(), "Final regressor")
    ("global_multiplier", po::value<float>(&global.global_multiplier)->default_value(1.0), "Global update multiplier")
    ("delayed_global", "Do delayed global updates")
    ("hash", po::value< string > (), "how to hash the features. Available options: strings, all")
    ("help,h","Output Arguments")
    ("version","Version information")
    ("initial_weight", po::value<float>(&global.initial_weight)->default_value(0.), "Set all weights to an initial value of 1.")
    ("initial_regressor,i", po::value< vector<string> >(), "Initial regressor(s)")
    ("initial_t", po::value<float>(&(par->t))->default_value(1.), "initial t value")
    ("min_prediction", po::value<double>(&global.min_label), "Smallest prediction to output")
    ("max_prediction", po::value<double>(&global.max_label), "Largest prediction to output")
    ("multisource", po::value<size_t>(), "multiple sources for daemon input")
    ("noop","do no learning")
    ("port", po::value<size_t>(),"port to listen on")
    ("power_t", po::value<float>(&vars.power_t)->default_value(0.5), "t power value")
    ("predictto", po::value< string > (), "host to send predictions to")
    ("learning_rate,l", po::value<float>(&global.eta)->default_value(10),
     "Set Learning Rate")
    ("passes", po::value<size_t>(&global.numpasses)->default_value(1),
     "Number of Training Passes")
    ("predictions,p", po::value< string >(), "File to output predictions to")
    ("quadratic,q", po::value< vector<string> > (),
     "Create and use quadratic features")
    ("quiet", "Don't output diagnostics")
    ("raw_predictions,r", po::value< string >(),
     "File to output unnormalized predictions to")
    ("sendto", po::value< vector<string> >(), "send example to <hosts>")
    ("testonly,t", "Ignore label information and just test")
    ("thread_bits", po::value<size_t>(&global.thread_bits)->default_value(0), "log_2 threads")
    ("loss_function", po::value<string>()->default_value("squared"), "Specify the loss function to be used, uses squared by default. Currently available ones are squared, hinge, logistic and quantile.")
    ("quantile_tau", po::value<double>()->default_value(0.5), "Parameter \\tau associated with Quantile loss. Defaults to 0.5")
    ("unique_id", po::value<size_t>(&global.unique_id)->default_value(0),"unique id used for cluster parallel")
    ("sort_features", "turn this on to disregard order in which features have been defined. This will lead to smaller cache sizes")
    ("ngram", po::value<size_t>(), "Generate N grams")
    ("skips", po::value<size_t>(), "Generate skips in N grams. This in conjunction with the ngram tag can be used to generate generalized n-skip-k-gram.");

  global.queries = 0;
  global.example_number = 0;
  global.weighted_examples = 0.;
  global.old_weighted_examples = 0.;
  global.backprop = false;
  global.corrective = false;
  global.delayed_global = false;
  global.conjugate_gradient = false;
  global.stride = 1;
  global.weighted_labels = 0.;
  global.total_features = 0;
  global.sum_loss = 0.0;
  global.sum_loss_since_last_dump = 0.0;
  global.dump_interval = exp(1.);
  global.num_bits = 18;
  global.default_bits = true;
  global.final_prediction_sink.begin = global.final_prediction_sink.end=global.final_prediction_sink.end_array = NULL;
  global.raw_prediction = -1;
  global.local_prediction = -1;
  global.print = print_result;
  global.min_label = 0.;
  global.max_label = 1.;

  global.adaptive = false;
  global.audit = false;
  global.active = false;
  global.active_simulation =false;
  global.reg = &r;

  po::positional_options_description p;
  // Be friendly: if -d was left out, treat positional param as data file
  p.add("data", -1);

  po::variables_map vm;

  po::store(po::command_line_parser(argc, argv).
	    options(desc).positional(p).run(), vm);
  po::notify(vm);

  global.weighted_unlabeled_examples = par->t;
  global.initial_t = par->t;
  global.partition_bits = global.thread_bits;

  if (vm.count("help") || argc == 1) {
    /* upon direct query for help -- spit it out to stdout */
    cout << "\n" << desc << "\n";
    exit(0);
  }

  if (vm.count("active_simulation"))
      global.active_simulation = true;

  if (vm.count("active_learning") && !global.active_simulation)
    global.active = true;

  if (vm.count("adaptive")) {
      global.adaptive = true;
      global.stride = 2;
      vars.power_t = 0.0;
  }

  if (vm.count("backprop")) {
      global.backprop = true;
      cout << "enabling backprop updates" << endl;
  }

  if (vm.count("corrective")) {
      global.corrective = true;
      cout << "enabling corrective updates" << endl;
  }

  if (vm.count("delayed_global")) {
      global.delayed_global = true;
      cout << "enabling delayed_global updates" << endl;
  }

  if (vm.count("conjugate_gradient")) {
    global.conjugate_gradient = true;
    global.stride = 4;
    cout << "enabling conjugate gradient based optimization" << endl;
  }

  if (vm.count("version") || argc == 1) {
    /* upon direct query for version -- spit it out to stdout */
    cout << version << "\n";
    exit(0);
  }

  if(vm.count("ngram")){
    global.ngram = vm["ngram"].as<size_t>();
    if(!vm.count("skip_gram")) cout << "You have chosen to generate " << global.ngram << "-grams" << endl;
  }
  if(vm.count("skips"))
    {
    global.skips = vm["skips"].as<size_t>();
    if(!vm.count("ngram"))
      {
	cout << "You can not skip unless ngram is > 1" << endl;
	exit(1);
      }
    cout << "You have chosen to generate " << global.skips << "-skip-" << global.ngram << "-grams" << endl;
    if(global.skips > 4)
      {
      cout << "*********************************" << endl;
      cout << "Generating these features might take quite some time" << endl;
      cout << "*********************************" << endl;
      }
    }
  if (vm.count("bit_precision"))
    {
      global.default_bits = false;
      global.num_bits = vm["bit_precision"].as< size_t>();
    }

  if(vm.count("compressed")){
    set_compressed(par);
  }

  if(vm.count("sort_features"))
    par->sort_features = true;

  if (global.num_bits > 30) {
    cerr << "The system limits at 30 bits of precision!\n" << endl;
    exit(1);
  }
  if (vm.count("quiet"))
    global.quiet = true;
  else
    global.quiet = false;

  if (vm.count("quadratic"))
    {
      global.pairs = vm["quadratic"].as< vector<string> >();
      if (!global.quiet)
	{
	  cerr << "creating quadratic features for pairs: ";
	  for (vector<string>::iterator i = global.pairs.begin(); i != global.pairs.end();i++) {
	    cerr << *i << " ";
	    if (i->length() > 2)
	      cerr << endl << "warning, ignoring characters after the 2nd.\n";
	    if (i->length() < 2) {
	      cerr << endl << "error, quadratic features must involve two sets.\n";
	      exit(0);
	    }
	  }
	  cerr << endl;
	}
    }

  parse_regressor_args(vm, r, final_regressor_name, global.quiet);

  if (vm.count("active_c0"))
    global.active_c0 = vm["active_c0"].as<float>();

  if (vm.count("min_prediction"))
    global.min_label = vm["min_prediction"].as<double>();
  if (vm.count("max_prediction"))
    global.max_label = vm["max_prediction"].as<double>();
  if (vm.count("min_prediction") || vm.count("max_prediction") || vm.count("testonly"))
    set_minmax = noop_mm;

  string loss_function;
  if(vm.count("loss_function"))
	  loss_function = vm["loss_function"].as<string>();
  else
	  loss_function = "squaredloss";

  double loss_parameter = 0.0;
  if(vm.count("quantile_tau"))
    loss_parameter = vm["quantile_tau"].as<double>();
  r.loss = getLossFunction(loss_function, loss_parameter);
  global.loss = r.loss;

  global.eta *= pow(par->t, vars.power_t);

  if (global.eta_decay_rate != default_decay && global.numpasses == 1)
    cerr << "Warning: decay_learning_rate has no effect when there is only one pass" << endl;

  if (pow(global.eta_decay_rate, global.numpasses) < 0.0001 )
    cerr << "Warning: the learning rate for the last pass is multiplied by: " << pow(global.eta_decay_rate, global.numpasses)
	 << " adjust to --decay_learning_rate larger to avoid this." << endl;

  parse_source_args(vm,par,global.quiet,global.numpasses);

  if (!global.quiet)
    {
      cerr << "Num weight bits = " << global.num_bits << endl;
      cerr << "learning rate = " << global.eta << endl;
      cerr << "initial_t = " << par->t << endl;
      cerr << "power_t = " << vars.power_t << endl;
      if (global.numpasses > 1)
	cerr << "decay_learning_rate = " << global.eta_decay_rate << endl;
    }

  if (vm.count("predictions")) {
    if (!global.quiet)
      cerr << "predictions = " <<  vm["predictions"].as< string >() << endl;
    if (strcmp(vm["predictions"].as< string >().c_str(), "stdout") == 0)
      {
	int_pair pf = {1,0};
	push(global.final_prediction_sink,pf);//stdout
      }
    else
      {
	const char* fstr = (vm["predictions"].as< string >().c_str());
	int_pair pf = {fileno(fopen(fstr,"w")),0};
	if (pf.fd < 0)
	  cerr << "Error opening the predictions file: " << fstr << endl;
	push(global.final_prediction_sink,pf);
      }
  }

  if (vm.count("raw_predictions")) {
    if (!global.quiet)
      cerr << "raw predictions = " <<  vm["raw_predictions"].as< string >() << endl;
    if (strcmp(vm["raw_predictions"].as< string >().c_str(), "stdout") == 0)
      global.raw_prediction = 1;//stdout
    else
      global.raw_prediction = fileno(fopen(vm["raw_predictions"].as< string >().c_str(), "w"));
  }

  if (vm.count("audit"))
    global.audit = true;

  parse_send_args(vm, global.pairs);

  if (vm.count("testonly"))
    {
      if (!global.quiet)
	cerr << "only testing" << endl;
      global.training = false;
    }
  else
    {
      global.training = true;
      if (!global.quiet)
	cerr << "learning_rate set to " << global.eta << endl;
    }

  if (vm.count("predictto"))
    {
      if (!global.quiet)
	cerr << "predictto = " << vm["predictto"].as< string >() << endl;
      global.local_prediction = open_socket(vm["predictto"].as< string > ().c_str(), global.unique_id);
    }

  return vm;
}

<|endoftext|>


<commit_before>#include "TestBlockLandApplication.h"
#include <Ogre.h>
#include <OIS/OIS.h>
#include <iostream>

TestBlockLandApplication::TestBlockLandApplication() {
	m_Blocks = new block_t[WORLD_SIZE * WORLD_SIZE * WORLD_SIZE];
	memset(m_Blocks, 0, sizeof(block_t) * WORLD_SIZE * WORLD_SIZE * WORLD_SIZE);
	initWorldBlocksSphere();
	m_ChunkID = 1;
}

TestBlockLandApplication::~TestBlockLandApplication() {
	delete[] m_Blocks;
}

void TestBlockLandApplication::createChunk(const int StartX, const int StartY, const int StartZ) {
	Ogre::ManualObject* MeshChunk = new Ogre::ManualObject("MeshManChunk" + Ogre::StringConverter::toString(m_ChunkID));
	MeshChunk->begin("BoxColor");

	int iVertex = 0;
	block_t Block;
	block_t Block1;

	for (int z = StartZ; z < CHUNK_SIZE + StartZ; ++z) {
		for (int y = StartY; y < CHUNK_SIZE + StartY; ++y) {
			for (int x = StartX; x < CHUNK_SIZE + StartX; ++x) {
				Block = GetBlock(x, y, z);
				if (Block == 0)
					continue;

				//x-1
				Block1 = 0;
				if (x > StartX)
					Block1 = GetBlock(x - 1, y, z);

				if (Block1 == 0) {
					MeshChunk->position(x, y, z + 1);
					MeshChunk->normal(-1, 0, 0);
					MeshChunk->textureCoord(0, 1);
					MeshChunk->position(x, y + 1, z + 1);
					MeshChunk->normal(-1, 0, 0);
					MeshChunk->textureCoord(1, 1);
					MeshChunk->position(x, y + 1, z);
					MeshChunk->normal(-1, 0, 0);
					MeshChunk->textureCoord(1, 0);
					MeshChunk->position(x, y, z);
					MeshChunk->normal(-1, 0, 0);
					MeshChunk->textureCoord(0, 0);

					MeshChunk->triangle(iVertex, iVertex + 1, iVertex + 2);
					MeshChunk->triangle(iVertex + 2, iVertex + 3, iVertex);

					iVertex += 4;
				}

				//x+1
				Block1 = 0;
				if (x < StartX + CHUNK_SIZE - 1)
					Block1 = GetBlock(x + 1, y, z);

				if (Block1 == 0) {
					MeshChunk->position(x + 1, y, z);
					MeshChunk->normal(1, 0, 0);
					MeshChunk->textureCoord(0, 1);
					MeshChunk->position(x + 1, y + 1, z);
					MeshChunk->normal(1, 0, 0);
					MeshChunk->textureCoord(1, 1);
					MeshChunk->position(x + 1, y + 1, z + 1);
					MeshChunk->normal(1, 0, 0);
					MeshChunk->textureCoord(1, 0);
					MeshChunk->position(x + 1, y, z + 1);
					MeshChunk->normal(1, 0, 0);
					MeshChunk->textureCoord(0, 0);

					MeshChunk->triangle(iVertex, iVertex + 1, iVertex + 2);
					MeshChunk->triangle(iVertex + 2, iVertex + 3, iVertex);

					iVertex += 4;
				}

				//y-1
				Block1 = 0;
				if (y > StartY)
					Block1 = GetBlock(x, y - 1, z);

				if (Block1 == 0) {
					MeshChunk->position(x, y, z);
					MeshChunk->normal(0, -1, 0);
					MeshChunk->textureCoord(0, 1);
					MeshChunk->position(x + 1, y, z);
					MeshChunk->normal(0, -1, 0);
					MeshChunk->textureCoord(1, 1);
					MeshChunk->position(x + 1, y, z + 1);
					MeshChunk->normal(0, -1, 0);
					MeshChunk->textureCoord(1, 0);
					MeshChunk->position(x, y, z + 1);
					MeshChunk->normal(0, -1, 0);
					MeshChunk->textureCoord(0, 0);

					MeshChunk->triangle(iVertex, iVertex + 1, iVertex + 2);
					MeshChunk->triangle(iVertex + 2, iVertex + 3, iVertex);

					iVertex += 4;
				}

				//y+1
				Block1 = 0;
				if (y < StartY + CHUNK_SIZE - 1)
					Block1 = GetBlock(x, y + 1, z);

				if (Block1 == 0) {
					MeshChunk->position(x, y + 1, z + 1);
					MeshChunk->normal(0, 1, 0);
					MeshChunk->textureCoord(0, 1);
					MeshChunk->position(x + 1, y + 1, z + 1);
					MeshChunk->normal(0, 1, 0);
					MeshChunk->textureCoord(1, 1);
					MeshChunk->position(x + 1, y + 1, z);
					MeshChunk->normal(0, 1, 0);
					MeshChunk->textureCoord(1, 0);
					MeshChunk->position(x, y + 1, z);
					MeshChunk->normal(0, 1, 0);
					MeshChunk->textureCoord(0, 0);

					MeshChunk->triangle(iVertex, iVertex + 1, iVertex + 2);
					MeshChunk->triangle(iVertex + 2, iVertex + 3, iVertex);

					iVertex += 4;
				}

				//z-1
				Block1 = 0;
				if (z > StartZ)
					Block1 = GetBlock(x, y, z - 1);

				if (Block1 == 0) {
					MeshChunk->position(x, y + 1, z);
					MeshChunk->normal(0, 0, -1);
					MeshChunk->textureCoord(0, 1);
					MeshChunk->position(x + 1, y + 1, z);
					MeshChunk->normal(0, 0, -1);
					MeshChunk->textureCoord(1, 1);
					MeshChunk->position(x + 1, y, z);
					MeshChunk->normal(0, 0, -1);
					MeshChunk->textureCoord(1, 0);
					MeshChunk->position(x, y, z);
					MeshChunk->normal(0, 0, -1);
					MeshChunk->textureCoord(0, 0);

					MeshChunk->triangle(iVertex, iVertex + 1, iVertex + 2);
					MeshChunk->triangle(iVertex + 2, iVertex + 3, iVertex);

					iVertex += 4;
				}

				//z+1
				Block1 = 0;
				if (z < StartZ + CHUNK_SIZE - 1)
					Block1 = GetBlock(x, y, z + 1);

				if (Block1 == 0) {
					MeshChunk->position(x, y, z + 1);
					MeshChunk->normal(0, 0, 1);
					MeshChunk->textureCoord(0, 1);
					MeshChunk->position(x + 1, y, z + 1);
					MeshChunk->normal(0, 0, 1);
					MeshChunk->textureCoord(1, 1);
					MeshChunk->position(x + 1, y + 1, z + 1);
					MeshChunk->normal(0, 0, 1);
					MeshChunk->textureCoord(1, 0);
					MeshChunk->position(x, y + 1, z + 1);
					MeshChunk->normal(0, 0, 1);
					MeshChunk->textureCoord(0, 0);

					MeshChunk->triangle(iVertex, iVertex + 1, iVertex + 2);
					MeshChunk->triangle(iVertex + 2, iVertex + 3, iVertex);

					iVertex += 4;
				}
			}
		}
	}

	MeshChunk->end();
	mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(MeshChunk);

	++m_ChunkID;
}

void TestBlockLandApplication::createSolidTexture(const Ogre::String& pName) {
	Ogre::MaterialPtr mat = Ogre::MaterialManager::getSingleton().create("BoxColor", "General", true);
	Ogre::Technique* tech = mat->getTechnique(0);
	Ogre::Pass* pass = tech->getPass(0);
	Ogre::TextureUnitState* tex = pass->createTextureUnitState();
	tex->setColourOperationEx(Ogre::LBX_MODULATE, Ogre::LBS_MANUAL, Ogre::LBS_CURRENT, Ogre::ColourValue(0, 0.5, 0));
}

void TestBlockLandApplication::createTexture(const Ogre::String& pName, const Ogre::String& pImageFilename) {
	Ogre::MaterialPtr mat = Ogre::MaterialManager::getSingleton().create("BoxColor", "General", true);
	Ogre::Technique* tech = mat->getTechnique(0);
	Ogre::Pass* pass = tech->getPass(0);
	Ogre::TextureUnitState* tex = pass->createTextureUnitState();

	tex->setTextureName(pImageFilename);
	tex->setNumMipmaps(4);
	tex->setTextureAnisotropy(1);
	tex->setTextureFiltering(Ogre::FO_POINT, Ogre::FO_POINT, Ogre::FO_POINT);
}

void TestBlockLandApplication::createWorldChunks() {
	Ogre::MaterialPtr mat = Ogre::MaterialManager::getSingleton().create("BoxColor", "General", true);
	Ogre::Technique* tech = mat->getTechnique(0);
	Ogre::Pass* pass = tech->getPass(0);
	Ogre::TextureUnitState* tex = pass->createTextureUnitState();
	tex->setColourOperationEx(Ogre::LBX_MODULATE, Ogre::LBS_MANUAL, Ogre::LBS_CURRENT, Ogre::ColourValue(0, 0.5, 0));

	for (int z = 0; z < WORLD_SIZE; z += CHUNK_SIZE) {
		for (int y = 0; y < WORLD_SIZE; y += CHUNK_SIZE) {
			for (int x = 0; x < WORLD_SIZE; x += CHUNK_SIZE) {
				createChunk(x, y, z);
			}
		}
	}
}

void TestBlockLandApplication::createScene() {
	mSceneMgr->setSkyDome(true, "Examples/CloudySky", 2, 8, 100);
	mSceneMgr->setFog(Ogre::FOG_LINEAR, Ogre::ColourValue(0.8, 0.8, 1), 0.05, 0.0, 200);

	mCamera->setFarClipDistance(256);
	mCamera->setNearClipDistance(0.01);

	mSceneMgr->setAmbientLight(Ogre::ColourValue(0.5, 0.5, 0.5));
	Ogre::Light* l = mSceneMgr->createLight("MainLight");
	l->setPosition(20, 80, 50);

	createWorldChunks();
}

void TestBlockLandApplication::initWorldBlocksSphere() {
	Ogre::Image heightMap;
	heightMap.load("heightmap.png", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
	const Ogre::PixelBox& pb = heightMap.getPixelBox();
	heightMap.scale(pb, Ogre::PixelBox(WORLD_SIZE, WORLD_SIZE, pb.getDepth(), Ogre::PF_BYTE_RGB));

	for (int z = 0; z < WORLD_SIZE; ++z) {
		for (int x = 0; x < WORLD_SIZE; ++x) {
			const Ogre::ColourValue& color = heightMap.getColourAt(x, z, 0);
			const int Height = static_cast<int>((((color.r + color.g + color.b) / 1.5f) - 1.0f) * WORLD_SIZE / 4.0f + WORLD_SIZE / 2.0f);
			for (int y = 0; y < Height; ++y) {
				GetBlock(x, y, z) = 1;
			}
		}
	}
}

#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#define WIN32_LEAN_AND_MEAN
#include "windows.h"
#endif

#ifdef __cplusplus
extern "C" {
#endif

#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
INT WINAPI WinMain(HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT)
#else
int main(int argc, char *argv[])
#endif
		{
	// Create application object
	TestBlockLandApplication app;

	try {
		app.go();
	} catch (Ogre::Exception& e) {
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
		MessageBox(NULL, e.getFullDescription().c_str(), "An exception has occurred!", MB_OK | MB_ICONERROR | MB_TASKMODAL);
#else
		std::cerr << "An exception has occurred: " << e.getFullDescription().c_str() << std::endl;
#endif
	}

	return 0;
}

#ifdef __cplusplus
}
#endif
<commit_msg>* fixed segfault at startup<commit_after>#include "TestBlockLandApplication.h"
#include <Ogre.h>
#include <OIS/OIS.h>
#include <iostream>

TestBlockLandApplication::TestBlockLandApplication() {
	m_Blocks = new block_t[WORLD_SIZE * WORLD_SIZE * WORLD_SIZE];
	memset(m_Blocks, 0, sizeof(block_t) * WORLD_SIZE * WORLD_SIZE * WORLD_SIZE);
	m_ChunkID = 1;
}

TestBlockLandApplication::~TestBlockLandApplication() {
	delete[] m_Blocks;
}

void TestBlockLandApplication::createChunk(const int StartX, const int StartY, const int StartZ) {
	Ogre::ManualObject* MeshChunk = new Ogre::ManualObject("MeshManChunk" + Ogre::StringConverter::toString(m_ChunkID));
	MeshChunk->begin("BoxColor");

	int iVertex = 0;
	block_t Block;
	block_t Block1;

	for (int z = StartZ; z < CHUNK_SIZE + StartZ; ++z) {
		for (int y = StartY; y < CHUNK_SIZE + StartY; ++y) {
			for (int x = StartX; x < CHUNK_SIZE + StartX; ++x) {
				Block = GetBlock(x, y, z);
				if (Block == 0)
					continue;

				//x-1
				Block1 = 0;
				if (x > StartX)
					Block1 = GetBlock(x - 1, y, z);

				if (Block1 == 0) {
					MeshChunk->position(x, y, z + 1);
					MeshChunk->normal(-1, 0, 0);
					MeshChunk->textureCoord(0, 1);
					MeshChunk->position(x, y + 1, z + 1);
					MeshChunk->normal(-1, 0, 0);
					MeshChunk->textureCoord(1, 1);
					MeshChunk->position(x, y + 1, z);
					MeshChunk->normal(-1, 0, 0);
					MeshChunk->textureCoord(1, 0);
					MeshChunk->position(x, y, z);
					MeshChunk->normal(-1, 0, 0);
					MeshChunk->textureCoord(0, 0);

					MeshChunk->triangle(iVertex, iVertex + 1, iVertex + 2);
					MeshChunk->triangle(iVertex + 2, iVertex + 3, iVertex);

					iVertex += 4;
				}

				//x+1
				Block1 = 0;
				if (x < StartX + CHUNK_SIZE - 1)
					Block1 = GetBlock(x + 1, y, z);

				if (Block1 == 0) {
					MeshChunk->position(x + 1, y, z);
					MeshChunk->normal(1, 0, 0);
					MeshChunk->textureCoord(0, 1);
					MeshChunk->position(x + 1, y + 1, z);
					MeshChunk->normal(1, 0, 0);
					MeshChunk->textureCoord(1, 1);
					MeshChunk->position(x + 1, y + 1, z + 1);
					MeshChunk->normal(1, 0, 0);
					MeshChunk->textureCoord(1, 0);
					MeshChunk->position(x + 1, y, z + 1);
					MeshChunk->normal(1, 0, 0);
					MeshChunk->textureCoord(0, 0);

					MeshChunk->triangle(iVertex, iVertex + 1, iVertex + 2);
					MeshChunk->triangle(iVertex + 2, iVertex + 3, iVertex);

					iVertex += 4;
				}

				//y-1
				Block1 = 0;
				if (y > StartY)
					Block1 = GetBlock(x, y - 1, z);

				if (Block1 == 0) {
					MeshChunk->position(x, y, z);
					MeshChunk->normal(0, -1, 0);
					MeshChunk->textureCoord(0, 1);
					MeshChunk->position(x + 1, y, z);
					MeshChunk->normal(0, -1, 0);
					MeshChunk->textureCoord(1, 1);
					MeshChunk->position(x + 1, y, z + 1);
					MeshChunk->normal(0, -1, 0);
					MeshChunk->textureCoord(1, 0);
					MeshChunk->position(x, y, z + 1);
					MeshChunk->normal(0, -1, 0);
					MeshChunk->textureCoord(0, 0);

					MeshChunk->triangle(iVertex, iVertex + 1, iVertex + 2);
					MeshChunk->triangle(iVertex + 2, iVertex + 3, iVertex);

					iVertex += 4;
				}

				//y+1
				Block1 = 0;
				if (y < StartY + CHUNK_SIZE - 1)
					Block1 = GetBlock(x, y + 1, z);

				if (Block1 == 0) {
					MeshChunk->position(x, y + 1, z + 1);
					MeshChunk->normal(0, 1, 0);
					MeshChunk->textureCoord(0, 1);
					MeshChunk->position(x + 1, y + 1, z + 1);
					MeshChunk->normal(0, 1, 0);
					MeshChunk->textureCoord(1, 1);
					MeshChunk->position(x + 1, y + 1, z);
					MeshChunk->normal(0, 1, 0);
					MeshChunk->textureCoord(1, 0);
					MeshChunk->position(x, y + 1, z);
					MeshChunk->normal(0, 1, 0);
					MeshChunk->textureCoord(0, 0);

					MeshChunk->triangle(iVertex, iVertex + 1, iVertex + 2);
					MeshChunk->triangle(iVertex + 2, iVertex + 3, iVertex);

					iVertex += 4;
				}

				//z-1
				Block1 = 0;
				if (z > StartZ)
					Block1 = GetBlock(x, y, z - 1);

				if (Block1 == 0) {
					MeshChunk->position(x, y + 1, z);
					MeshChunk->normal(0, 0, -1);
					MeshChunk->textureCoord(0, 1);
					MeshChunk->position(x + 1, y + 1, z);
					MeshChunk->normal(0, 0, -1);
					MeshChunk->textureCoord(1, 1);
					MeshChunk->position(x + 1, y, z);
					MeshChunk->normal(0, 0, -1);
					MeshChunk->textureCoord(1, 0);
					MeshChunk->position(x, y, z);
					MeshChunk->normal(0, 0, -1);
					MeshChunk->textureCoord(0, 0);

					MeshChunk->triangle(iVertex, iVertex + 1, iVertex + 2);
					MeshChunk->triangle(iVertex + 2, iVertex + 3, iVertex);

					iVertex += 4;
				}

				//z+1
				Block1 = 0;
				if (z < StartZ + CHUNK_SIZE - 1)
					Block1 = GetBlock(x, y, z + 1);

				if (Block1 == 0) {
					MeshChunk->position(x, y, z + 1);
					MeshChunk->normal(0, 0, 1);
					MeshChunk->textureCoord(0, 1);
					MeshChunk->position(x + 1, y, z + 1);
					MeshChunk->normal(0, 0, 1);
					MeshChunk->textureCoord(1, 1);
					MeshChunk->position(x + 1, y + 1, z + 1);
					MeshChunk->normal(0, 0, 1);
					MeshChunk->textureCoord(1, 0);
					MeshChunk->position(x, y + 1, z + 1);
					MeshChunk->normal(0, 0, 1);
					MeshChunk->textureCoord(0, 0);

					MeshChunk->triangle(iVertex, iVertex + 1, iVertex + 2);
					MeshChunk->triangle(iVertex + 2, iVertex + 3, iVertex);

					iVertex += 4;
				}
			}
		}
	}

	MeshChunk->end();
	mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(MeshChunk);

	++m_ChunkID;
}

void TestBlockLandApplication::createSolidTexture(const Ogre::String& pName) {
	Ogre::MaterialPtr mat = Ogre::MaterialManager::getSingleton().create("BoxColor", "General", true);
	Ogre::Technique* tech = mat->getTechnique(0);
	Ogre::Pass* pass = tech->getPass(0);
	Ogre::TextureUnitState* tex = pass->createTextureUnitState();
	tex->setColourOperationEx(Ogre::LBX_MODULATE, Ogre::LBS_MANUAL, Ogre::LBS_CURRENT, Ogre::ColourValue(0, 0.5, 0));
}

void TestBlockLandApplication::createTexture(const Ogre::String& pName, const Ogre::String& pImageFilename) {
	Ogre::MaterialPtr mat = Ogre::MaterialManager::getSingleton().create("BoxColor", "General", true);
	Ogre::Technique* tech = mat->getTechnique(0);
	Ogre::Pass* pass = tech->getPass(0);
	Ogre::TextureUnitState* tex = pass->createTextureUnitState();

	tex->setTextureName(pImageFilename);
	tex->setNumMipmaps(4);
	tex->setTextureAnisotropy(1);
	tex->setTextureFiltering(Ogre::FO_POINT, Ogre::FO_POINT, Ogre::FO_POINT);
}

void TestBlockLandApplication::createWorldChunks() {
	Ogre::MaterialPtr mat = Ogre::MaterialManager::getSingleton().create("BoxColor", "General", true);
	Ogre::Technique* tech = mat->getTechnique(0);
	Ogre::Pass* pass = tech->getPass(0);
	Ogre::TextureUnitState* tex = pass->createTextureUnitState();
	tex->setColourOperationEx(Ogre::LBX_MODULATE, Ogre::LBS_MANUAL, Ogre::LBS_CURRENT, Ogre::ColourValue(0, 0.5, 0));

	for (int z = 0; z < WORLD_SIZE; z += CHUNK_SIZE) {
		for (int y = 0; y < WORLD_SIZE; y += CHUNK_SIZE) {
			for (int x = 0; x < WORLD_SIZE; x += CHUNK_SIZE) {
				createChunk(x, y, z);
			}
		}
	}
}

void TestBlockLandApplication::createScene() {
	mSceneMgr->setSkyDome(true, "Examples/CloudySky", 2, 8, 100);
	mSceneMgr->setFog(Ogre::FOG_LINEAR, Ogre::ColourValue(0.8, 0.8, 1), 0.05, 0.0, 200);

	mCamera->setFarClipDistance(256);
	mCamera->setNearClipDistance(0.01);

	mSceneMgr->setAmbientLight(Ogre::ColourValue(0.5, 0.5, 0.5));
	Ogre::Light* l = mSceneMgr->createLight("MainLight");
	l->setPosition(20, 80, 50);

	initWorldBlocksSphere();

	createWorldChunks();
}

void TestBlockLandApplication::initWorldBlocksSphere() {
	Ogre::Image heightMap;
	heightMap.load("heightmap.png", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
	const Ogre::PixelBox& pb = heightMap.getPixelBox();
	heightMap.scale(pb, Ogre::PixelBox(WORLD_SIZE, WORLD_SIZE, pb.getDepth(), Ogre::PF_BYTE_RGB));

	for (int z = 0; z < WORLD_SIZE; ++z) {
		for (int x = 0; x < WORLD_SIZE; ++x) {
			const Ogre::ColourValue& color = heightMap.getColourAt(x, z, 0);
			const int height = static_cast<int>((((color.r + color.g + color.b) / 1.5f) - 1.0f) * WORLD_SIZE / 4.0f + WORLD_SIZE / 2.0f);
			for (int y = 0; y < height; ++y) {
				GetBlock(x, y, z) = 1;
			}
		}
	}
}

#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#define WIN32_LEAN_AND_MEAN
#include "windows.h"
#endif

#ifdef __cplusplus
extern "C" {
#endif

#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
INT WINAPI WinMain(HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT)
#else
int main(int argc, char *argv[])
#endif
		{
	// Create application object
	TestBlockLandApplication app;

	try {
		app.go();
	} catch (Ogre::Exception& e) {
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
		MessageBox(NULL, e.getFullDescription().c_str(), "An exception has occurred!", MB_OK | MB_ICONERROR | MB_TASKMODAL);
#else
		std::cerr << "An exception has occurred: " << e.getFullDescription().c_str() << std::endl;
#endif
	}

	return 0;
}

#ifdef __cplusplus
}
#endif
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
**     the names of its contributors may be used to endorse or promote
**     products derived from this software without specific prior written
**     permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
** $QT_END_LICENSE$
**
****************************************************************************/

#include "phonebook.h"
#include "contactlistpage.h"
#include "contacteditor.h"
#include "filterpage.h"

#include <QtGui>

PhoneBook::PhoneBook(QWidget *parent)
        : QMainWindow(parent)
{
    QWidget *centralWidget = new QWidget(this);

    m_editorPage = new ContactEditor(centralWidget);
    connect(m_editorPage, SIGNAL(showListPage()), this, SLOT(activateList()));

    m_filterPage = new FilterPage(centralWidget);
    connect(m_filterPage, SIGNAL(showListPage(QContactFilter)), this, SLOT(activateList(QContactFilter)));

    m_listPage = new ContactListPage(this, centralWidget);
    connect(m_listPage, SIGNAL(showEditorPage(QContactLocalId)), this, SLOT(activateEditor(QContactLocalId)));
    connect(m_listPage, SIGNAL(showFilterPage(QContactFilter)), this, SLOT(activateFind()));
    connect(m_listPage, SIGNAL(managerChanged(QContactManager*)), this, SLOT(managerChanged(QContactManager*)));
    connect(m_listPage, SIGNAL(clearFilter()), m_filterPage, SLOT(clearFilter()));

    m_stackedWidget = new QStackedWidget(centralWidget);
    m_stackedWidget->addWidget(m_listPage);
    m_stackedWidget->addWidget(m_editorPage);
    m_stackedWidget->addWidget(m_filterPage);
    m_stackedWidget->setCurrentIndex(0);

    QVBoxLayout *centralLayout = new QVBoxLayout;
    centralLayout->addWidget(m_stackedWidget);
    centralWidget->setLayout(centralLayout);

    setCentralWidget(centralWidget);
}

PhoneBook::~PhoneBook()
{
}

void PhoneBook::activateEditor(QContactLocalId contactId)
{
    menuBar()->setVisible(false);
    m_editorPage->setCurrentContact(m_manager, contactId);
    m_stackedWidget->setCurrentIndex(1); // list = 0, editor = 1, find = 2.
}

void PhoneBook::activateList(const QContactFilter& filter)
{
#if !(defined(Q_OS_SYMBIAN) || defined(Q_WS_MAEMO_5))
    menuBar()->setVisible(true);
#endif
    m_currentFilter = filter;
    activateList(); // call base now.
}

void PhoneBook::activateList()
{
#if !(defined(Q_OS_SYMBIAN) || defined(Q_WS_MAEMO_5))
    menuBar()->setVisible(true);
#endif
    m_listPage->rebuildList(m_currentFilter);
    m_stackedWidget->setCurrentIndex(0); // list = 0, editor = 1, find = 2.
}

void PhoneBook::activateFind()
{
    menuBar()->setVisible(false);
    m_stackedWidget->setCurrentIndex(2); // list = 0, editor = 1, find = 2.
}

void PhoneBook::managerChanged(QContactManager *manager)
{
    m_manager = manager;
    m_editorPage->setCurrentContact(m_manager, 0); // must reset the manager of the editor.
}
<commit_msg>Try to avoid SwEvent caps.<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
**     the names of its contributors may be used to endorse or promote
**     products derived from this software without specific prior written
**     permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
** $QT_END_LICENSE$
**
****************************************************************************/

#include "phonebook.h"
#include "contactlistpage.h"
#include "contacteditor.h"
#include "filterpage.h"

#include <QtGui>

PhoneBook::PhoneBook(QWidget *parent)
        : QMainWindow(parent)
{
    QWidget *centralWidget = new QWidget(this);

    m_editorPage = new ContactEditor(centralWidget);
    connect(m_editorPage, SIGNAL(showListPage()), this, SLOT(activateList()));

    m_filterPage = new FilterPage(centralWidget);
    connect(m_filterPage, SIGNAL(showListPage(QContactFilter)), this, SLOT(activateList(QContactFilter)));

    m_listPage = new ContactListPage(this, centralWidget);
    connect(m_listPage, SIGNAL(showEditorPage(QContactLocalId)), this, SLOT(activateEditor(QContactLocalId)));
    connect(m_listPage, SIGNAL(showFilterPage(QContactFilter)), this, SLOT(activateFind()));
    connect(m_listPage, SIGNAL(managerChanged(QContactManager*)), this, SLOT(managerChanged(QContactManager*)));
    connect(m_listPage, SIGNAL(clearFilter()), m_filterPage, SLOT(clearFilter()));

    m_stackedWidget = new QStackedWidget(centralWidget);
    m_stackedWidget->addWidget(m_listPage);
    m_stackedWidget->addWidget(m_editorPage);
    m_stackedWidget->addWidget(m_filterPage);
    m_stackedWidget->setCurrentIndex(0);

    QVBoxLayout *centralLayout = new QVBoxLayout;
    centralLayout->addWidget(m_stackedWidget);
    centralWidget->setLayout(centralLayout);

    setCentralWidget(centralWidget);
}

PhoneBook::~PhoneBook()
{
}

void PhoneBook::activateEditor(QContactLocalId contactId)
{
#if !(defined(Q_OS_SYMBIAN) || defined(Q_WS_MAEMO_5))
    menuBar()->setVisible(false);
#endif
    m_editorPage->setCurrentContact(m_manager, contactId);
    m_stackedWidget->setCurrentIndex(1); // list = 0, editor = 1, find = 2.
}

void PhoneBook::activateList(const QContactFilter& filter)
{
#if !(defined(Q_OS_SYMBIAN) || defined(Q_WS_MAEMO_5))
    menuBar()->setVisible(true);
#endif
    m_currentFilter = filter;
    activateList(); // call base now.
}

void PhoneBook::activateList()
{
#if !(defined(Q_OS_SYMBIAN) || defined(Q_WS_MAEMO_5))
    menuBar()->setVisible(true);
#endif
    m_listPage->rebuildList(m_currentFilter);
    m_stackedWidget->setCurrentIndex(0); // list = 0, editor = 1, find = 2.
}

void PhoneBook::activateFind()
{
#if !(defined(Q_OS_SYMBIAN) || defined(Q_WS_MAEMO_5))
    menuBar()->setVisible(false);
#endif
    m_stackedWidget->setCurrentIndex(2); // list = 0, editor = 1, find = 2.
}

void PhoneBook::managerChanged(QContactManager *manager)
{
    m_manager = manager;
    m_editorPage->setCurrentContact(m_manager, 0); // must reset the manager of the editor.
}
<|endoftext|>


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

/*
 * XSEC
 *
 * XKMSRequestAbstractTypeImpl := Implementation class for XKMS Request messages
 *
 * $Id$
 *
 */

// XSEC Includes

#include <xsec/framework/XSECDefs.hpp>
#include <xsec/framework/XSECError.hpp>
#include <xsec/framework/XSECEnv.hpp>
#include <xsec/xkms/XKMSConstants.hpp>

#include <xercesc/dom/DOM.hpp>
#include <xercesc/dom/DOMNodeList.hpp>

#include "XKMSRequestAbstractTypeImpl.hpp"
#include "XKMSRespondWithImpl.hpp"
#include "XKMSResponseMechanismImpl.hpp"

XERCES_CPP_NAMESPACE_USE

// --------------------------------------------------------------------------------
//           Construct/Destruct
// --------------------------------------------------------------------------------

XKMSRequestAbstractTypeImpl::XKMSRequestAbstractTypeImpl(
	const XSECEnv * env) :
XKMSMessageAbstractTypeImpl(env)
{
	mp_originalRequestIdAttr = NULL;
	mp_responseLimitAttr = NULL;
}

XKMSRequestAbstractTypeImpl::XKMSRequestAbstractTypeImpl(
	const XSECEnv * env,
	DOMElement * node) :
XKMSMessageAbstractTypeImpl(env, node)
{
	mp_originalRequestIdAttr = NULL;
	mp_responseLimitAttr = NULL;
}

XKMSRequestAbstractTypeImpl::~XKMSRequestAbstractTypeImpl() {

	RespondWithVectorType::iterator i;

	for (i = m_respondWithList.begin(); i < m_respondWithList.end(); ++i) {
		delete (*i);
	}

	ResponseMechanismVectorType::iterator j;

	for (j = m_responseMechanismList.begin(); j < m_responseMechanismList.end(); ++j) {
		delete (*j);
	}
};

// --------------------------------------------------------------------------------
//           Load
// --------------------------------------------------------------------------------

void XKMSRequestAbstractTypeImpl::load(void) {

	if (mp_messageAbstractTypeElement == NULL) {

		// Attempt to load an empty element
		throw XSECException(XSECException::RequestAbstractTypeError,
			"XKMSRequestAbstractType::load - called on empty DOM");

	}

	// Get any respond with elements
	DOMNodeList * nl = mp_messageAbstractTypeElement->getElementsByTagNameNS(
		XKMSConstants::s_unicodeStrURIXKMS,
		XKMSConstants::s_tagRespondWith);

	if (nl != NULL) {

		XKMSRespondWithImpl * rw;
		for (int i = 0; i < nl->getLength() ; ++ i) {

			XSECnew(rw, XKMSRespondWithImpl(mp_env, (DOMElement *) nl->item(i)));
			rw->load();
			m_respondWithList.push_back(rw);

		}

	}

	// Get any ResponseMechanism elements
	nl = mp_messageAbstractTypeElement->getElementsByTagNameNS(
		XKMSConstants::s_unicodeStrURIXKMS,
		XKMSConstants::s_tagResponseMechanism);

	if (nl != NULL) {

		XKMSResponseMechanismImpl * rm;
		for (int i = 0; i < nl->getLength() ; ++ i) {

			XSECnew(rm, XKMSResponseMechanismImpl(mp_env, (DOMElement *) nl->item(i)));
			rm->load();
			m_responseMechanismList.push_back(rm);

		}

	}

	mp_originalRequestIdAttr =
		mp_messageAbstractTypeElement->getAttributeNodeNS(NULL, XKMSConstants::s_tagOriginalRequestId);

	mp_responseLimitAttr =
		mp_messageAbstractTypeElement->getAttributeNodeNS(NULL, XKMSConstants::s_tagResponseLimit);

	XKMSMessageAbstractTypeImpl::load();

}

// --------------------------------------------------------------------------------
//           Create from scratch
// --------------------------------------------------------------------------------

DOMElement * XKMSRequestAbstractTypeImpl::createBlankRequestAbstractType(
		const XMLCh * tag,
		const XMLCh * service,
		const XMLCh * id) {

	return XKMSMessageAbstractTypeImpl::createBlankMessageAbstractType(tag, service, id);

}

// --------------------------------------------------------------------------------
//           Get/Set interface methods
// --------------------------------------------------------------------------------

const XMLCh * XKMSRequestAbstractTypeImpl::getOriginalRequestId(void) const {

	if (mp_originalRequestIdAttr != NULL)
		return mp_originalRequestIdAttr->getNodeValue();

	return NULL;
}

void XKMSRequestAbstractTypeImpl::setOriginalRequestId(const XMLCh * id) {

	if (mp_messageAbstractTypeElement == NULL) {

		// Attempt update when not initialised
		throw XSECException(XSECException::MessageAbstractTypeError,
			"XKMSRequestAbstractType::setOriginalRequestId - called on non-initialised structure");

	}

	mp_messageAbstractTypeElement->setAttributeNS(NULL, XKMSConstants::s_tagOriginalRequestId, id);
	mp_originalRequestIdAttr =
		mp_messageAbstractTypeElement->getAttributeNodeNS(NULL, XKMSConstants::s_tagOriginalRequestId);

}

unsigned int XKMSRequestAbstractTypeImpl::getResponseLimit(void) const {

	if (mp_responseLimitAttr == NULL)
		return 0;

	unsigned int ret;

	if (!XMLString::textToBin(mp_responseLimitAttr->getValue(), ret))
		return 0;

	return ret;
}

void XKMSRequestAbstractTypeImpl::setResponseLimit(unsigned int limit) {

	if (mp_messageAbstractTypeElement == NULL) {

		// Attempt update when not initialised
		throw XSECException(XSECException::MessageAbstractTypeError,
			"XKMSRequestAbstractType::setResponseLimit - called on non-initialised structure");

	}

	/* Convert the number to a string */
	XMLCh limitStr[10];
	XMLString::binToText(limit, limitStr, 9, 10);

	mp_messageAbstractTypeElement->setAttributeNS(NULL, XKMSConstants::s_tagResponseLimit, limitStr);
	mp_responseLimitAttr =
		mp_messageAbstractTypeElement->getAttributeNodeNS(NULL, XKMSConstants::s_tagResponseLimit);

}

// --------------------------------------------------------------------------------
//           RespondWith handling
// --------------------------------------------------------------------------------

int XKMSRequestAbstractTypeImpl::getRespondWithSize(void) {

	return m_respondWithList.size();

}

XKMSRespondWith * XKMSRequestAbstractTypeImpl::getRespondWithItem(int item) {

	if (item < 0 || item >= m_respondWithList.size()) {

		throw XSECException(XSECException::RequestAbstractTypeError,
			"XKMSRequestAbstractTypeImpl::getRespondWithItem - item out of range");

	}

	return m_respondWithList[item];

}

const XMLCh * XKMSRequestAbstractTypeImpl::getRespondWithItemStr(int item) {

	if (item < 0 || item >= m_respondWithList.size()) {

		throw XSECException(XSECException::RequestAbstractTypeError,
			"XKMSRequestAbstractTypeImpl::getRespondWithItem - item out of range");

	}

	return m_respondWithList[item]->getRespondWithString();

}

void XKMSRequestAbstractTypeImpl::appendRespondWithItem(XKMSRespondWith * item) {

}

void XKMSRequestAbstractTypeImpl::appendRespondWithItem(const XMLCh * item) {

	XKMSRespondWithImpl * rw;
	XSECnew(rw, XKMSRespondWithImpl(mp_env));

	// Create the RespondWith object
	DOMElement * elt = rw->createBlankRespondWith(item);

	// Add to the item
	DOMElement * c = findFirstElementChild(mp_messageAbstractTypeElement);
	while (c != NULL) {

		if (!strEquals(getXKMSLocalName(c), XKMSConstants::s_tagResponseMechanism))
			break;

	}

	if (c != NULL) {
		mp_messageAbstractTypeElement->insertBefore(elt, c);
		if (mp_env->getPrettyPrintFlag()) {
			mp_messageAbstractTypeElement->insertBefore(
				mp_env->getParentDocument()->createTextNode(DSIGConstants::s_unicodeStrNL), c);
		}
	}
	else {
		mp_messageAbstractTypeElement->appendChild(elt);
		mp_env->doPrettyPrint(mp_messageAbstractTypeElement);
	}

	// Add to the list
	m_respondWithList.push_back(rw);

}

// --------------------------------------------------------------------------------
//           ResponseMechanism handling
// --------------------------------------------------------------------------------

int XKMSRequestAbstractTypeImpl::getResponseMechanismSize(void) {

	return m_responseMechanismList.size();

}

XKMSResponseMechanism * XKMSRequestAbstractTypeImpl::getResponseMechanismItem(int item) {

	if (item < 0 || item >= m_responseMechanismList.size()) {

		throw XSECException(XSECException::RequestAbstractTypeError,
			"XKMSRequestAbstractTypeImpl::getResponseMechanismItem - item out of range");

	}

	return m_responseMechanismList[item];

}

const XMLCh * XKMSRequestAbstractTypeImpl::getResponseMechanismItemStr(int item) {

	if (item < 0 || item >= m_responseMechanismList.size()) {

		throw XSECException(XSECException::RequestAbstractTypeError,
			"XKMSRequestAbstractTypeImpl::getResponseMechanismItem - item out of range");

	}

	return m_responseMechanismList[item]->getResponseMechanismString();

}

void XKMSRequestAbstractTypeImpl::appendResponseMechanismItem(XKMSResponseMechanism * item) {

}

void XKMSRequestAbstractTypeImpl::appendResponseMechanismItem(const XMLCh * item) {

	XKMSResponseMechanismImpl * rw;
	XSECnew(rw, XKMSResponseMechanismImpl(mp_env));

	// Create the ResponseMechanism object
	DOMElement * elt = rw->createBlankResponseMechanism(item);

	// Add to the item
	DOMElement * c = findFirstElementChild(mp_messageAbstractTypeElement);
	while (c != NULL) {

		if (!strEquals(getXKMSLocalName(c), XKMSConstants::s_tagResponseMechanism))
			break;

	}

	if (c != NULL) {
		mp_messageAbstractTypeElement->insertBefore(elt, c);
		if (mp_env->getPrettyPrintFlag()) {
			mp_messageAbstractTypeElement->insertBefore(
				mp_env->getParentDocument()->createTextNode(DSIGConstants::s_unicodeStrNL), c);
		}
	}
	else {
		mp_messageAbstractTypeElement->appendChild(elt);
		mp_env->doPrettyPrint(mp_messageAbstractTypeElement);
	}

	// Add to the list
	m_responseMechanismList.push_back(rw);

}

void XKMSRequestAbstractTypeImpl::removeResponseMechanismItem(int item) {

	if (item < 0 || item >= m_responseMechanismList.size()) {

		throw XSECException(XSECException::RequestAbstractTypeError,
			"XKMSRequestAbstractTypeImpl::getResponseMechanismItem - item out of range");

	}

	XKMSResponseMechanism *rm = m_responseMechanismList[item];
	DOMNode * m = rm->getElement();
	m->getParentNode()->removeChild(m);
	m->release();

	// Now clean up our structure.
	ResponseMechanismVectorType::iterator i;
	int j = 0;
	i = m_responseMechanismList.begin();
	while (j < item) {
		j++;
		i++;
	}
	m_responseMechanismList.erase(i);

}

<commit_msg>Properly handle multiple Pending/Represent elements<commit_after>/*
 * Copyright 2004 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * imitations under the License.
 */

/*
 * XSEC
 *
 * XKMSRequestAbstractTypeImpl := Implementation class for XKMS Request messages
 *
 * $Id$
 *
 */

// XSEC Includes

#include <xsec/framework/XSECDefs.hpp>
#include <xsec/framework/XSECError.hpp>
#include <xsec/framework/XSECEnv.hpp>
#include <xsec/xkms/XKMSConstants.hpp>

#include <xercesc/dom/DOM.hpp>
#include <xercesc/dom/DOMNodeList.hpp>

#include "XKMSRequestAbstractTypeImpl.hpp"
#include "XKMSRespondWithImpl.hpp"
#include "XKMSResponseMechanismImpl.hpp"

XERCES_CPP_NAMESPACE_USE

// --------------------------------------------------------------------------------
//           Construct/Destruct
// --------------------------------------------------------------------------------

XKMSRequestAbstractTypeImpl::XKMSRequestAbstractTypeImpl(
	const XSECEnv * env) :
XKMSMessageAbstractTypeImpl(env)
{
	mp_originalRequestIdAttr = NULL;
	mp_responseLimitAttr = NULL;
}

XKMSRequestAbstractTypeImpl::XKMSRequestAbstractTypeImpl(
	const XSECEnv * env,
	DOMElement * node) :
XKMSMessageAbstractTypeImpl(env, node)
{
	mp_originalRequestIdAttr = NULL;
	mp_responseLimitAttr = NULL;
}

XKMSRequestAbstractTypeImpl::~XKMSRequestAbstractTypeImpl() {

	RespondWithVectorType::iterator i;

	for (i = m_respondWithList.begin(); i < m_respondWithList.end(); ++i) {
		delete (*i);
	}

	ResponseMechanismVectorType::iterator j;

	for (j = m_responseMechanismList.begin(); j < m_responseMechanismList.end(); ++j) {
		delete (*j);
	}
};

// --------------------------------------------------------------------------------
//           Load
// --------------------------------------------------------------------------------

void XKMSRequestAbstractTypeImpl::load(void) {

	if (mp_messageAbstractTypeElement == NULL) {

		// Attempt to load an empty element
		throw XSECException(XSECException::RequestAbstractTypeError,
			"XKMSRequestAbstractType::load - called on empty DOM");

	}

	// Get any respond with elements
	DOMNodeList * nl = mp_messageAbstractTypeElement->getElementsByTagNameNS(
		XKMSConstants::s_unicodeStrURIXKMS,
		XKMSConstants::s_tagRespondWith);

	if (nl != NULL) {

		XKMSRespondWithImpl * rw;
		for (int i = 0; i < nl->getLength() ; ++ i) {

			XSECnew(rw, XKMSRespondWithImpl(mp_env, (DOMElement *) nl->item(i)));
			rw->load();
			m_respondWithList.push_back(rw);

		}

	}

	// Get any ResponseMechanism elements
	nl = mp_messageAbstractTypeElement->getElementsByTagNameNS(
		XKMSConstants::s_unicodeStrURIXKMS,
		XKMSConstants::s_tagResponseMechanism);

	if (nl != NULL) {

		XKMSResponseMechanismImpl * rm;
		for (int i = 0; i < nl->getLength() ; ++ i) {

			XSECnew(rm, XKMSResponseMechanismImpl(mp_env, (DOMElement *) nl->item(i)));
			rm->load();
			m_responseMechanismList.push_back(rm);

		}

	}

	mp_originalRequestIdAttr =
		mp_messageAbstractTypeElement->getAttributeNodeNS(NULL, XKMSConstants::s_tagOriginalRequestId);

	mp_responseLimitAttr =
		mp_messageAbstractTypeElement->getAttributeNodeNS(NULL, XKMSConstants::s_tagResponseLimit);

	XKMSMessageAbstractTypeImpl::load();

}

// --------------------------------------------------------------------------------
//           Create from scratch
// --------------------------------------------------------------------------------

DOMElement * XKMSRequestAbstractTypeImpl::createBlankRequestAbstractType(
		const XMLCh * tag,
		const XMLCh * service,
		const XMLCh * id) {

	return XKMSMessageAbstractTypeImpl::createBlankMessageAbstractType(tag, service, id);

}

// --------------------------------------------------------------------------------
//           Get/Set interface methods
// --------------------------------------------------------------------------------

const XMLCh * XKMSRequestAbstractTypeImpl::getOriginalRequestId(void) const {

	if (mp_originalRequestIdAttr != NULL)
		return mp_originalRequestIdAttr->getNodeValue();

	return NULL;
}

void XKMSRequestAbstractTypeImpl::setOriginalRequestId(const XMLCh * id) {

	if (mp_messageAbstractTypeElement == NULL) {

		// Attempt update when not initialised
		throw XSECException(XSECException::MessageAbstractTypeError,
			"XKMSRequestAbstractType::setOriginalRequestId - called on non-initialised structure");

	}

	mp_messageAbstractTypeElement->setAttributeNS(NULL, XKMSConstants::s_tagOriginalRequestId, id);
	mp_originalRequestIdAttr =
		mp_messageAbstractTypeElement->getAttributeNodeNS(NULL, XKMSConstants::s_tagOriginalRequestId);

}

unsigned int XKMSRequestAbstractTypeImpl::getResponseLimit(void) const {

	if (mp_responseLimitAttr == NULL)
		return 0;

	unsigned int ret;

	if (!XMLString::textToBin(mp_responseLimitAttr->getValue(), ret))
		return 0;

	return ret;
}

void XKMSRequestAbstractTypeImpl::setResponseLimit(unsigned int limit) {

	if (mp_messageAbstractTypeElement == NULL) {

		// Attempt update when not initialised
		throw XSECException(XSECException::MessageAbstractTypeError,
			"XKMSRequestAbstractType::setResponseLimit - called on non-initialised structure");

	}

	/* Convert the number to a string */
	XMLCh limitStr[10];
	XMLString::binToText(limit, limitStr, 9, 10);

	mp_messageAbstractTypeElement->setAttributeNS(NULL, XKMSConstants::s_tagResponseLimit, limitStr);
	mp_responseLimitAttr =
		mp_messageAbstractTypeElement->getAttributeNodeNS(NULL, XKMSConstants::s_tagResponseLimit);

}

// --------------------------------------------------------------------------------
//           RespondWith handling
// --------------------------------------------------------------------------------

int XKMSRequestAbstractTypeImpl::getRespondWithSize(void) {

	return m_respondWithList.size();

}

XKMSRespondWith * XKMSRequestAbstractTypeImpl::getRespondWithItem(int item) {

	if (item < 0 || item >= m_respondWithList.size()) {

		throw XSECException(XSECException::RequestAbstractTypeError,
			"XKMSRequestAbstractTypeImpl::getRespondWithItem - item out of range");

	}

	return m_respondWithList[item];

}

const XMLCh * XKMSRequestAbstractTypeImpl::getRespondWithItemStr(int item) {

	if (item < 0 || item >= m_respondWithList.size()) {

		throw XSECException(XSECException::RequestAbstractTypeError,
			"XKMSRequestAbstractTypeImpl::getRespondWithItem - item out of range");

	}

	return m_respondWithList[item]->getRespondWithString();

}

void XKMSRequestAbstractTypeImpl::appendRespondWithItem(XKMSRespondWith * item) {

}

void XKMSRequestAbstractTypeImpl::appendRespondWithItem(const XMLCh * item) {

	XKMSRespondWithImpl * rw;
	XSECnew(rw, XKMSRespondWithImpl(mp_env));

	// Create the RespondWith object
	DOMElement * elt = rw->createBlankRespondWith(item);

	// Add to the item
	DOMElement * c = findFirstElementChild(mp_messageAbstractTypeElement);
	while (c != NULL) {

		if (!strEquals(getXKMSLocalName(c), XKMSConstants::s_tagResponseMechanism))
			break;

	}

	if (c != NULL) {
		mp_messageAbstractTypeElement->insertBefore(elt, c);
		if (mp_env->getPrettyPrintFlag()) {
			mp_messageAbstractTypeElement->insertBefore(
				mp_env->getParentDocument()->createTextNode(DSIGConstants::s_unicodeStrNL), c);
		}
	}
	else {
		mp_messageAbstractTypeElement->appendChild(elt);
		mp_env->doPrettyPrint(mp_messageAbstractTypeElement);
	}

	// Add to the list
	m_respondWithList.push_back(rw);

}

// --------------------------------------------------------------------------------
//           ResponseMechanism handling
// --------------------------------------------------------------------------------

int XKMSRequestAbstractTypeImpl::getResponseMechanismSize(void) {

	return m_responseMechanismList.size();

}

XKMSResponseMechanism * XKMSRequestAbstractTypeImpl::getResponseMechanismItem(int item) {

	if (item < 0 || item >= m_responseMechanismList.size()) {

		throw XSECException(XSECException::RequestAbstractTypeError,
			"XKMSRequestAbstractTypeImpl::getResponseMechanismItem - item out of range");

	}

	return m_responseMechanismList[item];

}

const XMLCh * XKMSRequestAbstractTypeImpl::getResponseMechanismItemStr(int item) {

	if (item < 0 || item >= m_responseMechanismList.size()) {

		throw XSECException(XSECException::RequestAbstractTypeError,
			"XKMSRequestAbstractTypeImpl::getResponseMechanismItem - item out of range");

	}

	return m_responseMechanismList[item]->getResponseMechanismString();

}

void XKMSRequestAbstractTypeImpl::appendResponseMechanismItem(XKMSResponseMechanism * item) {

}

void XKMSRequestAbstractTypeImpl::appendResponseMechanismItem(const XMLCh * item) {

	XKMSResponseMechanismImpl * rw;
	XSECnew(rw, XKMSResponseMechanismImpl(mp_env));

	// Create the ResponseMechanism object
	DOMElement * elt = rw->createBlankResponseMechanism(item);

	// Add to the item
	DOMElement * c = findFirstElementChild(mp_messageAbstractTypeElement);
	while (c != NULL) {

		if (!strEquals(getXKMSLocalName(c), XKMSConstants::s_tagResponseMechanism))
			break;

		c = findNextElementChild(c);

	}

	if (c != NULL) {
		mp_messageAbstractTypeElement->insertBefore(elt, c);
		if (mp_env->getPrettyPrintFlag()) {
			mp_messageAbstractTypeElement->insertBefore(
				mp_env->getParentDocument()->createTextNode(DSIGConstants::s_unicodeStrNL), c);
		}
	}
	else {
		mp_messageAbstractTypeElement->appendChild(elt);
		mp_env->doPrettyPrint(mp_messageAbstractTypeElement);
	}

	// Add to the list
	m_responseMechanismList.push_back(rw);

}

void XKMSRequestAbstractTypeImpl::removeResponseMechanismItem(int item) {

	if (item < 0 || item >= m_responseMechanismList.size()) {

		throw XSECException(XSECException::RequestAbstractTypeError,
			"XKMSRequestAbstractTypeImpl::getResponseMechanismItem - item out of range");

	}

	XKMSResponseMechanism *rm = m_responseMechanismList[item];
	DOMNode * m = rm->getElement();
	m->getParentNode()->removeChild(m);
	m->release();

	// Now clean up our structure.
	ResponseMechanismVectorType::iterator i;
	int j = 0;
	i = m_responseMechanismList.begin();
	while (j < item) {
		j++;
		i++;
	}
	m_responseMechanismList.erase(i);

}

<|endoftext|>