Beispiel #1
0
bool BaseApp::onKey(const uint key, const bool pressed){
//#if defined(DEBUG) && defined(WIN32)
#ifdef WIN32
	if (pressed && key == KEY_F12){
		if (OpenClipboard(hwnd)){
			EmptyClipboard();

			char str[256];
			int len = sprintf(str, "camPos = vec3(%.15ff, %.15ff, %.15ff);\r\nwx = %.15ff;\r\nwy = %.15ff;\r\n", camPos.x, camPos.y, camPos.z, wx, wy);

			HGLOBAL handle = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, len + 1);
			char *mem = (char *) GlobalLock(handle);
			if (mem != NULL){
				strcpy(mem, str);
				GlobalUnlock(handle);
				SetClipboardData(CF_TEXT, handle);
			}
			CloseClipboard();
		}
	}
#endif

	if (pressed && key == screenshotKey){
		if (!saveScreenshot()){
			ErrorMsg("Couldn't save screenshot");
		}
		return true;
	}

	if (pressed && key == benchmarkKey){
		if (benchMarkFile){
			fclose(benchMarkFile);
			benchMarkFile = NULL;
		} else {
			benchMarkFile = fopen("Benchmark.xls", "w");
			fprintf(benchMarkFile, "Frames/s\n");
		}
		return true;
	}


	bool processed = false;

	if (!mouseCaptured){
		if (widgets.goToFirst()){
			do {
				Widget *widget = widgets.getCurrent();
				if (widget->isVisible() || widget->isCapturing()){
					widgets.moveCurrentToTop();
					processed = widget->onKey(key, pressed);
					break;
				}
			} while (widgets.goToNext());
		}
	}

	if (!processed){
		if (pressed){
			processed = true;
			if (key == KEY_ESCAPE){
				if (!mouseCaptured || (fullscreen && mouseCaptured)){
					closeWindow(true, true);
				} else {
					captureMouse(false);
				}
			} else if (key == fpsKey){
				showFPS = !showFPS;
			} else if (key == resetKey){
				resetCamera();
			} else if (key == optionsKey){
				if (configDialog->isVisible()){
					configDialog->setVisible(false);
					if (keysDialog) keysDialog->setVisible(false);
					if (joystickDialog) joystickDialog->setVisible(false);
				} else {
					captureMouse(false);
					configDialog->setVisible(true);
					if (keysDialog) keysDialog->setVisible(true);
					if (joystickDialog) joystickDialog->setVisible(true);
				}
			} else {
				processed = false;
			}
		}
	}

	if (key < elementsOf(keys)) keys[key] = pressed;

	return processed;
}
Beispiel #2
0
bool OpenGLSdlGraphicsManager::notifyEvent(const Common::Event &event) {
	switch (event.type) {
	case Common::EVENT_KEYUP:
		return isHotkey(event);

	case Common::EVENT_KEYDOWN:
		if (event.kbd.hasFlags(Common::KBD_ALT)) {
			if (   event.kbd.keycode == Common::KEYCODE_RETURN
			    || event.kbd.keycode == (Common::KeyCode)SDLK_KP_ENTER) {
				// Alt-Return and Alt-Enter toggle full screen mode
				beginGFXTransaction();
					setFeatureState(OSystem::kFeatureFullscreenMode, !getFeatureState(OSystem::kFeatureFullscreenMode));
				endGFXTransaction();

#ifdef USE_OSD
				if (getFeatureState(OSystem::kFeatureFullscreenMode)) {
					displayMessageOnOSD(_("Fullscreen mode"));
				} else {
					displayMessageOnOSD(_("Windowed mode"));
				}
#endif
				return true;
			}

			if (event.kbd.keycode == Common::KEYCODE_s) {
				// Alt-s creates a screenshot
				Common::String filename;

				for (int n = 0;; n++) {
					SDL_RWops *file;

					filename = Common::String::format("scummvm%05d.bmp", n);
					file = SDL_RWFromFile(filename.c_str(), "r");
					if (!file)
						break;
					SDL_RWclose(file);
				}

				saveScreenshot(filename.c_str());
				debug("Saved screenshot '%s'", filename.c_str());

				return true;
			}
		} else if (event.kbd.hasFlags(Common::KBD_CTRL | Common::KBD_ALT)) {
			if (   event.kbd.keycode == Common::KEYCODE_PLUS || event.kbd.keycode == Common::KEYCODE_MINUS
			    || event.kbd.keycode == Common::KEYCODE_KP_PLUS || event.kbd.keycode == Common::KEYCODE_KP_MINUS) {
				// Ctrl+Alt+Plus/Minus Increase/decrease the size
				const int direction = (event.kbd.keycode == Common::KEYCODE_PLUS || event.kbd.keycode == Common::KEYCODE_KP_PLUS) ? +1 : -1;

				if (getFeatureState(OSystem::kFeatureFullscreenMode)) {
					// In case we are in fullscreen we will choose the previous
					// or next mode.

					// In case no modes are available we do nothing.
					if (_fullscreenVideoModes.empty()) {
						return true;
					}

					// Look for the current mode.
					VideoModeArray::const_iterator i = Common::find(_fullscreenVideoModes.begin(),
					                                                _fullscreenVideoModes.end(),
					                                                VideoMode(_desiredFullscreenWidth, _desiredFullscreenHeight));
					if (i == _fullscreenVideoModes.end()) {
						return true;
					}

					// Cycle through the modes in the specified direction.
					if (direction > 0) {
						++i;
						if (i == _fullscreenVideoModes.end()) {
							i = _fullscreenVideoModes.begin();
						}
					} else {
						if (i == _fullscreenVideoModes.begin()) {
							i = _fullscreenVideoModes.end();
						}
						--i;
					}

					_desiredFullscreenWidth  = i->width;
					_desiredFullscreenHeight = i->height;

					// Try to setup the mode.
					if (!setupMode(_lastRequestedWidth, _lastRequestedHeight)) {
						warning("OpenGLSdlGraphicsManager::notifyEvent: Fullscreen resize failed ('%s')", SDL_GetError());
						g_system->quit();
					}
				} else {
					// Calculate the next scaling setting. We approximate the
					// current scale setting in case the user resized the
					// window. Then we apply the direction change.
					int windowWidth = 0, windowHeight = 0;
					getWindowDimensions(&windowWidth, &windowHeight);
					_graphicsScale = MAX<int>(windowWidth / _lastRequestedWidth, windowHeight / _lastRequestedHeight);
					_graphicsScale = MAX<int>(_graphicsScale + direction, 1);

					// Since we overwrite a user resize here we reset its
					// flag here. This makes enabling AR smoother because it
					// will change the window size like in surface SDL.
					_gotResize = false;

					// Try to setup the mode.
					if (!setupMode(_lastRequestedWidth * _graphicsScale, _lastRequestedHeight * _graphicsScale)) {
						warning("OpenGLSdlGraphicsManager::notifyEvent: Window resize failed ('%s')", SDL_GetError());
						g_system->quit();
					}
				}

#ifdef USE_OSD
				int windowWidth = 0, windowHeight = 0;
				getWindowDimensions(&windowWidth, &windowHeight);
				const Common::String osdMsg = Common::String::format(_("Resolution: %dx%d"), windowWidth, windowHeight);
				displayMessageOnOSD(osdMsg.c_str());
#endif

				return true;
			} else if (event.kbd.keycode == Common::KEYCODE_a) {
				// In case the user changed the window size manually we will
				// not change the window size again here.
				_ignoreLoadVideoMode = _gotResize;

				// Ctrl+Alt+a toggles the aspect ratio correction state.
				beginGFXTransaction();
					setFeatureState(OSystem::kFeatureAspectRatioCorrection, !getFeatureState(OSystem::kFeatureAspectRatioCorrection));
				endGFXTransaction();

				// Make sure we do not ignore the next resize. This
				// effectively checks whether loadVideoMode has been called.
				assert(!_ignoreLoadVideoMode);

#ifdef USE_OSD
				if (getFeatureState(OSystem::kFeatureAspectRatioCorrection))
					displayMessageOnOSD(_("Enabled aspect ratio correction"));
				else
					displayMessageOnOSD(_("Disabled aspect ratio correction"));
#endif

				return true;
			} else if (event.kbd.keycode == Common::KEYCODE_f) {
				// Never ever try to resize the window when we simply want to enable or disable filtering.
				// This assures that the window size does not change.
				_ignoreLoadVideoMode = true;

				// Ctrl+Alt+f toggles filtering on/off
				beginGFXTransaction();
				setFeatureState(OSystem::kFeatureFilteringMode, !getFeatureState(OSystem::kFeatureFilteringMode));
				endGFXTransaction();

				// Make sure we do not ignore the next resize. This
				// effectively checks whether loadVideoMode has been called.
				assert(!_ignoreLoadVideoMode);

#ifdef USE_OSD
				if (getFeatureState(OSystem::kFeatureFilteringMode)) {
					displayMessageOnOSD(_("Filtering enabled"));
				} else {
					displayMessageOnOSD(_("Filtering disabled"));
				}
#endif

				return true;
			}
		}
		// Fall through

	default:
		return false;
	}
}
Beispiel #3
0
void cv::viz::InteractorStyle::OnKeyDown()
{
    CV_Assert("Interactor style not initialized. Please call Initialize() before continuing" && init_);
    FindPokedRenderer(Interactor->GetEventPosition()[0], Interactor->GetEventPosition()[1]);

    // Save the initial windows width/height
    if (win_size_[0] == -1 || win_size_[1] == -1)
        win_size_ = Vec2i(Interactor->GetRenderWindow()->GetSize());

    bool alt = Interactor->GetAltKey() != 0;

    std::string key(Interactor->GetKeySym());
    if (key.find("XF86ZoomIn") != std::string::npos)
        zoomIn();
    else if (key.find("XF86ZoomOut") != std::string::npos)
        zoomOut();

    switch (Interactor->GetKeyCode())
    {
    case 'h': case 'H':
    {
        std::cout << "| Help:\n"
                     "-------\n"
                     "          p, P   : switch to a point-based representation\n"
                     "          w, W   : switch to a wireframe-based representation (where available)\n"
                     "          s, S   : switch to a surface-based representation (where available)\n"
                     "\n"
                     "          j, J   : take a .PNG snapshot of the current window view\n"
                     "          k, K   : export scene to Wavefront .obj format\n"
                     "    ALT + k, K   : export scene to VRML format\n"
                     "          c, C   : display current camera/window parameters\n"
                     "          f, F   : fly to point mode, hold the key and move mouse where to fly\n"
                     "\n"
                     "          e, E   : exit the interactor\n"
                     "          q, Q   : stop and call VTK's TerminateApp\n"
                     "\n"
                     "           +/-   : increment/decrement overall point size\n"
                     "     +/- [+ ALT] : zoom in/out \n"
                     "\n"
                     "    r, R [+ ALT] : reset camera [to viewpoint = {0, 0, 0} -> center_{x, y, z}]\n"
                     "\n"
                     "    ALT + s, S   : turn stereo mode on/off\n"
                     "    ALT + f, F   : switch between maximized window mode and original size\n"
                     "\n"
                  << std::endl;
        break;
    }

        // Switch representation to points
    case 'p': case 'P':
    {
        vtkSmartPointer<vtkActorCollection> ac = CurrentRenderer->GetActors();
        vtkCollectionSimpleIterator ait;
        for (ac->InitTraversal(ait); vtkActor* actor = ac->GetNextActor(ait); )
            for (actor->InitPathTraversal(); vtkAssemblyPath* path = actor->GetNextPath(); )
            {
                vtkActor* apart = vtkActor::SafeDownCast(path->GetLastNode()->GetViewProp());
                apart->GetProperty()->SetRepresentationToPoints();
            }
        break;
    }

        // Save a PNG snapshot
    case 'j': case 'J':
        saveScreenshot(cv::format("screenshot-%d.png", (unsigned int)time(0))); break;

        // Export scene as in obj or vrml format
    case 'k': case 'K':
    {
        String format = alt ? "scene-%d.vrml" : "scene-%d";
        exportScene(cv::format(format.c_str(), (unsigned int)time(0)));
        break;
    }

        // display current camera settings/parameters
    case 'c': case 'C':
    {
        vtkSmartPointer<vtkCamera> cam = Interactor->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera();

        Vec2d clip(cam->GetClippingRange());
        Vec3d focal(cam->GetFocalPoint()), pos(cam->GetPosition()), view(cam->GetViewUp());
        Vec2i win_pos(Interactor->GetRenderWindow()->GetPosition());
        Vec2i win_size(Interactor->GetRenderWindow()->GetSize());
        double angle = cam->GetViewAngle () / 180.0 * CV_PI;

        String data = cv::format("clip(%f,%f) focal(%f,%f,%f) pos(%f,%f,%f) view(%f,%f,%f) angle(%f) winsz(%d,%d) winpos(%d,%d)",
                                 clip[0], clip[1], focal[0], focal[1], focal[2], pos[0], pos[1], pos[2], view[0], view[1], view[2],
                                 angle, win_size[0], win_size[1], win_pos[0], win_pos[1]);

        std::cout << data.c_str() << std::endl;

        break;
    }
    case '=':
    {
        zoomIn();
        break;
    }
    case 43:        // KEY_PLUS
    {
        if (alt)
            zoomIn();
        else
        {
            vtkSmartPointer<vtkActorCollection> ac = CurrentRenderer->GetActors();
            vtkCollectionSimpleIterator ait;
            for (ac->InitTraversal(ait); vtkActor* actor = ac->GetNextActor(ait); )
                for (actor->InitPathTraversal(); vtkAssemblyPath* path = actor->GetNextPath(); )
                {
                    vtkActor* apart = vtkActor::SafeDownCast(path->GetLastNode()->GetViewProp());
                    float psize = apart->GetProperty()->GetPointSize();
                    if (psize < 63.0f)
                        apart->GetProperty()->SetPointSize(psize + 1.0f);
                }
        }
        break;
    }
    case 45:        // KEY_MINUS
    {
        if (alt)
            zoomOut();
        else
        {
            vtkSmartPointer<vtkActorCollection> ac = CurrentRenderer->GetActors();
            vtkCollectionSimpleIterator ait;
            for (ac->InitTraversal(ait); vtkActor* actor = ac->GetNextActor(ait); )
                for (actor->InitPathTraversal(); vtkAssemblyPath* path = actor->GetNextPath(); )
                {
                    vtkActor* apart = vtkActor::SafeDownCast(path->GetLastNode()->GetViewProp());
                    float psize = apart->GetProperty()->GetPointSize();
                    if (psize > 1.0f)
                        apart->GetProperty()->SetPointSize(psize - 1.0f);
                }
        }
        break;
    }
        // Switch between maximize and original window size
    case 'f': case 'F':
    {
        if (alt)
        {
            Vec2i screen_size(Interactor->GetRenderWindow()->GetScreenSize());
            Vec2i win_size(Interactor->GetRenderWindow()->GetSize());

            // Is window size = max?
            if (win_size == max_win_size_)
            {
                Interactor->GetRenderWindow()->SetSize(win_size_.val);
                Interactor->GetRenderWindow()->SetPosition(win_pos_.val);
                Interactor->GetRenderWindow()->Render();
                Interactor->Render();
            }
            // Set to max
            else
            {
                win_pos_ = Vec2i(Interactor->GetRenderWindow()->GetPosition());
                win_size_ = win_size;

                Interactor->GetRenderWindow()->SetSize(screen_size.val);
                Interactor->GetRenderWindow()->Render();
                Interactor->Render();
                max_win_size_ = Vec2i(Interactor->GetRenderWindow()->GetSize());
            }
        }
        else
        {
            AnimState = VTKIS_ANIM_ON;
            Interactor->GetPicker()->Pick(Interactor->GetEventPosition()[0], Interactor->GetEventPosition()[1], 0.0, CurrentRenderer);
            vtkSmartPointer<vtkAbstractPropPicker> picker = vtkAbstractPropPicker::SafeDownCast(Interactor->GetPicker());
            if (picker)
                if (picker->GetPath())
                    Interactor->FlyTo(CurrentRenderer, picker->GetPickPosition());
            AnimState = VTKIS_ANIM_OFF;
        }
        break;
    }
        // 's'/'S' w/out ALT
    case 's': case 'S':
    {
        if (alt)
        {
            vtkSmartPointer<vtkRenderWindow> window = Interactor->GetRenderWindow();
            if (!window->GetStereoRender())
            {
                static Vec2i red_blue(4, 3), magenta_green(2, 5);
                window->SetAnaglyphColorMask (stereo_anaglyph_mask_default_ ? red_blue.val : magenta_green.val);
                stereo_anaglyph_mask_default_ = !stereo_anaglyph_mask_default_;
            }
            window->SetStereoRender(!window->GetStereoRender());
            Interactor->Render();
        }
        else
            Superclass::OnKeyDown();
        break;
    }

    case 'o': case 'O':
    {
        vtkSmartPointer<vtkCamera> cam = CurrentRenderer->GetActiveCamera();
        cam->SetParallelProjection(!cam->GetParallelProjection());
        CurrentRenderer->Render();
        break;
    }

        // Overwrite the camera reset
    case 'r': case 'R':
    {
        if (!alt)
        {
            Superclass::OnKeyDown();
            break;
        }

        WidgetActorMap::iterator it = widget_actor_map_->begin();
        // it might be that some actors don't have a valid transformation set -> we skip them to avoid a seg fault.
        for (; it != widget_actor_map_->end();  ++it)
        {
            vtkProp3D * actor = vtkProp3D::SafeDownCast(it->second);
            if (actor && actor->GetUserMatrix())
                break;
        }

        vtkSmartPointer<vtkCamera> cam = CurrentRenderer->GetActiveCamera();

        // if a valid transformation was found, use it otherwise fall back to default view point.
        if (it != widget_actor_map_->end())
        {
            vtkMatrix4x4* m = vtkProp3D::SafeDownCast(it->second)->GetUserMatrix();

            cam->SetFocalPoint(m->GetElement(0, 3) - m->GetElement(0, 2),
                               m->GetElement(1, 3) - m->GetElement(1, 2),
                               m->GetElement(2, 3) - m->GetElement(2, 2));

            cam->SetViewUp  (m->GetElement(0, 1), m->GetElement(1, 1), m->GetElement(2, 1));
            cam->SetPosition(m->GetElement(0, 3), m->GetElement(1, 3), m->GetElement(2, 3));
        }
        else
        {
            cam->SetPosition(0, 0, 0);
            cam->SetFocalPoint(0, 0, 1);
            cam->SetViewUp(0, -1, 0);
        }

        // go to the next actor for the next key-press event.
        if (it != widget_actor_map_->end())
            ++it;
        else
            it = widget_actor_map_->begin();

        CurrentRenderer->SetActiveCamera(cam);
        CurrentRenderer->ResetCameraClippingRange();
        CurrentRenderer->Render();
        break;
    }

    case 'q': case 'Q':
    {
        Interactor->ExitCallback();
        return;
    }
    default:
    {
        Superclass::OnKeyDown();
        break;
    }
    }

    KeyboardEvent event(KeyboardEvent::KEY_DOWN, Interactor->GetKeySym(), Interactor->GetKeyCode(), getModifiers());
    if (keyboardCallback_)
        keyboardCallback_(event, keyboard_callback_cookie_);
    Interactor->Render();
}
Beispiel #4
0
MainWindow::MainWindow() : QbWindow(config().geometry.mainWindow) {
  setObjectName("main-window");
  setWindowTitle(string() << bsnesTitle << " v" << bsnesVersion);
  setCloseOnEscape(false);

  //menu bar
  #if defined(PLATFORM_OSX)
  menuBar = new QMenuBar(0);
  #else
  menuBar = new QMenuBar;
  #endif

  system = menuBar->addMenu("&System");

  system_load = system->addAction("Load &Cartridge ...");
  system_load->setIcon(QIcon(":/16x16/document-open.png"));

  system_loadSpecial = system->addMenu("Load &Special");
  system_loadSpecial->setIcon(QIcon(":/16x16/document-open.png"));

  system_loadSpecial_bsxSlotted = system_loadSpecial->addAction("Load BS-X &Slotted Cartridge ...");
  system_loadSpecial_bsxSlotted->setIcon(QIcon(":/16x16/document-open.png"));

  system_loadSpecial_bsx = system_loadSpecial->addAction("Load &BS-X Cartridge ...");
  system_loadSpecial_bsx->setIcon(QIcon(":/16x16/document-open.png"));

  system_loadSpecial_sufamiTurbo = system_loadSpecial->addAction("Load Sufami &Turbo Cartridge ...");
  system_loadSpecial_sufamiTurbo->setIcon(QIcon(":/16x16/document-open.png"));

  system_loadSpecial_superGameBoy = system_loadSpecial->addAction("Load Super &Game Boy Cartridge ...");
  system_loadSpecial_superGameBoy->setIcon(QIcon(":/16x16/document-open.png"));

  system->addSeparator();

  system->addAction(system_power = new QbCheckAction("&Power", 0));

  system_reset = system->addAction("&Reset");
  system_reset->setIcon(QIcon(":/16x16/view-refresh.png"));

  system->addSeparator();

  system_port1 = system->addMenu("Controller Port &1");
  system_port1->setIcon(QIcon(":/16x16/input-gaming.png"));
  system_port1->addAction(system_port1_none = new QbRadioAction("&None", 0));
  system_port1->addAction(system_port1_gamepad = new QbRadioAction("&Gamepad", 0));
  system_port1->addAction(system_port1_asciipad = new QbRadioAction("&asciiPad", 0));
  system_port1->addAction(system_port1_multitap = new QbRadioAction("&Multitap", 0));
  system_port1->addAction(system_port1_mouse = new QbRadioAction("&Mouse", 0));

  system_port2 = system->addMenu("Controller Port &2");
  system_port2->setIcon(QIcon(":/16x16/input-gaming.png"));
  system_port2->addAction(system_port2_none = new QbRadioAction("&None", 0));
  system_port2->addAction(system_port2_gamepad = new QbRadioAction("&Gamepad", 0));
  system_port2->addAction(system_port2_asciipad = new QbRadioAction("&asciiPad", 0));
  system_port2->addAction(system_port2_multitap = new QbRadioAction("&Multitap", 0));
  system_port2->addAction(system_port2_mouse = new QbRadioAction("&Mouse", 0));
  system_port2->addAction(system_port2_superscope = new QbRadioAction("&Super Scope", 0));
  system_port2->addAction(system_port2_justifier = new QbRadioAction("&Justifier", 0));
  system_port2->addAction(system_port2_justifiers = new QbRadioAction("Two &Justifiers", 0));

  #if !defined(PLATFORM_OSX)
  system->addSeparator();
  #endif

  system_exit = system->addAction("E&xit");
  system_exit->setIcon(QIcon(":/16x16/process-stop.png"));
  system_exit->setMenuRole(QAction::QuitRole);

  settings = menuBar->addMenu("S&ettings");

  settings_videoMode = settings->addMenu("Video &Mode");
  settings_videoMode->setIcon(QIcon(":/16x16/video-display.png"));

  settings_videoMode->addAction(settings_videoMode_1x = new QbRadioAction("Scale &1x", 0));

  settings_videoMode->addAction(settings_videoMode_2x = new QbRadioAction("Scale &2x", 0));

  settings_videoMode->addAction(settings_videoMode_3x = new QbRadioAction("Scale &3x", 0));

  settings_videoMode->addAction(settings_videoMode_4x = new QbRadioAction("Scale &4x", 0));

  settings_videoMode->addAction(settings_videoMode_5x = new QbRadioAction("Scale &5x", 0));

  settings_videoMode->addSeparator();

  settings_videoMode->addAction(settings_videoMode_correctAspectRatio = new QbCheckAction("Correct &Aspect Ratio", 0));

  settings_videoMode->addSeparator();

  settings_videoMode->addAction(settings_videoMode_ntsc = new QbRadioAction("&NTSC", 0));
  settings_videoMode->addAction(settings_videoMode_pal = new QbRadioAction("&PAL", 0));

  if(filter.opened()) {
    settings_videoFilter = settings->addMenu("Video &Filter");
    settings_videoFilter->setIcon(QIcon(":/16x16/image-x-generic.png"));

    settings_videoFilter_configure = settings_videoFilter->addAction("&Configure Active Filter ...");
    settings_videoFilter_configure->setIcon(QIcon(":/16x16/preferences-desktop.png"));
    settings_videoFilter->addSeparator();

    settings_videoFilter->addAction(settings_videoFilter_none = new QbRadioAction("&None", 0));
    settings_videoFilter_list.add(settings_videoFilter_none);

    lstring filterlist;
    filterlist.split(";", filter.dl_supported());
    for(unsigned i = 0; i < filterlist.size(); i++) {
      QbRadioAction *action = new QbRadioAction(filterlist[i], 0);
      settings_videoFilter->addAction(action);
      settings_videoFilter_list.add(action);
    }
  }

  settings->addAction(settings_smoothVideo = new QbCheckAction("&Smooth Video Output", 0));

  settings->addSeparator();

  settings->addAction(settings_muteAudio = new QbCheckAction("&Mute Audio Output", 0));

  settings->addSeparator();

  settings_emulationSpeed = settings->addMenu("Emulation &Speed");
  settings_emulationSpeed->setIcon(QIcon(":/16x16/appointment-new.png"));

  settings_emulationSpeed->addAction(settings_emulationSpeed_slowest = new QbRadioAction("Slowest", 0));

  settings_emulationSpeed->addAction(settings_emulationSpeed_slow = new QbRadioAction("Slow", 0));

  settings_emulationSpeed->addAction(settings_emulationSpeed_normal = new QbRadioAction("Normal", 0));

  settings_emulationSpeed->addAction(settings_emulationSpeed_fast = new QbRadioAction("Fast", 0));

  settings_emulationSpeed->addAction(settings_emulationSpeed_fastest = new QbRadioAction("Fastest", 0));

  settings_emulationSpeed->addSeparator();

  settings_emulationSpeed->addAction(settings_emulationSpeed_syncVideo = new QbCheckAction("Sync &Video", 0));

  settings_emulationSpeed->addAction(settings_emulationSpeed_syncAudio = new QbCheckAction("Sync &Audio", 0));

  settings_configuration = settings->addAction("&Configuration ...");
  settings_configuration->setIcon(QIcon(":/16x16/preferences-desktop.png"));
  settings_configuration->setMenuRole(QAction::PreferencesRole);

  tools = menuBar->addMenu("&Tools");

  tools_movies = tools->addMenu("&Movies");
  tools_movies->setIcon(QIcon(":/16x16/applications-multimedia.png"));

  tools_movies_play = tools_movies->addAction("Play Movie ...");
  tools_movies_play->setIcon(QIcon(":/16x16/media-playback-start.png"));

  tools_movies_stop = tools_movies->addAction("Stop");
  tools_movies_stop->setIcon(QIcon(":/16x16/media-playback-stop.png"));

  tools_movies_recordFromPowerOn = tools_movies->addAction("Record Movie (and restart system)");
  tools_movies_recordFromPowerOn->setIcon(QIcon(":/16x16/media-record.png"));

  tools_movies_recordFromHere = tools_movies->addAction("Record Movie (starting from here)");
  tools_movies_recordFromHere->setIcon(QIcon(":/16x16/media-record.png"));

  tools_captureScreenshot = tools->addAction("&Capture Screenshot");
  tools_captureScreenshot->setIcon(QIcon(":/16x16/image-x-generic.png"));

  tools->addSeparator();

  tools_dialog = tools->addAction("&Tools Dialog ...");
  tools_dialog->setIcon(QIcon(":/16x16/preferences-desktop.png"));

  tools_debugger = tools->addAction("&Debugger ...");
  tools_debugger->setIcon(QIcon(":/16x16/utilities-terminal.png"));
  #if !defined(DEBUGGER)
  tools_debugger->setVisible(false);
  #endif

  help = menuBar->addMenu("&Help");

  help_documentation = help->addAction("&Documentation ...");
  help_documentation->setIcon(QIcon(":/16x16/text-x-generic.png"));

  help_license = help->addAction("&License ...");
  help_license->setIcon(QIcon(":/16x16/text-x-generic.png"));

  #if !defined(PLATFORM_OSX)
  help->addSeparator();
  #endif

  help_about = help->addAction("&About ...");
  help_about->setIcon(QIcon(":/16x16/help-browser.png"));
  help_about->setMenuRole(QAction::AboutRole);

  //canvas
  canvasContainer = new CanvasObject;
  canvasContainer->setAcceptDrops(true); {
    canvasContainer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    canvasContainer->setObjectName("backdrop");

    canvasLayout = new QVBoxLayout; {
      canvasLayout->setMargin(0);
      canvasLayout->setAlignment(Qt::AlignCenter);

      canvas = new CanvasWidget;
      canvas->setAcceptDrops(true);
      canvas->setFocusPolicy(Qt::StrongFocus);
      canvas->setAttribute(Qt::WA_PaintOnScreen, true);  //disable Qt painting on focus / resize

      QPalette palette;
      palette.setColor(QPalette::Window, QColor(0, 0, 0));
      canvas->setPalette(palette);
      canvas->setAutoFillBackground(true);
    }
    canvasLayout->addWidget(canvas);
  }
  canvasContainer->setLayout(canvasLayout);

  //status bar
  statusBar = new QStatusBar;
  statusBar->showMessage("");
  systemState = new QLabel;
  statusBar->addPermanentWidget(systemState);

  //layout
  layout = new QVBoxLayout;
  layout->setMargin(0);
  layout->setSpacing(0);
  #if !defined(PLATFORM_OSX)
  layout->addWidget(menuBar);
  #endif
  layout->addWidget(canvasContainer);
  layout->addWidget(statusBar);
  setLayout(layout);

  //slots
  connect(system_load, SIGNAL(triggered()), this, SLOT(loadCartridge()));
  connect(system_loadSpecial_bsxSlotted, SIGNAL(triggered()), this, SLOT(loadBsxSlottedCartridge()));
  connect(system_loadSpecial_bsx, SIGNAL(triggered()), this, SLOT(loadBsxCartridge()));
  connect(system_loadSpecial_sufamiTurbo, SIGNAL(triggered()), this, SLOT(loadSufamiTurboCartridge()));
  connect(system_loadSpecial_superGameBoy, SIGNAL(triggered()), this, SLOT(loadSuperGameBoyCartridge()));
  connect(system_power, SIGNAL(triggered()), this, SLOT(power()));
  connect(system_reset, SIGNAL(triggered()), this, SLOT(reset()));
  connect(system_port1_none, SIGNAL(triggered()), this, SLOT(setPort1None()));
  connect(system_port1_gamepad, SIGNAL(triggered()), this, SLOT(setPort1Gamepad()));
  connect(system_port1_asciipad, SIGNAL(triggered()), this, SLOT(setPort1Asciipad()));
  connect(system_port1_multitap, SIGNAL(triggered()), this, SLOT(setPort1Multitap()));
  connect(system_port1_mouse, SIGNAL(triggered()), this, SLOT(setPort1Mouse()));
  connect(system_port2_none, SIGNAL(triggered()), this, SLOT(setPort2None()));
  connect(system_port2_gamepad, SIGNAL(triggered()), this, SLOT(setPort2Gamepad()));
  connect(system_port2_asciipad, SIGNAL(triggered()), this, SLOT(setPort2Asciipad()));
  connect(system_port2_multitap, SIGNAL(triggered()), this, SLOT(setPort2Multitap()));
  connect(system_port2_mouse, SIGNAL(triggered()), this, SLOT(setPort2Mouse()));
  connect(system_port2_superscope, SIGNAL(triggered()), this, SLOT(setPort2SuperScope()));
  connect(system_port2_justifier, SIGNAL(triggered()), this, SLOT(setPort2Justifier()));
  connect(system_port2_justifiers, SIGNAL(triggered()), this, SLOT(setPort2Justifiers()));
  connect(system_exit, SIGNAL(triggered()), this, SLOT(quit()));
  connect(settings_videoMode_1x, SIGNAL(triggered()), this, SLOT(setVideoMode1x()));
  connect(settings_videoMode_2x, SIGNAL(triggered()), this, SLOT(setVideoMode2x()));
  connect(settings_videoMode_3x, SIGNAL(triggered()), this, SLOT(setVideoMode3x()));
  connect(settings_videoMode_4x, SIGNAL(triggered()), this, SLOT(setVideoMode4x()));
  connect(settings_videoMode_5x, SIGNAL(triggered()), this, SLOT(setVideoMode5x()));
  connect(settings_videoMode_correctAspectRatio, SIGNAL(triggered()), this, SLOT(toggleAspectCorrection()));
  connect(settings_videoMode_ntsc, SIGNAL(triggered()), this, SLOT(setVideoNtsc()));
  connect(settings_videoMode_pal, SIGNAL(triggered()), this, SLOT(setVideoPal()));
  if(filter.opened()) {
    connect(settings_videoFilter_configure, SIGNAL(triggered()), this, SLOT(configureFilter()));
    for(unsigned i = 0; i < settings_videoFilter_list.size(); i++) {
      connect(settings_videoFilter_list[i], SIGNAL(triggered()), this, SLOT(setFilter()));
    }
  }
  connect(settings_smoothVideo, SIGNAL(triggered()), this, SLOT(toggleSmoothVideo()));
  connect(settings_muteAudio, SIGNAL(triggered()), this, SLOT(muteAudio()));
  connect(settings_emulationSpeed_slowest, SIGNAL(triggered()), this, SLOT(setSpeedSlowest()));
  connect(settings_emulationSpeed_slow, SIGNAL(triggered()), this, SLOT(setSpeedSlow()));
  connect(settings_emulationSpeed_normal, SIGNAL(triggered()), this, SLOT(setSpeedNormal()));
  connect(settings_emulationSpeed_fast, SIGNAL(triggered()), this, SLOT(setSpeedFast()));
  connect(settings_emulationSpeed_fastest, SIGNAL(triggered()), this, SLOT(setSpeedFastest()));
  connect(settings_emulationSpeed_syncVideo, SIGNAL(triggered()), this, SLOT(syncVideo()));
  connect(settings_emulationSpeed_syncAudio, SIGNAL(triggered()), this, SLOT(syncAudio()));
  connect(settings_configuration, SIGNAL(triggered()), this, SLOT(showConfigWindow()));
  connect(tools_movies_play, SIGNAL(triggered()), this, SLOT(playMovie()));
  connect(tools_movies_stop, SIGNAL(triggered()), this, SLOT(stopMovie()));
  connect(tools_movies_recordFromPowerOn, SIGNAL(triggered()), this, SLOT(recordMovieFromPowerOn()));
  connect(tools_movies_recordFromHere, SIGNAL(triggered()), this, SLOT(recordMovieFromHere()));
  connect(tools_captureScreenshot, SIGNAL(triggered()), this, SLOT(saveScreenshot()));
  connect(tools_debugger, SIGNAL(triggered()), this, SLOT(showDebugger()));
  connect(tools_dialog, SIGNAL(triggered()), this, SLOT(showToolsDialog()));
  connect(help_documentation, SIGNAL(triggered()), this, SLOT(showDocumentation()));
  connect(help_license, SIGNAL(triggered()), this, SLOT(showLicense()));
  connect(help_about, SIGNAL(triggered()), this, SLOT(showAbout()));

  syncUi();
}
Beispiel #5
0
void doIdle()
{
  char s[20]="picxxxx.ppm";
  int i;
  
  // save screen to file
  s[3] = 48 + (sprite / 1000);
  s[4] = 48 + (sprite % 1000) / 100;
  s[5] = 48 + (sprite % 100 ) / 10;
  s[6] = 48 + sprite % 10;

  if (saveScreenToFile==1)
  {
    saveScreenshot(windowWidth, windowHeight, s);
    //saveScreenToFile=0; // save only once, change this if you want continuos image generation (i.e. animation)
    sprite++;
  }

  if (sprite >= 300) // allow only 300 snapshots
  {
    exit(0);	
  }

  if (pause == 0)
  {
    // insert code which appropriately performs one step of the cube simulation:
	  if (Integration[0] == 'E') {
		   Euler(&jello);
	  }else if (Integration[0] == 'R') {
		  RK4(&jello);
	  }else {
		  exit(0);
	  }

  }
	
	if (Fx == 1) {
		jello.Force.x += 1;
		Fx = 0;
	}
	if (Fx == -1) {
		jello.Force.x -= 1;
		Fx = 0;
	}
	if (Fy == 1) {
		jello.Force.y += 1;
		Fy = 0;
	}
	if (Fy == -1) {
		jello.Force.y -= 1;
		Fy = 0;
	}
	if (Fa == 1) {
		alpha += 1;
		Fa = 0;
	}
	if (Fa == -1) {
		if (alpha != 0) {
			alpha -= 1;
			Fa = 0;
		}
	}
	if (Fb == 1) {
		beta += 0.1;
		Fb = 0;
	}
	if (Fb == -1) {
		beta -= 0.1;
		Fb = 0;
	}
	if (PNoise == -1) {
		jello.Force.x = 0;
		jello.Force.y = -1;
		PNoise = 0;
		for (int i=0; i<particleNum; i++) {
			jello.v[i].x = 0;
			jello.v[i].y = 0;
			jello.v[i].z = 0;
			jello.a[i].x = 0;
			jello.a[i].y = 0;
			jello.a[i].z = 0;
		}
	}	
	if (PNoise == 1) {
		srand(time(NULL));
		PerlinNoise P;
		if (alpha == 0) {
			jello.Force.x = P.PerlinNoise1D(rand()%100, particleNum , 0.3);
			jello.Force.y = P.PerlinNoise1D(rand()%100, particleNum , 0.3);
		}else {
			jello.Force.x = P.PerlinNoise1D(rand()%100, particleNum , 0.3) * 20;
			jello.Force.y = P.PerlinNoise1D(rand()%100, particleNum , 0.3) * 20;
		}
	}
		
	//reset everything
	if (Fx == -5) {
		for (int i=0; i<particleNum; i++) {
			jello.v[i].x = 0;
			jello.v[i].y = 0;
			jello.v[i].z = 0;
			jello.a[i].x = 0;
			jello.a[i].y = 0;
			jello.a[i].z = 0;
		}
		jello.Force.x = 0;
		jello.Force.y = -1;
		alpha = 0;
		beta = 0;
		PNoise = 0;
		Fx = 0;
	}
	

  glutPostRedisplay();
}
Beispiel #6
0
	void Emulator::on_actionScreenshot_triggered(bool checked) {
        saveScreenshot();
	}
Beispiel #7
0
bool InputManager::handleKeyboardInput(const SDL_Event &event)
{
    bool used = false;
    bool metaKeyHeld = false;

    // Key press events
    if (event.type == SDL_KEYDOWN)
    {
        if (setupWindow->isVisible() &&
            keyboard.getNewKeyIndex() > keyboard.KEY_NO_VALUE)
        {
            keyboard.setNewKey((int) event.key.keysym.sym);
            keyboard.callbackNewKey();
            keyboard.setNewKeyIndex(keyboard.KEY_NO_VALUE);
            return false;
        }

        // If the user is configuring the keys then don't respond.
        if (!keyboard.isEnabled())
            return false;

        const int tKey = keyboard.getKeyIndex(event.key.keysym.sym);

        // Ignore input if either "ignore" key is pressed
        // Stops the character moving about if the user's window manager
        // uses "ignore+arrow key" to switch virtual desktops.
        if (keyboard.isKeyActive(keyboard.KEY_IGNORE_INPUT_1) ||
            keyboard.isKeyActive(keyboard.KEY_IGNORE_INPUT_2))
        {
            return false;
        }

        if (keyboard.isKeyLocked(event.key.keysym.sym))
            return false;

        gcn::Window *requestedWindow = NULL;

        switch (tKey)
        {
            // In-game Help
            case KeyboardConfig::KEY_WINDOW_HELP:
                requestedWindow = helpDialog;
                break;
            // Quitting confirmation dialog
            case KeyboardConfig::KEY_QUIT:
                stateManager->promptForQuit();
                used = true;
                break;
            case KeyboardConfig::KEY_WINDOW_DEBUG:
                requestedWindow = debugWindow;
                break;
            case KeyboardConfig::KEY_WINDOW_SETUP:
                requestedWindow = setupWindow;
                break;
            // Screenshot (picture, hence the p)
            case KeyboardConfig::KEY_SCREENSHOT:
                saveScreenshot();
                used = true;
                break;
        }

        if (stateManager->isInGame())
        {
            switch (tKey)
            {
                case KeyboardConfig::KEY_SCROLL_CHAT_UP:
                    if (chatWindow && chatWindow->isVisible())
                    {
                        chatWindow->scroll(-DEFAULT_CHAT_WINDOW_SCROLL);
                        used = true;
                    }
                    break;
                case KeyboardConfig::KEY_SCROLL_CHAT_DOWN:
                    if (chatWindow && chatWindow->isVisible())
                    {
                        chatWindow->scroll(DEFAULT_CHAT_WINDOW_SCROLL);
                        used = true;
                    }
                    break;
                case KeyboardConfig::KEY_WINDOW_STATUS:
                    requestedWindow = statusWindow;
                    break;
                case KeyboardConfig::KEY_WINDOW_INVENTORY:
                    requestedWindow = inventoryWindow;
                    break;
                case KeyboardConfig::KEY_WINDOW_EQUIPMENT:
                    requestedWindow = equipmentWindow;
                    break;
                case KeyboardConfig::KEY_WINDOW_SKILL:
                    requestedWindow = skillDialog;
                    break;
                case KeyboardConfig::KEY_WINDOW_MINIMAP:
                    minimap->toggle();
                    break;
                case KeyboardConfig::KEY_WINDOW_CHAT:
                    requestedWindow = chatWindow;
                    break;
                case KeyboardConfig::KEY_WINDOW_EMOTE:
                    requestedWindow = emoteWindow;
                    break;
                case KeyboardConfig::KEY_WINDOW_ITEM_SHORTCUT:
                    requestedWindow = itemShortcutWindow;
                    break;
                case KeyboardConfig::KEY_WINDOW_EMOTE_SHORTCUT:
                    requestedWindow = emoteShortcutWindow;
                    break;
                // Hide certain windows
                case KeyboardConfig::KEY_HIDE_WINDOWS:
                    statusWindow->hide();
                    inventoryWindow->hide();
                    equipmentWindow->hide();
                    skillDialog->hide();
                    chatWindow->hide();
                    itemShortcutWindow->hide();
                    setupWindow->hide();
                    debugWindow->hide();
                    emoteWindow->hide();
                    helpDialog->hide();
                    emoteShortcutWindow->hide();
                    minimap->hide();
                    used = true;
                    break;
                // Find path to mouse (debug purpose)
                case KeyboardConfig::KEY_PATHFIND:
                    viewport->toggleDebugPath();
                    used = true;
                    break;
                default:
                    break;
            }

            metaKeyHeld = keyboard.isKeyActive(keyboard.KEY_METAKEY);

            for (int i = 0; i <= SHORTCUTS; i++)
            {
                ShortcutHandler *shortcut = metaKeyHeld ? (ShortcutHandler *) emoteShortcut :
                                                          (ShortcutHandler *) itemShortcut;
                const int offset = metaKeyHeld ? KeyboardConfig::KEY_EMOTE_SHORTCUT_1 :
                                                 KeyboardConfig::KEY_ITEM_SHORTCUT_1;

                if (keyboard.isKeyActive(i + offset))
                {
                    shortcut->useShortcut(i);
                    used = true;
                    break;
                }
            }

            if (keyboard.isKeyActive(keyboard.KEY_TOGGLE_CHAT) && chatWindow)
            {
                chatWindow->requestChatFocus();
                used = true;
            }

            // Player actions
            if (player_node && player_node->mAction != Being::DEAD)
            {
                Being *target = player_node->getTarget();
                const Uint16 x = player_node->mX;
                const Uint16 y = player_node->mY;

                if (!keyboard.isKeyActive(keyboard.KEY_CLEAR_TARGET))
                {
                    Being::Type type = Being::INVALID;

                    // Target the nearest monster
                    if (keyboard.isKeyActive(keyboard.KEY_TARGET_MONSTER))
                        type = Being::MONSTER;
                    // Target the nearest player
                    else if (keyboard.isKeyActive(keyboard.KEY_TARGET_PLAYER))
                        type = Being::PLAYER;
                    // Target the nearest npc
                    else if (keyboard.isKeyActive(keyboard.KEY_TARGET_NPC))
                        type = Being::NPC;

                    target = beingManager->findNearestLivingBeing(x, y, 20,
                                           type != Being::INVALID ? type :
                                                   Being::UNKNOWN);

                    if (type != Being::INVALID && !targetKeyHeld)
                    {
                        player_node->setTarget(target);
                        targetKeyHeld = true;
                        used = true;
                    }
                    else if (player_node->isAttacking())
                        target = NULL;

                    if (keyboard.isKeyActive(keyboard.KEY_ATTACK) && target)
                    {
                        player_node->attack(player_node->getTarget() ?
                                            player_node->getTarget() : target,
                                            target->getType() != Being::NPC);
                        used = true;
                    }
                }
                // Stop attacking
                else if (keyboard.isKeyActive(keyboard.KEY_CLEAR_TARGET))
                {
                    player_node->stopAttack();
                    targetKeyHeld = false;
                }

                if (keyboard.isKeyActive(keyboard.KEY_BEING_MENU))
                {
                    target = player_node->getTarget();

                    if (!target)
                        target = beingManager->findNearestLivingBeing(x, y, 20);

                    if (target)
                    {
                        Map *map = viewport->getMap();
                        viewport->showPopup(target->mX * map->getTileWidth() -
                                            viewport->getCameraX() +
                                           (map->getTileWidth() / 2),
                                            target->mY * map->getTileHeight() -
                                            viewport->getCameraY(), target);
                    }
                    used = true;
                }

                switch (tKey)
                {
                    case KeyboardConfig::KEY_PICKUP:
                        {
                            Uint16 x = player_node->mX;
                            Uint16 y = player_node->mY;
                            FloorItem *item = floorItemManager->
                                                  findNearestItem(x, y);

                            if (item)
                                player_node->pickUp(item);

                            used = true;
                        }
                        break;
                    // Player sit action
                    case KeyboardConfig::KEY_SIT:
                        player_node->toggleSit();
                        used = true;
                        break;
                    // Toggle accepting of incoming trade requests
                    case KeyboardConfig::KEY_TRADE:
                        {
                            unsigned int deflt = player_relations.getDefault();
                            if (deflt & PlayerRelation::TRADE)
                            {
                                chatWindow->chatLog(_("Ignoring incoming "
                                                      "trade requests"),
                                                      Palette::SYSTEM);
                                deflt &= ~PlayerRelation::TRADE;
                            }
                            else
                            {
                                chatWindow->chatLog(_("Accepting incoming "
                                                      "trade requests"),
                                                      Palette::SYSTEM);
                                deflt |= PlayerRelation::TRADE;
                            }

                            player_relations.setDefault(deflt);
                            used = true;
                        }
                        break;
               }
            }
        }

        if (requestedWindow)
        {
            requestedWindow->setVisible(!requestedWindow->isVisible());
            used = true;
        }
    }
    else if (event.type == SDL_KEYUP)
    {
        const int tKey = keyboard.getKeyIndex(event.key.keysym.sym);

        // Stop protecting the target keys
        if (tKey == KeyboardConfig::KEY_TARGET_MONSTER ||
            tKey == KeyboardConfig::KEY_TARGET_PLAYER || 
            tKey == KeyboardConfig::KEY_TARGET_NPC)
        {
            targetKeyHeld = false;
        }
    }

    // At the moment, this is the only bit of logic left not assigned to a
    // specific SDL input poll, because it was causing continuous walking
    // without stopping. It would be better in the long run if this would get
    // fixed and then moved to one of them (in case we ever use other input
    // libraries. If everything is already grouped together, it'd be easier to
    // adapt to a new library, instead of having to rely on special cases)
    if (stateManager->isInGame() && player_node->mAction != Being::DEAD && !used)
    {
        unsigned char direction = 0;

        // Get the state of the keyboard keys
        keyboard.refreshActiveKeys();

        // Translate pressed keys to movement and direction
        if (keyboard.isKeyActive(keyboard.KEY_MOVE_UP))
            direction |= Being::UP;
        else if (keyboard.isKeyActive(keyboard.KEY_MOVE_DOWN))
            direction |= Being::DOWN;

        if (keyboard.isKeyActive(keyboard.KEY_MOVE_LEFT))
            direction |= Being::LEFT;
        else if (keyboard.isKeyActive(keyboard.KEY_MOVE_RIGHT))
            direction |= Being::RIGHT;

        if (metaKeyHeld && direction != 0)
            player_node->setDirection(direction);
        else
            player_node->setWalkingDir(direction);
    }

    return used;
}
Beispiel #8
0
void ScreenGrabber::saveScreenshot( const GLEWContext* context, const std::string& nameTemplate, int w, int h, int numBytes )
{
    saveScreenshot( context, nameTemplate, eq::fabric::PixelViewport( 0, 0, w, h ), numBytes );
}
bool OpenGLSdlGraphicsManager::notifyEvent(const Common::Event &event) {
	switch (event.type) {
	case Common::EVENT_KEYUP:
		return isHotkey(event);

	case Common::EVENT_KEYDOWN:
		if (event.kbd.hasFlags(Common::KBD_ALT)) {
			if (   event.kbd.keycode == Common::KEYCODE_RETURN
			    || event.kbd.keycode == (Common::KeyCode)SDLK_KP_ENTER) {
				// Alt-Return and Alt-Enter toggle full screen mode
				beginGFXTransaction();
					setFeatureState(OSystem::kFeatureFullscreenMode, !getFeatureState(OSystem::kFeatureFullscreenMode));
				endGFXTransaction();

#ifdef USE_OSD
				if (getFeatureState(OSystem::kFeatureFullscreenMode)) {
					displayMessageOnOSD("Fullscreen mode");
				} else {
					displayMessageOnOSD("Windowed mode");
				}
#endif
				return true;
			}

			if (event.kbd.keycode == Common::KEYCODE_s) {
				// Alt-s creates a screenshot
				Common::String filename;

				for (int n = 0;; n++) {
					SDL_RWops *file;

					filename = Common::String::format("scummvm%05d.bmp", n);
					file = SDL_RWFromFile(filename.c_str(), "r");
					if (!file)
						break;
					SDL_RWclose(file);
				}

				saveScreenshot(filename.c_str());
				debug("Saved screenshot '%s'", filename.c_str());

				return true;
			}
		} else if (event.kbd.hasFlags(Common::KBD_CTRL | Common::KBD_ALT)) {
			if (   event.kbd.keycode == Common::KEYCODE_PLUS || event.kbd.keycode == Common::KEYCODE_MINUS
			    || event.kbd.keycode == Common::KEYCODE_KP_PLUS || event.kbd.keycode == Common::KEYCODE_KP_MINUS) {
				// Ctrl+Alt+Plus/Minus Increase/decrease the size
				const int direction = (event.kbd.keycode == Common::KEYCODE_PLUS || event.kbd.keycode == Common::KEYCODE_KP_PLUS) ? +1 : -1;

				if (getFeatureState(OSystem::kFeatureFullscreenMode)) {
					// In case we are in fullscreen we will choose the previous
					// or next mode.

					// In case no modes are available we do nothing.
					if (_fullscreenVideoModes.empty()) {
						return true;
					}

					// Look for the current mode.
					VideoModeArray::const_iterator i = Common::find(_fullscreenVideoModes.begin(),
					                                                _fullscreenVideoModes.end(),
					                                                VideoMode(_desiredFullscreenWidth, _desiredFullscreenHeight));
					if (i == _fullscreenVideoModes.end()) {
						return true;
					}

					// Cycle through the modes in the specified direction.
					if (direction > 0) {
						++i;
						if (i == _fullscreenVideoModes.end()) {
							i = _fullscreenVideoModes.begin();
						}
					} else {
						if (i == _fullscreenVideoModes.begin()) {
							i = _fullscreenVideoModes.end();
						}
						--i;
					}

					_desiredFullscreenWidth  = i->width;
					_desiredFullscreenHeight = i->height;

					// Try to setup the mode.
					if (!setupMode(_lastRequestedWidth, _lastRequestedHeight)) {
						warning("OpenGLSdlGraphicsManager::notifyEvent: Fullscreen resize failed ('%s')", SDL_GetError());
						g_system->quit();
					}
				} else {
					// Calculate the next scaling setting. We approximate the
					// current scale setting in case the user resized the
					// window. Then we apply the direction change.
					_graphicsScale = MAX<int>(_hwScreen->w / _lastRequestedWidth, _hwScreen->h / _lastRequestedHeight);
					_graphicsScale = MAX<int>(_graphicsScale + direction, 1);

					// Since we overwrite a user resize here we reset its
					// flag here. This makes enabling AR smoother because it
					// will change the window size like in surface SDL.
					_gotResize = false;

					// Try to setup the mode.
					if (!setupMode(_lastRequestedWidth * _graphicsScale, _lastRequestedHeight * _graphicsScale)) {
						warning("OpenGLSdlGraphicsManager::notifyEvent: Window resize failed ('%s')", SDL_GetError());
						g_system->quit();
					}
				}

#ifdef USE_OSD
				const Common::String osdMsg = Common::String::format("Resolution: %dx%d", _hwScreen->w, _hwScreen->h);
				displayMessageOnOSD(osdMsg.c_str());
#endif

				return true;
			} else if (event.kbd.keycode == Common::KEYCODE_a) {
				// In case the user changed the window size manually we will
				// not change the window size again here.
				_ignoreLoadVideoMode = _gotResize;

				// Ctrl+Alt+a toggles the aspect ratio correction state.
				beginGFXTransaction();
					setFeatureState(OSystem::kFeatureAspectRatioCorrection, !getFeatureState(OSystem::kFeatureAspectRatioCorrection));
				endGFXTransaction();

				// Make sure we do not ignore the next resize. This
				// effectively checks whether loadVideoMode has been called.
				assert(!_ignoreLoadVideoMode);

#ifdef USE_OSD
				Common::String osdMsg = "Aspect ratio correction: ";
				osdMsg += getFeatureState(OSystem::kFeatureAspectRatioCorrection) ? "enabled" : "disabled";
				displayMessageOnOSD(osdMsg.c_str());
#endif

				return true;
			} else if (event.kbd.keycode == Common::KEYCODE_f) {
				// Ctrl+Alt+f toggles the graphics modes.

				// We are crazy we will allow the OpenGL base class to
				// introduce new graphics modes like shaders for special
				// filtering. If some other OpenGL subclass needs this,
				// we can think of refactoring this.
				int mode = getGraphicsMode();
				const OSystem::GraphicsMode *supportedModes = getSupportedGraphicsModes();
				const OSystem::GraphicsMode *modeDesc = nullptr;

				// Search the current mode.
				for (; supportedModes->name; ++supportedModes) {
					if (supportedModes->id == mode) {
						modeDesc = supportedModes;
						break;
					}
				}
				assert(modeDesc);

				// Try to use the next mode in the list.
				++modeDesc;
				if (!modeDesc->name) {
					modeDesc = getSupportedGraphicsModes();
				}

				// Never ever try to resize the window when we simply want to
				// switch the graphics mode. This assures that the window size
				// does not change.
				_ignoreLoadVideoMode = true;

				beginGFXTransaction();
					setGraphicsMode(modeDesc->id);
				endGFXTransaction();

				// Make sure we do not ignore the next resize. This
				// effectively checks whether loadVideoMode has been called.
				assert(!_ignoreLoadVideoMode);

#ifdef USE_OSD
				const Common::String osdMsg = Common::String::format("Graphics mode: %s", _(modeDesc->description));
				displayMessageOnOSD(osdMsg.c_str());
#endif

				return true;
			}
		}
		// Fall through

	default:
		return false;
	}
}
Beispiel #10
0
int main(int argc, char *argv[])
{
	float td;
	long then, lastFrameTime, frames;
	long expireTextTimer;
	SDL_Event event;
	
	memset(&app, 0, sizeof(App));
	memset(&dev, 0, sizeof(Dev));
	
	handleLoggingArgs(argc, argv);
	
	atexit(cleanup);

	srand(time(NULL));
	
	init18N(argc, argv);
	
	initLookups();

	initSDL();
	
	initGameSystem();
	
	createScreenshotFolder();
	
	if (fileExists(getSaveFilePath(SAVE_FILENAME)))
	{
		loadGame();
	}
	
	handleMissionArgs(argc, argv);
	
	dev.fps = frames = td = 0;
	then = SDL_GetTicks();
	lastFrameTime = SDL_GetTicks() + 1000;
	expireTextTimer = SDL_GetTicks() + (1000 * 10);
	
	while (1)
	{
		td += (SDL_GetTicks() - then);
		
		then = SDL_GetTicks();
		
		while (SDL_PollEvent(&event))
		{
			switch (event.type)
			{
				case SDL_MOUSEMOTION:
					doMouseMotion(&event.motion);
					break;
				
				case SDL_MOUSEWHEEL:
					doMouseWheel(&event.wheel);
					break;
				
				case SDL_MOUSEBUTTONDOWN:
					doMouseDown(&event.button);
					break;

				case SDL_MOUSEBUTTONUP:
					doMouseUp(&event.button);
					break;
				
				case SDL_KEYDOWN:
					doKeyDown(&event.key);
					break;
					
				case SDL_KEYUP:
					doKeyUp(&event.key);
					break;

				case SDL_QUIT:
					exit(0);
					break;
			}
		}
		
		if (app.modalDialog.type != MD_NONE)
		{
			doModalDialog();
		}
		
		while (td >= LOGIC_RATE)
		{
			/* let the delegate decide during logic() */
			app.doTrophyAlerts = 0;
			
			app.delegate.logic();
			
			td -= LOGIC_RATE;
			
			if (app.doTrophyAlerts)
			{
				doTrophyAlerts();
			}
			
			if (app.resetTimeDelta)
			{
				td = 0;
				then = SDL_GetTicks();
				app.resetTimeDelta = 0;
			}
			
			game.stats[STAT_TIME]++;
		}
		
		prepareScene();

		app.delegate.draw();
		
		if (app.doTrophyAlerts)
		{
			drawTrophyAlert();
		}
		
		if (app.modalDialog.type != MD_NONE)
		{
			drawModalDialog();
		}
		
		presentScene();
		
		doDevKeys();
		
		frames++;
		
		if (SDL_GetTicks() > lastFrameTime)
		{
			dev.fps = frames;
			frames = 0;
			lastFrameTime = SDL_GetTicks() + 1000;
			
			if (dev.takeScreenshots)
			{
				saveScreenshot();
			}
		}
		
		if (isControl(CONTROL_SCREENSHOT))
		{
			saveScreenshot();
			
			clearControl(CONTROL_SCREENSHOT);
		}
		
		if (SDL_GetTicks() > expireTextTimer)
		{
			expireTexts(0);
			
			expireTextTimer = SDL_GetTicks() + (1000 * 10);
		}
		
		/* don't save more than once per request, and not in the middle of battle */
		if (app.saveGame && battle.status != MS_IN_PROGRESS)
		{
			saveGame();
			app.saveGame = 0;
		}
		
		/* always zero the mouse motion */
		app.mouse.dx = app.mouse.dy = 0;

		SDL_Delay(1);
	}

	return 0;
}
bool OSystem_IPOD::pollEvent(Event &event) {
	SDL_Event ev;
	int axis;
	byte b = 0;

	handleKbdMouse();

	// If the screen mode changed, send an EVENT_SCREEN_CHANGED
	if (_modeChanged) {
		_modeChanged = false;
		event.type = EVENT_SCREEN_CHANGED;
		return true;
	}

	while(SDL_PollEvent(&ev)) {
		switch(ev.type) {
		case SDL_KEYDOWN:{
			b = event.kbd.flags = SDLModToOSystemKeyFlags(SDL_GetModState());

			// Alt-Return and Alt-Enter toggle full screen mode
			if (b == KBD_ALT && (ev.key.keysym.sym == SDLK_RETURN
			                  || ev.key.keysym.sym == SDLK_KP_ENTER)) {
				setFullscreenMode(!_fullscreen);
#ifdef USE_OSD
				if (_fullscreen)
					displayMessageOnOSD("Fullscreen mode");
				else
					displayMessageOnOSD("Windowed mode");
#endif

				break;
			}

			// Alt-S: Create a screenshot
			if (b == KBD_ALT && ev.key.keysym.sym == 's') {
				char filename[20];

				for (int n = 0;; n++) {
					SDL_RWops *file;

					sprintf(filename, "scummvm%05d.bmp", n);
					file = SDL_RWFromFile(filename, "r");
					if (!file)
						break;
					SDL_RWclose(file);
				}
				if (saveScreenshot(filename))
					printf("Saved '%s'\n", filename);
				else
					printf("Could not save screenshot!\n");
				break;
			}

			// Ctrl-m toggles mouse capture
			if (b == KBD_CTRL && ev.key.keysym.sym == 'm') {
				toggleMouseGrab();
				break;
			}

#ifdef MACOSX
			// On Macintosh', Cmd-Q quits
			if ((ev.key.keysym.mod & KMOD_META) && ev.key.keysym.sym == 'q') {
				event.type = EVENT_QUIT;
				return true;
			}
#elif defined(UNIX)
			// On other unices, Control-Q quits
			if ((ev.key.keysym.mod & KMOD_CTRL) && ev.key.keysym.sym == 'q') {
				event.type = EVENT_QUIT;
				return true;
			}
#else
			// Ctrl-z and Alt-X quit
			if ((b == KBD_CTRL && ev.key.keysym.sym == 'z') || (b == KBD_ALT && ev.key.keysym.sym == 'x')) {
				event.type = EVENT_QUIT;
				return true;
			}
#endif

			// Ctrl-Alt-<key> will change the GFX mode
			if ((b & (KBD_CTRL|KBD_ALT)) == (KBD_CTRL|KBD_ALT)) {

				handleScalerHotkeys(ev.key);
				break;
			}
			const bool event_complete = remapKey(ev,event);

			if (event_complete)
				return true;

			event.type = EVENT_KEYDOWN;
			event.kbd.keycode = ev.key.keysym.sym;
			event.kbd.ascii = mapKey(ev.key.keysym.sym, ev.key.keysym.mod, ev.key.keysym.unicode);

			return true;
			}
		case SDL_KEYUP:
			{
			const bool event_complete = remapKey(ev,event);

			if (event_complete)
				return true;

			event.type = EVENT_KEYUP;
			event.kbd.keycode = ev.key.keysym.sym;
			event.kbd.ascii = mapKey(ev.key.keysym.sym, ev.key.keysym.mod, ev.key.keysym.unicode);
			b = event.kbd.flags = SDLModToOSystemKeyFlags(SDL_GetModState());

			// Ctrl-Alt-<key> will change the GFX mode
			if ((b & (KBD_CTRL|KBD_ALT)) == (KBD_CTRL|KBD_ALT)) {
				// Swallow these key up events
				break;
			}

			return true;
			}
		case SDL_MOUSEMOTION:
			event.type = EVENT_MOUSEMOVE;
			fillMouseEvent(event, ev.motion.x, ev.motion.y);

			setMousePos(event.mouse.x, event.mouse.y);
			return true;

		case SDL_MOUSEBUTTONDOWN:
			if (ev.button.button == SDL_BUTTON_LEFT)
				event.type = EVENT_LBUTTONDOWN;
			else if (ev.button.button == SDL_BUTTON_RIGHT)
				event.type = EVENT_RBUTTONDOWN;
#if defined(SDL_BUTTON_WHEELUP) && defined(SDL_BUTTON_WHEELDOWN)
			else if (ev.button.button == SDL_BUTTON_WHEELUP)
				event.type = EVENT_WHEELUP;
			else if (ev.button.button == SDL_BUTTON_WHEELDOWN)
				event.type = EVENT_WHEELDOWN;
#endif
			else
				break;

			fillMouseEvent(event, ev.button.x, ev.button.y);

			return true;

		case SDL_MOUSEBUTTONUP:
			if (ev.button.button == SDL_BUTTON_LEFT)
				event.type = EVENT_LBUTTONUP;
			else if (ev.button.button == SDL_BUTTON_RIGHT)
				event.type = EVENT_RBUTTONUP;
			else
				break;
			fillMouseEvent(event, ev.button.x, ev.button.y);

			return true;

		case SDL_JOYBUTTONDOWN:
			if (ev.jbutton.button == JOY_BUT_LMOUSE) {
				event.type = EVENT_LBUTTONDOWN;
				fillMouseEvent(event, _km.x, _km.y);
			} else if (ev.jbutton.button == JOY_BUT_RMOUSE) {
				event.type = EVENT_RBUTTONDOWN;
				fillMouseEvent(event, _km.x, _km.y);
			} else {
				event.type = EVENT_KEYDOWN;
				switch (ev.jbutton.button) {
					case JOY_BUT_ESCAPE:
						event.kbd.keycode = SDLK_ESCAPE;
						event.kbd.ascii = mapKey(SDLK_ESCAPE, ev.key.keysym.mod, 0);
						break;
					case JOY_BUT_PERIOD:
						event.kbd.keycode = SDLK_PERIOD;
						event.kbd.ascii = mapKey(SDLK_PERIOD, ev.key.keysym.mod, 0);
						break;
					case JOY_BUT_SPACE:
						event.kbd.keycode = SDLK_SPACE;
						event.kbd.ascii = mapKey(SDLK_SPACE, ev.key.keysym.mod, 0);
						break;
					case JOY_BUT_F5:
						event.kbd.keycode = SDLK_F5;
						event.kbd.ascii = mapKey(SDLK_F5, ev.key.keysym.mod, 0);
						break;
				}
			}
			return true;

		case SDL_JOYBUTTONUP:
			if (ev.jbutton.button == JOY_BUT_LMOUSE) {
				event.type = EVENT_LBUTTONUP;
				fillMouseEvent(event, _km.x, _km.y);
			} else if (ev.jbutton.button == JOY_BUT_RMOUSE) {
				event.type = EVENT_RBUTTONUP;
				fillMouseEvent(event, _km.x, _km.y);
			} else {
				event.type = EVENT_KEYUP;
				switch (ev.jbutton.button) {
					case JOY_BUT_ESCAPE:
						event.kbd.keycode = SDLK_ESCAPE;
						event.kbd.ascii = mapKey(SDLK_ESCAPE, ev.key.keysym.mod, 0);
						break;
					case JOY_BUT_PERIOD:
						event.kbd.keycode = SDLK_PERIOD;
						event.kbd.ascii = mapKey(SDLK_PERIOD, ev.key.keysym.mod, 0);
						break;
					case JOY_BUT_SPACE:
						event.kbd.keycode = SDLK_SPACE;
						event.kbd.ascii = mapKey(SDLK_SPACE, ev.key.keysym.mod, 0);
						break;
					case JOY_BUT_F5:
						event.kbd.keycode = SDLK_F5;
						event.kbd.ascii = mapKey(SDLK_F5, ev.key.keysym.mod, 0);
						break;
				}
			}
			return true;

		case SDL_JOYAXISMOTION:
			axis = ev.jaxis.value;
			if ( axis > JOY_DEADZONE) {
				axis -= JOY_DEADZONE;
				event.type = EVENT_MOUSEMOVE;
			} else if ( axis < -JOY_DEADZONE ) {
				axis += JOY_DEADZONE;
				event.type = EVENT_MOUSEMOVE;
			} else
				axis = 0;

			if ( ev.jaxis.axis == JOY_XAXIS) {
#ifdef JOY_ANALOG
				_km.x_vel = axis/2000;
				_km.x_down_count = 0;
#else
				if (axis != 0) {
					_km.x_vel = (axis > 0) ? 1:-1;
					_km.x_down_count = 1;
				} else {
					_km.x_vel = 0;
					_km.x_down_count = 0;
				}
#endif

			} else if (ev.jaxis.axis == JOY_YAXIS) {
#ifndef JOY_INVERT_Y
				axis = -axis;
#endif
#ifdef JOY_ANALOG
				_km.y_vel = -axis / 2000;
				_km.y_down_count = 0;
#else
				if (axis != 0) {
					_km.y_vel = (-axis > 0) ? 1: -1;
					_km.y_down_count = 1;
				} else {
					_km.y_vel = 0;
					_km.y_down_count = 0;
				}
#endif
			}

			fillMouseEvent(event, _km.x, _km.y);

			return true;

		case SDL_VIDEOEXPOSE:
			_forceFull = true;
			break;

		case SDL_QUIT:
			event.type = EVENT_QUIT;
			return true;
		}
	}
	return false;
}
Beispiel #12
0
/*
	doIdle - The idle-function that can be used to update the screen
*/
void doIdle()
{
	if (g_bRayTrace)
	{
		g_ScreenBuffer[g_Y][g_X] = g_RayTrace.CalculatePixel (g_X, g_Y);

		//printf ("Drawing %d, %d\n", g_X, g_Y);

		// Move to the next pixel
		g_X++;
		if (g_X >= Scene::WINDOW_WIDTH)
		{
			// Move to the next row
			g_X = 0;
			g_Y++;

			/* You can uncomment the next line 
				to see the raytrace "in-action" */
			glutPostRedisplay();
		}

		// Check for the end of the screen
		if (g_Y >= Scene::WINDOW_HEIGHT)
		{
			g_bRayTrace = false;
			glutPostRedisplay ();

			if (recording)
			{
				// ** Save frame
				std::string fileName ("frame_" + std::to_string(frame) +".jpg");
				char *file = const_cast<char*>(fileName.c_str());
				saveScreenshot(file);
				++frame;

				// ** Move to the next position
				Vector dir = g_RayTrace.m_Scene.m_Camera.GetTarget() - g_RayTrace.m_Scene.m_Camera.GetPosition();
				float tar_posDist = dir.Magnitude();
				dir.Normalize();
				Vector right = dir.Cross(g_RayTrace.m_Scene.m_Camera.GetUp());
				Vector tempVec;
				float turnSpeed = 0.01f;
				// - Turn Left -
				// Simulate a Left-Turn by finding a position just a little to the left of the direction
				tempVec = dir - right * turnSpeed;
				tempVec.Normalize();
				g_RayTrace.m_Scene.m_Camera.SetTarget(g_RayTrace.m_Scene.m_Camera.GetPosition() + tempVec * tar_posDist);

				// ** Start rendering again
				g_X = 0;
				g_Y = 0;
				g_bRayTrace = true;

				// ** Finish check
				if (frame > 650)
				{
					recording = false;
					g_bRayTrace = false;
				}
			}
		}
	}
	else
	{
		glutPostRedisplay ();
	}
}
bool OpenGLSdlGraphicsManager::notifyEvent(const Common::Event &event) {
	switch ((int)event.type) {
	case Common::EVENT_KEYDOWN:
		if (event.kbd.hasFlags(Common::KBD_ALT)) {
			// Alt-Return and Alt-Enter toggle full screen mode
			if (event.kbd.keycode == Common::KEYCODE_RETURN ||
				event.kbd.keycode == (Common::KeyCode)SDLK_KP_ENTER) {
				toggleFullScreen(0);
				return true;
			}

			// Alt-S create a screenshot
			if (event.kbd.keycode == 's') {
				char filename[20];

				for (int n = 0;; n++) {
					SDL_RWops *file;

					sprintf(filename, "scummvm%05d.bmp", n);
					file = SDL_RWFromFile(filename, "r");
					if (!file)
						break;
					SDL_RWclose(file);
				}
				if (saveScreenshot(filename))
					debug("Saved screenshot '%s'", filename);
				else
					warning("Could not save screenshot");
				return true;
			}
		}

		if (event.kbd.hasFlags(Common::KBD_CTRL|Common::KBD_ALT)) {
			// Ctrl-Alt-Return and Ctrl-Alt-Enter switch between full screen modes
			if (event.kbd.keycode == Common::KEYCODE_RETURN ||
				event.kbd.keycode == (Common::KeyCode)SDLK_KP_ENTER) {
				toggleFullScreen(1);
				return true;
			}

			// Ctrl-Alt-a switch between display modes
			if (event.kbd.keycode == 'a') {
				beginGFXTransaction();
					setFeatureState(OSystem::kFeatureAspectRatioCorrection, !getFeatureState(OSystem::kFeatureAspectRatioCorrection));
				endGFXTransaction();
#ifdef USE_OSD
			char buffer[128];
			if (getFeatureState(OSystem::kFeatureAspectRatioCorrection))
				sprintf(buffer, "Enabled aspect ratio correction\n%d x %d -> %d x %d",
				        _videoMode.screenWidth, _videoMode.screenHeight,
				        _hwscreen->w, _hwscreen->h);
			else
				sprintf(buffer, "Disabled aspect ratio correction\n%d x %d -> %d x %d",
				        _videoMode.screenWidth, _videoMode.screenHeight,
				        _hwscreen->w, _hwscreen->h);
			displayMessageOnOSD(buffer);
#endif
				internUpdateScreen();
				return true;
			}

			// Ctrl-Alt-f toggles antialiasing
			if (event.kbd.keycode == 'f') {
				beginGFXTransaction();
					toggleAntialiasing();
				endGFXTransaction();

#ifdef USE_OSD
				// TODO: This makes guesses about what internal antialiasing
				// modes we use, we might want to consider a better way of
				// displaying information to the user.
				if (getAntialiasingState())
					displayMessageOnOSD("Active filter mode: Linear");
				else
					displayMessageOnOSD("Active filter mode: Nearest");
#endif
				return true;
			}

			SDLKey sdlKey = (SDLKey)event.kbd.keycode;

			// Ctrl+Alt+Plus/Minus Increase/decrease the scale factor
			if ((sdlKey == SDLK_EQUALS || sdlKey == SDLK_PLUS || sdlKey == SDLK_MINUS ||
				sdlKey == SDLK_KP_PLUS || sdlKey == SDLK_KP_MINUS)) {
				int factor = getScale();
				factor += (sdlKey == SDLK_MINUS || sdlKey == SDLK_KP_MINUS) ? -1 : +1;
				if (0 < factor && factor < 4) {
					// Check if the desktop resolution has been detected
					if (_desktopWidth > 0 && _desktopHeight > 0)
						// If the new scale factor is too big, do not scale
						if (_videoMode.screenWidth * factor > _desktopWidth || 
							_videoMode.screenHeight * factor > _desktopHeight)
							return false;

					beginGFXTransaction();
						setScale(factor);
					endGFXTransaction();
#ifdef USE_OSD
					displayScaleChangedMsg();
#endif
					return true;
				}
			}

			const bool isNormalNumber = (SDLK_1 <= sdlKey && sdlKey <= SDLK_3);
			const bool isKeypadNumber = (SDLK_KP1 <= sdlKey && sdlKey <= SDLK_KP3);

			// Ctrl-Alt-<number key> will change the GFX mode
			if (isNormalNumber || isKeypadNumber) {
				if (sdlKey - (isNormalNumber ? SDLK_1 : SDLK_KP1) <= 3) {
#ifdef USE_OSD
					int lastMode = _videoMode.mode;
#endif
					// We need to query the scale and set it up, because
					// setGraphicsMode sets the default scale to 2
					int oldScale = getScale();
					beginGFXTransaction();
						setGraphicsMode(sdlKey - (isNormalNumber ? SDLK_1 : SDLK_KP1));
						setScale(oldScale);
					endGFXTransaction();
#ifdef USE_OSD
					if (lastMode != _videoMode.mode)
						displayModeChangedMsg();
#endif
					internUpdateScreen();
				}
			}
		}

		if (event.kbd.hasFlags(Common::KBD_CTRL|Common::KBD_SHIFT)) {
			// Ctrl-Shift-Return and Ctrl-Shift-Enter switch backwards between full screen modes
			if (event.kbd.keycode == Common::KEYCODE_RETURN ||
				event.kbd.keycode == (Common::KeyCode)SDLK_KP_ENTER) {
				toggleFullScreen(-1);
				return true;
			}
		}
		break;
	case Common::EVENT_KEYUP:
		return isHotkey(event);
	// HACK: Handle special SDL event 
	// The new screen size is saved on the mouse event as part of HACK,
	// there is no common resize event.
	case OSystem_SDL::kSdlEventResize:
		// Do not resize if ignoring resize events.
		if (!_ignoreResizeFrames && !getFullscreenMode()) {
			bool scaleChanged = false;
			beginGFXTransaction();
				_videoMode.hardwareWidth = event.mouse.x;
				_videoMode.hardwareHeight = event.mouse.y;

				if (_videoMode.mode != OpenGL::GFX_ORIGINAL) {
					_screenResized = true;
					calculateDisplaySize(_videoMode.hardwareWidth, _videoMode.hardwareHeight);
				}

				int scale = MIN(_videoMode.hardwareWidth / _videoMode.screenWidth,
				                _videoMode.hardwareHeight / _videoMode.screenHeight);

				if (getScale() != scale) {
					scaleChanged = true;
					setScale(MAX(MIN(scale, 3), 1));
				}

				if (_videoMode.mode == OpenGL::GFX_ORIGINAL) {
					calculateDisplaySize(_videoMode.hardwareWidth, _videoMode.hardwareHeight);
				}

				_transactionDetails.sizeChanged = true;
			endGFXTransaction();
#ifdef USE_OSD
			if (scaleChanged)
				displayScaleChangedMsg();
#endif
		}
		return true;

	default:
		break;
	}

	return OpenGLGraphicsManager::notifyEvent(event);
}
bool OpenGLSdlGraphicsManager::notifyEvent(const Common::Event &event) {
	switch ((int)event.type) {
	case Common::EVENT_KEYDOWN:
		if (event.kbd.hasFlags(Common::KBD_ALT)) {
			// Alt-Return and Alt-Enter toggle full screen mode
			if (event.kbd.keycode == Common::KEYCODE_RETURN ||
				event.kbd.keycode == (Common::KeyCode)SDLK_KP_ENTER) {
				toggleFullScreen(0);
				return true;
			}

			// Alt-S create a screenshot
			if (event.kbd.keycode == 's') {
				char filename[20];

				for (int n = 0;; n++) {
					SDL_RWops *file;

					sprintf(filename, "scummvm%05d.bmp", n);
					file = SDL_RWFromFile(filename, "r");
					if (!file)
						break;
					SDL_RWclose(file);
				}
				if (saveScreenshot(filename))
					printf("Saved '%s'\n", filename);
				else
					printf("Could not save screenshot!\n");
				return true;
			}
		}

		if (event.kbd.hasFlags(Common::KBD_CTRL|Common::KBD_ALT)) {
			// Ctrl-Alt-Return and Ctrl-Alt-Enter switch between full screen modes
			if (event.kbd.keycode == Common::KEYCODE_RETURN ||
				event.kbd.keycode == (Common::KeyCode)SDLK_KP_ENTER) {
				toggleFullScreen(1);
				return true;
			}

			// Ctrl-Alt-a switch between display modes
			if (event.kbd.keycode == 'a') {
				beginGFXTransaction();
					switchDisplayMode(-1);
				endGFXTransaction();
#ifdef USE_OSD
				displayModeChangedMsg();
#endif
				internUpdateScreen();
				return true;
			}

			// Ctrl-Alt-f toggles antialiasing
			if (event.kbd.keycode == 'f') {
				beginGFXTransaction();
					_videoMode.antialiasing = !_videoMode.antialiasing;
					_transactionDetails.filterChanged = true;
				endGFXTransaction();
#ifdef USE_OSD
				if (_videoMode.antialiasing)
					displayMessageOnOSD("Active filter mode: Linear");
				else
					displayMessageOnOSD("Active filter mode: Nearest");
#endif
				return true;
			}

			SDLKey sdlKey = (SDLKey)event.kbd.keycode;

			// Ctrl+Alt+Plus/Minus Increase/decrease the scale factor
			if ((sdlKey == SDLK_EQUALS || sdlKey == SDLK_PLUS || sdlKey == SDLK_MINUS ||
				sdlKey == SDLK_KP_PLUS || sdlKey == SDLK_KP_MINUS)) {
				int factor = _videoMode.scaleFactor;
				factor += (sdlKey == SDLK_MINUS || sdlKey == SDLK_KP_MINUS) ? -1 : +1;
				if (0 < factor && factor < 4) {
					// Check if the desktop resolution has been detected
					if (_desktopWidth > 0 && _desktopHeight > 0)
						// If the new scale factor is too big, do not scale
						if (_videoMode.screenWidth * factor > _desktopWidth || 
							_videoMode.screenHeight * factor > _desktopHeight)
							return false;

					beginGFXTransaction();
						setScale(factor);
					endGFXTransaction();
#ifdef USE_OSD
					displayScaleChangedMsg();
#endif
					return true;
				}
			}

			const bool isNormalNumber = (SDLK_1 <= sdlKey && sdlKey <= SDLK_4);
			const bool isKeypadNumber = (SDLK_KP1 <= sdlKey && sdlKey <= SDLK_KP4);

			// Ctrl-Alt-<number key> will change the GFX mode
			if (isNormalNumber || isKeypadNumber) {
				if (sdlKey - (isNormalNumber ? SDLK_1 : SDLK_KP1) <= 4) {
					int lastMode = _videoMode.mode;
					beginGFXTransaction();
						_videoMode.mode = sdlKey - (isNormalNumber ? SDLK_1 : SDLK_KP1);
						_transactionDetails.needRefresh = true;
						_aspectRatioCorrection = false;
					endGFXTransaction();
#ifdef USE_OSD
					if (lastMode != _videoMode.mode)
						displayModeChangedMsg();
#endif
					internUpdateScreen();
				}
			}
		}

		if (event.kbd.hasFlags(Common::KBD_CTRL|Common::KBD_SHIFT)) {
			// Ctrl-Shift-Return and Ctrl-Shift-Enter switch backwards between full screen modes
			if (event.kbd.keycode == Common::KEYCODE_RETURN ||
				event.kbd.keycode == (Common::KeyCode)SDLK_KP_ENTER) {
				toggleFullScreen(-1);
				return true;
			}

			// Ctrl-Shift-a switch backwards between display modes
			if (event.kbd.keycode == 'a') {
				beginGFXTransaction();
					switchDisplayMode(-2);
				endGFXTransaction();
#ifdef USE_OSD
				displayModeChangedMsg();
#endif
				internUpdateScreen();
				return true;
			}
		}
		break;
	case Common::EVENT_KEYUP:
		return isHotkey(event);
	// HACK: Handle special SDL event 
	// The new screen size is saved on the mouse event as part of HACK,
	// there is no common resize event.
	case OSystem_SDL::kSdlEventResize:
		// Do not resize if ignoring resize events.
		if (!_ignoreResizeFrames && !_videoMode.fullscreen) {
			bool scaleChanged = false;
			beginGFXTransaction();
				_videoMode.hardwareWidth = event.mouse.x;
				_videoMode.hardwareHeight = event.mouse.y;

				if (_videoMode.mode != OpenGL::GFX_ORIGINAL) {
					_screenResized = true;
					calculateDisplaySize(_videoMode.hardwareWidth, _videoMode.hardwareHeight);
				}

				int scale = MIN(_videoMode.hardwareWidth / _videoMode.screenWidth,
							_videoMode.hardwareHeight / _videoMode.screenHeight);
				if (_videoMode.scaleFactor != scale) {
					scaleChanged = true;
					_videoMode.scaleFactor = MAX(MIN(scale, 3), 1);
				}

				if (_videoMode.mode == OpenGL::GFX_ORIGINAL) {
					calculateDisplaySize(_videoMode.hardwareWidth, _videoMode.hardwareHeight);
				}

				_transactionDetails.sizeChanged = true;
			endGFXTransaction();
#ifdef USE_OSD
			if (scaleChanged)
				displayScaleChangedMsg();
#endif
		}
		return true;

	default:
		break;
	}

	return OpenGLGraphicsManager::notifyEvent(event);
}
Beispiel #15
0
MainWindow::MainWindow() : QbWindow(config.geometry.mainWindow) {
  setObjectName("main-window");
  setWindowTitle(utf8() << bsnesTitle << " v" << bsnesVersion);

  //menu bar
  #if defined(PLATFORM_OSX)
  menuBar = new QMenuBar(0);
  #else
  menuBar = new QMenuBar;
  #endif

  system = menuBar->addMenu("System");
    system_load = system->addAction("Load Cartridge ...");
    system_load->setIcon(QIcon(":/16x16/document-open.png"));
    system_loadSpecial = system->addMenu("Load Special");
    system_loadSpecial->setIcon(QIcon(":/16x16/document-open.png"));
      system_loadSpecial_bsxSlotted = system_loadSpecial->addAction("Load BS-X Slotted Cartridge ...");
      system_loadSpecial_bsxSlotted->setIcon(QIcon(":/16x16/document-open.png"));
      system_loadSpecial_bsx = system_loadSpecial->addAction("Load BS-X Cartridge ...");
      system_loadSpecial_bsx->setIcon(QIcon(":/16x16/document-open.png"));
      system_loadSpecial_sufamiTurbo = system_loadSpecial->addAction("Load Sufami Turbo Cartridge ...");
      system_loadSpecial_sufamiTurbo->setIcon(QIcon(":/16x16/document-open.png"));
      system_loadSpecial_superGameBoy = system_loadSpecial->addAction("Load Super Game Boy Cartridge ...");
      system_loadSpecial_superGameBoy->setIcon(QIcon(":/16x16/document-open.png"));
    system->addSeparator();
    system->addAction(system_power = new QbCheckAction("Power", 0));
    system_reset = system->addAction("Reset");
    system_reset->setIcon(QIcon(":/16x16/view-refresh.png"));
    system->addSeparator();
    system_port1 = system->addMenu("Controller Port 1");
    system_port1->setIcon(QIcon(":/16x16/input-gaming.png"));
      system_port1->addAction(system_port1_none = new QbRadioAction("None", 0));
      system_port1->addAction(system_port1_joypad = new QbRadioAction("Joypad", 0));
      system_port1->addAction(system_port1_multitap = new QbRadioAction("Multitap", 0));
      system_port1->addAction(system_port1_mouse = new QbRadioAction("Mouse", 0));
    system_port2 = system->addMenu("Controller Port 2");
    system_port2->setIcon(QIcon(":/16x16/input-gaming.png"));
      system_port2->addAction(system_port2_none = new QbRadioAction("None", 0));
      system_port2->addAction(system_port2_joypad = new QbRadioAction("Joypad", 0));
      system_port2->addAction(system_port2_multitap = new QbRadioAction("Multitap", 0));
      system_port2->addAction(system_port2_mouse = new QbRadioAction("Mouse", 0));
      system_port2->addAction(system_port2_superscope = new QbRadioAction("Super Scope", 0));
      system_port2->addAction(system_port2_justifier = new QbRadioAction("Justifier", 0));
      system_port2->addAction(system_port2_justifiers = new QbRadioAction("Two Justifiers", 0));
    #if !defined(PLATFORM_OSX)
    system->addSeparator();
    #endif
    system_exit = system->addAction("Exit");
    system_exit->setIcon(QIcon(":/16x16/process-stop.png"));
    system_exit->setMenuRole(QAction::QuitRole);

  settings = menuBar->addMenu("Settings");
    settings_videoMode = settings->addMenu("Video Mode");
    settings_videoMode->setIcon(QIcon(":/16x16/video-display.png"));
      settings_videoMode->addAction(settings_videoMode_1x = new QbRadioAction("Scale 1x", 0));
      settings_videoMode->addAction(settings_videoMode_2x = new QbRadioAction("Scale 2x", 0));
      settings_videoMode->addAction(settings_videoMode_3x = new QbRadioAction("Scale 3x", 0));
      settings_videoMode->addAction(settings_videoMode_4x = new QbRadioAction("Scale 4x", 0));
      settings_videoMode->addAction(settings_videoMode_max = new QbRadioAction("Scale Max", 0));
      settings_videoMode->addSeparator();
      settings_videoMode->addAction(settings_videoMode_correctAspectRatio = new QbCheckAction("Correct Aspect Ratio", 0));
      settings_videoMode->addAction(settings_videoMode_fullscreen = new QbCheckAction("Fullscreen", 0));
      settings_videoMode->addSeparator();
      settings_videoMode->addAction(settings_videoMode_ntsc = new QbRadioAction("NTSC", 0));
      settings_videoMode->addAction(settings_videoMode_pal = new QbRadioAction("PAL", 0));

    if(filter.opened()) {
      settings_videoFilter = settings->addMenu("Video Filter");
      settings_videoFilter->setIcon(QIcon(":/16x16/image-x-generic.png"));

      settings_videoFilter_configure = settings_videoFilter->addAction("Configure Active Filter ...");
      settings_videoFilter_configure->setIcon(QIcon(":/16x16/preferences-desktop.png"));
      settings_videoFilter->addSeparator();

      settings_videoFilter->addAction(settings_videoFilter_none = new QbRadioAction("None", 0));
      settings_videoFilter_list.add(settings_videoFilter_none);

      lstring filterlist;
      filterlist.split(";", filter.dl_supported());
      for(unsigned i = 0; i < filterlist.size(); i++) {
        QbRadioAction *action = new QbRadioAction(utf8() << filterlist[i], 0);
        settings_videoFilter->addAction(action);
        settings_videoFilter_list.add(action);
      }
    }

    settings->addAction(settings_smoothVideo = new QbCheckAction("Smooth Video Output", 0));
    settings->addSeparator();
    settings->addAction(settings_muteAudio = new QbCheckAction("Mute Audio Output", 0));
    settings->addSeparator();
    settings_emulationSpeed = settings->addMenu("Emulation Speed");
    settings_emulationSpeed->setIcon(QIcon(":/16x16/appointment-new.png"));
      settings_emulationSpeed->addAction(settings_emulationSpeed_slowest = new QbRadioAction("50%", 0));
      settings_emulationSpeed->addAction(settings_emulationSpeed_slow = new QbRadioAction("75%", 0));
      settings_emulationSpeed->addAction(settings_emulationSpeed_normal = new QbRadioAction("100%", 0));
      settings_emulationSpeed->addAction(settings_emulationSpeed_fast = new QbRadioAction("150%", 0));
      settings_emulationSpeed->addAction(settings_emulationSpeed_fastest = new QbRadioAction("200%", 0));
      settings_emulationSpeed->addSeparator();
      settings_emulationSpeed->addAction(settings_emulationSpeed_syncVideo = new QbCheckAction("Sync Video", 0));
      settings_emulationSpeed->addAction(settings_emulationSpeed_syncAudio = new QbCheckAction("Sync Audio", 0));
    settings_configuration = settings->addAction("Configuration ...");
    settings_configuration->setIcon(QIcon(":/16x16/preferences-desktop.png"));
    settings_configuration->setMenuRole(QAction::PreferencesRole);

  tools = menuBar->addMenu("Tools");
    tools_cheatEditor = tools->addAction("Cheat Editor ...");
    tools_cheatEditor->setIcon(QIcon(":/16x16/accessories-text-editor.png"));
    tools_cheatFinder = tools->addAction("Cheat Finder ...");
    tools_cheatFinder->setIcon(QIcon(":/16x16/system-search.png"));
    tools_stateManager = tools->addAction("State Manager ...");
    tools_stateManager->setIcon(QIcon(":/16x16/system-file-manager.png"));
    tools->addSeparator();
    tools_captureScreenshot = tools->addAction("Capture Screenshot");
    tools_captureScreenshot->setIcon(QIcon(":/16x16/image-x-generic.png"));
    tools_debugger = tools->addAction("Debugger ...");
    tools_debugger->setIcon(QIcon(":/16x16/utilities-terminal.png"));
    #if !defined(DEBUGGER)
    tools_debugger->setVisible(false);
    #endif

  help = menuBar->addMenu("Help");
    help_documentation = help->addAction("Documentation ...");
    help_documentation->setIcon(QIcon(":/16x16/text-x-generic.png"));
    help_license = help->addAction("License ...");
    help_license->setIcon(QIcon(":/16x16/text-x-generic.png"));
    #if !defined(PLATFORM_OSX)
    help->addSeparator();
    #endif
    help_about = help->addAction("About ...");
    help_about->setIcon(QIcon(":/16x16/help-browser.png"));
    help_about->setMenuRole(QAction::AboutRole);

  //canvas
  canvasContainer = new CanvasObject;
  canvasContainer->setAcceptDrops(true); {
    canvasContainer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    canvasContainer->setObjectName("backdrop");

    canvasLayout = new QVBoxLayout; {
      canvasLayout->setMargin(0);
      canvasLayout->setAlignment(Qt::AlignCenter);

      canvas = new CanvasWidget;
      canvas->setAcceptDrops(true);
      canvas->setFocusPolicy(Qt::StrongFocus);
      canvas->setAttribute(Qt::WA_PaintOnScreen, true);  //disable Qt painting on focus / resize

      QPalette palette;
      palette.setColor(QPalette::Window, QColor(0, 0, 0));
      canvas->setPalette(palette);
      canvas->setAutoFillBackground(true);
    }
    canvasLayout->addWidget(canvas);
  }
  canvasContainer->setLayout(canvasLayout);

  //status bar
  statusBar = new QStatusBar;
  statusBar->showMessage("");
  systemState = new QLabel;
  statusBar->addPermanentWidget(systemState);

  //layout
  layout = new QVBoxLayout;
  layout->setMargin(0);
  layout->setSpacing(0);
  #if !defined(PLATFORM_OSX)
  layout->addWidget(menuBar);
  #endif
  layout->addWidget(canvasContainer);
  layout->addWidget(statusBar);
  setLayout(layout);

  //slots
  connect(system_load, SIGNAL(triggered()), this, SLOT(loadCartridge()));
  connect(system_loadSpecial_bsxSlotted, SIGNAL(triggered()), this, SLOT(loadBsxSlottedCartridge()));
  connect(system_loadSpecial_bsx, SIGNAL(triggered()), this, SLOT(loadBsxCartridge()));
  connect(system_loadSpecial_sufamiTurbo, SIGNAL(triggered()), this, SLOT(loadSufamiTurboCartridge()));
  connect(system_loadSpecial_superGameBoy, SIGNAL(triggered()), this, SLOT(loadSuperGameBoyCartridge()));
  connect(system_power, SIGNAL(triggered()), this, SLOT(power()));
  connect(system_reset, SIGNAL(triggered()), this, SLOT(reset()));
  connect(system_port1_none, SIGNAL(triggered()), this, SLOT(setPort1None()));
  connect(system_port1_joypad, SIGNAL(triggered()), this, SLOT(setPort1Joypad()));
  connect(system_port1_multitap, SIGNAL(triggered()), this, SLOT(setPort1Multitap()));
  connect(system_port1_mouse, SIGNAL(triggered()), this, SLOT(setPort1Mouse()));
  connect(system_port2_none, SIGNAL(triggered()), this, SLOT(setPort2None()));
  connect(system_port2_joypad, SIGNAL(triggered()), this, SLOT(setPort2Joypad()));
  connect(system_port2_multitap, SIGNAL(triggered()), this, SLOT(setPort2Multitap()));
  connect(system_port2_mouse, SIGNAL(triggered()), this, SLOT(setPort2Mouse()));
  connect(system_port2_superscope, SIGNAL(triggered()), this, SLOT(setPort2SuperScope()));
  connect(system_port2_justifier, SIGNAL(triggered()), this, SLOT(setPort2Justifier()));
  connect(system_port2_justifiers, SIGNAL(triggered()), this, SLOT(setPort2Justifiers()));
  connect(system_exit, SIGNAL(triggered()), this, SLOT(quit()));
  connect(settings_videoMode_1x, SIGNAL(triggered()), this, SLOT(setVideoMode1x()));
  connect(settings_videoMode_2x, SIGNAL(triggered()), this, SLOT(setVideoMode2x()));
  connect(settings_videoMode_3x, SIGNAL(triggered()), this, SLOT(setVideoMode3x()));
  connect(settings_videoMode_4x, SIGNAL(triggered()), this, SLOT(setVideoMode4x()));
  connect(settings_videoMode_max, SIGNAL(triggered()), this, SLOT(setVideoModeMax()));
  connect(settings_videoMode_correctAspectRatio, SIGNAL(triggered()), this, SLOT(toggleAspectCorrection()));
  connect(settings_videoMode_fullscreen, SIGNAL(triggered()), this, SLOT(toggleFullscreen()));
  connect(settings_videoMode_ntsc, SIGNAL(triggered()), this, SLOT(setVideoNtsc()));
  connect(settings_videoMode_pal, SIGNAL(triggered()), this, SLOT(setVideoPal()));
  if(filter.opened()) {
    connect(settings_videoFilter_configure, SIGNAL(triggered()), this, SLOT(configureFilter()));
    for(unsigned i = 0; i < settings_videoFilter_list.size(); i++) {
      connect(settings_videoFilter_list[i], SIGNAL(triggered()), this, SLOT(setFilter()));
    }
  }
  connect(settings_smoothVideo, SIGNAL(triggered()), this, SLOT(toggleSmoothVideo()));
  connect(settings_muteAudio, SIGNAL(triggered()), this, SLOT(muteAudio()));
  connect(settings_emulationSpeed_slowest, SIGNAL(triggered()), this, SLOT(setSpeedSlowest()));
  connect(settings_emulationSpeed_slow, SIGNAL(triggered()), this, SLOT(setSpeedSlow()));
  connect(settings_emulationSpeed_normal, SIGNAL(triggered()), this, SLOT(setSpeedNormal()));
  connect(settings_emulationSpeed_fast, SIGNAL(triggered()), this, SLOT(setSpeedFast()));
  connect(settings_emulationSpeed_fastest, SIGNAL(triggered()), this, SLOT(setSpeedFastest()));
  connect(settings_emulationSpeed_syncVideo, SIGNAL(triggered()), this, SLOT(syncVideo()));
  connect(settings_emulationSpeed_syncAudio, SIGNAL(triggered()), this, SLOT(syncAudio()));
  connect(settings_configuration, SIGNAL(triggered()), this, SLOT(showConfigWindow()));
  connect(tools_cheatEditor, SIGNAL(triggered()), this, SLOT(showCheatEditor()));
  connect(tools_cheatFinder, SIGNAL(triggered()), this, SLOT(showCheatFinder()));
  connect(tools_stateManager, SIGNAL(triggered()), this, SLOT(showStateManager()));
  connect(tools_captureScreenshot, SIGNAL(triggered()), this, SLOT(saveScreenshot()));
  connect(tools_debugger, SIGNAL(triggered()), this, SLOT(showDebugger()));
  connect(help_documentation, SIGNAL(triggered()), this, SLOT(showDocumentation()));
  connect(help_license, SIGNAL(triggered()), this, SLOT(showLicense()));
  connect(help_about, SIGNAL(triggered()), this, SLOT(showAbout()));

  syncUi();
}
Beispiel #16
0
MainWindow::MainWindow() {
  setObjectName("main-window");
  setWindowTitle(string() << SNES::Info::Name << " v" << SNES::Info::Version);
  setCloseOnEscape(false);
  setGeometryString(&config().geometry.mainWindow);
  application.windowList.append(this);

  //menu bar
  #if defined(PLATFORM_OSX)
  menuBar = new QMenuBar(0);
  #else
  menuBar = new QMenuBar;
  #endif

  system = menuBar->addMenu("&System");

  system_load = system->addAction("Load &Cartridge ...");

  system_loadSpecial = system->addMenu("Load &Special");

  system_loadSpecial_bsx = system_loadSpecial->addAction("Load &BS-X Cartridge ...");
  
  system_loadSpecial_bsxSlotted = system_loadSpecial->addAction("Load BS-X &Slotted Cartridge ...");

  system_loadSpecial_sufamiTurbo = system_loadSpecial->addAction("Load Sufami &Turbo Cartridge ...");

  system_loadSpecial_superGameBoy = system_loadSpecial->addAction("Load Super &Game Boy Cartridge ...");

  system_saveMemoryPack = system->addAction("Save Memory Pack ...");
  system_saveMemoryPack->setVisible(false);

  system_reload = system->addAction("Re&load");

  system->addSeparator();

  system->addAction(system_power = new CheckAction("&Power", 0));

  system_reset = system->addAction("&Reset");

  system->addSeparator();

  system_port1 = system->addMenu("Controller Port &1");
  system_port1->addAction(system_port1_none = new RadioAction("&None", 0));
  system_port1->addAction(system_port1_gamepad = new RadioAction("&Gamepad", 0));
  system_port1->addAction(system_port1_asciipad = new RadioAction("&asciiPad", 0));
  system_port1->addAction(system_port1_multitap = new RadioAction("&Multitap", 0));
  system_port1->addAction(system_port1_mouse = new RadioAction("&Mouse", 0));
  system_port1->addAction(system_port1_nttdatakeypad = new RadioAction("NTT Data &Keypad", 0));

  system_port2 = system->addMenu("Controller Port &2");
  system_port2->addAction(system_port2_none = new RadioAction("&None", 0));
  system_port2->addAction(system_port2_gamepad = new RadioAction("&Gamepad", 0));
  system_port2->addAction(system_port2_asciipad = new RadioAction("&asciiPad", 0));
  system_port2->addAction(system_port2_multitap = new RadioAction("&Multitap", 0));
  system_port2->addAction(system_port2_mouse = new RadioAction("&Mouse", 0));
  system_port2->addAction(system_port2_superscope = new RadioAction("&Super Scope", 0));
  system_port2->addAction(system_port2_justifier = new RadioAction("&Justifier", 0));
  system_port2->addAction(system_port2_justifiers = new RadioAction("Two &Justifiers", 0));

  #if !defined(PLATFORM_OSX)
  system->addSeparator();
  #endif

  system_exit = system->addAction("E&xit");
  system_exit->setMenuRole(QAction::QuitRole);

  settings = menuBar->addMenu("S&ettings");

  settings_videoMode = settings->addMenu("Video &Mode");

  settings_videoMode->addAction(settings_videoMode_1x = new RadioAction("Scale &1x", 0));

  settings_videoMode->addAction(settings_videoMode_2x = new RadioAction("Scale &2x", 0));

  settings_videoMode->addAction(settings_videoMode_3x = new RadioAction("Scale &3x", 0));

  settings_videoMode->addAction(settings_videoMode_4x = new RadioAction("Scale &4x", 0));

  settings_videoMode->addAction(settings_videoMode_5x = new RadioAction("Scale &5x", 0));

  settings_videoMode->addAction(settings_videoMode_max_normal = new RadioAction("Scale Max - &Normal", 0));

  settings_videoMode->addAction(settings_videoMode_max_wide = new RadioAction("Scale Max - &Wide", 0));

  settings_videoMode->addAction(settings_videoMode_max_wideZoom = new RadioAction("Scale Max - Wide &Zoom", 0));

  settings_videoMode->addSeparator();

  settings_videoMode->addAction(settings_videoMode_correctAspectRatio = new CheckAction("Correct &Aspect Ratio", 0));

  settings_videoMode->addSeparator();

  settings_videoMode->addAction(settings_videoMode_ntsc = new RadioAction("&NTSC", 0));
  settings_videoMode->addAction(settings_videoMode_pal = new RadioAction("&PAL", 0));

  if(filter.opened()) {
    settings_videoFilter = settings->addMenu("Video &Filter");

    settings_videoFilter_configure = settings_videoFilter->addAction("&Configure Active Filter ...");
    settings_videoFilter->addSeparator();

    settings_videoFilter->addAction(settings_videoFilter_none = new RadioAction("&None", 0));
    settings_videoFilter_list.append(settings_videoFilter_none);

    lstring filterlist;
    filterlist.split(";", filter.dl_supported());
    for(unsigned i = 0; i < filterlist.size(); i++) {
      RadioAction *action = new RadioAction(filterlist[i], 0);
      settings_videoFilter->addAction(action);
      settings_videoFilter_list.append(action);
    }
  }

  settings->addAction(settings_smoothVideo = new CheckAction("&Smooth Video Output", 0));

  settings->addSeparator();

  settings->addAction(settings_muteAudio = new CheckAction("&Mute Audio Output", 0));

  settings->addSeparator();

  settings_emulationSpeed = settings->addMenu("Emulation &Speed");

  settings_emulationSpeed->addAction(settings_emulationSpeed_slowest = new RadioAction("Slowest", 0));

  settings_emulationSpeed->addAction(settings_emulationSpeed_slow = new RadioAction("Slow", 0));

  settings_emulationSpeed->addAction(settings_emulationSpeed_normal = new RadioAction("Normal", 0));

  settings_emulationSpeed->addAction(settings_emulationSpeed_fast = new RadioAction("Fast", 0));

  settings_emulationSpeed->addAction(settings_emulationSpeed_fastest = new RadioAction("Fastest", 0));

  settings_emulationSpeed->addSeparator();

  settings_emulationSpeed->addAction(settings_emulationSpeed_syncVideo = new CheckAction("Sync &Video", 0));

  settings_emulationSpeed->addAction(settings_emulationSpeed_syncAudio = new CheckAction("Sync &Audio", 0));

  settings_configuration = settings->addAction("&Configuration ...");
  settings_configuration->setMenuRole(QAction::PreferencesRole);

  tools = menuBar->addMenu("&Tools");

  tools_movies = tools->addMenu("&Movies");

  tools_movies_play = tools_movies->addAction("Play Movie ...");

  tools_movies_stop = tools_movies->addAction("Stop");

  tools_movies_recordFromPowerOn = tools_movies->addAction("Record Movie (and restart system)");

  tools_movies_recordFromHere = tools_movies->addAction("Record Movie (starting from here)");

  tools_captureScreenshot = tools->addAction("&Capture Screenshot");
  
  tools_captureSPC = tools->addAction("Capture &SPC Dump");

  tools->addSeparator();

  tools_loadState = tools->addMenu("&Load Quick State");
  for(unsigned i = 0; i < 10; i++) {
    QAction *loadAction = new QAction(string("Slot ", i + 1), 0);
    loadAction->setData(i);
    connect(loadAction, SIGNAL(triggered()), this, SLOT(loadState()));
    tools_loadState->addAction(loadAction);
  }

  tools_saveState = tools->addMenu("&Save Quick State");
  for(unsigned i = 0; i < 10; i++) {
    QAction *saveAction = new QAction(string("Slot ", i + 1), 0);
    saveAction->setData(i);
    connect(saveAction, SIGNAL(triggered()), this, SLOT(saveState()));
    tools_saveState->addAction(saveAction);
  }

  tools->addSeparator();

  tools_cheatEditor = tools->addAction("Cheat &Editor ...");

  tools_cheatFinder = tools->addAction("Cheat &Finder ...");

  tools_stateManager = tools->addAction("&State Manager ...");

  tools_effectToggle = tools->addAction("Effect &Toggle ...");
  if(!SNES::PPU::SupportsLayerEnable && !SNES::DSP::SupportsChannelEnable)
    tools_effectToggle->setVisible(false);
  
  tools_manifestViewer = tools->addAction("&Manifest Viewer ...");
  
  tools_soundViewer = tools->addAction("Sound &Viewer ...");

  tools_debugger = tools->addAction("&Debugger ...");
  #if !defined(DEBUGGER)
  tools_debugger->setVisible(false);
  #endif

  help = menuBar->addMenu("&Help");

  help_documentation = help->addAction("&Documentation ...");

  help_license = help->addAction("&License ...");

  #if !defined(PLATFORM_OSX)
  help->addSeparator();
  #endif

  help_about = help->addAction("&About ...");
  help_about->setMenuRole(QAction::AboutRole);

  //canvas
  canvasContainer = new CanvasObject;
  canvasContainer->setAcceptDrops(true); {
    canvasContainer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    canvasContainer->setObjectName("backdrop");

    canvasLayout = new QVBoxLayout; {
      canvasLayout->setMargin(0);
      canvasLayout->setAlignment(Qt::AlignCenter);

      canvas = new CanvasWidget;
      canvas->setAcceptDrops(true);
      canvas->setFocusPolicy(Qt::StrongFocus);
      canvas->setAttribute(Qt::WA_PaintOnScreen, true);  //disable Qt painting on focus / resize
      canvas->setAttribute(Qt::WA_NoSystemBackground, true);
    }
    canvasLayout->addWidget(canvas);
  }
  canvasContainer->setLayout(canvasLayout);

  //status bar
  statusBar = new QStatusBar;
  statusBar->setSizeGripEnabled(false);
  statusBar->showMessage("");
  systemState = new QLabel;
  statusBar->addPermanentWidget(systemState);

  //layout
  layout = new QVBoxLayout;
  layout->setMargin(0);
  layout->setSpacing(0);
  #if !defined(PLATFORM_OSX)
  layout->addWidget(menuBar);
  #endif
  layout->addWidget(canvasContainer);
  layout->addWidget(statusBar);
  setLayout(layout);

  //cursor hide timer
  cursorTimer = new QTimer(this);
  cursorTimer->setSingleShot(true);
  cursorTimer->setInterval(5*1000);

  //slots
  connect(system_load, SIGNAL(triggered()), this, SLOT(loadCartridge()));
  connect(system_reload, SIGNAL(triggered()), this, SLOT(reloadCartridge()));
  connect(system_loadSpecial_bsxSlotted, SIGNAL(triggered()), this, SLOT(loadBsxSlottedCartridge()));
  connect(system_loadSpecial_bsx, SIGNAL(triggered()), this, SLOT(loadBsxCartridge()));
  connect(system_loadSpecial_sufamiTurbo, SIGNAL(triggered()), this, SLOT(loadSufamiTurboCartridge()));
  connect(system_loadSpecial_superGameBoy, SIGNAL(triggered()), this, SLOT(loadSuperGameBoyCartridge()));
  connect(system_saveMemoryPack, SIGNAL(triggered()), this, SLOT(saveMemoryPack()));
  connect(system_power, SIGNAL(triggered()), this, SLOT(power()));
  connect(system_reset, SIGNAL(triggered()), this, SLOT(reset()));
  connect(system_port1_none, SIGNAL(triggered()), this, SLOT(setPort1None()));
  connect(system_port1_gamepad, SIGNAL(triggered()), this, SLOT(setPort1Gamepad()));
  connect(system_port1_asciipad, SIGNAL(triggered()), this, SLOT(setPort1Asciipad()));
  connect(system_port1_multitap, SIGNAL(triggered()), this, SLOT(setPort1Multitap()));
  connect(system_port1_mouse, SIGNAL(triggered()), this, SLOT(setPort1Mouse()));
  connect(system_port1_nttdatakeypad, SIGNAL(triggered()), this, SLOT(setPort1NTTDataKeypad()));
  connect(system_port2_none, SIGNAL(triggered()), this, SLOT(setPort2None()));
  connect(system_port2_gamepad, SIGNAL(triggered()), this, SLOT(setPort2Gamepad()));
  connect(system_port2_asciipad, SIGNAL(triggered()), this, SLOT(setPort2Asciipad()));
  connect(system_port2_multitap, SIGNAL(triggered()), this, SLOT(setPort2Multitap()));
  connect(system_port2_mouse, SIGNAL(triggered()), this, SLOT(setPort2Mouse()));
  connect(system_port2_superscope, SIGNAL(triggered()), this, SLOT(setPort2SuperScope()));
  connect(system_port2_justifier, SIGNAL(triggered()), this, SLOT(setPort2Justifier()));
  connect(system_port2_justifiers, SIGNAL(triggered()), this, SLOT(setPort2Justifiers()));
  connect(system_exit, SIGNAL(triggered()), this, SLOT(quit()));
  connect(settings_videoMode_1x, SIGNAL(triggered()), this, SLOT(setVideoMode1x()));
  connect(settings_videoMode_2x, SIGNAL(triggered()), this, SLOT(setVideoMode2x()));
  connect(settings_videoMode_3x, SIGNAL(triggered()), this, SLOT(setVideoMode3x()));
  connect(settings_videoMode_4x, SIGNAL(triggered()), this, SLOT(setVideoMode4x()));
  connect(settings_videoMode_5x, SIGNAL(triggered()), this, SLOT(setVideoMode5x()));
  connect(settings_videoMode_max_normal, SIGNAL(triggered()), this, SLOT(setVideoModeMaxNormal()));
  connect(settings_videoMode_max_wide, SIGNAL(triggered()), this, SLOT(setVideoModeMaxWide()));
  connect(settings_videoMode_max_wideZoom, SIGNAL(triggered()), this, SLOT(setVideoModeMaxWideZoom()));
  connect(settings_videoMode_correctAspectRatio, SIGNAL(triggered()), this, SLOT(toggleAspectCorrection()));
  connect(settings_videoMode_ntsc, SIGNAL(triggered()), this, SLOT(setVideoNtsc()));
  connect(settings_videoMode_pal, SIGNAL(triggered()), this, SLOT(setVideoPal()));
  if(filter.opened()) {
    connect(settings_videoFilter_configure, SIGNAL(triggered()), this, SLOT(configureFilter()));
    for(unsigned i = 0; i < settings_videoFilter_list.size(); i++) {
      connect(settings_videoFilter_list[i], SIGNAL(triggered()), this, SLOT(setFilter()));
    }
  }
  connect(settings_smoothVideo, SIGNAL(triggered()), this, SLOT(toggleSmoothVideo()));
  connect(settings_muteAudio, SIGNAL(triggered()), this, SLOT(muteAudio()));
  connect(settings_emulationSpeed_slowest, SIGNAL(triggered()), this, SLOT(setSpeedSlowest()));
  connect(settings_emulationSpeed_slow, SIGNAL(triggered()), this, SLOT(setSpeedSlow()));
  connect(settings_emulationSpeed_normal, SIGNAL(triggered()), this, SLOT(setSpeedNormal()));
  connect(settings_emulationSpeed_fast, SIGNAL(triggered()), this, SLOT(setSpeedFast()));
  connect(settings_emulationSpeed_fastest, SIGNAL(triggered()), this, SLOT(setSpeedFastest()));
  connect(settings_emulationSpeed_syncVideo, SIGNAL(triggered()), this, SLOT(syncVideo()));
  connect(settings_emulationSpeed_syncAudio, SIGNAL(triggered()), this, SLOT(syncAudio()));
  connect(settings_configuration, SIGNAL(triggered()), this, SLOT(showConfigWindow()));
  connect(tools_movies_play, SIGNAL(triggered()), this, SLOT(playMovie()));
  connect(tools_movies_stop, SIGNAL(triggered()), this, SLOT(stopMovie()));
  connect(tools_movies_recordFromPowerOn, SIGNAL(triggered()), this, SLOT(recordMovieFromPowerOn()));
  connect(tools_movies_recordFromHere, SIGNAL(triggered()), this, SLOT(recordMovieFromHere()));
  connect(tools_captureScreenshot, SIGNAL(triggered()), this, SLOT(saveScreenshot()));
  connect(tools_captureSPC, SIGNAL(triggered()), this, SLOT(saveSPC()));
  connect(tools_cheatEditor, SIGNAL(triggered()), this, SLOT(showCheatEditor()));
  connect(tools_cheatFinder, SIGNAL(triggered()), this, SLOT(showCheatFinder()));
  connect(tools_stateManager, SIGNAL(triggered()), this, SLOT(showStateManager()));
  connect(tools_effectToggle, SIGNAL(triggered()), this, SLOT(showEffectToggle()));
  connect(tools_manifestViewer, SIGNAL(triggered()), this, SLOT(showManifestViewer()));
  connect(tools_soundViewer, SIGNAL(triggered()), this, SLOT(showSoundViewer()));
  connect(tools_debugger, SIGNAL(triggered()), this, SLOT(showDebugger()));
  connect(help_documentation, SIGNAL(triggered()), this, SLOT(showDocumentation()));
  connect(help_license, SIGNAL(triggered()), this, SLOT(showLicense()));
  connect(help_about, SIGNAL(triggered()), this, SLOT(showAbout()));

  syncUi();
}
Beispiel #17
0
int RunGLTest (void)
{

#ifdef GL
	int mm=1;
#else
	int mm = 0;
#endif
	int mode=0;
	cam.x=0;
	cam.y=0;
	int bpp;
	int w = 200;
	int h = 200;
	int done = 0;
	int shrink=0;
	int grow=0;
	int gofullscreen=0;
	int mustresize = 1;
	int justresized = 0;
	xy  ss = parsemodes(w,h,"mode",1,0,0);
	printf("wtf\n");
	if (ss.x!=-1){w=ss.x;h=ss.y;};
	SDL_Surface* s;
#ifdef GL
	s=initsdl(w,h,&bpp,SDL_OPENGL

#else
	gltextsdlsurface=s=initsdl(w,h,&bpp,
#endif

	+0);printf("inito\n");
	SDL_InitSubSystem( SDL_INIT_TIMER);
	SDL_EnableUNICODE(1);
	SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY/2, SDL_DEFAULT_REPEAT_INTERVAL*2);
#ifdef GL
	newtermmsg=GetFileIntoCharPointer1("newtermmsg");
	printf("pretty far\n");
	wm(w,h);
	int down=0;
	glEnable(GL_BLEND);
	glShadeModel(GL_FLAT);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE);
	glClearColor( 0.0, 0.0, 0.04, 0.0 );
	glLineWidth(lv);
#else
	gltextsdlsurface=s;
#endif
	roteface *face1;
	roteface *activeface;
	face1=add_face();
	activeface =face1 ;
	face1->next=add_face();
	printf("still?\n");
	add_terminal(face1);
	printf("2threaad\n");
	loadl2();
	struct state *nerv=0;
#ifdef nerve
	nerv=nerverot_init(w,h);
#endif

	int dirty=1;
	printf("mainloop descent commencing\n");
	while( !done )
	{	
	        lockterms(face1);


		if(dirty||faces_dirty(face1))
		{
			dirty=0;
			facesclean(face1);
#ifdef GL
			glClear(GL_COLOR_BUFFER_BIT);
#else
			SDL_FillRect	( s, NULL, 0 );

#endif

#ifndef GL

#else

				if(nerv)
				{
				    shownerv(nerv);
				    dirty=1;
				}
				glPushMatrix();
				glScalef(sx,sy,0.004);
				glTranslatef(cam.x,cam.y,0);
				

#endif
				Uint8 * k;
				int integer;

				k=SDL_GetKeyState(&integer);
				if(k[SDLK_RCTRL])
					focusline(activeface);
				int nf;
				switch(mode)
				{
				    case 0:
					showfaces(face1);
				    break;
#ifdef GL
				    case 1:
					krychlus(face1);
				    break;
#endif
				}
#ifdef GL
				glPopMatrix();
#endif


#ifndef GL
			SDL_UpdateRect(s,0,0,0,0);
#else
			SDL_GL_SwapBuffers( );
#endif
			facesclean(face1);
			
		}
#ifdef GL
		GLenum gl_error;
		gl_error = glGetError( );
		if( gl_error != GL_NO_ERROR )
		{
			if(gl_error==GL_STACK_OVERFLOW)
				printf("QUACK QUACK QUACK, OVERFLOVING STACK\n");
			else if(gl_error==GL_INVALID_OPERATION)
				printf("INVALID OPERATION, PATIENT EXPLODED\n");
			else	fprintf( stderr, "testgl: OpenGL error: %d\n", gl_error );
			
		}
#endif
		char* sdl_error;
		sdl_error = SDL_GetError( );
		if( sdl_error[0] != '\0' )
		{
		    fprintf(stderr, "testgl: SDL error '%s'\n", sdl_error);
		    SDL_ClearError();
		}

		SDL_TimerID x=0;
		if(dirty)
		    x= SDL_AddTimer(55, NewTimerCallback, 0);
		                     
		unlockterms(face1);
//		printf("---------unlocked wating\n");
		SDL_Event event;
		if(SDL_WaitEvent( &event ))
		{
	    	    lockterms(face1);
//		    printf("---------locked goooin %i\n", event.type);
		    if(x)SDL_RemoveTimer(x);x=0;	    	    
		    do {
			int mod=event.key.keysym.mod;
			int key=event.key.keysym.sym;
    			Uint8 *keystate = SDL_GetKeyState(NULL);

			switch( event.type )
			{
			
#ifdef GL
				case SDL_MOUSEMOTION:
				if((SDL_BUTTON(1)|SDL_BUTTON(2))&SDL_GetMouseState(0,0))
				{
					activeface->x+=event.motion.xrel;
					activeface->y+=event.motion.yrel;
				}
				if((SDL_BUTTON(3)|SDL_BUTTON(2))&SDL_GetMouseState(0,0))
				{
					cam.x-=event.motion.xrel;
					cam.y-=event.motion.yrel;
				}
				
				break;
#endif
				case SDL_KEYUP:
				{
					if ( (key == SDLK_RCTRL) )
					{
						dirty=1;
					}
				}
				break;
				case SDL_KEYDOWN:
				

					if(mod&KMOD_RSHIFT&&(key==SDLK_PAGEUP||key==SDLK_PAGEDOWN))
					{
						if(key==SDLK_PAGEUP)
							tscroll+=9;
						if(key==SDLK_PAGEDOWN)
							tscroll-=9;
						if(tscroll<0)tscroll=0;
//						printf("scroll:%i,logl:%i, log&%i, t:%i ,b:%i\n", tscroll,activeface->t->logl, activeface->t->log,activeface->t->scrolltop,activeface->t->scrollbottom);
					}
					else
					if(key==SDLK_RCTRL||mod&KMOD_RCTRL)
					{
						dirty=1;
						switch (key)
						{
							case SDLK_TAB:
							    cycle(face1, &activeface);
							break;
							case SDLK_F2:
							    gofullscreen=1;
							break;
							case SDLK_F3:
							    rastio+=0.05;
							    mustresize=1;
							    dirty=1;
							break;
							case SDLK_F4:
							    rastio-=0.05;
							    mustresize=1;
							    dirty=1;
							break;
							case SDLK_F5:
							    sx-=0.001;
							    sy+=0.001;
							break;
							case SDLK_F6:
							    sx+=0.001;
							    sy-=0.001;
							break;

							case SDLK_F7:
							    savemode(w,h);
							break;
							case SDLK_F8:
							    loadl2();
							break;
							case SDLK_p:
							    saveScreenshot();
							break;
#ifdef GL
							case SDLK_F9:
							    lv-=1;	glLineWidth(lv);
							break;
							case SDLK_F10:
							    lv+=1;	glLineWidth(lv);
							break;
#endif
							case SDLK_F11:
							    shrink=1;
							break;
							case SDLK_F12:
							    grow=1;
							break;
							case SDLK_PAGEUP:
							     mode++;
							     if(mode>mm)mode= mm;
							break;
							case SDLK_INSERT:
							     mode--;
							     if(mode<0)mode= 0;
							break;
							case SDLK_END:
							    resizooo(activeface, 0,1,keystate);
							break;
							case SDLK_HOME:
							    resizooo(activeface, 0,-1,keystate);
							break;
							case SDLK_DELETE:
							    resizooo(activeface, -1,0,keystate);
							break;
							case SDLK_PAGEDOWN:
							    resizooo(activeface, 1,0,keystate);
							break;
#ifdef nerve
							case SDLK_F1:
								if(nerv)
								{
									nerverot_free(nerv);
							        	dirty=1;
									nerv=0;
								}
								else
								{
							        	nerv=nerverot_init(w,h);
									
									dirty=1;
								}
							break;
#endif
						}
					}
					else
					{
					    if(activeface->t==0)
					    {
						printf("debug messages r fun\n");
						add_terminal(activeface);
						activeface->next=add_face();
					    }
					    if ( (key >= SDLK_F1) && (key <= SDLK_F15) )
					    {
						char *k;
						if(asprintf(&k ,"kf%i", key-SDLK_F1+1)!=-1)
						{
						    rote_vt_terminfo(activeface->t, k);
						    free(k);
						}
					    }
					    else
					    if ( (key == SDLK_SPACE) )
						keyp(activeface,32);
					    else
					    #define magic(x) rote_vt_terminfo(activeface->t, x )
					    if ( (key == SDLK_BACKSPACE) )
						magic( "kbs");
					    else
					    if ( (key == SDLK_ESCAPE) )
						keyp(activeface,27);
					    else
					    if ( (key == SDLK_LEFT) )
						magic("kcub1");
					    else
					    if ( (key == SDLK_RIGHT) )
						magic( "kcuf1");
					    else
					    if ( (key == SDLK_UP) )
						magic( "kcuu1");
					    else
					    if ( (key == SDLK_DOWN) )
						magic( "kcud1");
					    else
					    if ( (key == SDLK_END) )
						magic( "kend");
					    else
					    if ( (key == SDLK_HOME) )
						magic("khome");
					    else
					    if ( (key == SDLK_DELETE) )
						magic( "kdch1");
					    else
					    if ( (key == SDLK_PAGEDOWN) )
						magic( "knp");
					    else
					    if ( (key == SDLK_INSERT) )
					    	magic( "kich1");
					    else
					    if ( (key == SDLK_PAGEUP) )
						magic ( "kpp" );
					    else
					    if ( (key == SDLK_RETURN) )
						keyp(activeface,10);
					    else
					    if( event.key.keysym.unicode && ( (event.key.keysym.unicode & 0xFF80) == 0 ) )
						keyp(activeface, event.key.keysym.unicode);
					}
				break;
	 			case SDL_QUIT:
					done = 1;
					break;
#ifndef GL
	 			case SDL_MOUSEBUTTONDOWN:
					rote_vt_mousedown(activeface->t,event.button.x/13, event.button.y/26);
					break;
	 			case SDL_MOUSEBUTTONUP:
					rote_vt_mouseup  (activeface->t,event.button.x/13, event.button.y/26);
					break;
	 			case SDL_MOUSEMOTION:
					rote_vt_mousemove(activeface->t,event.button.x/13, event.button.y/26);
					break;
#endif
				case SDL_VIDEORESIZE:
				    {
					w=event.resize.w;h=event.resize.h;
//					printf("videoresize %i %i\n", w,h);
					dirty=1;
					if (s=SDL_SetVideoMode( w,h, bpp, s->flags ) ) 
//						printf("hmm\n");
					wm(w,h);
				    if(!justresized)

					mustresize=1;
				        justresized=0;
				        
				    }

					break;
				case SDL_USEREVENT:
					if(event.user.code==1)
					    RemoveTerm(&activeface,&face1, event.user.data1);
					break;
			}
		    }
		    while (SDL_PollEvent(&event));
		    if (shrink||grow)
		    { 
		        resize(&w,&h,&bpp,&s->flags,&shrink,&grow);
		        wm(w,h);
		    }
		    if (mustresize)
		    {
			mustresize=0;
			justresized=1;
//			if(activeface->t->cols!=event.resize.w/13/rastio||
//			    activeface->t->rows!=event.resize.h/26/rastio)
				//rote_vt_resize(activeface->t,event.resize.h/26/rastio ,event.resize.w/13/rastio);
		    }
		    if(gofullscreen)
			if(s->flags & SDL_FULLSCREEN )
			{
    			    s=SDL_SetVideoMode( w,h, bpp, (s->flags & ~SDL_FULLSCREEN ));
			
			}
			else
    			    s=SDL_SetVideoMode( w,h, bpp, (s->flags | SDL_FULLSCREEN ));
		    gofullscreen=0;
		    unlockterms(face1);
		}

	}
	SDL_Quit( );
	return(0);
}
void idle(void*)
{
  if (previousPlayButtonStatus == ON)  
  {
    // it means we should measure the interval between two frames
    // if it is too tiny, we should slow down the motion
    performanceCounter.StopCounter();
    double actualTimeCostOneFrame = performanceCounter.GetElapsedTime(); // in seconds

    // time spent on saving the screen in previous time-step should be excluded
    if (saveFileTimeCost > 0.0)   
      actualTimeCostOneFrame -= saveFileTimeCost;

    framesIncrementDoublePrecision = actualTimeCostOneFrame * expectedFPS;
  }
  // start counter at the beginning of the new round
  if (playButton == ON)
    performanceCounter.StartCounter();

  if(rewindButton == ON)
  {
    currentFrameIndex = 0;
    currentFrameIndexDoublePrecision = 0.0;
    for (int i = 0; i < displayer.GetNumSkeletons(); i++)
    {
      if (displayer.GetSkeletonMotion(i) != NULL)
      {
        Posture * initSkeleton = displayer.GetSkeletonMotion(i)->GetPosture(0);
        displayer.GetSkeleton(i)->setPosture(*initSkeleton);
      }
    }
    rewindButton = OFF;
  }

  // Initialization
  saveFileTimeCost = -1.0;

  if(playButton == ON) 
  {
    if (saveScreenToFile == SAVE_CONTINUOUS)
    {
      saveFileTimeCounter.StartCounter();
      CreateScreenFilename(SAVE_CONTINUOUS, saveScreenToFileContinuousCount, saveScreenToFileContinuousFilename);
      saveScreenshot(640, 480, saveScreenToFileContinuousFilename);
      printf("%s is saved to disk.\n", saveScreenToFileContinuousFilename);
      saveScreenToFileContinuousCount++;
      saveFileTimeCounter.StopCounter();
      saveFileTimeCost = saveFileTimeCounter.GetElapsedTime();
    }

    if (saveScreenToFile == SAVE_CONTINUOUS)
    {
      currentFrameIndexDoublePrecision += 1.0;
    }
    else
    {
      currentFrameIndexDoublePrecision += framesIncrementDoublePrecision;
    }

    currentFrameIndex = (int)currentFrameIndexDoublePrecision;

    if(currentFrameIndex >= maxFrames)
    {
      if (repeatButton == ON)
      {
        currentFrameIndex = 0;
        currentFrameIndexDoublePrecision = 0.0;
      }
      else  // repeat button is OFF
      {
        currentFrameIndex = maxFrames - 1;
        currentFrameIndexDoublePrecision = currentFrameIndex;
        playButton = OFF;  // important, especially in "recording" mode
      }
    }

    if (currentFrameIndex < 0)
    {
      currentFrameIndex = 0;
      currentFrameIndexDoublePrecision = 0.0;
    }

    SetSkeletonsToSpecifiedFrame(currentFrameIndex);

    frame_slider->value((double) currentFrameIndex + 1);
  }  // if(playButton == ON)

  if (minusOneButton == ON)
    if (displayer.GetNumSkeletons() != 0)
    {
      currentFrameIndex--;
      if (currentFrameIndex < 0)
        currentFrameIndex = 0;
      frame_slider->value((double) currentFrameIndex + 1);

      SetSkeletonsToSpecifiedFrame(currentFrameIndex);    
      if (saveScreenToFile == SAVE_CONTINUOUS)
      {
        CreateScreenFilename(SAVE_CONTINUOUS, saveScreenToFileContinuousCount, saveScreenToFileContinuousFilename);
        saveScreenshot(640, 480, saveScreenToFileContinuousFilename);
        printf("%s is saved to disk.\n", saveScreenToFileContinuousFilename);
        saveScreenToFileContinuousCount++;
      }
      minusOneButton = OFF;
    }

  if (plusOneButton == ON)
  {
    if (displayer.GetNumSkeletons() != 0)
    {
      currentFrameIndex++;
      if (currentFrameIndex >= maxFrames)
        currentFrameIndex = maxFrames - 1;
      frame_slider->value((double) currentFrameIndex + 1);

      SetSkeletonsToSpecifiedFrame(currentFrameIndex);
      if (saveScreenToFile == SAVE_CONTINUOUS)
      {
        CreateScreenFilename(SAVE_CONTINUOUS, saveScreenToFileContinuousCount, saveScreenToFileContinuousFilename);
        saveScreenshot(640, 480, saveScreenToFileContinuousFilename);
        printf("%s is saved to disk.\n", saveScreenToFileContinuousFilename);
        saveScreenToFileContinuousCount++;
      }
      plusOneButton = OFF;
    }
  }

  frame_slider->value((double)(currentFrameIndex + 1));

  previousPlayButtonStatus = playButton; // Super important updating

  glwindow->redraw();
}
void MedeaTwoSunsWorldObserver::step()
{

	if ( gWorld->getIterations() % ( int(MedeaTwoSunsSharedData::gEvaluationTime * MedeaTwoSunsSharedData::gSunLifetime) ) == 0 )
	{
		gEnergyPoints[MedeaTwoSunsSharedData::gActiveSun].hide();
		MedeaTwoSunsSharedData::gActiveSun = ( MedeaTwoSunsSharedData::gActiveSun + 1 ) % 2;
		std::cout << "\nActive Sun #" << MedeaTwoSunsSharedData::gActiveSun << "\n";
		gEnergyPoints[MedeaTwoSunsSharedData::gActiveSun].display();
	}



	// ***
	// * update iteration and generation counters + switch btw experimental setups if required
	// ***
	
	_lifeIterationCount++;

	if( _lifeIterationCount >= MedeaTwoSunsSharedData::gEvaluationTime ) // go to next generation.
	{
		// * monitoring: count number of active agents.

		int activeCount = 0;
		for ( int i = 0 ; i != gAgentCounter ; i++ )
		{
			if ( (dynamic_cast<MedeaTwoSunsAgentWorldModel*>(gWorld->getAgent(i)->getWorldModel()))->getActiveStatus() == true )
				activeCount++;
		}

		if ( !gVerbose )
		{
			std::cout << "[" << activeCount << "]";
		}
	
		gLogFile << "Info(" << gWorld->getIterations() << ") : active count is " << activeCount << std::endl;
	
		
		// * monitor and log orientation and distance to center for all agents
		
		// build heatmap
		
		int heatmapSize = 100; // arbitrary, but should be enough to get precise view
		int maxDistance = sqrt ( gAreaWidth*gAreaWidth + gAreaHeight*gAreaHeight ) / 2.0 ; // distance max to center.
		
		int *distanceHeatmap;
		distanceHeatmap = new int[heatmapSize];
		int *orientationHeatmap;
		orientationHeatmap = new int[heatmapSize];

		for (int i = 0 ; i != heatmapSize ; i++ )
		{
			distanceHeatmap[i] = 0;
			orientationHeatmap[i] = 0;
		}
			
		double xRef = gAreaWidth / 2.0 ;
		double yRef = gAreaHeight / 2.0 ;

		for ( int i = 0 ; i != gAgentCounter ; i++ )
		{
			MedeaTwoSunsAgentWorldModel *wm = (dynamic_cast<MedeaTwoSunsAgentWorldModel*>(gWorld->getAgent(i)->getWorldModel()));
			if ( wm->getActiveStatus() == true ) // only active agents
			{
				// monitor distance
				
				double dist = getEuclidianDistance( xRef, yRef, wm->_xReal, wm->_yReal );
				int indexDist = (int)dist * heatmapSize / maxDistance; // normalize within heatmap bounds
				distanceHeatmap[indexDist]++;
				
				// monitor orientationHeatmap

				double orient = acos ( ( wm->_xReal - xRef ) / (double)dist );
				if ( wm->_yReal - yRef > 0 ) // [trick] why ">0" ?  : it should be <0, but as the 2D-display norm for the coordinate system origin is upper-left (and not bottom-left), the sign is inversed.
				{
					orient = -orient;
				}
				
				int indexOrient = ( orient + M_PI ) * heatmapSize / (2.0 * M_PI);
				orientationHeatmap[heatmapSize-1-((indexOrient+((heatmapSize*3)/4))%heatmapSize)]++; // index is such that list ordering is as follow: [South-West-North-East-South]
				
				//std::cout << "\n agent[" << wm->_xReal << "," << wm->_yReal << "](" << dist << "," << orient << ") -- " << wm->_xReal << ";" << xRef << ";" << ( ( wm->_xReal - xRef ) / (double)dist ) << ";" << acos ( ( wm->_xReal - xRef ) / (double)dist ); //debug
			}
		}		
		//std::cout << "\n"; //debug
		
		
		// update log file
		
		std::string str_agentDistancesToRef ="";
		std::string str_agentOrientationsToRef = "";
		
		for (int i = 0 ; i != heatmapSize ; i++ )
		{
			str_agentDistancesToRef += convertToString(distanceHeatmap[i]);
			str_agentDistancesToRef += ",";
			str_agentOrientationsToRef += convertToString(orientationHeatmap[i]);
			str_agentOrientationsToRef += ",";
		}
		
		//gLogFile
		//std::cout << std::endl << std::endl;//debug
		//gLogFile << "Info(" << gWorld->getIterations() << ") : monitor distance to ref - " << (_generationCount+1) << "," << gAgentCounter << "," << str_agentDistancesToRef << std::endl;
		//gLogFile << "Info(" << gWorld->getIterations() << ") : monitor orientation to ref - " << (_generationCount+1) << "," << gAgentCounter << "," << str_agentOrientationsToRef << std::endl;

		for ( int i = 0 ; i != heatmapSize ; i++ )
		{
			gLogFile << "monitorDistance: " << gAgentCounter << "," << (int)sqrt(gMaxRadioDistanceToSquare) << "," << (_generationCount+1) << "," << i << "," << distanceHeatmap[i] << std::endl;
			gLogFile << "monitorOrientation: " << gAgentCounter << "," << (int)sqrt(gMaxRadioDistanceToSquare) << "," << (_generationCount+1) << "," << i << "," << orientationHeatmap[i] << std::endl;
		}
		//gLogFile << "Info(" << gWorld->getIterations() << ") : monitor distance to ref - " << (_generationCount+1) << "," << gAgentCounter << "," << str_agentDistancesToRef << std::endl;
		//gLogFile << "Info(" << gWorld->getIterations() << ") : monitor orientation to ref - " << (_generationCount+1) << "," << gAgentCounter << "," << str_agentOrientationsToRef << std::endl;
				
		delete [] distanceHeatmap;
		delete [] orientationHeatmap;

		// * update iterations and generations counters

		_lifeIterationCount = 0;
		_generationCount++;
		
		// * Switch btw experiment setups, if required	
	
		updateExperimentalSettings();

	}

	// * Update environment status wrt. nature and availability of energy resources (update at each iteration)

	updateEnvironmentResources();

	// * update energy level for each agents (ONLY active agents)
	
	updateAllAgentsEnergyLevel();
	
	// prepape and take screenshot of ultimate iteration
	
	if ( gWorld->getIterations() == gMaxIt-2 )
	{
		gDisplayMode = 0;
		gDisplaySensors = true; // prepape for next it.
	}
	else
	{
		if ( gWorld->getIterations() == gMaxIt-1 )
			saveScreenshot("lastIteration");
	}
	
}
Beispiel #20
0
void
pcl::visualization::PCLVisualizerInteractorStyle::OnKeyDown ()
{
  if (!init_)
  {
    pcl::console::print_error ("[PCLVisualizerInteractorStyle] Interactor style not initialized. Please call Initialize () before continuing.\n");
    return;
  }

  if (!rens_)
  {
    pcl::console::print_error ("[PCLVisualizerInteractorStyle] No renderer collection given! Use SetRendererCollection () before continuing.\n");
    return;
  }

  FindPokedRenderer (Interactor->GetEventPosition ()[0], Interactor->GetEventPosition ()[1]);

  if (wif_->GetInput () == NULL)
  {
    wif_->SetInput (Interactor->GetRenderWindow ());
    wif_->Modified ();
    snapshot_writer_->Modified ();
  }

  // Save the initial windows width/height
  if (win_height_ == -1 || win_width_ == -1)
  {
    int *win_size = Interactor->GetRenderWindow ()->GetSize ();
    win_height_ = win_size[0];
    win_width_  = win_size[1];
  }

  // Get the status of special keys (Cltr+Alt+Shift)
  bool shift = Interactor->GetShiftKey   ();
  bool ctrl  = Interactor->GetControlKey ();
  bool alt   = Interactor->GetAltKey ();

  bool keymod = false;
  switch (modifier_)
  {
    case INTERACTOR_KB_MOD_ALT:
    {
      keymod = alt;
      break;
    }
    case INTERACTOR_KB_MOD_CTRL:
    {
      keymod = ctrl;
      break;
    }
    case INTERACTOR_KB_MOD_SHIFT:
    {
      keymod = shift;
      break;
    }
  }

  // ---[ Check the rest of the key codes

  // Switch between point color/geometry handlers
  if (Interactor->GetKeySym () && Interactor->GetKeySym ()[0]  >= '0' && Interactor->GetKeySym ()[0] <= '9')
  {
    CloudActorMap::iterator it;
    int index = Interactor->GetKeySym ()[0] - '0' - 1;
    if (index == -1) index = 9;

    // Add 10 more for CTRL+0..9 keys
    if (ctrl)
      index += 10;

    // Geometry ?
    if (keymod)
    {
      for (it = actors_->begin (); it != actors_->end (); ++it)
      {
        CloudActor *act = &(*it).second;
        if (index >= static_cast<int> (act->geometry_handlers.size ()))
          continue;

        // Save the geometry handler index for later usage
        act->geometry_handler_index_ = index;

        // Create the new geometry
        PointCloudGeometryHandler<sensor_msgs::PointCloud2>::ConstPtr geometry_handler = act->geometry_handlers[index];

        // Use the handler to obtain the geometry
        vtkSmartPointer<vtkPoints> points;
        geometry_handler->getGeometry (points);

        // Set the vertices
        vtkSmartPointer<vtkCellArray> vertices = vtkSmartPointer<vtkCellArray>::New ();
        for (vtkIdType i = 0; i < static_cast<vtkIdType> (points->GetNumberOfPoints ()); ++i)
          vertices->InsertNextCell (static_cast<vtkIdType>(1), &i);

        // Create the data
        vtkSmartPointer<vtkPolyData> data = vtkSmartPointer<vtkPolyData>::New ();
        data->SetPoints (points);
        data->SetVerts (vertices);
        // Modify the mapper
        if (use_vbos_)
        {
          vtkVertexBufferObjectMapper* mapper = static_cast<vtkVertexBufferObjectMapper*>(act->actor->GetMapper ());
          mapper->SetInput (data);
          // Modify the actor
          act->actor->SetMapper (mapper);
        }
        else
        {
          vtkPolyDataMapper* mapper = static_cast<vtkPolyDataMapper*>(act->actor->GetMapper ());
          mapper->SetInput (data);
          // Modify the actor
          act->actor->SetMapper (mapper);
        }
        act->actor->Modified ();
      }
    }
    else
    {
      for (it = actors_->begin (); it != actors_->end (); ++it)
      {
        CloudActor *act = &(*it).second;
        // Check for out of bounds
        if (index >= static_cast<int> (act->color_handlers.size ()))
          continue;

        // Save the color handler index for later usage
        act->color_handler_index_ = index;

        // Get the new color
        PointCloudColorHandler<sensor_msgs::PointCloud2>::ConstPtr color_handler = act->color_handlers[index];

        vtkSmartPointer<vtkDataArray> scalars;
        color_handler->getColor (scalars);
        double minmax[2];
        scalars->GetRange (minmax);
        // Update the data
        vtkPolyData *data = static_cast<vtkPolyData*>(act->actor->GetMapper ()->GetInput ());
        data->GetPointData ()->SetScalars (scalars);
        data->Update ();
        // Modify the mapper
        if (use_vbos_)
        {
          vtkVertexBufferObjectMapper* mapper = static_cast<vtkVertexBufferObjectMapper*>(act->actor->GetMapper ());
          mapper->SetScalarRange (minmax);
          mapper->SetScalarModeToUsePointData ();
          mapper->SetInput (data);
          // Modify the actor
          act->actor->SetMapper (mapper);
        }
        else
        {
          vtkPolyDataMapper* mapper = static_cast<vtkPolyDataMapper*>(act->actor->GetMapper ());
          mapper->SetScalarRange (minmax);
          mapper->SetScalarModeToUsePointData ();
          mapper->SetInput (data);
          // Modify the actor
          act->actor->SetMapper (mapper);
        }
        act->actor->Modified ();
      }
    }

    Interactor->Render ();
    return;
  }

  std::string key (Interactor->GetKeySym ());
  if (key.find ("XF86ZoomIn") != std::string::npos)
    zoomIn ();
  else if (key.find ("XF86ZoomOut") != std::string::npos)
    zoomOut ();

  switch (Interactor->GetKeyCode ())
  {
    case 'h': case 'H':
    {
      pcl::console::print_info ("| Help:\n"
                  "-------\n"
                  "          p, P   : switch to a point-based representation\n"
                  "          w, W   : switch to a wireframe-based representation (where available)\n"
                  "          s, S   : switch to a surface-based representation (where available)\n"
                  "\n"
                  "          j, J   : take a .PNG snapshot of the current window view\n"
                  "          c, C   : display current camera/window parameters\n"
                  "          f, F   : fly to point mode\n"
                  "\n"
                  "          e, E   : exit the interactor\n"
                  "          q, Q   : stop and call VTK's TerminateApp\n"
                  "\n"
                  "           +/-   : increment/decrement overall point size\n"
                  "     +/- [+ ALT] : zoom in/out \n"
                  "\n"
                  "          g, G   : display scale grid (on/off)\n"
                  "          u, U   : display lookup table (on/off)\n"
                  "\n"
                  "    r, R [+ ALT] : reset camera [to viewpoint = {0, 0, 0} -> center_{x, y, z}]\n"
                  "\n"
                  "    ALT + s, S   : turn stereo mode on/off\n"
                  "    ALT + f, F   : switch between maximized window mode and original size\n"
                  "\n"
                  "          l, L           : list all available geometric and color handlers for the current actor map\n"
                  "    ALT + 0..9 [+ CTRL]  : switch between different geometric handlers (where available)\n"
                  "          0..9 [+ CTRL]  : switch between different color handlers (where available)\n"
                  "\n"
                  "    SHIFT + left click   : select a point\n"
          );
      break;
    }

    // Get the list of available handlers
    case 'l': case 'L':
    {
      // Iterate over the entire actors list and extract the geomotry/color handlers list
      for (CloudActorMap::iterator it = actors_->begin (); it != actors_->end (); ++it)
      {
        std::list<std::string> geometry_handlers_list, color_handlers_list;
        CloudActor *act = &(*it).second;
        for (size_t i = 0; i < act->geometry_handlers.size (); ++i)
          geometry_handlers_list.push_back (act->geometry_handlers[i]->getFieldName ());
        for (size_t i = 0; i < act->color_handlers.size (); ++i)
          color_handlers_list.push_back (act->color_handlers[i]->getFieldName ());

        if (!geometry_handlers_list.empty ())
        {
          int i = 0;
          pcl::console::print_info ("List of available geometry handlers for actor "); pcl::console::print_value ("%s: ", (*it).first.c_str ());
          for (std::list<std::string>::iterator git = geometry_handlers_list.begin (); git != geometry_handlers_list.end (); ++git)
            pcl::console::print_value ("%s(%d) ", (*git).c_str (), ++i);
          pcl::console::print_info ("\n");
        }
        if (!color_handlers_list.empty ())
        {
          int i = 0;
          pcl::console::print_info ("List of available color handlers for actor "); pcl::console::print_value ("%s: ", (*it).first.c_str ());
          for (std::list<std::string>::iterator cit = color_handlers_list.begin (); cit != color_handlers_list.end (); ++cit)
            pcl::console::print_value ("%s(%d) ", (*cit).c_str (), ++i);
          pcl::console::print_info ("\n");
        }
      }

      break;
    }

    // Switch representation to points
    case 'p': case 'P':
    {
      vtkSmartPointer<vtkActorCollection> ac = CurrentRenderer->GetActors ();
      vtkCollectionSimpleIterator ait;
      for (ac->InitTraversal (ait); vtkActor* actor = ac->GetNextActor (ait); )
      {
        for (actor->InitPathTraversal (); vtkAssemblyPath* path = actor->GetNextPath (); )
        {
          vtkSmartPointer<vtkActor> apart = reinterpret_cast <vtkActor*> (path->GetLastNode ()->GetViewProp ());
          apart->GetProperty ()->SetRepresentationToPoints ();
        }
      }
      break;
    }
    // Save a PNG snapshot with the current screen
    case 'j': case 'J':
    {
      char cam_fn[80], snapshot_fn[80];
      unsigned t = static_cast<unsigned> (time (0));
      sprintf (snapshot_fn, "screenshot-%d.png" , t);
      saveScreenshot (snapshot_fn);

      sprintf (cam_fn, "screenshot-%d.cam", t);
      ofstream ofs_cam;
      ofs_cam.open (cam_fn);
      vtkSmartPointer<vtkCamera> cam = Interactor->GetRenderWindow ()->GetRenderers ()->GetFirstRenderer ()->GetActiveCamera ();
      double clip[2], focal[3], pos[3], view[3];
      cam->GetClippingRange (clip);
      cam->GetFocalPoint (focal);
      cam->GetPosition (pos);
      cam->GetViewUp (view);
      int *win_pos = Interactor->GetRenderWindow ()->GetPosition ();
      int *win_size = Interactor->GetRenderWindow ()->GetSize ();
      ofs_cam << clip[0]  << "," << clip[1]  << "/" << focal[0] << "," << focal[1] << "," << focal[2] << "/" <<
                 pos[0]   << "," << pos[1]   << "," << pos[2]   << "/" << view[0]  << "," << view[1]  << "," << view[2] << "/" <<
                 cam->GetViewAngle () / 180.0 * M_PI  << "/" << win_size[0] << "," << win_size[1] << "/" << win_pos[0] << "," << win_pos[1]
              << endl;
      ofs_cam.close ();

      pcl::console::print_info ("Screenshot (%s) and camera information (%s) successfully captured.\n", snapshot_fn, cam_fn);
      break;
    }
    // display current camera settings/parameters
    case 'c': case 'C':
    {
      vtkSmartPointer<vtkCamera> cam = Interactor->GetRenderWindow ()->GetRenderers ()->GetFirstRenderer ()->GetActiveCamera ();
      double clip[2], focal[3], pos[3], view[3];
      cam->GetClippingRange (clip);
      cam->GetFocalPoint (focal);
      cam->GetPosition (pos);
      cam->GetViewUp (view);
      int *win_pos = Interactor->GetRenderWindow ()->GetPosition ();
      int *win_size = Interactor->GetRenderWindow ()->GetSize ();
      std::cerr << clip[0]  << "," << clip[1]  << "/" << focal[0] << "," << focal[1] << "," << focal[2] << "/" <<
                   pos[0]   << "," << pos[1]   << "," << pos[2]   << "/" << view[0]  << "," << view[1]  << "," << view[2] << "/" <<
                   cam->GetViewAngle () / 180.0 * M_PI  << "/" << win_size[0] << "," << win_size[1] << "/" << win_pos[0] << "," << win_pos[1]
                << endl;
      break;
    }
    case '=':
    {
      zoomIn();
      break;
    }
    case 43:        // KEY_PLUS
    {
      if(alt)
        zoomIn ();
      else
      {
        vtkSmartPointer<vtkActorCollection> ac = CurrentRenderer->GetActors ();
        vtkCollectionSimpleIterator ait;
        for (ac->InitTraversal (ait); vtkActor* actor = ac->GetNextActor (ait); )
        {
          for (actor->InitPathTraversal (); vtkAssemblyPath* path = actor->GetNextPath (); )
          {
            vtkSmartPointer<vtkActor> apart = reinterpret_cast <vtkActor*> (path->GetLastNode ()->GetViewProp ());
            float psize = apart->GetProperty ()->GetPointSize ();
            if (psize < 63.0f)
              apart->GetProperty ()->SetPointSize (psize + 1.0f);
          }
        }
      }
      break;
    }
    case 45:        // KEY_MINUS
    {
      if(alt)
        zoomOut ();
      else
      {
        vtkSmartPointer<vtkActorCollection> ac = CurrentRenderer->GetActors ();
        vtkCollectionSimpleIterator ait;
        for (ac->InitTraversal (ait); vtkActor* actor = ac->GetNextActor (ait); )
        {
          for (actor->InitPathTraversal (); vtkAssemblyPath* path = actor->GetNextPath (); )
          {
            vtkSmartPointer<vtkActor> apart = static_cast<vtkActor*> (path->GetLastNode ()->GetViewProp ());
            float psize = apart->GetProperty ()->GetPointSize ();
            if (psize > 1.0f)
              apart->GetProperty ()->SetPointSize (psize - 1.0f);
          }
        }
      }
      break;
    }
    // Switch between maximize and original window size
    case 'f': case 'F':
    {
      if (keymod)
      {
        // Get screen size
        int *temp = Interactor->GetRenderWindow ()->GetScreenSize ();
        int scr_size[2]; scr_size[0] = temp[0]; scr_size[1] = temp[1];

        // Get window size
        temp = Interactor->GetRenderWindow ()->GetSize ();
        int win_size[2]; win_size[0] = temp[0]; win_size[1] = temp[1];
        // Is window size = max?
        if (win_size[0] == max_win_height_ && win_size[1] == max_win_width_)
        {
          // Set the previously saved 'current' window size
          Interactor->GetRenderWindow ()->SetSize (win_height_, win_width_);
          // Set the previously saved window position
          Interactor->GetRenderWindow ()->SetPosition (win_pos_x_, win_pos_y_);
          Interactor->GetRenderWindow ()->Render ();
          Interactor->Render ();
        }
        // Set to max
        else
        {
          int *win_pos = Interactor->GetRenderWindow ()->GetPosition ();
          // Save the current window position
          win_pos_x_  = win_pos[0];
          win_pos_y_  = win_pos[1];
          // Save the current window size
          win_height_ = win_size[0];
          win_width_  = win_size[1];
          // Set the maximum window size
          Interactor->GetRenderWindow ()->SetSize (scr_size[0], scr_size[1]);
          Interactor->GetRenderWindow ()->Render ();
          Interactor->Render ();
          int *win_size = Interactor->GetRenderWindow ()->GetSize ();
          // Save the maximum window size
          max_win_height_ = win_size[0];
          max_win_width_  = win_size[1];
        }
      }
      else
      {
        AnimState = VTKIS_ANIM_ON;
        vtkAssemblyPath *path = NULL;
        Interactor->GetPicker ()->Pick (Interactor->GetEventPosition ()[0], Interactor->GetEventPosition ()[1], 0.0, CurrentRenderer);
        vtkAbstractPropPicker *picker;
        if ((picker = vtkAbstractPropPicker::SafeDownCast (Interactor->GetPicker ())))
          path = picker->GetPath ();
        if (path != NULL)
          Interactor->FlyTo (CurrentRenderer, picker->GetPickPosition ());
        AnimState = VTKIS_ANIM_OFF;
      }
      break;
    }
    // 's'/'S' w/out ALT
    case 's': case 'S':
    {
      if (keymod)
      {
        int stereo_render = Interactor->GetRenderWindow ()->GetStereoRender ();
        if (!stereo_render)
        {
          if (stereo_anaglyph_mask_default_)
          {
            Interactor->GetRenderWindow ()->SetAnaglyphColorMask (4, 3);
            stereo_anaglyph_mask_default_ = false;
          }
          else
          {
            Interactor->GetRenderWindow ()->SetAnaglyphColorMask (2, 5);
            stereo_anaglyph_mask_default_ = true;
          }
        }
        Interactor->GetRenderWindow ()->SetStereoRender (!stereo_render);
        Interactor->GetRenderWindow ()->Render ();
        Interactor->Render ();
      }
      else
        Superclass::OnKeyDown ();
      break;
    }

    // Display a grid/scale over the screen
    case 'g': case 'G':
    {
      if (!grid_enabled_)
      {
        grid_actor_->TopAxisVisibilityOn ();
        CurrentRenderer->AddViewProp (grid_actor_);
        grid_enabled_ = true;
      }
      else
      {
        CurrentRenderer->RemoveViewProp (grid_actor_);
        grid_enabled_ = false;
      }
      break;
    }

    case 'o': case 'O':
    {
      vtkSmartPointer<vtkCamera> cam = CurrentRenderer->GetActiveCamera ();
      int flag = cam->GetParallelProjection ();
      cam->SetParallelProjection (!flag);

      CurrentRenderer->SetActiveCamera (cam);
      CurrentRenderer->Render ();
      break;
    }
    // Display a LUT actor on screen
    case 'u': case 'U':
    {
      CloudActorMap::iterator it;
      for (it = actors_->begin (); it != actors_->end (); ++it)
      {
        CloudActor *act = &(*it).second;

        vtkScalarsToColors* lut = act->actor->GetMapper ()->GetLookupTable ();
        lut_actor_->SetLookupTable (lut);
        lut_actor_->Modified ();
      }
      if (!lut_enabled_)
      {
        CurrentRenderer->AddActor (lut_actor_);
        lut_actor_->SetVisibility (true);
        lut_enabled_ = true;
      }
      else
      {
        CurrentRenderer->RemoveActor (lut_actor_);
        lut_enabled_ = false;
      }
      CurrentRenderer->Render ();
      break;
    }

    // Overwrite the camera reset
    case 'r': case 'R':
    {
      if (!keymod)
      {
        Superclass::OnKeyDown ();
        break;
      }

      vtkSmartPointer<vtkCamera> cam = CurrentRenderer->GetActiveCamera ();
      
      static CloudActorMap::iterator it = actors_->begin ();
      // it might be that some actors don't have a valid transformation set -> we skip them to avoid a seg fault.
      bool found_transformation = false;
      for (unsigned idx = 0; idx < actors_->size (); ++idx, ++it)
      {
        if (it == actors_->end ())
          it = actors_->begin ();
        
        const CloudActor& actor = it->second;
        if (actor.viewpoint_transformation_.GetPointer ())
        {
          found_transformation = true;
          break;
        }
      }
      
      // if a valid transformation was found, use it otherwise fall back to default view point.
      if (found_transformation)
      {
        const CloudActor& actor = it->second;
        cam->SetPosition (actor.viewpoint_transformation_->GetElement (0, 3),
                          actor.viewpoint_transformation_->GetElement (1, 3),
                          actor.viewpoint_transformation_->GetElement (2, 3));

        cam->SetFocalPoint (actor.viewpoint_transformation_->GetElement (0, 3) - actor.viewpoint_transformation_->GetElement (0, 2),
                            actor.viewpoint_transformation_->GetElement (1, 3) - actor.viewpoint_transformation_->GetElement (1, 2),
                            actor.viewpoint_transformation_->GetElement (2, 3) - actor.viewpoint_transformation_->GetElement (2, 2));

        cam->SetViewUp (actor.viewpoint_transformation_->GetElement (0, 1),
                        actor.viewpoint_transformation_->GetElement (1, 1),
                        actor.viewpoint_transformation_->GetElement (2, 1));
      }
      else
      {
        cam->SetPosition (0, 0, 0);
        cam->SetFocalPoint (0, 0, 1);
        cam->SetViewUp (0, -1, 0);
      }

      // go to the next actor for the next key-press event.
      if (it != actors_->end ())
        ++it;
      else
        it = actors_->begin ();
      
      CurrentRenderer->SetActiveCamera (cam);
      CurrentRenderer->ResetCameraClippingRange ();
      CurrentRenderer->Render ();
      break;
    }

    case 'q': case 'Q':
    {
      Interactor->ExitCallback ();
      return;
    }
    default:
    {
      Superclass::OnKeyDown ();
      break;
    }
  }

  KeyboardEvent event (true, Interactor->GetKeySym (), Interactor->GetKeyCode (), Interactor->GetAltKey (), Interactor->GetControlKey (), Interactor->GetShiftKey ());
  keyboard_signal_ (event);

  rens_->Render ();
  Interactor->Render ();
}
bool OpenGLSdlGraphicsManager::notifyEvent(const Common::Event &event) {
	switch ((int)event.type) {
	case Common::EVENT_KEYDOWN:
		if (event.kbd.hasFlags(Common::KBD_ALT)) {
			// Alt-Return and Alt-Enter toggle full screen mode
			if (event.kbd.keycode == Common::KEYCODE_RETURN ||
				event.kbd.keycode == (Common::KeyCode)SDLK_KP_ENTER) {
				toggleFullScreen(0);
				return true;
			}

			// Alt-S create a screenshot
			if (event.kbd.keycode == 's') {
				Common::String filename;

				for (int n = 0;; n++) {
					SDL_RWops *file;

					filename = Common::String::format("scummvm%05d.bmp", n);
					file = SDL_RWFromFile(filename.c_str(), "r");
					if (!file)
						break;
					SDL_RWclose(file);
				}
				if (saveScreenshot(filename.c_str()))
					debug("Saved screenshot '%s'", filename.c_str());
				else
					warning("Could not save screenshot");
				return true;
			}
		}

		if (event.kbd.hasFlags(Common::KBD_CTRL|Common::KBD_ALT)) {
			// Ctrl-Alt-Return and Ctrl-Alt-Enter switch between full screen modes
			if (event.kbd.keycode == Common::KEYCODE_RETURN ||
				event.kbd.keycode == (Common::KeyCode)SDLK_KP_ENTER) {
				toggleFullScreen(1);
				return true;
			}

			// Ctrl-Alt-a switch between display modes
			if (event.kbd.keycode == 'a') {
				beginGFXTransaction();
					setFeatureState(OSystem::kFeatureAspectRatioCorrection, !getFeatureState(OSystem::kFeatureAspectRatioCorrection));
				endGFXTransaction();
#ifdef USE_OSD
			Common::String osdMessage;
			if (getFeatureState(OSystem::kFeatureAspectRatioCorrection))
				osdMessage = Common::String::format("%s\n%d x %d -> %d x %d",
				        _("Enabled aspect ratio correction"),
				        _videoMode.screenWidth, _videoMode.screenHeight,
				        _hwscreen->w, _hwscreen->h);
			else
				osdMessage = Common::String::format("%s\n%d x %d -> %d x %d",
				        _("Disabled aspect ratio correction"),
				        _videoMode.screenWidth, _videoMode.screenHeight,
				        _hwscreen->w, _hwscreen->h);
			displayMessageOnOSD(osdMessage.c_str());
#endif
				internUpdateScreen();
				return true;
			}

			// Ctrl-Alt-f toggles antialiasing
			if (event.kbd.keycode == 'f') {
				beginGFXTransaction();
					toggleAntialiasing();
				endGFXTransaction();

#ifdef USE_OSD
				// TODO: This makes guesses about what internal antialiasing
				// modes we use, we might want to consider a better way of
				// displaying information to the user.
				if (getAntialiasingState())
					displayMessageOnOSD(_("Active filter mode: Linear"));
				else
					displayMessageOnOSD(_("Active filter mode: Nearest"));
#endif
				return true;
			}

			SDLKey sdlKey = (SDLKey)event.kbd.keycode;

			// Ctrl+Alt+Plus/Minus Increase/decrease the scale factor
			if ((sdlKey == SDLK_EQUALS || sdlKey == SDLK_PLUS || sdlKey == SDLK_MINUS ||
				sdlKey == SDLK_KP_PLUS || sdlKey == SDLK_KP_MINUS)) {
				int factor = getScale();
				factor += (sdlKey == SDLK_MINUS || sdlKey == SDLK_KP_MINUS) ? -1 : +1;
				if (0 < factor && factor < 4) {
					// Check if the desktop resolution has been detected
					if (_desktopWidth > 0 && _desktopHeight > 0)
						// If the new scale factor is too big, do not scale
						if (_videoMode.screenWidth * factor > _desktopWidth ||
							_videoMode.screenHeight * factor > _desktopHeight)
							return false;

					beginGFXTransaction();
						setScale(factor);
					endGFXTransaction();
#ifdef USE_OSD
					displayScaleChangedMsg();
#endif
					return true;
				}
			}

			const bool isNormalNumber = (SDLK_1 <= sdlKey && sdlKey <= SDLK_3);
			const bool isKeypadNumber = (SDLK_KP1 <= sdlKey && sdlKey <= SDLK_KP3);

			// Ctrl-Alt-<number key> will change the GFX mode
			if (isNormalNumber || isKeypadNumber) {
				if (sdlKey - (isNormalNumber ? SDLK_1 : SDLK_KP1) <= 3) {
#ifdef USE_OSD
					int lastMode = _videoMode.mode;
#endif
					// We need to query the scale and set it up, because
					// setGraphicsMode sets the default scale to 2
					int oldScale = getScale();
					beginGFXTransaction();
						setGraphicsMode(sdlKey - (isNormalNumber ? SDLK_1 : SDLK_KP1));
						setScale(oldScale);
					endGFXTransaction();
#ifdef USE_OSD
					if (lastMode != _videoMode.mode)
						displayModeChangedMsg();
#endif
					internUpdateScreen();
				}
			}
		}

		if (event.kbd.hasFlags(Common::KBD_CTRL|Common::KBD_SHIFT)) {
			// Ctrl-Shift-Return and Ctrl-Shift-Enter switch backwards between full screen modes
			if (event.kbd.keycode == Common::KEYCODE_RETURN ||
				event.kbd.keycode == (Common::KeyCode)SDLK_KP_ENTER) {
				toggleFullScreen(-1);
				return true;
			}
		}
		break;

	case Common::EVENT_KEYUP:
		return isHotkey(event);

	default:
		break;
	}

	return false;
}
/**
 * This method is call on press of key
 */
void Visualizer::onKeyboard(unsigned char key, int, int)
{
  	if (key>='A' && key<='Z') key+='a'-'A';       /* convert upper char on lower */

  	switch (key) {                                /* press key */
    		case '1' :                                  	/* show vertex */
      			glPolygonMode(GL_FRONT, GL_POINT);
      			glPolygonMode(GL_BACK, GL_POINT);
      			glutPostRedisplay();
      			break;
    		case '2' :                                  	/* show wireframe */
      			glPolygonMode(GL_FRONT, GL_LINE);
      			glPolygonMode(GL_BACK, GL_LINE);
      			glutPostRedisplay();
     			break;
    		case '3' :                                  	/* show fill polygons */
      			glPolygonMode(GL_FRONT, GL_FILL);
      			glPolygonMode(GL_BACK, GL_FILL);
      			glutPostRedisplay();
      			break;
    		case '5' :                                  	/* decrease vision angle */
      			if (fov>0) fov--;
      			onReshape(WindowWidth, WindowHeight);
      			glutPostRedisplay();
     			break;
    		case '6' :
      			if (fov<180) fov++;                     /* increase vision angle */
      			onReshape(WindowWidth, WindowHeight);
      			glutPostRedisplay();
      			break;
    		case '7' :                                  	/* zoom in trim plain */
      			if (line_width > 0) line_width -= 0.5;	
		  	glLineWidth(line_width);                
		  	glPointSize(line_width);                
      			onReshape(WindowWidth, WindowHeight);
      			glutPostRedisplay();
      			break;
    		case '8' :                                  	/* zoom out trim plain */
      			if (line_width < 10) line_width += 0.5;
		  	glLineWidth(line_width);                
		  	glPointSize(line_width);                
      			onReshape(WindowWidth, WindowHeight);
      			glutPostRedisplay();
      			break;
		case 's' :				    	/* print to bitmap - screenshot */
			saveScreenshot(screenshotFileName);
			break;
    		case 27 :                                   	/* Escape */
    		case 'q' :
      			exit(0);                                /* exit */
      			break;
    		case 'm' :
			colorInput = INTERPOLATE_RADIOSITY;	/* interpolate radiosity */
			createCallList();
			glutPostRedisplay();
			break;
    		case 'b' :
			colorInput = INTERPOLATE_RADIOSITY_RAW;	/* interpolate radiosity */
			createCallList();
			glutPostRedisplay();
			break;
    		case 'v' :
			colorInput = RADIOSITY;	/* radiosity */
			createCallList();
			glutPostRedisplay();
			break;
    		case 'n' :
			colorInput = RADIOSITY_LAST;	/* radiosity */
			createCallList();
			glutPostRedisplay();
			break;
		case 'z' :
			colorInput = REFLECTIVITY;	/* reflectivity + emission */
			createCallList();
			glutPostRedisplay();
			break;
		case 'x' :
			colorInput = EMISSION;	/* reflectivity */
			createCallList();
			glutPostRedisplay();
			break;
		case 'c' :
			colorInput = REFLECT_EMISS;	/* emission */
			createCallList();
			glutPostRedisplay();
			break;
   		case 'f' :
      			glutFullScreen();                      	/* fullscrean */
      			break;
    		case 'w' :
      			glutReshapeWindow(WindowWidth, WindowHeight);              /* go back to window */
      			break;
    		default:
      			break;
  	}
}