Ejemplo n.º 1
0
/**
 * Focus the next widget either downwards or upwards.
 *
 * \param reverse True means navigating up, false means down.
 */
void EventHandler::navigate(const int playerID, Input::InputType type, const bool pressedDown, const bool reverse)
{
    IGUIElement *el = NULL, *closest = NULL;

    if (type == Input::IT_STICKBUTTON && !pressedDown)
        return;

    Widget* w = GUIEngine::getFocusForPlayer(playerID);
    if (w != NULL)
    {
        el = w->getIrrlichtElement();
    }

    // list widgets are a bit special, because up/down keys are also used
    // to navigate between various list items, not only to navigate between
    // components
    if (w != NULL && w->m_type == WTYPE_LIST)
    {
        ListWidget* list = (ListWidget*) w;

        const bool stay_within_list = reverse ? list->getSelectionID() > 0 :
            list->getSelectionID() < list->getItemCount() - 1;

        if (stay_within_list)
        {
            if (reverse)
                list->setSelectionID(list->getSelectionID() - 1);
            else
                list->setSelectionID(list->getSelectionID() + 1);
            return;
        }
        else
        {
            list->setSelectionID(-1);
        }
    }

    if (w != NULL && ((reverse && w->m_tab_up_root != -1) || (!reverse && w->m_tab_down_root != -1)))
    {
        Widget* next = GUIEngine::getWidget(reverse ? w->m_tab_up_root : w->m_tab_down_root);
        assert(next != NULL);
        el = next->getIrrlichtElement();

        if (el == NULL)
        {
            std::cerr << "WARNING : m_tab_down/up_root is set to an ID for which I can't find the widget\n";
            return;
        }
    }

    // don't allow navigating to any widget when a dialog is shown; only navigate to widgets in the dialog
    if (ModalDialog::isADialogActive() && !ModalDialog::getCurrent()->isMyIrrChild(el))
    {
        el = NULL;
    }

    bool found = false;

    // find closest widget
    if (el != NULL && el->getTabGroup() != NULL)
    {
        // Up: if the current widget is e.g. 15, search for widget 14, 13, 12, ... (up to 10 IDs may be missing)
        // Down: if the current widget is e.g. 5, search for widget 6, 7, 8, 9, ..., 15 (up to 10 IDs may be missing)
        for (int n = 1; n < 10 && !found; n++)
        {
            closest = GUIEngine::getGUIEnv()->getRootGUIElement()->getElementFromId(el->getTabOrder() + (reverse ? -n : n), true);

            if (closest != NULL && Widget::isFocusableId(closest->getID()))
            {
                Widget* closestWidget = GUIEngine::getWidget( closest->getID() );

                if (playerID != PLAYER_ID_GAME_MASTER && !closestWidget->m_supports_multiplayer) return;

                // if a dialog is shown, restrict to items in the dialog
                if (ModalDialog::isADialogActive() && !ModalDialog::getCurrent()->isMyChild(closestWidget))
                    continue;

                if (NAVIGATION_DEBUG)
                {
                    std::cout << "Navigating " << (reverse ? "up" : "down") << " to " << closest->getID() << std::endl;
                }

                assert(closestWidget != NULL);

                if (!closestWidget->isVisible() || !closestWidget->isActivated())
                    continue;

                closestWidget->setFocusForPlayer(playerID);

                // another list exception : when entering a list by going down, select the first item
                // when focusing a list by going up, select the last item of the list
                if (closestWidget->m_type == WTYPE_LIST)
                {
                    ListWidget* list = (ListWidget*) closestWidget;
                    assert(list != NULL);
                    list->setSelectionID(reverse ? list->getItemCount() - 1 : 0);
                }
                found = true;
            }
        } // end for
    }

    if (!found)
    {
        if (NAVIGATION_DEBUG)
            std::cout << "EventHandler::navigat : wrap around\n";

        // select the last/first widget
        Widget* wrapWidget = NULL;

        if (ModalDialog::isADialogActive())
        {
            wrapWidget = reverse ? ModalDialog::getCurrent()->getLastWidget() :
                ModalDialog::getCurrent()->getFirstWidget();
        }
        else
        {
            Screen* screen = GUIEngine::getCurrentScreen();
            if (screen == NULL) return;
            wrapWidget = reverse ? screen->getLastWidget() :
                screen->getFirstWidget();
        }

        if (wrapWidget != NULL)  wrapWidget->setFocusForPlayer(playerID);
    }
}
Ejemplo n.º 2
0
int main(){
    Screen* screen = new Screen;

    screen->createWindow(DUNGEON);
    screen->createWindow(LOG);

    int cx = screen->dungeon()->_maxx/2;
    int cy = screen->dungeon()->_maxy/2;
    int c;

    while(((c=getch()))!=27){
        switch(c){
        case(KEY_UP):
            if(cy-1 > 0) {
                cy--;
                screen->print("Moved up");
            }
            break;
        case(KEY_DOWN):
            if(cy+1 < (screen->height() - 1)) {
                cy++;
                screen->print("Moved down");
            }
            break;
        case(KEY_LEFT):
            if(cx-1 > 0) {
                cx--;
                screen->print("Moved left");
            }
            break;
        case(KEY_RIGHT):
            if(cx+1 < (screen->width()/2 - 1)) {
                cx++;
                screen->print("Moved right");
            }
            break;
        }
        screen->drawWorld(cy, cx);
    }
    return 0;
}
Ejemplo n.º 3
0
HelloPolycodeApp::HelloPolycodeApp(PolycodeView *view) : EventHandler() {

    core = new POLYCODE_CORE(view, 640,480,false,false,0,0,90);

    CoreServices::getInstance()->getResourceManager()->addArchive("Resources/default.pak");
    CoreServices::getInstance()->getResourceManager()->addDirResource("default", false);

    Screen *hud = new Screen();

    onGroundLabel = new ScreenLabel("Arrow keys to control, spacebar to brake, press R to reset car", 16);
    hud->addChild(onGroundLabel);

    scene = new PhysicsScene();

    ScenePrimitive *ground = new ScenePrimitive(ScenePrimitive::TYPE_PLANE, 30, 30);
    ground->loadTexture("Resources/green_texture.png");
    scene->addPhysicsChild(ground, PhysicsSceneEntity::SHAPE_PLANE, 0.0);

    // Some obstacles
    ScenePrimitive *box = new ScenePrimitive(ScenePrimitive::TYPE_BOX, 4,4,6);
    box->setPitch(25.0);
    box->setPosition(7,-1.05, 0.0);
    box->setColor(0.5,0.5,1.0,1.0);
    box->loadTexture("Resources/green_texture.png");
    scene->addPhysicsChild(box, PhysicsSceneEntity::SHAPE_BOX, 0.0);

    box = new ScenePrimitive(ScenePrimitive::TYPE_BOX, 4,4,6);
    box->setPitch(25.0);
    box->setPosition(-7,-1.05, 0.0);
    box->setColor(0.5,0.5,1.0,1.0);
    box->loadTexture("Resources/green_texture.png");
    scene->addPhysicsChild(box, PhysicsSceneEntity::SHAPE_BOX, 0.0);

    box = new ScenePrimitive(ScenePrimitive::TYPE_BOX, 20,2,5);
    box->setPosition(0.0,1.0, -4.3);
    box->setColor(0.5,0.5,1.0,1.0);
    box->loadTexture("Resources/green_texture.png");
    scene->addPhysicsChild(box, PhysicsSceneEntity::SHAPE_BOX, 0.0);

    for(int i=0; i < 10; i++) {
        ScenePrimitive *box = new ScenePrimitive(ScenePrimitive::TYPE_BOX, 0.7,0.7,0.7);
        box->loadTexture("Resources/pink_texture.png");
        box->Roll(-45 + (rand() % 90));
        box->Pitch(-45 + (rand() % 90));
        box->setPosition(-3 + (rand() % 6), 2 + i*0.5, -5 + (rand() % 3));
        scene->addPhysicsChild(box, PhysicsSceneEntity::SHAPE_BOX, 1.0);
    }

    // The vehicle
    vehicle = new ScenePrimitive(ScenePrimitive::TYPE_BOX, 1.0,0.5,2.0);
    vehicle->loadTexture("Resources/pink_texture.png");
    vehicle->setColor(1.0, 1.0, 0.0, 1.0);
    vehicle->setPosition(6,1,5);
    vehicleController = scene->addVehicleChild(vehicle, 5.0, 1.0);

    ScenePrimitive *wheel = new ScenePrimitive(ScenePrimitive::TYPE_SPHERE, 0.3, 10, 10);
    wheel->loadTexture("Resources/pink_texture.png");
    wheel->setColor(0.0, 1.0, 0.0, 1.0);
    vehicleController->addWheel(wheel, Vector3(0.6,0,-0.5), Vector3(0,-1,0), Vector3(-1,0,0), 0.2,  0.3, true);
    scene->addEntity(wheel);

    wheel = new ScenePrimitive(ScenePrimitive::TYPE_SPHERE, 0.3, 10, 10);
    wheel->loadTexture("Resources/pink_texture.png");
    wheel->setColor(0.0, 1.0, 0.0, 1.0);
    vehicleController->addWheel(wheel, Vector3(-0.6,0,-0.5), Vector3(0,-1,0), Vector3(-1,0,0), 0.2,  0.3, true);
    scene->addEntity(wheel);

    wheel = new ScenePrimitive(ScenePrimitive::TYPE_SPHERE, 0.3, 10, 10);
    wheel->loadTexture("Resources/pink_texture.png");
    wheel->setColor(0.0, 1.0, 0.0, 1.0);
    vehicleController->addWheel(wheel, Vector3(0.6,0,0.5), Vector3(0,-1,0), Vector3(-1,0,0), 0.2,  0.3, false);
    scene->addEntity(wheel);

    wheel = new ScenePrimitive(ScenePrimitive::TYPE_SPHERE, 0.3, 10, 10);
    wheel->loadTexture("Resources/pink_texture.png");
    wheel->setColor(0.0, 1.0, 0.0, 1.0);
    vehicleController->addWheel(wheel, Vector3(-0.6,0,0.5), Vector3(0,-1,0), Vector3(-1,0,0), 0.2,  0.3, false);
    scene->addEntity(wheel);

    steeringValue = 0;
    engineForce = 0;
    breaking = false;

    testBox = new ScenePrimitive(ScenePrimitive::TYPE_BOX, 4, 4, 4);
    testBox->loadTexture("Resources/pink_texture.png");
    testBox->setColor(0.3,0.5, 1.0,0.4);
    testBox->setPosition(-5,2,7);
    scene->addCollisionChild(testBox, PhysicsSceneEntity::SHAPE_BOX);


    scene->getDefaultCamera()->setPosition(16,16,16);
    scene->getDefaultCamera()->lookAt(Vector3(0,0,0));

    core->getInput()->addEventListener(this, InputEvent::EVENT_KEYDOWN);
    core->getInput()->addEventListener(this, InputEvent::EVENT_KEYUP);
}
Ejemplo n.º 4
0
  Test ()
  {
      //создание сцены

    sprite [0] = Sprite::Create ();
    
    sprite [0]->SetMaterial ("sprite_material");
    sprite [0]->SetScale (10.0f, 10.0f, 1.0f);
    sprite [0]->SetPosition (-3.0f, -3.0f, 0.5f);
    sprite [0]->Rotate (math::anglef (), math::anglef (), math::degree (22.5f));
    sprite [0]->SetColor (1.0f, 1.0f, 0.0f);
    sprite [0]->SetMode (SpriteMode_Oriented);
    
    sprite [0]->BindToScene (scene);
    
    sprite [1] = Sprite::Create ();
    
    sprite [1]->SetMaterial ("sprite_material");
    sprite [1]->SetScale (10.0f, 10.0f, 1.0f);
    sprite [1]->SetPosition (3.0f, 3.0f, 0.1f);
    sprite [1]->SetColor (1.0f, 0.0f, 1.0f);
    sprite [1]->SetMode (SpriteMode_Oriented);
    
    sprite [1]->BindToScene (scene);
    
    sprite [2] = Sprite::Create ();    

    sprite [2]->SetMaterial ("sprite_material");
    sprite [2]->SetScale (10.0f, 10.0f, 1.0f);
    sprite [2]->SetPosition (3.0f, -1.5f, 0.75f);
    sprite [2]->SetColor (0.0f, 1.0f, 1.0f);
    sprite [2]->SetMode (SpriteMode_Oriented);
    
    sprite [2]->BindToScene (scene);        

    input_zone [0] = InputZone::Create ();

    input_zone [0]->SetName      ("zone1");
    input_zone [0]->BindToParent (*sprite [0]);
    
    input_zone [0]->RegisterNotificationHandler (&Test::InputNotify);
    
    input_zone [1] = InputZone::Create ();
    
    input_zone [1]->SetName      ("zone2");
    input_zone [1]->BindToParent (*sprite [1]);
    
    input_zone [1]->RegisterNotificationHandler (&Test::InputNotify);    
    
    input_zone [2] = InputZone::Create ();
    
    input_zone [2]->SetName      ("zone3");
    input_zone [2]->BindToParent (*sprite [2]);
    
    input_zone [2]->RegisterNotificationHandler (&Test::InputNotify);

    camera = PerspectiveCamera::Create ();

    camera->BindToScene (scene);
    camera->SetName     ("Camera1");
    camera->SetPosition (0, 0, -18.f);
    camera->SetFovX     (math::degree (70.f));
    camera->SetFovY     (math::degree (70.f));
    camera->SetZNear    (0.1f);
    camera->SetZFar     (20.f);
    
      //создание областей вывода

    Viewport vp1;

    vp1.SetName            ("Viewport1");
    vp1.SetZOrder          (0);
    vp1.SetTechnique       ("default");
    vp1.SetCamera          (camera.get ());

    screen.Attach (vp1);

      //настройка ввода
    
    application.InputManager ().SetScreen (&screen);
//    application.InputManager ().SetTouchSize (1.0f);

      //настройка целевых буферов вывода

    RenderTarget& render_target = application.RenderTarget ();

    render_target.SetScreen (&screen);

      //загрузка ресурсов

    application.LoadResources ();
  }
Ejemplo n.º 5
0
void Screen::displayNotImplemented()
{
    screen.displayStrings(PSTR("Function not"), PSTR("implemented yet"));
}
void initProjectionScreen(double _focalDist)
{   screen.setWidthHeight(SCREEN_WIDE_SIZE, SCREEN_WIDE_SIZE*SCREEN_HEIGHT/SCREEN_WIDTH);
    screen.setOffset(alignmentX,alignmentY);
    screen.setFocalDistance(_focalDist);
    cam.init(screen);
}
Ejemplo n.º 7
0
static void plot(int x, int y, int colour, void *data) {
	Screen *screen = (Screen *)data;
	screen->plotPoint(x, y, (uint8) colour);
}
Ejemplo n.º 8
0
/**
*  @brief
*    Constructor
*/
Gui::Gui(const String &sGui) :
	m_pGuiImpl(nullptr),
	m_bShutdown(false),
	m_pTheme(nullptr),
	m_nHoverTime(2000),
	m_cFontManager(*this),
	m_cCursorManager(*this),
	m_cClipBoard(*this),
	m_bActive(true),
	m_nNextWidgetID(1),
	m_pDefaultScreen(nullptr),
	m_bMouseVisible(true),
	m_pRootWidget(nullptr),
	m_pMouseOverWidget(nullptr),
	m_pMouseOverWidgetNew(nullptr),
	m_pHoverTimer(nullptr),
	m_pFocusWidget(nullptr),
	m_pFocusWidgetNew(nullptr),
	m_pTooltip(nullptr),
	EventHandlerOnHoverTimer(&Gui::OnHoverTimer, this)
{
	// Check name of GUI backend
	if (sGui.GetLength()) {
		// Find GUI class
		const Class *pClass = ClassManager::GetInstance()->GetClass(sGui);
		if (pClass && pClass->IsDerivedFrom("PLGui::GuiImpl")) {
			// Create the specified GUI implementation
			m_pGuiImpl = static_cast<GuiImpl*>(pClass->Create(Params<Object*, Gui*>(this)));
		}
	} else {
		// Create system GUI
		#if defined(WIN32)
			m_pGuiImpl = new GuiWindows(this);
		#elif defined(ANDROID)
			m_pGuiImpl = new GuiAndroid(this);
		#elif defined(LINUX)
			m_pGuiImpl = new GuiLinux(this);
		#else
			// Unknown system
			#error "Unsupported platform"
		#endif
	}

	// Get list of screens
	m_pGuiImpl->EnumerateScreens(m_lstScreens);
	for (uint32 i=0; i<m_lstScreens.GetNumOfElements(); i++) {
		// Save default screen
		Screen *pScreen = m_lstScreens[i];
		if (pScreen->IsDefault()) {
			m_pDefaultScreen = pScreen;
		}
	}

	// Create dummy root widget
	m_pRootWidget = new Widget(this);

	// Initialize ClipBoard
	m_cClipBoard.InitClipBoard();

	// Create theme
	m_pTheme = new ThemeDesktop(*this);
}
Ejemplo n.º 9
0
Screen::Screen(const Vector2i &size, const std::string &caption,
               bool resizable, bool fullscreen)
    : Widget(nullptr), mGLFWWindow(nullptr), mNVGContext(nullptr),
      mCursor(Cursor::Arrow), mCaption(caption) {
    memset(mCursors, 0, sizeof(GLFWcursor *) * (int) Cursor::CursorCount);

    /* Request a forward compatible OpenGL 3.3 core profile context */
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    /* Request a RGBA8 buffer without MSAA */
    glfwWindowHint(GLFW_SAMPLES, 0);
    glfwWindowHint(GLFW_RED_BITS, 8);
    glfwWindowHint(GLFW_GREEN_BITS, 8);
    glfwWindowHint(GLFW_BLUE_BITS, 8);
    glfwWindowHint(GLFW_ALPHA_BITS, 8);
    glfwWindowHint(GLFW_STENCIL_BITS, 8);
    glfwWindowHint(GLFW_DEPTH_BITS, 24);
    glfwWindowHint(GLFW_VISIBLE, GL_FALSE);
    glfwWindowHint(GLFW_RESIZABLE, resizable ? GL_TRUE : GL_FALSE);

    if (fullscreen) {
        GLFWmonitor *monitor = glfwGetPrimaryMonitor();
        const GLFWvidmode *mode = glfwGetVideoMode(monitor);
        mGLFWWindow = glfwCreateWindow(mode->width, mode->height,
                                       caption.c_str(), monitor, nullptr);
    } else {
        mGLFWWindow = glfwCreateWindow(size.x(), size.y(), caption.c_str(),
                                       nullptr, nullptr);
    }

    if (!mGLFWWindow)
        throw std::runtime_error("Could not create an OpenGL 3.3 context!");

    glfwMakeContextCurrent(mGLFWWindow);

#if defined(_WIN32)
    if (!glewInitialized) {
        glewExperimental = GL_TRUE;
        glewInitialized = true;
        if (glewInit() != GLEW_NO_ERROR)
            throw std::runtime_error("Could not initialize GLEW!");
        glGetError(); // pull and ignore unhandled errors like GL_INVALID_ENUM
    }
#endif

    glfwGetFramebufferSize(mGLFWWindow, &mFBSize[0], &mFBSize[1]);
    glViewport(0, 0, mFBSize[0], mFBSize[1]);
    glClearColor(mBackground[0], mBackground[1], mBackground[2], 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
    glfwSwapInterval(0);
    glfwSwapBuffers(mGLFWWindow);

#if defined(__APPLE__)
    /* Poll for events once before starting a potentially
       lengthy loading process. This is needed to be
       classified as "interactive" by other software such
       as iTerm2 */

    glfwPollEvents();
#endif

    /* Propagate GLFW events to the appropriate Screen instance */
    glfwSetCursorPosCallback(mGLFWWindow,
        [](GLFWwindow *w,double x,double y) {
            auto it = __nanogui_screens.find(w);
            if (it == __nanogui_screens.end())
                return;
            Screen *s = it->second;
            if (!s->mProcessEvents)
                return;
            s->cursorPosCallbackEvent(x, y);
        }
    );

    glfwSetMouseButtonCallback(mGLFWWindow,
        [](GLFWwindow *w, int button, int action, int modifiers) {
            auto it = __nanogui_screens.find(w);
            if (it == __nanogui_screens.end())
                return;
            Screen *s = it->second;
            if (!s->mProcessEvents)
                return;
            s->mouseButtonCallbackEvent(button, action, modifiers);
        }
    );

    glfwSetKeyCallback(mGLFWWindow,
        [](GLFWwindow *w, int key, int scancode, int action, int mods) {
            auto it = __nanogui_screens.find(w);
            if (it == __nanogui_screens.end())
                return;
            Screen *s = it->second;
            if (!s->mProcessEvents)
                return;
            s->keyCallbackEvent(key, scancode, action, mods);
        }
    );

    glfwSetCharCallback(mGLFWWindow,
        [](GLFWwindow *w, unsigned int codepoint) {
            auto it = __nanogui_screens.find(w);
            if (it == __nanogui_screens.end())
                return;
            Screen *s = it->second;
            if (!s->mProcessEvents)
                return;
            s->charCallbackEvent(codepoint);
        }
    );

    glfwSetDropCallback(mGLFWWindow,
        [](GLFWwindow *w,int count,const char **filenames) {
            auto it = __nanogui_screens.find(w);
            if (it == __nanogui_screens.end())
                return;
            Screen *s = it->second;
            if (!s->mProcessEvents)
                return;
            s->dropCallbackEvent(count, filenames);
        }
    );

    glfwSetScrollCallback(mGLFWWindow, 
        [](GLFWwindow *w, double x, double y) {
            auto it = __nanogui_screens.find(w);
            if (it == __nanogui_screens.end())
                return;
            Screen *s = it->second;
            if (!s->mProcessEvents)
                return;
            s->scrollCallbackEvent(x, y);
        }
    );

    initialize(mGLFWWindow);
}
Ejemplo n.º 10
0
Archivo: Menu.cpp Proyecto: 3dik/MPong
//RunEditProfile
bool Menu::RunEditProfile (wstring sName, bool *pbModified)
{
    Err fErr (m_Err, L"RunEditProfile");
    if (sName.empty () || pbModified == NULL)
    {
        return fErr.Set (sERR_ARGUMENTS);
    }

    *pbModified = false;

    Config *pProfile;
    bool bCreated;
    if (!m_pProfiles->GetByName (sName, &pProfile, &bCreated))
    {
        return false;
    }

    wstring sMenuEdit, sLeft, sRight, sSpecial, sSet, sOk, sUndefined;
    if (!m_pLanguage->Get (L"ProfileEditTitle", &sMenuEdit) ||
        !m_pLanguage->Get (L"ProfileEditLeft", &sLeft) ||
        !m_pLanguage->Get (L"ProfileEditRight", &sRight) ||
        !m_pLanguage->Get (L"ProfileEditSpecial", &sSpecial) ||
        !m_pLanguage->Get (L"ProfileEditSet", &sSet) ||
        !m_pLanguage->Get (L"ProfileEditOk", &sOk) ||
        !m_pLanguage->Get (L"ProfileEditUndefined", &sUndefined))
    {
        return false;
    }
    sLeft += L": ";
    sRight += L": ";
    sSpecial += L": ";

    wstring sLeftVal, sRightVal, sSpecialVal;
    if (!pProfile->Get (sKEY_LEFT, &sLeftVal) ||
        !pProfile->Get (sKEY_RIGHT, &sRightVal) ||
        !pProfile->Get (sKEY_SPECIAL, &sSpecialVal))
    {
        return false;
    }

    unsigned int nAction;
    do
    {
        if (sLeftVal.empty ())
        {
            sLeftVal = sUndefined;
        }
        if (sRightVal.empty ())
        {
            sRightVal = sUndefined;
        }
        if (sSpecialVal.empty ())
        {
            sSpecialVal = sUndefined;
        }
        Screen EditScreen;
        if (!EditScreen.Init (&m_Err, m_pProfiles, m_pWindow, sMenuEdit + sName) ||
            !EditScreen.AddLabel (sLeft + sLeftVal, Vector2f (300, 150)) ||
            !EditScreen.AddButton (sSet, Vector2f (50, 140),
                                   eProfileEditButtonLeft) ||
            !EditScreen.AddLabel (sRight + sRightVal, Vector2f (300, 250)) ||
            !EditScreen.AddButton (sSet, Vector2f (50, 240),
                                   eProfileEditButtonRight) ||
            !EditScreen.AddLabel (sSpecial + sSpecialVal,
                                  Vector2f (300, 350)) ||
            !EditScreen.AddButton (sSet, Vector2f (50, 340),
                                   eProfileEditButtonSpecial) ||
            !EditScreen.AddButton (m_sAbort, Vector2f (700, 540),
                                   eProfileEditButtonAbort) ||
            !EditScreen.AddButton (sOk, Vector2f (700, 600),
                                   eProfileEditButtonOk))
        {
            return false;
        }
        if (!EditScreen.Run ())
        {
            return false;
        }
        if (EditScreen.IsQuit ())
        {
            m_bClose = true;
            break;
        }
        if (!EditScreen.GetSelectId (&nAction))
        {
            return false;
        }

        wstring *psCurKey = NULL;
        switch (nAction)
        {
            case (eProfileEditButtonLeft):
                psCurKey = &sLeftVal;
                break;
            case (eProfileEditButtonRight):
                psCurKey = &sRightVal;
                break;
            case (eProfileEditButtonSpecial):
                psCurKey = &sSpecialVal;
                break;
            case (eProfileEditButtonOk):
                pProfile->Set (sKEY_LEFT, sLeftVal);
                pProfile->Set (sKEY_RIGHT, sRightVal);
                pProfile->Set (sKEY_SPECIAL, sSpecialVal);
                if (!pProfile->Save ())
                {
                    return false;
                }
                *pbModified = true;
                nAction = eProfileEditButtonAbort;
                break;
        }

        if (psCurKey != NULL)
        {
            wstring sCode;
            if (!AwaitInput (&sCode))
            {
                return false;
            }
            if (!sCode.empty ())
            {
                *psCurKey = sCode;
            }
        }
    } while (!m_bClose && nAction != eProfileEditButtonAbort);

    return true;
}//RunEditProfile
Ejemplo n.º 11
0
	static void SetScreen(const Screen &screen)
	{
		SetDrawScreen(screen.getHandle());
	}
Ejemplo n.º 12
0
Archivo: Menu.cpp Proyecto: 3dik/MPong
//ManageProfileScreens
bool Menu::ManageProfileScreens ()
{
    Err fErr (m_Err, L"ManageProfileScreens");

    Screen Overview;
    if (!InitProfilesScreen (&Overview))
    {
        return false;
    }

    unsigned int nAction;
    do
    {
        if (!Overview.Run ())
        {
            return false;
        }
        if (Overview.IsQuit ())
        {
            m_bClose = true;
            break;
        }
        if (!Overview.GetSelectId (&nAction))
        {
            return false;
        }

        wstring sName;
        if (!Overview.Get (eProfilesListChoice, &sName))
        {
            return false;
        }

        switch (nAction)
        {
            case (eProfilesButtonEdit):
                {
                    bool bModified;
                    if (!RunEditProfile (sName, &bModified))
                    {
                        return false;
                    }
                    if (bModified && !m_pProfiles->Reload ())
                    {
                        return false;
                    }
                }
                break;
            case (eProfilesButtonCreate):
                {
                    wstring sName;
                    if (!Overview.Get (eProfilesEditCreateName, &sName))
                    {
                        return false;
                    }
                    if (sName.empty ())
                    {
                        fErr.Set (L"The given profile name is empty");
                    }
                    if (!AddProfile (sName) ||
                        !InitProfilesScreen (&Overview))
                    {
                        return false;
                    }
                }
                break;
            case (eProfilesButtonDelete):
                if (!m_pProfiles->DeleteProfile (sName) ||
                    !InitProfilesScreen (&Overview))
                {
                    return false;
                }
                break;
        }

        if (!Overview.Reset ())
        {
            return false;
        }
    } while (!m_bClose && nAction != eProfilesButtonAbort);

    return true;
}//ManageProfileScreens
Ejemplo n.º 13
0
void update(int value)
{
    // Conta i cicli di presentazione dello stimolo
    if ( (sumOutside > str2num<int>(parameters.find("StimulusCycles")) ) &&  (trialMode == STIMULUSMODE) )
    {
        sumOutside=0;
        trialMode++;
        trialMode=trialMode%4;
    }

    if (conditionInside && (sumOutside*2 > str2num<int>(parameters.find("FixationCycles"))) && (trialMode ==FIXATIONMODE )  )
    {
        sumOutside=0;
        trialMode++;
        trialMode=trialMode%4;
        stimulusDuration.start();
    }
    if ( trialMode == STIMULUSMODE )
        stimulusFrames++;
    if ( trialMode == FIXATIONMODE )
        stimulusFrames=0;

    Screen screenPassive;

    screenPassive.setWidthHeight(SCREEN_WIDE_SIZE, SCREEN_WIDE_SIZE*SCREEN_HEIGHT/SCREEN_WIDTH);
    screenPassive.setOffset(alignmentX,alignmentY);
    screenPassive.setFocalDistance(0);
    screenPassive.transform(headEyeCoords.getRigidStart().getFullTransformation()*Translation3d(center));

    camPassive.init(screenPassive);
    camPassive.setDrySimulation(true);
    camPassive.setEye(eyeRight);
    objectPassiveTransformation = ( camPassive.getModelViewMatrix()*objectActiveTransformation );
    // Coordinates picker
    markers = optotrak.getAllPoints();
    if ( isVisible(markers[1]) && isVisible(markers[2]) && isVisible(markers[3]) )
        headEyeCoords.update(markers[1],markers[2],markers[3]);
    Affine3d active = headEyeCoords.getRigidStart().getFullTransformation();

    eulerAngles.init( headEyeCoords.getRigidStart().getFullTransformation().rotation() );

    eyeLeft = headEyeCoords.getLeftEye();
    eyeRight = headEyeCoords.getRightEye();

    cyclopeanEye = (eyeLeft+eyeRight)/2.0;

    // Projection of view normal on the focal plane
    Vector3d directionOfSight = (active.rotation()*Vector3d(0,0,-1)).normalized();
    Eigen::ParametrizedLine<double,3> lineOfSightRight = Eigen::ParametrizedLine<double,3>::Through( eyeRight , eyeRight+directionOfSight );
    Eigen::ParametrizedLine<double,3> lineOfSightLeft  = Eigen::ParametrizedLine<double,3>::Through( eyeLeft, eyeLeft+directionOfSight );

    double lineOfSightRightDistanceToFocalPlane = lineOfSightRight.intersection(focalPlane);
    double lineOfSightLeftDistanceToFocalPlane = lineOfSightLeft.intersection(focalPlane);

    //double lenghtOnZ = (active*(center-eyeCalibration )+eyeRight).z();
    projPointEyeRight = lineOfSightRightDistanceToFocalPlane *(directionOfSight)+ (eyeRight);
    projPointEyeLeft= lineOfSightLeftDistanceToFocalPlane * (directionOfSight) + (eyeLeft);
    // second projection the fixation point computed with z non constant but perfectly parallel to projPointEyeRight
    lineOfSightRightDistanceToFocalPlane= (( active.rotation()*(center)) - eyeRight).norm();
    Vector3d secondProjection = lineOfSightRightDistanceToFocalPlane *(directionOfSight)+ (eyeRight);

    if ( !zOnFocalPlane )
        projPointEyeRight=secondProjection ;

    // Compute the translation to move the eye in order to avoid shear components
    Vector3d posAlongLineOfSight = (headEyeCoords.getRigidStart().getFullTransformation().rotation())*(eyeRight -eyeCalibration);

    switch ( (int)factors["Translation"] )
    {
    case -1:
    case -2:
        translationFactor.setZero();
        if ( trialMode == STIMULUSMODE )
            projPointEyeRight=center;
        break;
    case 0:
        translationFactor.setZero();
        break;
    case 1:
        translationFactor = factors["TranslationConstant"]*Vector3d(posAlongLineOfSight.z(),0,0);
        break;
    case 2:
        translationFactor = factors["TranslationConstant"]*Vector3d(0,posAlongLineOfSight.z(),0);
        break;
    }
    if ( passiveMode )
        initProjectionScreen(0,headEyeCoords.getRigidStart().getFullTransformation()*Translation3d(Vector3d(0,0,focalDistance)));
    else
        initProjectionScreen(focalDistance,Affine3d::Identity());

    checkBounds();
    /**** Save to file part ****/
    // Markers file save the used markers and time-depending experimental variable to a file
    // (Make sure that in passive experiment the list of variables has the same order)
    markersFile << trialNumber << " " << headCalibrationDone << " " << trialMode << " " ;
    markersFile <<markers[1].transpose() << " " << markers[2].transpose() << " " << markers[3].transpose() << " " << markers[17].transpose() << " " << markers[18].transpose() << " " ;

    markersFile <<	factors["Tilt"] << " " <<
                factors["Slant"] << " " <<
                factors["Translation"] << " " <<
                factors["Onset"] << " " <<
                factors["TranslationConstant"] <<
                endl;

    ofstream outputfile;
    outputfile.open("data.dat");
    outputfile << "Subject Name: " << parameters.find("SubjectName") << endl;
    outputfile << "Passive matrix:" << endl << objectPassiveTransformation.matrix() << endl;
    outputfile << "Yaw: " << toDegrees(eulerAngles.getYaw()) << endl <<"Pitch: " << toDegrees(eulerAngles.getPitch()) << endl;
    outputfile << "EyeLeft: " <<  headEyeCoords.getLeftEye().transpose() << endl;
    outputfile << "EyeRight: " << headEyeCoords.getRightEye().transpose() << endl << endl;
    outputfile << "Slant: " << instantPlaneSlant << endl;
    outputfile << "(Width,Height) [px]: " << getPlaneDimensions().transpose() << " " << endl;
    outputfile << "Factors:" << endl;
    for (map<string,double>::iterator iter=factors.begin(); iter!=factors.end(); ++iter)
    {
        outputfile << "\t\t" << iter->first << "= " << iter->second << endl;
    }
    outputfile << "Trial remaining: " << trial.getRemainingTrials()+1 << endl;
    outputfile << "Last response: " << probeAngle << endl;
    // Here we save plane projected width and height


    // now rewind the file
    outputfile.clear();
    outputfile.seekp(0,ios::beg);

    // Write down frame by frame the trajectories and angles of eyes and head
    if ( trialMode == STIMULUSMODE && headCalibrationDone > 2 )
    {
        trajFile << setw(6) << left <<
                 trialNumber << " " <<
                 stimulusFrames << " " <<
                 eyeRight.transpose() << endl;

        anglesFile << setw(6) << left <<
                   trialNumber << " " <<
                   stimulusFrames << " " <<
                   toDegrees(eulerAngles.getPitch()) << " " <<
                   toDegrees(eulerAngles.getRoll()) << " " <<
                   toDegrees(eulerAngles.getYaw()) << " " <<
                   instantPlaneSlant << endl;

        matrixFile << setw(6) << left <<
                   trialNumber << " " <<
                   stimulusFrames << " " ;
        for (int i=0; i<3; i++)
            matrixFile << objectPassiveTransformation.matrix().row(i) << " " ;
        matrixFile << endl;

        // Write the 13 special extremal points on stimFile
        stimFile << setw(6) << left <<
                 trialNumber << " " <<
                 stimulusFrames << " " ;
        double winx=0,winy=0,winz=0;

        for (PointsRandIterator iRand = redDotsPlane.specialPointsRand.begin(); iRand!=redDotsPlane.specialPointsRand.end(); ++iRand)
        {   Point3D *p=(*iRand);
            Vector3d v = objectActiveTransformation*Vector3d( p->x, p->y, p->z);

            gluProject(v.x(),v.y(),v.z(), (&cam)->getModelViewMatrix().data(), (&cam)->getProjectiveMatrix().data(), (&cam)->getViewport().data(), &winx,&winy,&winz);
            stimFile << winx << " " << winy << " " << winz << " ";
        }
        stimFile << endl;
    }

    glutPostRedisplay();
    glutTimerFunc(TIMER_MS, update, 0);
}
Ejemplo n.º 14
0
void handleInput(std::string const& _line, cliHandler& _clihandler, Screen& _nscr, bool const _neverAskFlag)
{
   switch (_clihandler.handleInput(_line))
      {
      case cliHandler::INPUT_OK:
         {
            // Check if the remote command produced a response.
            if (_clihandler.outputAvailable())
               {
                  _nscr.setOutput("Response: " + _clihandler.getOutput());
               }
            else if (_clihandler.errorAvailable())
               {
                  _nscr.setOutput("Response: " + _clihandler.getError());

                  if ((global_btg_run == GR_QUIT) || (global_btg_run == GR_FATAL))
                     {
                        sleep(3);
                     }
               }

            break;
         }
      case cliHandler::INPUT_IGNORE:
         {
            // There is nothing to output, as nothing was sent to the
            // daemon.
            break;
         }
      case cliHandler::INPUT_LOCAL:
         {
            if (_clihandler.outputAvailable())
               {
                  _nscr.setOutput("Response: " + _clihandler.getOutput());
                  if (global_btg_run == GR_QUIT)
                     {
                        sleep(1);
                     }
               }
            break;
         }
      case cliHandler::INPUT_SURE_QUERY:
         {
            if (!_neverAskFlag)
               {
                  // Ask the user if he is sure.
                  if (_nscr.isUserSure())
                     {
                        // The user is sure, use handle a saved command.
                        // This is used for handling quit and kill at this
                        // point.
                        _clihandler.handleInput(_line, true /* Handle saved command. */);
                     }
               }
            else
               {
                  // Not asking questions.
                  _clihandler.handleInput(_line, true);
               }
            break;
         }
      case cliHandler::INPUT_ERROR:
         {
            // The entered text was not a command.
            if (_clihandler.errorAvailable())
               {
                  _nscr.setOutput("Error: " + _clihandler.getError());
               }
            break;
         }
      case cliHandler::INPUT_NOT_A_COMMAND:
         {
            // No error was specified, so write a default error.
            _nscr.setOutput("Error: '" + _line + "', wrong syntax or command.");
            break;
         }
      case cliHandler::UNDEFINED_RESPONSE:
         {
            _nscr.setOutput("Undefined message. Something is really wrong.");
            break;
         }
      }
}
Ejemplo n.º 15
0
static v8::Handle<v8::Value> availWidthAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info)
{
    INC_STATS("DOM.Screen.availWidth._get");
    Screen* imp = V8Screen::toNative(info.Holder());
    return v8::Integer::NewFromUnsigned(imp->availWidth());
}
Ejemplo n.º 16
0
int main() {

	Screen screen;
	
	long long previousTime = (long long)Util::getCurrentTimeInMiliseconds();
	long long accumulateTime = 0;
	Keyboard::startListening();
	
	Point f_pos(50,20);
	Color  f_col(255,255,255,255);
	Pixel f_plane(f_pos, f_col);
	propeller.setDrawPosition(145,30);
	
	bird.setPosition(50,20);
	fish.setPosition(50,20);

	roda1.setRadius(10);
	roda1.setCenter(Point(40,50));

	roda2.setRadius(10);
	roda2.setCenter(Point(120,50));
	parasut.setPosition(50,10);
	//plane.setPosition(200,10);
	//plane.fillColor(f_plane);
	//plane.fillPattern(&bird);
	
	ship.setPosition(10,250);
	
	
	
	f_pos.x = 50; f_pos.y = 20;
	Pixel f_ship(f_pos, f_col);
	//ship.fillColor(f_ship);
	
	f_pos.x = ship.getWidth() / 2;
	f_pos.y = ship.getHeight() / 2;
	
	
	ship.fillWithFloodFill(f_pos,&fish);
	

	int ii = 0;

	float speed = 0;
	float initialPercentage = 0;
	
	/* Game Clock */
	while (true) {
		if (accumulateTime>(SECONDS_PER_FRAME)) {
			handleInput();
			
			printf("%c[%d;%df",0x1B,199,99);
			screen.beginBatch();
			
			
			if (isPlane){
			  //planeEx += 0.05f;
			  //meledak.setPosition(meledak.getPosition().x - 2,meledak.getPosition().y - 2);

			
	
			    initialPercentage += 0.07;
			plane.explode(initialPercentage);
				speed += 0.1f;

			propeller.applyGravity((int)speed);

			applyGravity(&parasut,(int)speed);
			screen.draw(&parasut);

			if (!isPlaneGrounded){
				isPlaneGrounded = roda1.applyGravity((int)speed);
				roda2.applyGravity((int)speed);
			}else{
				propeller.setState(0);
				isBanSelesai = !roda1.bounce();
				roda2.bounce();
			}

			usleep(FRAMERATE/4);
			  //screen.draw(&meledak, planeEx);
			  
			  if (isBanSelesai){

			      //screen.beginBatch();
			      //screen.endBatch();

			  	  isPlane = false;
			      //isAftermath = true;

				//gotoxy(1, 10);
			      //printf("\t\tSHIP WIN!\n\n\n\n\n\n\n\n\n\n");
			      isFinish = true;

				  /* TODO:
			         - Animasi pesawat pecah
			         - Kasih Gravity tiap pecahan pesawat biar jatuh:
			           - baling-baling
			           - ban
			           - potongan badan pesawat
			           - pilot keluar dari pesawat pake parasut
			         - Bikin ban mantul-mantul di atas tanah -_-
			      */

			      // gotoxy(10, 10);
			      // printf("SHIP WIN!\n\n\n\n\n\n\n\n\n\n");

			      // exit(0);

			  }
			}

			screen.draw(&plane, isFlipPlane);
			screen.draw(&roda1);
			screen.draw(&roda2);
			

			propeller.draw(&screen);

			if (isShip){
			  shipEx += 0.05f;
			  
			  meledak.setPosition(meledak.getPosition().x - 2,meledak.getPosition().y - 2);
			  screen.draw(&meledak, shipEx);
			  
			  if (shipEx > 2){
			      screen.beginBatch();
			      screen.endBatch();
			      //gotoxy(10, 10);
			      //printf("PLANE WIN!\n\n\n\n\n\n\n\n\n\n");
			      isFinish = true;
			      isShip = false;
			  }
			}else if (!isPlane) screen.draw(&ship, isFlipShip);
			
			// handle peluru
			for (int i = 0; i < 100; i++){
				if (b[i] != NULL){
					Point st = b[i]->getPoint();
					bool arah = b[i]->arah;
					b[i] = bf.create(BulletFactory::LASER);
					
					if (arah == true){ //pesawat yang nembak, pelurunya kebawah
						b[i]->arah = true;
						b[i]->rotate(180);
						b[i]->setPoint(Point(st.x, st.y + 1));
						
						if (st.y > 330) b[i] = NULL;
						
						if (st.x > ship.getPosition().x  - 10 && st.x < ship.getPosition().x + 150 && st.y > 220){	// COLLISION
						    meledak.setPosition(ship.getPosition().x,ship.getPosition().y);
						    isShip = true;
						    b[i] = NULL;
						}
						
					}else{
						b[i]->arah = false;
						b[i]->setPoint(Point(st.x, st.y - 1));
						
						if (st.y < 0) b[i] = NULL;
						
						if (st.x > plane.getPosition().x - 5 && st.x < plane.getPosition().x + 180 && st.y < 40){	// COLLISION
						    meledak.setPosition(plane.getPosition().x,plane.getPosition().y);
						    isPlane = true;
						    b[i] = NULL;

							Point explosionCenter(plane.getWidth()/2,plane.getHeight()/2);

							//Ini harus dipanggil sebelum meledak
							plane.startExplode(explosionCenter);
						}
					}
					if (b[i] != NULL) screen.draw(b[i]);
				}
			}

			if (isAftermath) {
				
			//	speed += 1; // speed untuk gravity pull
			//	isPlaneGrounded = plane.applyGravity(speed); /* Kasih efek gravity, return valuenya bakal 1 kalo object nya udah sampe "tanah" */				
			//	screen.draw(&plane, isFlipPlane); /* Ini buat gambar objek2 yang udah mulai jatoh ke tanah */
			//	usleep(FRAMERATE); // ini buat ngedelay kecepetan refresh frame biar gak terlalu cepet
				initialPercentage += 0.01;
				plane.explode(initialPercentage);

				if(initialPercentage == 1) { // periksa kalo semua objek udah sampe tanah, berarti game nya pindah ke state finish
					isAftermath = false;
					isFinish = true;

					screen.beginBatch();
					screen.draw(&plane, isFlipPlane); // ini buat gambar object2 yang udah berserakan di tanah
					screen.endBatch();

					//gotoxy(10,10);
				//	printf("Ship Wins!\n\n\n\n\n");
				//	gotoxy(40,40);
				//	printf("\n");
				}
			}

			if (isFinish) {
				exit(0);
			}

			screen.endBatch();
			
			while (accumulateTime<(SECONDS_PER_FRAME))
				accumulateTime -= (SECONDS_PER_FRAME);
				
		}
		else {
			long long currentTime = (long long)Util::getCurrentTimeInMiliseconds();
			accumulateTime += (currentTime - previousTime);
			previousTime = currentTime;
		}
	}

	return 0;	
}
Ejemplo n.º 17
0
manual_thrusters_test_app::manual_thrusters_test_app(PolycodeView *view):
	thruster_sys(thruster_cfg),
	EventHandler()
{
	core = new POLYCODE_CORE(view, SCREEN_WIDTH, SCREEN_HEIGHT, false, false, 0, 0, 90);

	CoreServices::getInstance()->getResourceManager()->addArchive("Resources/default.pak");
	CoreServices::getInstance()->getResourceManager()->addDirResource("default", false);

	Screen *screen = new Screen();			

	ship_base = new ScreenShape(ScreenShape::SHAPE_RECT, SHIP_BASE_SIZE, SHIP_BASE_SIZE);
	ship_base->setColor(0.0,0.0,0.0,1.0);
	ship_base->colorAffectsChildren = false;
	ship_base->setPosition(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2);
	ship_base->setRotation(0);	// degrees
	screen->addChild(ship_base);

/*	ship_front = new ScreenShape(ScreenShape::SHAPE_CIRCLE, SHIP_BASE_SIZE, SHIP_BASE_SIZE, 3);
	ship_front->setColor(0.0,0.0,0.0,1.0);
	double temp = SHIP_BASE_SIZE - sqrt((1.7320508 * 0.5 * SHIP_BASE_SIZE * 1.7320508 * 0.5 * SHIP_BASE_SIZE) -
		(0.5 * 1.7320508 * 0.5 * SHIP_BASE_SIZE * 0.5 * 1.7320508 * 0.5 * SHIP_BASE_SIZE));
	ship_front->setPosition(0, -(SHIP_BASE_SIZE - temp));
	ship_front->setRotation(-90);	// degrees
	ship_base->addChild(ship_front);
*/
	thruster_cfg = thruster_presets::square_minimal();
	thruster_sys.sync_to_cfg();

	int const num_thrusters = thruster_cfg.thrusters.size();
	thruster_shapes.resize(num_thrusters);

	// TODO: For now rotations are hard coded
	thruster_shapes[0] = new ScreenShape(ScreenShape::SHAPE_CIRCLE, THRUSTER_SIZE, THRUSTER_SIZE, 3);
	thruster_shapes[0]->setRotation(0);

	thruster_shapes[1] = new ScreenShape(ScreenShape::SHAPE_CIRCLE, THRUSTER_SIZE, THRUSTER_SIZE, 3);
	thruster_shapes[1]->setRotation(180);

	thruster_shapes[2] = new ScreenShape(ScreenShape::SHAPE_CIRCLE, THRUSTER_SIZE, THRUSTER_SIZE, 3);
	thruster_shapes[2]->setRotation(180);

	thruster_shapes[3] = new ScreenShape(ScreenShape::SHAPE_CIRCLE, THRUSTER_SIZE, THRUSTER_SIZE, 3);
	thruster_shapes[3]->setRotation(0);


	for(int t = 0; t < num_thrusters; ++t)
	{
		thruster_shapes[t]->setPosition(Vector3(
			thruster_cfg[t].pos[0] * SHIP_BASE_SIZE / 2,
			thruster_cfg[t].pos[1] * SHIP_BASE_SIZE / 2,
			thruster_cfg[t].pos[2] * SHIP_BASE_SIZE / 2));
		ship_base->addChild(thruster_shapes[t]);
	}

//	thrust = 0;
	linearSpeed = Vector3(0, 0, 0);
	
//	torque = 0;
	rotationSpeed = 0;
	
	core->getInput()->addEventListener(this, InputEvent::EVENT_KEYDOWN);
	core->getInput()->addEventListener(this, InputEvent::EVENT_KEYUP);	
}
Ejemplo n.º 18
0
boost::optional<IdfObject> ForwardTranslator::translateScreen( Screen & modelObject )
{
  IdfObject idfObject( openstudio::IddObjectType::WindowMaterial_Screen);

  m_idfObjects.push_back(idfObject);

  idfObject.setString(WindowMaterial_ScreenFields::Name, modelObject.name().get());
  
  OptionalString s = modelObject.getString(OS_WindowMaterial_ScreenFields::ReflectedBeamTransmittanceAccountingMethod, false, true);
  if (s){
    idfObject.setString(WindowMaterial_ScreenFields::ReflectedBeamTransmittanceAccountingMethod, *s);
  }

  OptionalDouble d = modelObject.getDouble(OS_WindowMaterial_ScreenFields::DiffuseSolarReflectance, false);
  if (d){
    idfObject.setDouble(WindowMaterial_ScreenFields::DiffuseSolarReflectance, *d);
  }else{
    LOG(Error, "Missing required input 'Diffuse Solar Reflectance' for WindowMaterial:Screen named '" << modelObject.name().get() << "'");
  }

  d = modelObject.getDouble(OS_WindowMaterial_ScreenFields::DiffuseVisibleReflectance, false);
  if (d){
    idfObject.setDouble(WindowMaterial_ScreenFields::DiffuseVisibleReflectance, *d);
  }else{
    LOG(Error, "Missing required input 'Diffuse Visible Reflectance' for WindowMaterial:Screen named '" << modelObject.name().get() << "'");
  }

  d = modelObject.getDouble(OS_WindowMaterial_ScreenFields::ThermalHemisphericalEmissivity, false);
  if (d){
    idfObject.setDouble(WindowMaterial_ScreenFields::ThermalHemisphericalEmissivity, *d);
  }

  d = modelObject.getDouble(OS_WindowMaterial_ScreenFields::Conductivity, false);
  if (d){
    idfObject.setDouble(WindowMaterial_ScreenFields::Conductivity, *d);
  }

  d = modelObject.getDouble(OS_WindowMaterial_ScreenFields::ScreenMaterialSpacing, false);
  if (d){
    idfObject.setDouble(WindowMaterial_ScreenFields::ScreenMaterialSpacing, *d);
  }else{
    LOG(Error, "Missing required input 'Screen Material Spacing' for WindowMaterial:Screen named '" << modelObject.name().get() << "'");
  }

  d = modelObject.getDouble(OS_WindowMaterial_ScreenFields::ScreenMaterialDiameter, false);
  if (d){
    idfObject.setDouble(WindowMaterial_ScreenFields::ScreenMaterialDiameter, *d);
  }else{
    LOG(Error, "Missing required input 'Screen Material Diameter' for WindowMaterial:Screen named '" << modelObject.name().get() << "'");
  }

  d = modelObject.getDouble(OS_WindowMaterial_ScreenFields::ScreentoGlassDistance, false);
  if (d){
    idfObject.setDouble(WindowMaterial_ScreenFields::ScreentoGlassDistance, *d);
  }

  d = modelObject.getDouble(OS_WindowMaterial_ScreenFields::TopOpeningMultiplier, false);
  if (d){
    idfObject.setDouble(WindowMaterial_ScreenFields::TopOpeningMultiplier, *d);
  }

  d = modelObject.getDouble(OS_WindowMaterial_ScreenFields::BottomOpeningMultiplier, false);
  if (d){
    idfObject.setDouble(WindowMaterial_ScreenFields::BottomOpeningMultiplier, *d);
  }

  d = modelObject.getDouble(OS_WindowMaterial_ScreenFields::LeftSideOpeningMultiplier, false);
  if (d){
    idfObject.setDouble(WindowMaterial_ScreenFields::LeftSideOpeningMultiplier, *d);
  }

  d = modelObject.getDouble(OS_WindowMaterial_ScreenFields::RightSideOpeningMultiplier, false);
  if (d){
    idfObject.setDouble(WindowMaterial_ScreenFields::RightSideOpeningMultiplier, *d);
  }

  s = modelObject.getString(OS_WindowMaterial_ScreenFields::AngleofResolutionforScreenTransmittanceOutputMap, false, true);
  if (s){
    idfObject.setString(WindowMaterial_ScreenFields::AngleofResolutionforScreenTransmittanceOutputMap, *s);
  }

  return boost::optional<IdfObject>(idfObject);
}
Ejemplo n.º 19
0
PolycodeIDEApp::PolycodeIDEApp(PolycodeView *view) : EventDispatcher() {
    core = new POLYCODE_CORE(view, 900,700,false,true, 0, 0,30, -1);
//	core->pauseOnLoseFocus = true;

    runNextFrame = false;

    core->addEventListener(this, Core::EVENT_CORE_RESIZE);
    core->addEventListener(this, Core::EVENT_LOST_FOCUS);
    core->addEventListener(this, Core::EVENT_GAINED_FOCUS);

    globalClipboard = new PolycodeClipboard();

    CoreServices::getInstance()->getRenderer()->setTextureFilteringMode(Renderer::TEX_FILTERING_NEAREST);

    CoreServices::getInstance()->getResourceManager()->addArchive("default.pak");
    CoreServices::getInstance()->getResourceManager()->addDirResource("default");

    CoreServices::getInstance()->getResourceManager()->addArchive("hdr.pak");
    CoreServices::getInstance()->getResourceManager()->addDirResource("hdr");


    CoreServices::getInstance()->getResourceManager()->addArchive("api.pak");
    CoreServices::getInstance()->getResourceManager()->addArchive("Physics2D.pak");
    CoreServices::getInstance()->getResourceManager()->addArchive("Physics3D.pak");
    CoreServices::getInstance()->getResourceManager()->addArchive("UI.pak");

    CoreServices::getInstance()->getConfig()->loadConfig("Polycode", "UIThemes/default/theme.xml");
    CoreServices::getInstance()->getResourceManager()->addArchive("UIThemes/default/");
    CoreServices::getInstance()->getResourceManager()->addArchive("Images/");

    CoreServices::getInstance()->getFontManager()->registerFont("section", "Fonts/Roboto-Thin.ttf");

    CoreServices::getInstance()->getRenderer()->clearColor.setColorHexFromString(CoreServices::getInstance()->getConfig()->getStringValue("Polycode", "uiBgColor"));

//	CoreServices::getInstance()->getRenderer()->setTextureFilteringMode(Renderer::TEX_FILTERING_LINEAR);
    CoreServices::getInstance()->getRenderer()->setTextureFilteringMode(Renderer::TEX_FILTERING_NEAREST);

    willRunProject = false;

    globalMenu	= new UIGlobalMenu();

    printf("creating font editor\n");

    Screen *screen = new Screen();
    screen->rootEntity.setDefaultScreenOptions(true);

    editorManager = new PolycodeEditorManager();

    frame = new PolycodeFrame();
    frame->setPositionMode(ScreenEntity::POSITION_TOPLEFT);

    frame->editorManager = editorManager;
    editorManager->addEventListener(frame, Event::CHANGE_EVENT);

    frame->console->backtraceWindow->addEventListener(this, BackTraceEvent::EVENT_BACKTRACE_SELECTED);

    frame->textInputPopup->addEventListener(this, UIEvent::OK_EVENT);

    frame->yesNoPopup->addEventListener(this, UIEvent::OK_EVENT);
    frame->yesNoPopup->addEventListener(this, UIEvent::CANCEL_EVENT);

    frame->yesNoCancelPopup->addEventListener(this, UIEvent::YES_EVENT);
    frame->yesNoCancelPopup->addEventListener(this, UIEvent::NO_EVENT);


    frame->newProjectWindow->addEventListener(this, UIEvent::OK_EVENT);
    frame->exportProjectWindow->addEventListener(this, UIEvent::OK_EVENT);
    frame->newFileWindow->addEventListener(this, UIEvent::OK_EVENT);
    frame->exampleBrowserWindow->addEventListener(this, UIEvent::OK_EVENT);

    frame->playButton->addEventListener(this, UIEvent::CLICK_EVENT);
    frame->stopButton->addEventListener(this, UIEvent::CLICK_EVENT);

    screen->addChild(frame);


    projectManager = new PolycodeProjectManager();
    projectManager->setProjectBrowser(frame->getProjectBrowser());

    frame->projectManager = projectManager;

    projectManager->addEventListener(frame, Event::CHANGE_EVENT);

    frame->getProjectBrowser()->addEventListener(this, Event::CHANGE_EVENT);
    frame->getProjectBrowser()->addEventListener(this, PolycodeProjectBrowserEvent::HANDLE_MENU_COMMAND);

    frame->Resize(core->getXRes(), core->getYRes());


    debugger = new PolycodeRemoteDebugger(projectManager);
    frame->console->setDebugger(debugger);

    editorManager->registerEditorFactory(new PolycodeImageEditorFactory());
    editorManager->registerEditorFactory(new PolycodeMaterialEditorFactory());
    editorManager->registerEditorFactory(new PolycodeScreenEditorFactory());
    editorManager->registerEditorFactory(new PolycodeFontEditorFactory());
    editorManager->registerEditorFactory(new PolycodeTextEditorFactory());
    editorManager->registerEditorFactory(new PolycodeProjectEditorFactory(projectManager));
    editorManager->registerEditorFactory(new PolycodeSpriteEditorFactory());


    screen->addChild(globalMenu);

    loadConfigFile();
    frame->console->applyTheme();

#ifdef USE_POLYCODEUI_MENUBAR
    menuBar = new UIMenuBar(100, globalMenu);

    UIMenuBarEntry *fileEntry = menuBar->addMenuBarEntry("File");
    fileEntry->addItem("New File", "new_file", KEY_n);
    fileEntry->addItem("New Project", "new_project", KEY_LSHIFT, KEY_n);
    fileEntry->addItem("New Folder", "new_folder", KEY_LSHIFT, KEY_f);
    fileEntry->addItem("Open Project", "open_project", KEY_LSHIFT, KEY_o);
    fileEntry->addItem("Close Project", "close_project", KEY_LSHIFT, KEY_w);
    fileEntry->addItem("Remove File", "remove_file");
    fileEntry->addItem("Refresh Project", "refresh_project");
    fileEntry->addItem("Save File", "save_file", KEY_s);
    fileEntry->addItem("Browse Examples", "browse_examples", KEY_LSHIFT, KEY_e);
    fileEntry->addItem("Quit", "quit");

    UIMenuBarEntry *editEntry = menuBar->addMenuBarEntry("Edit");
    editEntry->addItem("Undo", "undo");
    editEntry->addItem("Redo", "redo");
    editEntry->addItem("Cut", "cut");
    editEntry->addItem("Copy", "copy");

    UIMenuBarEntry *projectEntry = menuBar->addMenuBarEntry("Project");
    projectEntry->addItem("Run Project", "run_project", KEY_r);
    projectEntry->addItem("Publish Project", "export_project");

    UIMenuBarEntry *helpEntry = menuBar->addMenuBarEntry("Help");
    helpEntry->addItem("API Reference", "show_api");
    helpEntry->addItem("About Polycode", "show_about");


    menuBar->addEventListener(this, UIEvent::OK_EVENT);

    screen->addChild(menuBar);
    frame->position.y = 25;
#else
    menuBar = NULL;
#endif
    core->setVideoMode(1100, 700, false, true, 0, 0);

    needsRedraw = false;
    lastConnected = false;
}
Ejemplo n.º 20
0
int main(int argc,char** argv)
{
	int tl;
	bool quit;
	Screen* screen;

	cout<<PACKAGE_STRING<<" beta"<<endl<<endl
		<<"Jorge Riquelme Santana  <*****@*****.**>"<<endl
		<<"http://www.totex.cl"<<endl<<endl;
#ifdef HAVE_CHDIR
	if(chdir(DATADIR))
	{
		cout<<"Ups! no pude encontrar data en "<<DATADIR<<endl;
		if(chdir("./data"))
		{
			cout<<"ah! no pude encontrar data"<<endl;
			return 1;
		}
		else
			cout<<"data encontrada en ./data, haz un make install :p"<<endl;
	}
	else
		cout<<"data encontrada en "<<DATADIR<<"..."<<endl;
#else
	cout<<"Ups! HAVE_CHDIR no esta definida!"<<endl;
#endif

#if defined(HAVE_SYS_STAT_H) and defined(HAVE_SYS_TYPES_H)
	string homedir=(string)getenv("HOME")+"/.qbos/";

	int k=mkdir(homedir.c_str(),S_IRWXU|S_IROTH|S_IXOTH|S_IRGRP|S_IXGRP);
	if(!k)
		cout<<"creando directorio ~/.qbos ..."<<endl;
#else
	cout<<"Ups! HAVE_SYS_STAT_H y HAVE_SYS_TYPES_H no estan definidas!"<<endl;
	string homedir="";
#endif

	try
	{
		if(touch(homedir+"high_scores"))
		{
			cout<<"creando archivo "+homedir+"high_scores ..."<<endl;
			HighScoresScreen::makeDefaultRanking(homedir+"high_scores");
		}
		if(touch(homedir+"config"))
			cout<<"creando archivo "+homedir+"config ..."<<endl;
	}
	catch(const exception& ex)
	{
		cout<<ex.what()<<endl;
		return 2;
	}


	SDLScreen* sdl_screen=0;

	try
	{
		sdl_screen=new SDLScreen(436,560,BPP);
		sdl_screen->setTitle((string)PACKAGE_STRING+" beta");
		Util::setDefaultSurfaceProperties(SDL_SWSURFACE,BPP,RMASK,GMASK,BMASK,AMASK);

	}
	catch(const exception& ex)
	{
		cout<<ex.what()<<endl;
		return 3;
	}

	try
	{
		Configuration config;
		config.load(homedir+"config");
		SDL_EnableKeyRepeat(config.getRepeatDelay(),config.getRepeatInterval());

		screen=new MenuScreen(sdl_screen);
	}
	catch(const exception& ex)
	{
		cout<<ex.what()<<endl;
		delete sdl_screen;
		return 4;
	}

	tl=SDL_GetTicks();

	quit=false;
	while(!quit)
	{
		int t=SDL_GetTicks();
		if(t-tl>=10)
		{
			int rep=(t-tl)/10;

			screen->ticks(rep);
			tl+=10*rep;

			try
			{
				Screen* new_screen=screen->processEvents(quit);
				if(new_screen)
				{
					delete screen;
					screen=new_screen;
				}
				screen->update();
			}
			catch(const exception& ex)
			{
				cout<<ex.what()<<endl;
				delete screen;
				delete sdl_screen;
				return 5;
			}
		}
		else
			SDL_Delay(10-(t-tl));
	}
	delete screen;
	delete sdl_screen;

	cout<<endl<<"chauuu! :p"<<endl;

	return 0;
}
Ejemplo n.º 21
0
int main()
{
	GLFWwindow* window = nullptr;
	if(!init(window))
	{
		system("pause");
		exit(0);
	}

	glClearColor(0.0, 0.0, 0.0, 0.0);

	//set up audio engine
	SoundSystemClass sounds;

	GLSLProgram shaders;
	//load shaders, compile and link	
	shaders.compileShaderFromFile("triangle.v.glsl", VERTEX);
	shaders.compileShaderFromFile("triangle.f.glsl", FRAGMENT);
	shaders.link();
	shaders.use();

	Screen* currentScreen;

	MainMenuScreen *mms = new MainMenuScreen(&sounds, &shaders);
	currentScreen = mms;
	
	//Text t(glm::vec3(0, 0, 0), glm::vec4(1.0, 0.0, 0.0, 1.0), 40, 40, "arial_0.png", "arial.fnt");

	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	
	//create projection matrix
	glm::mat4 projectionMatrix = glm::ortho(0.0f, 800.0f, 0.0f, 600.0f);
	double lastTime = glfwGetTime(), currentTime;

	while(!glfwWindowShouldClose(window) && currentScreen != nullptr)
	{
		//calculate delta time
		currentTime = glfwGetTime();
		double deltaTime = currentTime - lastTime;

		//draw
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		
		currentScreen->Draw();

		glfwSwapBuffers(window);
		
		//update
		Screen* next = currentScreen->Update(deltaTime);
		//if returned screen is null, pop current screen
		if(next != currentScreen)
		{
			delete currentScreen;
			currentScreen = next;
		}
		//else continue with current top of stack

		
		glfwPollEvents();
		lastTime = currentTime;
	}

	glfwDestroyWindow(window);
	glfwTerminate();
	return 0;
}
Ejemplo n.º 22
0
GUI_status VideoDialog::callback(uint16 msg, GUI_CallBack *caller, void *data) {
    if(caller == (GUI_CallBack *)cancel_button) {
        return close_dialog();
    } else if(fullscreen_button && caller == (GUI_CallBack *)fullscreen_button) {
        rebuild_buttons(false);
#ifndef SCALER_AND_SCALE_CANNOT_BE_CHANGED
    } else if(caller == (GUI_CallBack *)scaler_button) {
        if(scaler_button->GetSelection() > 1) {
            scale_button->Hide();
            only2x_button->Show();
        } else {
            scale_button->Show();
            only2x_button->Hide();
        }
    } else if(caller == (GUI_CallBack *)scaler_win_button) {
        if(scaler_win_button->GetSelection() > 1) {
            scale_win_button->Hide();
            only2x_button->Show();
        } else {
            scale_win_button->Show();
            only2x_button->Hide();
        }
#endif /* !SCALER_AND_SCALE_CANNOT_BE_CHANGED */
    } else if(caller == (GUI_CallBack *)save_button) {
        Game *game = Game::get_game();
        Screen *screen = Game::get_game()->get_screen();
        Configuration *config = Game::get_game()->get_config();
        bool fullscreen = fullscreen_button ? fullscreen_button->GetSelection() : screen->is_fullscreen();
#if SCALER_AND_SCALE_CANNOT_BE_CHANGED
        if(fullscreen != screen->is_fullscreen())
            screen->toggle_fullscreen();
        bool non_square_pixels = non_square_pixels_button ? (bool)non_square_pixels_button->GetSelection() : false;
        screen->set_non_square_pixels(non_square_pixels);
#else
        // scaler
        int scaler;
        if(fullscreen)
            scaler = scaler_button->GetSelection();
        else
            scaler = scaler_win_button->GetSelection();
        config->set("config/video/scale_method", screen->get_scaler_reg()->GetNameForIndex(scaler));
        // scale
        int scale;
        if(fullscreen)
            scale = scale_button->GetSelection() + 1;
        else
            scale = scale_win_button->GetSelection() + 1;
        config->set("config/video/scale_factor", scale);
#endif
        // fullscreen
        config->set("config/video/fullscreen", fullscreen ? "yes" : "no");
        // non-square pixels
        config->set("config/video/non_square_pixels", non_square_pixels ? "yes" : "no");
        // roof mode
        bool roof_mode = roof_button->GetSelection();
        game->set_roof_mode(roof_mode);
        game->get_map_window()->set_roof_mode(roof_mode);
        game->get_game_map()->set_roof_mode(roof_mode);
        config->set(config_get_game_key(config) + "/roof_mode", roof_mode ? "yes" : "no");
        // use_new_dolls
        if(doll_button && old_use_new_dolls != (doll_button->GetSelection() ? 1 : 0)) {
            config->set(config_get_game_key(config) + "/use_new_dolls", doll_button->GetSelection() ? "yes" : "no");
            ViewManager *vm = game->get_view_manager();
            InventoryView *iv = vm->get_inventory_view();
            if(vm->get_current_view() == iv) // showing a doll so need to reset
                iv->set_party_member(iv->get_party_member_num());
        }
        // tile_lighting_b
        if(old_use_tile_lighting != tile_lighting_b->GetSelection()) {
            config->set(config_get_game_key(config) + "/map_tile_lighting", tile_lighting_b->GetSelection() ? "yes" : "no");
            game->get_map_window()->using_map_tile_lighting = tile_lighting_b->GetSelection() == 1;
            game->get_map_window()->updateAmbience();
        }
        // lighting
        const char *lighting_char;
        int lighting = lighting_button->GetSelection();
        if(lighting == 0)
            lighting_char = "none";
        else if(lighting == 1)
            lighting_char = "smooth";
        else
            lighting_char = "original";
        config->set("config/general/lighting", lighting_char);
        // sprites
        const char *sprite_char;
        if(sprites_b->GetSelection() == 2)
            sprite_char = "default";
        else
            sprite_char = sprites_b->GetSelection() ? "yes" : "no";
        config->set(config_get_game_key(config) + "/custom_actor_tiles", sprite_char);
        // game_style
        const char *game_style_text[4];
        game_style_text[0] = "original";
        game_style_text[1] = "new";
        game_style_text[2] = "original+";
        game_style_text[3] = "original+_full_map";
        config->set("config/video/game_style", game_style_text[game_style_button->GetSelection()]);
        // dither
        const char *dither_char;
        uint8 dither = dither_button->GetSelection();
        if(dither == 0)
            dither_char = "none";
        else if(dither == 1)
            dither_char = "cga";
        else
            dither_char = "ega";
        config->set("config/general/dither_mode", dither_char);

        config->write();
        close_dialog();
        return GUI_YUM;
    }

    return GUI_PASS;
}
Ejemplo n.º 23
0
Archivo: main.cpp Proyecto: kapyar/---
int main()
{
   const int size=10;
   Screen demo(size, size);
   cout<<"Empty screen created"<<endl<<endl;
   demo.show();
   for(int i=0; i<=size; i++)
      demo.set('*').move(i, i);
   cout<<"The screen filled"<<endl<<endl;
   for(int i=0; i<=size; i++)
      demo.move(size-i-1, i).set('*');
   demo.show();
   demo.clear();
   demo.show();
   cout<<"operator<<"<<endl;
   cout<<demo<<endl;
   

  Screen v(4, 4, "1111222233334444");
  const Screen cv(5, 5, "aaaaabbbbbcccccdddddeeeee");

  cout<<"v: "<<endl;
  v.show();
  cout<<"cv: "<<endl;
  cv.show();
  cout<<"-=CONST SHOW=-"<<endl;
  cv.show();
  //cv.clear();
  cout<<cv<<endl;



cout<<endl<<"1. Transitivity"<<endl;
//Screen v(4, 4, "1111222233334444");
v.show().set('*').move(1, 1).set('*').
      move(2, 2).set('*').
      move(3, 3).set('*').show();

cout<<endl<<"2. Const transitivity"<<endl;
//const Screen cv(5, 5, "aaaaabbbbbcccccdddddeeeee");
cv.show().move(1, 1).showCurrent().
      move(2, 2).showCurrent().
      move(3, 3).showCurrent().show();

const NonConstAction menuNonConst[]=
{
   &Screen::home, 
   &Screen::move, 
   &Screen::back, 
   &Screen::clear,
   &Screen::show,
   &Screen::showCurrent
};

cout<<endl<<"******User menu********"<<endl;
int k, n;
char ch;
cout<<"3. Menu Non Const"<<endl;
v.show();
do
{
   cout<<"your action?(0-home:1-move:2-back:3-clear:4-show:5-showCurrent)";
   cin>>k;
   cout<<"multiplicity? ";
   cin>>n;
   doActionNonConst(v, menuNonConst[k], n);
   cout<<"Repeat(y/n)?";
   cin>>ch;
}
while(ch=='y');
cout<<"Non const Screen after changes: "<<endl;
v.show();

const ConstAction menuConst[]=
{
   &Screen::home, 
   &Screen::move, 
   &Screen::back, 
   &Screen::show,
   &Screen::showCurrent
};
cout<<"4. Menu Const"<<endl;
cv.show();
do
{
   cout<<"your action?(0-home:1-move:2-back:3-show:4-showCurrent)";
   cin>>k;
   cout<<"multiplicity? ";
   cin>>n;
   doActionConst(cv, menuConst[k], n);
   cout<<"Repeat(y/n)?";
   cin>>ch;
}
while(ch=='y');
cv.show();


return 0;
}
Ejemplo n.º 24
0
bool VideoDialog::init() {
    int colX[] = { 9, 29, 63, 232, 270};
    int height = 12;
    int yesno_width = 32;
    int buttonY = 9;
    uint8 textY = 11;
    uint8 row_h = 13;
    last_index = 0;;
    b_index_num = -1;
    bool no_fullscreen = false; // no compatible fullscreen setting found
    GUI_Widget *widget;
    GUI *gui = GUI::get_gui();
    GUI_Font *font = gui->get_font();
    Game *game = Game::get_game();
    Screen *screen = game->get_screen();
    uint16 bpp = screen->get_bpp();
    uint16 scr_width = screen->get_width();
    uint16 scr_height = screen->get_height();
    const char* const yesno_text[] = { "no", "yes" };
#define SCALER_AND_SCALE_CANNOT_BE_CHANGED 1 // FIXME need to be able to change these in game -- they also haven't been updated for keyboard controls and the size of the gump isn't right
#if SCALER_AND_SCALE_CANNOT_BE_CHANGED
    only2x_button = NULL;
    scale_button = scaler_button = scale_win_button = scaler_win_button = NULL;
    int scale = screen->get_scale_factor();
#if SDL_VERSION_ATLEAST(2, 0, 0)
    no_fullscreen = false;
#else
    no_fullscreen = !SDL_VideoModeOK(scr_width * scale, scr_height * scale, bpp, SDL_FULLSCREEN);
#endif

#else
    int textY[] = { 11, 24, 37, 50, 63 , 76, 89, 102, 115, 128, 141 };
    int buttonY[] = { 9, 22, 35, 48, 61, 74, 87, 100, 113, 126, 139, 152 };
// scaler
    int num_scalers = screen->get_scaler_reg()->GetNumScalers();
    const char *scaler_text[num_scalers];
    for (int i = 0; i <= num_scalers; i++)
        scaler_text[i] = screen->get_scaler_reg()->GetNameForIndex(i);

    widget = (GUI_Widget *) new GUI_Text(colX[0], textY[0], 0, 0, 0, "Scaler:", font);
    AddWidget(widget);
// scaler(fullscreen)
    int num_scalers_fullscreen, fullscreen_scaler_selection;
    bool no_only2x_scalers = !SDL_VideoModeOK(scr_width * 2, scr_height * 2, bpp, SDL_FULLSCREEN);
    if(no_only2x_scalers) {
        num_scalers_fullscreen = 2;
        fullscreen_scaler_selection = (screen->get_scaler_index() == 1) ? 1 : 0;
    }
    else {
        num_scalers_fullscreen = num_scalers;
        fullscreen_scaler_selection = screen->get_scaler_index();
    }
    scaler_button = new GUI_TextToggleButton(this, colX[2], buttonY[0], 208, height, scaler_text, num_scalers_fullscreen, fullscreen_scaler_selection, font, BUTTON_TEXTALIGN_CENTER, this, 0);
    AddWidget(scaler_button);
// scaler (windowed)
    scaler_win_button = new GUI_TextToggleButton(this, colX[2], buttonY[0], 208, height, scaler_text, num_scalers, screen->get_scaler_index(), font, BUTTON_TEXTALIGN_CENTER, this, 0);
    AddWidget(scaler_win_button);
// scale
    widget = (GUI_Widget *) new GUI_Text(colX[0], textY[1], 0, 0, 0, "Scale:", gui->get_font());
    AddWidget(widget);
    const char *scale_win_text[10];
    scale_win_text[0] = "1";
    scale_win_text[1] = "2";
    scale_win_text[2] = "3";
    scale_win_text[3] = "4";
    scale_win_text[4] = "5";
    scale_win_text[5] = "6";
    scale_win_text[6] = "7";
    scale_win_text[7] = "8";
    int scale = screen->get_scale_factor();
    char buff [4];
    itoa (scale, buff, 10); // write current scale to buff
// scale (fullscreen)
    const char *scale_text[10];
    int num_scale = 0;
    int scale_selection = 9;

    for (int i = 1; i < 9; i++) {
        if(SDL_VideoModeOK(scr_width * i, scr_height * i, bpp, SDL_FULLSCREEN)) {
            scale_text[num_scale] = scale_win_text[i - 1];
            if(i == scale)
                scale_selection = num_scale;
            num_scale++;
        }
    }
    if(scale_selection == 9) { // current scale is greater than 8 (or wasn't returned as okay)
        if(screen->is_fullscreen() || (scale > 8 && SDL_VideoModeOK(scr_width * scale, scr_height * scale, bpp, SDL_FULLSCREEN))) {
            scale_selection = num_scale;
            scaler_text[num_scale] = buff; // current scale
            num_scale++;
        } else if (num_scale > 0) {
            scale_selection = 0;
        } else {
            no_fullscreen = true;
        }
    }
    if(no_fullscreen) {
        scale_button = NULL;
        scaler_button->Delete();
        scaler_button = NULL;
    } else {
        scale_button = new GUI_TextToggleButton(this, colX[4], buttonY[1], yesno_width, height, scale_text, num_scale, scale_selection, font, BUTTON_TEXTALIGN_CENTER, this, 0);
        AddWidget(scale_button);
    }
// scale (windowed)
    int num_win_scale, scale_win_selection;
    if(scale < 9) {
        num_win_scale = 8;
        scale_win_selection = scale -1;
    } else {
        num_win_scale = 9;
        scale_win_selection = 8;
        scale_win_text[8] = buff;
    }
    scale_win_button = new GUI_TextToggleButton(this, colX[4], buttonY[1], yesno_width, height, scale_win_text, num_win_scale, scale_win_selection, font, BUTTON_TEXTALIGN_CENTER, this, 0);
    AddWidget(scale_win_button);
// scale (only2x scale button for scalers that aren't point or interlaced)
    only2x_button = new GUI_Button(this, colX[3], buttonY[1], 70, height, "2x only", font, BUTTON_TEXTALIGN_CENTER, 0, this, 0);
    AddWidget(only2x_button);
// fullscreen_toggle
    fullscreen_button = new GUI_TextToggleButton(this, colX[4], buttonY[2], yesno_width, height, yesno_text, 2, screen->is_fullscreen(), font, BUTTON_TEXTALIGN_CENTER, this, 0);
    AddWidget(fullscreen_button);

    if(no_fullscreen && !screen->is_fullscreen()) {
        fullscreen_button->Hide();
    } else {
        widget = (GUI_Widget *) new GUI_Text(colX[0], textY[2], 0, 0, 0, "Fullscreen:", gui->get_font());
        AddWidget(widget);
    }
#endif /* !SCALER_AND_SCALE_CANNOT_BE_CHANGED */

    bool first_index = true;
#if SCALER_AND_SCALE_CANNOT_BE_CHANGED
// fullscreen_toggle
    if(!no_fullscreen || screen->is_fullscreen())
    {
        widget = (GUI_Widget *) new GUI_Text(colX[0], textY, 0, 0, 0, "Fullscreen:", gui->get_font());
        AddWidget(widget);

        fullscreen_button = new GUI_TextToggleButton(this, colX[4], buttonY, yesno_width, height, yesno_text, 2, screen->is_fullscreen(), font, BUTTON_TEXTALIGN_CENTER, this, 0);
        AddWidget(fullscreen_button);
        button_index[last_index] = fullscreen_button;

        widget = (GUI_Widget *) new GUI_Text(colX[0], textY += row_h, 0, 0, 0, "Non-square pixels:", gui->get_font());
        AddWidget(widget);
        non_square_pixels_button = new GUI_TextToggleButton(this, colX[4], buttonY += row_h, yesno_width, height, yesno_text, 2, screen->is_non_square_pixels(), font, BUTTON_TEXTALIGN_CENTER, this, 0);
        AddWidget(non_square_pixels_button);
        button_index[last_index += 1] = non_square_pixels_button;

        first_index = false;
    }
    else
        fullscreen_button = NULL;
#endif

    Configuration *config = Game::get_game()->get_config();

// show roofs
    widget = (GUI_Widget *) new GUI_Text(colX[0], textY += first_index ? 0 : row_h, 0, 0, 0, "Show roofs:", gui->get_font());
    AddWidget(widget);
    roof_button = new GUI_TextToggleButton(this, colX[4], buttonY += first_index ? 0 : row_h, yesno_width, height, yesno_text, 2, game->is_roof_mode(), font, BUTTON_TEXTALIGN_CENTER, this, 0);
    AddWidget(roof_button);
    button_index[(last_index += first_index ? 0 : 1)] = roof_button;
// use_new_dolls
    if(game->is_new_style()) {
        doll_button = NULL;
        old_use_new_dolls = true;
    } else {
        widget = (GUI_Widget *) new GUI_Text(colX[0], textY += row_h, 0, 0, 0, "Use new actor dolls:", gui->get_font());
        AddWidget(widget);
        bool use_new_dolls;
        config->value(config_get_game_key(config) + "/use_new_dolls", use_new_dolls, false);
        old_use_new_dolls = use_new_dolls;
        doll_button = new GUI_TextToggleButton(this, colX[4], buttonY += row_h, yesno_width, height, yesno_text, 2, use_new_dolls, font, BUTTON_TEXTALIGN_CENTER, this, 0);
        AddWidget(doll_button);
        button_index[last_index+=1] = doll_button;
    }
// tile_lighting_b
    widget = (GUI_Widget *) new GUI_Text(colX[0], textY += row_h, 0, 0, 0, "Use lighting data from map tiles:", gui->get_font());
    AddWidget(widget);
    old_use_tile_lighting = game->get_map_window()->using_map_tile_lighting;
    tile_lighting_b = new GUI_TextToggleButton(this, colX[4], buttonY += row_h, yesno_width, height, yesno_text, 2, old_use_tile_lighting, font, BUTTON_TEXTALIGN_CENTER, this, 0);
    AddWidget(tile_lighting_b);
    button_index[last_index+=1] = tile_lighting_b;
// needs restart text
    widget = (GUI_Widget *) new GUI_Text(colX[0], textY += row_h*2, 0, 0, 0, "The following require a restart:", gui->get_font());
    AddWidget(widget);
// lighting (needs reset)
    widget = (GUI_Widget *) new GUI_Text(colX[1], textY += row_h, 0, 0, 0, "Lighting mode:", gui->get_font());
    AddWidget(widget);
    const char* const lighting_text[] = { "none", "smooth", "original" };
    lighting_button = new GUI_TextToggleButton(this, colX[3], buttonY += row_h*3, 70, height, lighting_text, 3, screen->get_old_lighting_style(), font, BUTTON_TEXTALIGN_CENTER, this, 0);
    AddWidget(lighting_button);
    button_index[last_index+=1] = lighting_button;
// sprites (needs reset)
    widget = (GUI_Widget *) new GUI_Text(colX[1], textY += row_h, 0, 0, 0, "Use custom actor tiles:", gui->get_font());
    AddWidget(widget);
    const char* const sprite_text[] = { "no", "yes", "default" };
    std::string custom_tile_str;
    int custom_tiles;
    config->value(config_get_game_key(config) +"/custom_actor_tiles", custom_tile_str, "default");
    if(custom_tile_str == "default")
        custom_tiles = 2;
    else
        custom_tiles = custom_tile_str == "yes" ? 1 : 0;
    sprites_b = new GUI_TextToggleButton(this, colX[3], buttonY += row_h, 70, height, sprite_text, 3, custom_tiles, font, BUTTON_TEXTALIGN_CENTER, this, 0);
    AddWidget(sprites_b);
    button_index[last_index+=1] = sprites_b;
// game_style (needs reset)
    const char *game_style_text[4];
    game_style_text[0] = "original style";
    game_style_text[1] = "new style";
    game_style_text[2] = "original+";
    game_style_text[3] = "original+ full map";
    widget = (GUI_Widget *) new GUI_Text(colX[1], textY += row_h, 0, 0, 0, "Game style:", gui->get_font());
    AddWidget(widget);
    game_style_button = new GUI_TextToggleButton(this, colX[3] - 84, buttonY += row_h, 154, height, game_style_text, 4, game->get_game_style(), font, BUTTON_TEXTALIGN_CENTER, this, 0);
    AddWidget(game_style_button);
    button_index[last_index+=1] = game_style_button;
// dithering (needs reset)
    widget = (GUI_Widget *) new GUI_Text(colX[1], textY += row_h, 0, 0, 0, "Old video graphics:", gui->get_font());
    AddWidget(widget);
    const char* const dither_text[] = { "no", "CGA", "EGA" };
    dither_button = new GUI_TextToggleButton(this, colX[4], buttonY += row_h, yesno_width, height, dither_text, 3, game->get_dither()->get_mode(), font, BUTTON_TEXTALIGN_CENTER, this, 0);
    AddWidget(dither_button);
    button_index[last_index+=1] = dither_button;
// cancel/save buttons
    cancel_button = new GUI_Button(this, 95, VD_HEIGHT - 20, 54, height, "Cancel", font, BUTTON_TEXTALIGN_CENTER, 0, this, 0);
    AddWidget(cancel_button);
    button_index[last_index+=1] = cancel_button;
    save_button = new GUI_Button(this, 170, VD_HEIGHT - 20, 40, height, "Save", font, BUTTON_TEXTALIGN_CENTER, 0, this, 0);
    AddWidget(save_button);
    button_index[last_index+=1] = save_button;

    rebuild_buttons(true);
    return true;
}
Ejemplo n.º 25
0
int main( int argc, char* args[] )
{
    //Initialize
    init();
    Screen game;
    int score = 0;
    game.init();
    int random;
    srand(time(NULL));

    game.update=new Timer();
    game.update->start();
    Mix_Chunk *pantalla = Mix_LoadWAV( "pantalla.wav" );

    TTF_Font *font = TTF_OpenFont( "letra.ttf", 35 );
    SDL_Color textColor = { 0, 0, 0 };
    SDL_Surface * score_surface = NULL;


    SDL_Surface * game_over = IMG_Load( "game_over.png" );


    Background background(game.getScreen());
    background.setNumPantalla(0);
    Player player(game.getScreen());
    Enemy enemy(game.getScreen());
    Llama llama(game.getScreen());


    SDL_Event event;
    Mix_PlayChannel( -1, pantalla, 5 );
    //Quit flag
    bool quit = false;
    while( quit == false )
    {
        //If there's an event to handle
        if( SDL_PollEvent( &event ) )
        {
            //If a key was pressed
            if( event.type == SDL_KEYDOWN )
            {
                //Set the proper message surface
                switch( event.key.keysym.sym )
                {
                    case SDLK_ESCAPE: quit = true; break;
                    case SDLK_0:
                        background.setNumPantalla(0);
                        break;
                    case SDLK_1:
                        background.setNumPantalla(1);
                        break;
                    case SDLK_2:
                        background.setNumPantalla(2);
                        break;
                    case SDLK_3:
                        quit = true;
                        break;
                }
            }
            //If the user has Xed out the window
            else if( event.type == SDL_QUIT )
            {
                //Quit the program
                 quit = true;
            }
        }


        background.logic();
        player.isJump();
        if (background.getNumPantalla() == 1){

            game.update;
            player.logic();
            player.isJump();
            random = rand() % 2;
            if (random == 0)
                enemy.logic();
            if (random == 1)
                llama.logic();
            player.perdio(enemy.x, enemy.y);
            player.perdio(llama.x, llama.y);
            if (player.murio){
                break;
            }

        }

        SDL_Surface * score_surface = TTF_RenderText_Solid( font, toString(score+=5).c_str(), textColor );
        SDL_BlitSurface( score_surface, NULL, game.getScreen(), &game.offset );
        SDL_Flip(game.getScreen());
        //SDL_FreeSurface( score_surface );

        background.render();
        player.isJump();
        if (background.getNumPantalla() == 1)
        {
            player.isJump();
            player.render();
                enemy.render();
                llama.render();
        }



        game.frameCap();



        //Update the screen
        if( SDL_Flip( game.getScreen() ) == -1 )
        {
            return 1;
        }


    }
    while( quit == false )
    {
        //If there's an event to handle
        if( SDL_PollEvent( &event ) )
        {
            //If a key was pressed
            if( event.type == SDL_KEYDOWN )
            {
                //Set the proper message surface
                switch( event.key.keysym.sym )
                {
                    case SDLK_ESCAPE: quit = true; break;
                    case SDLK_0:
                        background.setNumPantalla(0);
                        break;
                    case SDLK_3:

                        quit = true;
                        break;
                }
            }
            //If the user has Xed out the window
            else if( event.type == SDL_QUIT )
            {
                //Quit the program
                quit = true;
            }
        }

        SDL_Rect offset;
        game.offset.x = 0;
        game.offset.y = 0;


        SDL_BlitSurface( game_over, NULL, game.getScreen(), &game.offset );

        game.frameCap();

//        Update the screen
        if( SDL_Flip( game.getScreen() ) == -1 )
        {
            return 1;
        }
    }

    SDL_Quit();

    return 0;
}
//this function calls the show results function in the view and outputs the final statistics
void Battle::results(Screen& s){
	s.showResults((tortSuccess/totalRuns*2*100), (tortPartSuccess/totalRuns*2*100), (tortFail/totalRuns*2*100), (hareSuccess/totalRuns*2*100), 
			(harePartSuccess/totalRuns*2*100), (hareFail/totalRuns*2*100), totalRuns/2);
}	
Ejemplo n.º 27
0
bool ScreenManager::scanRandR(xcb_connection_t *conn)
{
    if (!configureRandR(conn)) {
        LOG_ERROR("RandR extension not found.");
        return false;
    }

    xcb_randr_get_screen_resources_current_reply_t *res =
        xcb_randr_get_screen_resources_current_reply(conn,
            xcb_randr_get_screen_resources_current(conn, _rootWindow), NULL);
    if (!res) {
        LOG_ERROR("Failed to retrieve screen resources by RandR.");
        return false;
    }

    int length = xcb_randr_get_screen_resources_current_outputs_length(res);
    xcb_randr_output_t *outputs =
        xcb_randr_get_screen_resources_current_outputs(res);

    std::vector<xcb_randr_get_output_info_cookie_t> cookies;
    xcb_randr_get_output_info_reply_t *output_info;
    xcb_randr_get_crtc_info_reply_t *crtc;
    char *output_name;

    if (length == 0) {
        LOG_ERROR("No screen found using RandR.");
        return false;
    } else {
        LOG_INFO("Found %d screen(s).", length);
    }

    for (int i = 0; i < length; i++) {
        cookies.push_back(xcb_randr_get_output_info(conn, outputs[i],
            res->config_timestamp));
    }
    for (auto iter = cookies.begin(); iter != cookies.end(); ++iter) {
        output_info = xcb_randr_get_output_info_reply(conn, *iter, NULL);
        if (output_info == NULL) {
            continue;
        }
        asprintf(&output_name, "%.*s",
            xcb_randr_get_output_info_name_length(output_info),
            xcb_randr_get_output_info_name(output_info));

        Screen s;
        s.setName(output_name);
        free(output_name);

        if (output_info->crtc == XCB_NONE) {
            LOG_INFO("  Screen %s is disabled.", s.getName().c_str());
            continue;
        }
        crtc = xcb_randr_get_crtc_info_reply(conn,
            xcb_randr_get_crtc_info(
                conn, output_info->crtc, res->config_timestamp),
            NULL);
        if (!crtc) {
            LOG_ERROR("Failed to retrieve CRTC on screen %s.",
                s.getName().c_str());
            return 0;
        }
        s.setX(crtc->x);
        s.setY(crtc->y);
        s.setWidth(crtc->width);
        s.setHeight(crtc->height);
        updateScreen(s);
        free(crtc);
        free(output_info);
    }
    free(res);
    return true;
}
Ejemplo n.º 28
0
/**
 * Creates and adds main layout to the screen.
 */
void MainScreen::createMainLayout()
{
	// create the first screen
	Screen* firstScreen = new Screen();
    firstScreen->setTitle("Edit box");

    // create the vertical layout that will contain all the
    // elements from the first screen
    VerticalLayout* firstScreenVerticalLayout = new VerticalLayout();

    // edit box creation
	mEditBox = new EditBox();
	mEditBox->setPlaceholder("Enter text...");
	mEditBox->setHeight((mScreenHeight/12)*2);
	mEditBox->fillSpaceHorizontally();
	firstScreenVerticalLayout->addChild(mEditBox);

	// create the horizontal layout that will contain the
	// set text button (resets the text to 'DEFAULT') and the
	// get text button
	HorizontalLayout* layout = new HorizontalLayout();
	layout->setHeight(mScreenHeight/12);
	firstScreenVerticalLayout->addChild(layout);

	mSetTextButton = new Button();
	mSetTextButton->setText("Reset text to DEFAULT ");
	layout->addChild(mSetTextButton);

	mGetTextButton = new Button();
	mGetTextButton->setText("Get text");
	layout->addChild(mGetTextButton);

	mGetTextLabel = new Label();
	firstScreenVerticalLayout->addChild(mGetTextLabel);

	// create and add the show/hide keyboard button
	mKeyboardButton = new Button();
	mKeyboardButton->setText("Show/hide keyboard");
	mKeyboardButton->setHeight(mScreenHeight/12);
	mKeyboardButton->fillSpaceHorizontally();
	firstScreenVerticalLayout->addChild(mKeyboardButton);

	// Create layout for widgets.
	this->createDecimalEditBoxView(mMaxTextLengthEditBox, firstScreenVerticalLayout, MAX_TEXT_LENGTH_LABEL_TEXT);
	this->createDecimalEditBoxView(mMaxLinesEditBox, firstScreenVerticalLayout, MAX_LINES_LABEL_TEXT);
	this->createDecimalEditBoxView(mMinLinesEditBox, firstScreenVerticalLayout, MIN_LINES_LABEL_TEXT);
	this->createDecimalEditBoxView(mLinesNumberEditBox, firstScreenVerticalLayout, LINES_NUMBER_LABEL_TEXT);
	this->createDecimalEditBoxView(mPlaceholderColorEditBox, firstScreenVerticalLayout, PLACEHOLDER_COLOR_LABEL_TEXT);

	// Create widgets for testing MAW_EDIT_BOX_MODE property on iOS.
	if (isIOS())
	{
		firstScreenVerticalLayout->addChild(this->createModePropertyLayout());
	}

	// set the main widget for the first screen and
	// then add it as a application tab
	firstScreen->setMainWidget(firstScreenVerticalLayout);
	this->addTab(firstScreen);

	// create the second screen and the horizontal
	// layout that will contain the input modes and flags lists
	Screen* secondScreen = new Screen();
	secondScreen->setTitle("Modes/flags");
	VerticalLayout* secondScreenVerticalLayout = new VerticalLayout();

	this->createInputModeListView(secondScreenVerticalLayout);

	// create a black separator between the lists
	HorizontalLayout* separatorLayout = new HorizontalLayout();
	separatorLayout->setBackgroundColor(0x000000);
	separatorLayout->setHeight(mScreenHeight/12);
	secondScreenVerticalLayout->addChild(separatorLayout);

	this->createInputFlagListView(secondScreenVerticalLayout);

	// set the main widget for the second screen and
	// then add it as a application tab
	secondScreen->setMainWidget(secondScreenVerticalLayout);
	this->addTab(secondScreen);

	maSetColor(0x8A2BE2);
}
Ejemplo n.º 29
0
ScreenOrientation::ScreenOrientation(Screen& screen)
    : DOMWindowProperty(screen.frame())
{
}
Ejemplo n.º 30
0
void EventHandler::processGUIAction(const PlayerAction action,
                                    int deviceID,
                                    const unsigned int value,
                                    Input::InputType type,
                                    const int playerID)
{
    Screen* screen = GUIEngine::getCurrentScreen();
    if (screen != NULL)
    {
        EventPropagation propg = screen->filterActions(action, deviceID, value,
                                                       type, playerID);
        if (propg == EVENT_BLOCK) return;
    }

    const bool pressedDown = value > Input::MAX_VALUE*2/3;

    if (!pressedDown && type == Input::IT_STICKMOTION) return;

    switch (action)
    {
        case PA_STEER_LEFT:
        case PA_MENU_LEFT:
        {
            Widget* w = GUIEngine::getFocusForPlayer(playerID);
            if (w == NULL) break;

            Widget* widget_to_call = w;

            /* Find topmost parent. Stop looping if a widget event handler's is itself, to not fall
             in an infinite loop (this can happen e.g. in checkboxes, where they need to be
             notified of clicks onto themselves so they can toggle their state. )
             On the way, also notify everyone in the chain of the left press. */
            while (widget_to_call->m_event_handler != NULL && widget_to_call->m_event_handler != widget_to_call)
            {
                if (widget_to_call->leftPressed(playerID) == EVENT_LET)
                {
                    sendEventToUser(w, w->m_properties[PROP_ID], playerID);
                }
                widget_to_call = widget_to_call->m_event_handler;
            }


            if (widget_to_call->leftPressed(playerID) == EVENT_LET)
            {
                sendEventToUser(widget_to_call, widget_to_call->m_properties[PROP_ID], playerID);
            }
        }
        break;

        case PA_STEER_RIGHT:
        case PA_MENU_RIGHT:
        {
            Widget* w = GUIEngine::getFocusForPlayer(playerID);
            if (w == NULL) break;

            Widget* widget_to_call = w;
            /* Find topmost parent. Stop looping if a widget event handler's is itself, to not fall
             in an infinite loop (this can happen e.g. in checkboxes, where they need to be
             notified of clicks onto themselves so they can toggle their state. )
             On the way, also notify everyone in the chain of the right press */
            while (widget_to_call->m_event_handler != NULL && widget_to_call->m_event_handler != widget_to_call)
            {
                if (widget_to_call->rightPressed(playerID) == EVENT_LET)
                {
                    sendEventToUser(widget_to_call, w->m_properties[PROP_ID], playerID);
                }
                widget_to_call = widget_to_call->m_event_handler;
            }

            if (widget_to_call->rightPressed(playerID) == EVENT_LET)
            {
                sendEventToUser(widget_to_call, widget_to_call->m_properties[PROP_ID], playerID);
            }
        }
        break;

        case PA_ACCEL:
        case PA_MENU_UP:
            navigate(playerID, type, pressedDown, true);
            break;

        case PA_BRAKE:
        case PA_MENU_DOWN:
            navigate(playerID, type, pressedDown, false);
            break;

        case PA_RESCUE:
        case PA_MENU_CANCEL:
            if (pressedDown) GUIEngine::getStateManager()->escapePressed();
            break;

        case PA_FIRE:
        case PA_MENU_SELECT:
            if (pressedDown && !isWithinATextBox())
            {
                Widget* w = GUIEngine::getFocusForPlayer(playerID);
                if (w == NULL) break;

                // FIXME : consider returned value?
                onWidgetActivated( w, playerID );
            }
            break;
        default:
            return;
    }
}