Ejemplo n.º 1
0
int main(int argc, char** argv)
{
	int gameState = 0;
	
	srand(time(NULL));
	// ================ Initialising ! ================
	// Create main window
	// Black screen
	sf::RenderWindow App(sf::VideoMode(WINDOW_WIDTH, WINDOW_HEIGHT), "SIMPLE RUMBLE !!!");
	
	sf::CircleShape circle;
	circle.setRadius(150);
	circle.setOutlineColor(sf::Color::Red);
	circle.setOutlineThickness(5);
	circle.setPosition(10, 20);
//	App.draw(circle);

	sf::Clock clock;
	while (App.isOpen())
	{
		// Process events
		sf::Event event;
		sf::Time elapsedTime = clock.getElapsedTime();
		clock.restart();

		while (App.pollEvent(event))
		{
			// Event processing
			if(event.type == sf::Event::Closed){ App.close(); }
			if(event.type == sf::Event::KeyPressed)
			{
				if (event.key.code == sf::Keyboard::Escape){ App.close(); }
			}
		}
		App.draw(circle);
		App.display();
	}

	return EXIT_SUCCESS;
}
int
main(int argc, char** argv) 
{
  int rc = 0;
  Miro::Client client(argc, argv);

  try {
    QApplication App(argc, argv);
    PolicyEditorClass PolicyEditor(argc, argv, client);
    

    // TODO warning dialog
    if (argc>2) { 
      std::cout << argv[0] << " [policyfile]" << std::endl; 
      return 1;
    }

    // TODO load comman line argument policy here

    App.setMainWidget(&PolicyEditor);
    PolicyEditor.show();
    App.exec();
    
  }

  catch (const std::string& s) {
    std::cerr << "Uncought exception: " << s << std::endl;
    rc = 1;
  }
  catch (const Miro::Exception& e) {
    std::cerr << "Uncought Miro exception: " << e << endl;
    rc = 1;
  }
  catch (const CORBA::Exception& e) {
    std::cerr << "Uncought CORBA exception: " << e << endl;
    rc = 1;
  }

  return rc;
}
Ejemplo n.º 3
0
int main(int argc, char *argv[]) {
	QApplication App(argc, argv);
	QImage MemoryImage("D:/Vyzkumak/Workspace/Qt/Qt/Debug/Picture.png");
	QImage ShowImage("D:/Vyzkumak/Workspace/Qt/Qt/Debug/Picture.png");
	QLabel label;
	label.setPixmap(QPixmap::fromImage(ShowImage));
	label.show();

    int w = MemoryImage.width();
    int h = MemoryImage.height();
	start = time (NULL);
	for (int j=0; j<1; j++){
		qreal H, S, V;
		QColor Color;
		qreal cont=0;
		for (int i=0; i<100; i++){
			cont=cont+0.01;

			for ( int x = 0; x < w; x++ ){
				for ( int y = 0; y < h; y++ ){
					QRgb Rgb = MemoryImage.pixel( x, y);
					Color.setRgb(Rgb);
					Color.getHsvF(&H, &S, &V);
					qreal v=V*cont;
					Color.setHsvF(H, S, v);
					Rgb = Color.rgb();
					ShowImage.setPixel(x, y, Rgb);
				}
			}
			label.setPixmap(QPixmap::fromImage(ShowImage));
			label.repaint();
		}
	}
	end = time (NULL);
	int length = (int) (end - start);
	std::cout << "Length of rendering 100 frames was: " << length << " seconds.\n";
	std::cout << "Average fps is: " << 100. / (float)length << " frames per seconds.\n";
	App.exec();
}
Ejemplo n.º 4
0
int main(int argc, char** argv) {
    GApp::Settings settings;
    
    settings.useDeveloperTools = false;

    settings.window.fullScreen = false;
    settings.window.framed = ! settings.window.fullScreen;
    settings.window.msaaSamples = 1;
    settings.dataDir = "./";
    settings.window.defaultIconFilename = "g3d.ico";

#   ifdef G3D_WIN32
	if (!FileSystem::exists(settings.window.defaultIconFilename)) {
        // We are probably running in the debugger and launched from the wrong directory
        chdir("../build/win-i386-vc9.0/bin/gfxmeter");
		debugAssert(FileSystem::exists(settings.window.defaultIconFilename));
    }
#   endif

    App(settings).run();
    return 0;
}
Ejemplo n.º 5
0
void OBSBasicPreview::GetStretchHandleData(const vec2 &pos)
{
	OBSBasic *main = reinterpret_cast<OBSBasic*>(App()->GetMainWindow());

	OBSScene scene = main->GetCurrentScene();
	if (!scene)
		return;

	HandleFindData data(pos, main->previewScale);
	obs_scene_enum_items(scene, FindHandleAtPos, &data);

	stretchItem     = std::move(data.item);
	stretchHandle   = data.handle;

	if (stretchHandle != ItemHandle::None) {
		matrix4 boxTransform;
		vec3    itemUL;
		float   itemRot;

		stretchItemSize = GetItemSize(stretchItem);

		obs_sceneitem_get_box_transform(stretchItem, &boxTransform);
		itemRot = obs_sceneitem_getrot(stretchItem);
		vec3_from_vec4(&itemUL, &boxTransform.t);

		/* build the item space conversion matrices */
		matrix4_identity(&itemToScreen);
		matrix4_rotate_aa4f(&itemToScreen, &itemToScreen,
				0.0f, 0.0f, 1.0f, RAD(itemRot));
		matrix4_translate3f(&itemToScreen, &itemToScreen,
				itemUL.x, itemUL.y, 0.0f);

		matrix4_identity(&screenToItem);
		matrix4_translate3f(&screenToItem, &screenToItem,
				-itemUL.x, -itemUL.y, 0.0f);
		matrix4_rotate_aa4f(&screenToItem, &screenToItem,
				0.0f, 0.0f, 1.0f, RAD(-itemRot));
	}
}
Ejemplo n.º 6
0
Archivo: main.cpp Proyecto: jmimu/DDcar
int main(int argc, char** argv)
{
    (void) argc;
    (void) argv;

    sf::Font MyFont;
    //MyFont.LoadFromFile("data/Polsku.ttf");
    MyFont.LoadFromFile("data/Junicode-Bold.ttf");

    // Create main window
    sf::RenderWindow App(sf::VideoMode(SCREEN_W, SCREEN_H), "DDcar", sf::Style::Fullscreen);
    App.UseVerticalSync(true);

    App.SetFramerateLimit(60);
    //const sf::Input& Input = App.GetInput();

    //main menu ?
    Menu menu(&App,&MyFont);
    menu.create();

    bool quit_game=false;
    while (!quit_game)
    {
      if (menu.show())
	{
	  quit_game=true;continue;
	}

      //Race race(&App,"data/track2.xml",15);
      Race race(&App,&MyFont,menu.get_track(),menu.get_rule(),menu.get_nbr_cars());
      if (race.run())
        {
	  quit_game=true;
        }
    }
    App.Close();

	return 0;
}
Ejemplo n.º 7
0
OBSProjector::OBSProjector(QWidget *widget, obs_source_t *source_, bool window)
	: OBSQTDisplay                 (widget,
	                                Qt::Window),
	  source                       (source_),
	  removedSignal                (obs_source_get_signal_handler(source),
	                                "remove", OBSSourceRemoved, this)
{
	if (!window) {
		setWindowFlags(Qt::FramelessWindowHint |
				Qt::X11BypassWindowManagerHint);
	}

	setAttribute(Qt::WA_DeleteOnClose, true);

	//disable application quit when last window closed
	setAttribute(Qt::WA_QuitOnClose, false);

	installEventFilter(CreateShortcutFilter());

	auto addDrawCallback = [this] ()
	{
		obs_display_add_draw_callback(GetDisplay(), OBSRender, this);
		obs_display_set_background_color(GetDisplay(), 0x000000);
	};

	connect(this, &OBSQTDisplay::DisplayCreated, addDrawCallback);

	bool hideCursor = config_get_bool(GetGlobalConfig(),
			"BasicWindow", "HideProjectorCursor");
	if (hideCursor && !window) {
		QPixmap empty(16, 16);
		empty.fill(Qt::transparent);
		setCursor(QCursor(empty));
	}

	App()->IncrementSleepInhibition();
	resize(480, 270);
}
Ejemplo n.º 8
0
bool OBSBasicPreview::DrawSelectedItem(obs_scene_t scene, obs_sceneitem_t item,
		void *param)
{
	if (!obs_sceneitem_selected(item))
		return true;

	OBSBasic *main = reinterpret_cast<OBSBasic*>(App()->GetMainWindow());

	gs_load_vertexbuffer(main->circle);

	matrix4 boxTransform;
	obs_sceneitem_get_box_transform(item, &boxTransform);

	gs_matrix_push();
	gs_matrix_scale3f(HANDLE_RADIUS, HANDLE_RADIUS, 1.0f);
	DrawCircleAtPos(0.0f, 0.0f, boxTransform, main->previewScale);
	DrawCircleAtPos(0.0f, 1.0f, boxTransform, main->previewScale);
	DrawCircleAtPos(1.0f, 0.0f, boxTransform, main->previewScale);
	DrawCircleAtPos(1.0f, 1.0f, boxTransform, main->previewScale);
	DrawCircleAtPos(0.5f, 0.0f, boxTransform, main->previewScale);
	DrawCircleAtPos(0.0f, 0.5f, boxTransform, main->previewScale);
	DrawCircleAtPos(0.5f, 1.0f, boxTransform, main->previewScale);
	DrawCircleAtPos(1.0f, 0.5f, boxTransform, main->previewScale);
	gs_matrix_pop();

	gs_load_vertexbuffer(main->box);

	gs_matrix_push();
	gs_matrix_set(&boxTransform);
	gs_matrix_scale3f(main->previewScale, main->previewScale, 1.0f);
	gs_draw(GS_LINESTRIP, 0, 0);

	gs_matrix_pop();

	UNUSED_PARAMETER(scene);
	UNUSED_PARAMETER(param);
	return true;
}
Ejemplo n.º 9
0
Archivo: App.cpp Proyecto: lieff/g3d
int main(int argc, const char* argv[]) {
    {
        G3DSpecification g3dSpec;
        g3dSpec.audio = false;
        initGLG3D(g3dSpec);
    }

    GApp::Settings settings(argc, argv);

    // Change the window and other startup parameters by modifying the
    // settings class.  For example:
    settings.window.caption             = argv[0];
    // settings.window.debugContext     = true;

    // settings.window.width              =  854; settings.window.height       = 480;
    // settings.window.width            = 1024; settings.window.height       = 768;
     settings.window.width            = 1280; settings.window.height       = 720;
//    settings.window.width               = 1920; settings.window.height       = 1080;
    // settings.window.width            = OSWindow::primaryDisplayWindowSize().x; settings.window.height = OSWindow::primaryDisplayWindowSize().y;
    settings.window.fullScreen          = false;
    settings.window.resizable           = ! settings.window.fullScreen;
    settings.window.framed              = ! settings.window.fullScreen;

    // Set to true for a significant performance boost if your app can't render at 60fps,
    // or if you *want* to render faster than the display.
    settings.window.asynchronous        = false;

    settings.depthGuardBandThickness    = Vector2int16(64, 64);
    settings.colorGuardBandThickness    = Vector2int16(0, 0);
    settings.dataDir                    = FileSystem::currentDirectory();
    settings.screenshotDirectory        = "../journal/";

    settings.renderer.deferredShading = false;
    settings.renderer.orderIndependentTransparency = false;


    return App(settings).run();
}
Ejemplo n.º 10
0
void OBSBasicPreview::DrawSceneEditing()
{
	OBSBasic *main = reinterpret_cast<OBSBasic*>(App()->GetMainWindow());

	effect_t    solid = obs_get_solid_effect();
	technique_t tech  = effect_gettechnique(solid, "Solid");

	vec4 color;
	vec4_set(&color, 1.0f, 0.0f, 0.0f, 1.0f);
	effect_setvec4(solid, effect_getparambyname(solid, "color"), &color);

	technique_begin(tech);
	technique_beginpass(tech, 0);

	OBSScene scene = main->GetCurrentScene();
	if (scene)
		obs_scene_enum_items(scene, DrawSelectedItem, this);

	gs_load_vertexbuffer(nullptr);

	technique_endpass(tech);
	technique_end(tech);
}
void OBSBasic::on_actionExportProfile_triggered()
{
	char path[512];

	QString home = QDir::homePath();

	QString currentProfile =
		QString::fromUtf8(config_get_string(App()->GlobalConfig(),
		"Basic", "ProfileDir"));

	int ret = GetConfigPath(path, 512, "obs-studio/basic/profiles/");
	if (ret <= 0) {
		blog(LOG_WARNING, "Failed to get profile config path");
		return;
	}

	QString dir = QFileDialog::getExistingDirectory(
			this,
			QTStr("Basic.MainMenu.Profile.Export"),
			home,
			QFileDialog::ShowDirsOnly |
			QFileDialog::DontResolveSymlinks);

	if (!dir.isEmpty() && !dir.isNull()) {
		QString outputDir = dir + "/" + currentProfile;
		QString inputPath = QString::fromUtf8(path);
		QDir folder(outputDir);

		if (!folder.exists()) {
			folder.mkpath(outputDir);
			QFile::copy(inputPath + currentProfile + "/basic.ini",
					outputDir + "/basic.ini");
			QFile::copy(inputPath + currentProfile + "/service.json",
					outputDir + "/service.json");
		}
	}
}
Ejemplo n.º 12
0
int main()
{
    // Create the main window
    sf::RenderWindow App(sf::VideoMode(800, 600, 32), "Hello World - SFML");
 
    // Start the main loop
    while (App.isOpen())
    {
        // Process events
        sf::Event Event;
        while (App.pollEvent(Event))
        {
            // Close window : exit
            if (Event.type == sf::Event::Closed)
                App.close();
        }
        // Clear screen, and fill it with blue
        App.clear(sf::Color::Blue);
 
        // Display the content of the window on screen
        App.display();
    }
    return 0;
}
bool AddNew(QWidget *parent, const char *id, const char *name,
		const bool visible, OBSSource &newSource)
{
	OBSBasic     *main = reinterpret_cast<OBSBasic*>(App()->GetMainWindow());
	OBSScene     scene = main->GetCurrentScene();
	bool         success = false;
	if (!scene)
		return false;

	obs_source_t *source = obs_get_source_by_name(name);
	if (source) {
		OBSMessageBox::information(parent,
				QTStr("NameExists.Title"),
				QTStr("NameExists.Text"));

	} else {
		source = obs_source_create(id, name, NULL, nullptr);

		if (source) {
			AddSourceData data;
			data.source = source;
			data.visible = visible;

			obs_enter_graphics();
			obs_scene_atomic_update(scene, AddSource, &data);
			obs_leave_graphics();

			newSource = source;

			success = true;
		}
	}

	obs_source_release(source);
	return success;
}
Ejemplo n.º 14
0
vec3 OBSBasicPreview::GetScreenSnapOffset(const vec3 &tl, const vec3 &br)
{
	OBSBasic *main = reinterpret_cast<OBSBasic*>(App()->GetMainWindow());
	vec2 screenSize = GetOBSScreenSize();
	vec3 clampOffset;

	vec3_zero(&clampOffset);

	const float clampDist = CLAMP_DISTANCE / main->previewScale;

	if (fabsf(tl.x) < clampDist)
		clampOffset.x = -tl.x;
	if (fabsf(clampOffset.x) < EPSILON &&
	    fabsf(screenSize.x - br.x) < clampDist)
		clampOffset.x = screenSize.x - br.x;

	if (fabsf(tl.y) < clampDist)
		clampOffset.y = -tl.y;
	if (fabsf(clampOffset.y) < EPSILON &&
	    fabsf(screenSize.y - br.y) < clampDist)
		clampOffset.y = screenSize.y - br.y;

	return clampOffset;
}
Ejemplo n.º 15
0
int main()
{
	bool x = true;

	sf::Clock clock;
	float lastTime = clock.GetElapsedTime();
    sf::RenderWindow App(sf::VideoMode(800, 600), "Rogalik");
	ImageRes::getInstance().loadImages("tiles.png", 8, 0);
	Game game;


    while (App.IsOpened())
    {
        sf::Event Event;
        while (App.GetEvent(Event))
        {
            if (Event.Type == sf::Event::Closed)
                App.Close();
            else if (Event.Type == sf::Event::KeyPressed)
			{
				game.getInput(Event.Key);
			}
			
        }

		float dt = clock.GetElapsedTime() - lastTime;
		lastTime += dt;

        App.Clear();
		game.draw(App);
		
        App.Display();
    }

    return EXIT_SUCCESS;
}
Ejemplo n.º 16
0
void testFullRender(bool generateGoldStandard) {
    initGLG3D();

    GApp::Settings settings;

    settings.window.caption			= "Test Renders";
    settings.window.width        = 1280; settings.window.height       = 720;
    settings.film.preferredColorFormats.clear();
    settings.film.preferredColorFormats.append(ImageFormat::RGB32F());

	// Enable vsync.  Disable for a significant performance boost if your app can't render at 60fps,
	// or if you *want* to render faster than the display.
	settings.window.asynchronous	= false;
    settings.depthGuardBandThickness    = Vector2int16(64, 64);
    settings.colorGuardBandThickness    = Vector2int16(16, 16);
    settings.dataDir				= FileSystem::currentDirectory();
    if(generateGoldStandard) { // Warning! Do not change these directories without changing the App... it relies on these directories to tell what mode we are in
        settings.screenshotDirectory	= "../data-files/RenderTest/GoldStandard";
    } else {
        settings.screenshotDirectory	= "../data-files/RenderTest/Results";
    }  
    int result = App(settings).run();
    testAssertM(result == 0 ,"App failed to run");
}
void OBSBasic::RefreshSceneCollections()
{
	QList<QAction*> menuActions = ui->sceneCollectionMenu->actions();
	int count = 0;

	for (int i = 0; i < menuActions.count(); i++) {
		QVariant v = menuActions[i]->property("fileName");
		if (v.typeName() != nullptr)
			delete menuActions[i];
	}

	const char *cur_name = config_get_string(App()->GlobalConfig(),
			"Basic", "SceneCollection");

	auto addCollection = [&](const char *name, const char *path)
	{
		std::string file = strrchr(path, '/') + 1;
		file.erase(file.size() - 5, 5);

		QAction *action = new QAction(QT_UTF8(name), this);
		action->setProperty("fileName", QT_UTF8(path));
		connect(action, &QAction::triggered,
				this, &OBSBasic::ChangeSceneCollection);
		action->setCheckable(true);

		action->setChecked(strcmp(name, cur_name) == 0);

		ui->sceneCollectionMenu->addAction(action);
		count++;
		return true;
	};

	EnumSceneCollections(addCollection);

	ui->actionRemoveSceneCollection->setEnabled(count > 1);
}
void SplineGenerator::drawSpline(Path p,int x, int y)
{
    sf::RenderWindow App(sf::VideoMode(x, y, 32), "SFML Graphics");

    // Start game loop
    while (App.IsOpened())
    {
        // Process events
        sf::Event Event;
        while (App.GetEvent(Event))
        {
            // Close window : exit
            if (Event.Type == sf::Event::Closed)
                App.Close();
        }

        // Clear the screen (fill it with black color)
        App.Clear();

        //Draw path
        Path::iterator iPath = p.begin();
        Vector2d prevPoint = *iPath;
        ++iPath;
        while(iPath!=p.end())
        {
            Vector2d currPoint = *iPath;
            sf::Shape line   = sf::Shape::Line(prevPoint.x * x, prevPoint.y * y,currPoint.x * x , currPoint.y * y, 1, sf::Color::Red);
            App.Draw(line);
            ++iPath;
            prevPoint = currPoint;
        }

        // Display window contents on screen
        App.Display();
    }
}
Ejemplo n.º 19
0
int main()
{
    srand(static_cast<unsigned int> (time(NULL)));

    // Create the main window
    sf::RenderWindow App(sf::VideoMode(WINDOW_W, WINDOW_H), "Game of Life");
	App.setFramerateLimit(60);
    sf::Clock clock;
    float elapsedTime=0;

    //Game of life;
    CellularAutomaton gameOfLife(WINDOW_W, WINDOW_H);
	int gen=0;
    bool pausedGame = true;

    //View (pour zoom)
	sf::View mainView = App.getDefaultView();
    sf::View zoomView;
    zoomView.setSize(WINDOW_W / ZOOM_FRACTION, WINDOW_H / ZOOM_FRACTION);
    bool zoom = false;

        // Start the game loop
    while (App.isOpen())
    {
        // Process events
        sf::Event event;
        while (App.pollEvent(event))
        {
            // Close window : exit
            if (event.type == sf::Event::Closed)
                App.close();
            // Simulation controls
            if (event.type == sf::Event::KeyPressed)
            {
				switch(event.key.code)
				{
				case sf::Keyboard::Space : // Pause simulation
					if(event.key.code == sf::Keyboard::Space)
					{
						if(pausedGame)
							pausedGame = false;
						else
							pausedGame = true;
					}
					break;
				case sf::Keyboard::Z : // Toggle zoom
					if(event.key.code == sf::Keyboard::Z)
					{
						if(zoom)
						{
							zoom = false;
							App.setView(App.getDefaultView());
						}
						else
						{
							zoom = true;
							App.setView(zoomView);
						}
					}
					break;
				case sf::Keyboard::R : // reset grid with random cell states
                    gameOfLife.reset();
					break;
				case sf::Keyboard::C: // clear all living cells
                    gameOfLife.clear(false);
					break;
				case sf::Keyboard::Right :
					if(pausedGame)
					{
						if(event.key.control)
							for(unsigned int i=0; i<10; i++)
								gameOfLife.nextStep();
						else
							gameOfLife.nextStep();
					}
					break;
				default :
					break;
				}
            }
            if(event.type == sf::Event::MouseMoved)
            {
                if(!zoom)
                {
					sf::Vector2f mousePos =  App.mapPixelToCoords(sf::Mouse::getPosition(App));

					mousePos.x = floor(mousePos.x);
					mousePos.y = floor(mousePos.y);
                    zoomView.setCenter(mousePos);
                }
            }

            // Change cell state according to mouse button
            if(event.type == sf::Event::MouseButtonReleased && zoom)
            {
                sf::Vector2f mousePos =  App.mapPixelToCoords(sf::Mouse::getPosition(App));

                mousePos.x = floor(mousePos.x);
                mousePos.y = floor(mousePos.y);

                if(event.mouseButton.button == sf::Mouse::Left)
                    gameOfLife.setCell((int) mousePos.x, (int) mousePos.y, true);
                if(event.mouseButton.button == sf::Mouse::Right)
                    gameOfLife.setCell((int) mousePos.x, (int) mousePos.y, false);
            }

			if(event.type == sf::Event::Resized)
			{
				mainView.setSize((float)App.getSize().x, (float)App.getSize().y);
				mainView.setCenter(App.getSize().x/2.f, App.getSize().y/2.f);
				zoomView.setSize((float)App.getSize().x / ZOOM_FRACTION, (float)App.getSize().y / ZOOM_FRACTION);
				gameOfLife.resize(App.getSize().x, App.getSize().y);
			}
        }

        if(zoom)
        {
            sf::Vector2i mousePos =  sf::Mouse::getPosition(App);

            if(mousePos.x < SCROLL_WIDTH)
                zoomView.move(elapsedTime*(-SCROLL_SPEED), 0);
            else if(mousePos.x > (int)(App.getSize().x - SCROLL_WIDTH))
                zoomView.move(elapsedTime*(SCROLL_SPEED), 0);

            if(mousePos.y < SCROLL_WIDTH)
                zoomView.move(0, elapsedTime*(-SCROLL_SPEED));
            else if(mousePos.y > (int)(App.getSize().y - SCROLL_WIDTH))
                zoomView.move(0, elapsedTime*(SCROLL_SPEED));

            App.setView(zoomView);
        }
		else
			App.setView(mainView);


        if(!pausedGame)
            gameOfLife.nextStep();

        App.clear(sf::Color(GREY,GREY,GREY));

		gameOfLife.draw(App);

		App.display();
		
		elapsedTime = clock.getElapsedTime().asSeconds();
		clock.restart();
    }

    return EXIT_SUCCESS;
}
void OBSBasic::on_actionRemoveProfile_triggered()
{
	std::string newName;
	std::string newPath;
	ConfigFile config;

	std::string oldDir = config_get_string(App()->GlobalConfig(),
			"Basic", "ProfileDir");
	std::string oldName = config_get_string(App()->GlobalConfig(),
			"Basic", "Profile");

	auto cb = [&](const char *name, const char *filePath)
	{
		if (strcmp(oldName.c_str(), name) != 0) {
			newName = name;
			newPath = filePath;
			return false;
		}

		return true;
	};

	EnumProfiles(cb);

	/* this should never be true due to menu item being grayed out */
	if (newPath.empty())
		return;

	QString text = QTStr("ConfirmRemove.Text");
	text.replace("$1", QT_UTF8(oldName.c_str()));

	QMessageBox::StandardButton button = QMessageBox::question(this,
			QTStr("ConfirmRemove.Title"), text);
	if (button == QMessageBox::No)
		return;

	size_t newPath_len = newPath.size();
	newPath += "/basic.ini";

	if (config.Open(newPath.c_str(), CONFIG_OPEN_ALWAYS) != 0) {
		blog(LOG_ERROR, "ChangeProfile: Failed to load file '%s'",
				newPath.c_str());
		return;
	}

	newPath.resize(newPath_len);

	const char *newDir = strrchr(newPath.c_str(), '/') + 1;

	config_set_string(App()->GlobalConfig(), "Basic", "Profile",
			newName.c_str());
	config_set_string(App()->GlobalConfig(), "Basic", "ProfileDir",
			newDir);

	config.Swap(basicConfig);
	InitBasicConfigDefaults();
	ResetProfileData();
	DeleteProfile(oldName.c_str(), oldDir.c_str());
	RefreshProfiles();
	config_save_safe(App()->GlobalConfig(), "tmp", nullptr);

	blog(LOG_INFO, "Switched to profile '%s' (%s)",
			newName.c_str(), newDir);
	blog(LOG_INFO, "------------------------------------------------");

	UpdateTitleBar();
}
Ejemplo n.º 21
0
////////////////////////////////////////////////////////////
/// Entry point of application
///
/// \return Application exit code
///
////////////////////////////////////////////////////////////
int main()
{
	// Create the window of the application
	sf::RenderWindow App( sf::VideoMode( 1004, 650, 32 ), "GWEN: SFML", sf::Style::Close );

	Gwen::Renderer::SFML GwenRenderer( App );

	//
	// Create a GWEN skin
	//
	//Gwen::Skin::Simple skin;
	//skin.SetRender( &GwenRenderer );

	Gwen::Skin::TexturedBase skin( &GwenRenderer );
	skin.Init( "DefaultSkin.png" );

	// The fonts work differently in SFML - it can't use
	// system fonts. So force the skin to use a local one.
	skin.SetDefaultFont( L"OpenSans.ttf", 11 );


	//
	// Create a Canvas (it's root, on which all other GWEN panels are created)
	//
	Gwen::Controls::Canvas* pCanvas = new Gwen::Controls::Canvas( &skin );
	pCanvas->SetSize( App.GetWidth(), App.GetHeight() );
	pCanvas->SetDrawBackground( true );
	pCanvas->SetBackgroundColor( Gwen::Color( 150, 170, 170, 255 ) );


	//
	// Create our unittest control (which is a Window with controls in it)
	//
	UnitTest* pUnit = new UnitTest( pCanvas );
	//pUnit->SetPos( 10, 10 );

	//
	// Create an input processor
	//
	Gwen::Input::SFML GwenInput;
	GwenInput.Initialize( pCanvas );
	
#if SFML_VERSION_MAJOR == 2
	while ( App.IsOpen() )
#else
	while ( App.IsOpened() )
#endif
	{
		// Handle events
		sf::Event Event;

#if SFML_VERSION_MAJOR == 2
		while ( App.PollEvent(Event) )
#else
		while ( App.GetEvent(Event) )
#endif
		{
			// Window closed or escape key pressed : exit
#if SFML_VERSION_MAJOR == 2
			if ((Event.Type == sf::Event::Closed) || 
				((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Keyboard::Escape)))
#else
			if ((Event.Type == sf::Event::Closed) || 
				((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::Escape)))
#endif
			{
				App.Close();
				break;
			}

			GwenInput.ProcessMessage( Event );
		}

		// Clear the window
		App.Clear();
		
		pCanvas->RenderCanvas();
		
		App.Display();
	}

	return EXIT_SUCCESS;
}
Ejemplo n.º 22
0
int main(void)
{
  sf::Window App(sf::VideoMode(800, 600, 32), "SFML OpenGL");
  sf::Clock Clock;
  SDL_Surface *w = NULL;
  SDL_Surface *p = NULL;
  SDL_Rect pos;
  std::list<Button*> buttonList;
  int matrixBin[480][640];

  buttonList.push_back(new Button(new coords(320, 350, 100), 30));
  buttonList.push_back(new Button(new coords(350, 380, 100), 30));
  buttonList.push_back(new Button(new coords(380, 410, 100), 30));
  buttonList.push_back(new Button(new coords(410, 440, 100), 30));
  buttonList.push_back(new Button(new coords(440, 470, 100), 30));
  p = SDL_CreateRGBSurface(SDL_HWSURFACE, 1, 1, 32, 0, 0, 0, 0);
  SDL_Init(SDL_INIT_VIDEO);
  w = SDL_SetVideoMode(800, 600, 32, SDL_HWSURFACE);

  device = &freenect.createDevice<MyFreenectDevice>(0);
  device->startDepth();
  device->startVideo();
  // Set color and depth clear value
  glClearDepth(1.f);
  glClearColor(0.f, 0.f, 0.f, 0.f);
  // Enable Z-buffer read and write
  glEnable(GL_DEPTH_TEST);
  glDepthMask(GL_TRUE);
  
  GLuint gl_rgb_tex, gl_rgb_tex2;
  // glGenTextures(1, &gl_rgb_tex);
  glGenTextures(1, &gl_rgb_tex2);
  glBindTexture(GL_TEXTURE_2D, gl_rgb_tex2);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

  // glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);  // Setup a perspective projection
  // glBindTexture(GL_TEXTURE_2D, gl_rgb_tex);
  // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  // glMatrixMode(GL_MODELVIEW);
  gluPerspective(90.f, 1.f, 1.f, 2500.f);  App.SetActive();
  device->setVideoFormat((freenect_video_format)0);
  int x, y, z;
  x = -250;
  y = 100;
  z = -270;
  int r = 45;
  bool b = false;
  float rotateY = 0;
  while (App.IsOpened())
    {
      int tmpx = 0, tmpy = 0;
      while (tmpy < 480)
	{
	  tmpx = 0;
	  while (tmpx < 640)
	    {
	      matrixBin[tmpy][tmpx] = 0;
	      matrixDetectOrder[tmpy][tmpx] = 0;
	      ++tmpx;
	    }
	  ++tmpy;
	}
      sf::Event Event;
      glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
      glMatrixMode(GL_MODELVIEW);
      glLoadIdentity();
      
      glTranslatef(x, y, z);
      // glRotated(180, 1, 0, 0);
      // glBegin(GL_POINTS);
      // glPointSize(1.0);
      kk = 0;
      std::list<Button*>::iterator itBut = buttonList.begin();
      while (App.GetEvent(Event))
	{
	  if (Event.Type == sf::Event::Closed)
	    {
	      device->stopDepth();
	      device->stopVideo();
	      exit(0);
	    }
	  if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::Escape))
	    {
	      device->stopDepth();
	      device->stopVideo();
	      exit(0);
	    }
	  if ((Event.Type == sf::Event::KeyPressed))
	    {
	      if (Event.Key.Code == sf::Key::Z)
		{
		  --rotateY;
		}
	      if (Event.Key.Code == sf::Key::X)
		{
		  ++rotateY;
		}
	      if ((Event.Key.Code == sf::Key::Up))
		{
		  r += 10;
		  device->setTiltDegrees(r);
		}
	      if ((Event.Key.Code == sf::Key::Down))
		{
		  r -= 10;
		  device->setTiltDegrees(r);
		}
	      if ((Event.Key.Code == sf::Key::W))
		{z+=10;
		}
	      if ((Event.Key.Code == sf::Key::S))
		{z-=10;
		}
	      if ((Event.Key.Code == sf::Key::A))
		{x+=10;
		}
	      if ((Event.Key.Code == sf::Key::D))
		{x-=10;}
	      if ((Event.Key.Code == sf::Key::E))
		{y+=10;}
	      if ((Event.Key.Code == sf::Key::Q))
		{y-=10;}
	    }
	}
      if (b == false && device->m_new_depth_frame && device->m_new_rgb_frame)
      	{
      	  resetView(b);
      	}
      else if (device->m_new_depth_frame || device->m_new_rgb_frame)
	{
	  SDL_FillRect(w, NULL, SDL_MapRGB(w->format, 0, 0, 0));
	  glRotatef(rotateY, 0, 1,0);
	  glRotated(180, 1, 0, 0);
	  int i = 0, j = 0;
	  // LoadRGBMatrix();
	  // LoadVertexMatrix();
	  // LoadVertexMatrix();
	  glBegin(GL_POINTS);
	  int x = 0;
	  int y = 0;
	  glPointSize(1);
	  while (y < (480))
	    {
	      x = 0;
	      while (x < 640)
		{
		  if (rgb != 0)
		    {
		      if (y > 200)
			{
			  if (device->xyzCoords[y][x][2] < 2047
			      && xyzCoords[y][x][2] < 2047)
			    {
			      if(device->xyzCoords[y][x][2] < xyzCoords[y][x][2] - 2
				 && device->xyzCoords[y][x][2] > xyzCoords[y][x][2] - 20
				 && compareRgb(device, x, y))
				{
				  // glColor3f(device->rgb[(y * 640 + x) * 3] / 255.0, 
				  // 	    device->rgb[(y * 640 + x) * 3 + 1] / 255.0,
				  // 	    device->rgb[(y * 640 + x) * 3 + 2] / 255.0);
				  glColor3f(1, 1, 1);
				  SDL_FillRect(p, NULL, SDL_MapRGB(w->format, 255, 255,255));                          
				  pos.x = x;
				  pos.y = y;
				  SDL_BlitSurface(p, NULL, w, &pos);
				  glVertex3f(x, y, device->xyzCoords[y][x][2]);
				}
			      glColor3f(device->rgb[(y * 640 + x) * 3] / 255.0, 
					device->rgb[(y * 640 + x) * 3 + 1] / 255.0,
					device->rgb[(y * 640 + x) * 3 + 2] / 255.0);
			      glVertex3f(x, y, device->xyzCoords[y][x][2]);
			    }
			}
		    }
		  ++x;
		}
	      ++y;
	    }
	  glEnd();
	}
      fingList.clear();
      SDL_Flip(w);
      glFlush();
      App.Display();
    }
  return 0;
}
bool OBSBasic::AddProfile(bool create_new, const char *title, const char *text,
		const char *init_text)
{
	std::string newName;
	std::string newDir;
	ConfigFile config;

	if (!GetProfileName(this, newName, newDir, title, text, init_text))
		return false;

	std::string curDir = config_get_string(App()->GlobalConfig(),
			"Basic", "ProfileDir");

	char newPath[512];
	int ret = GetConfigPath(newPath, 512, "obs-studio/basic/profiles/");
	if (ret <= 0) {
		blog(LOG_WARNING, "Failed to get profiles config path");
		return false;
	}

	strcat(newPath, newDir.c_str());

	if (os_mkdir(newPath) < 0) {
		blog(LOG_WARNING, "Failed to create profile directory '%s'",
				newDir.c_str());
		return false;
	}

	if (!create_new)
		CopyProfile(curDir.c_str(), newPath);

	strcat(newPath, "/basic.ini");

	if (config.Open(newPath, CONFIG_OPEN_ALWAYS) != 0) {
		blog(LOG_ERROR, "Failed to open new config file '%s'",
				newDir.c_str());
		return false;
	}

	config_set_string(App()->GlobalConfig(), "Basic", "Profile",
			newName.c_str());
	config_set_string(App()->GlobalConfig(), "Basic", "ProfileDir",
			newDir.c_str());

	config_set_string(config, "General", "Name", newName.c_str());
	config.SaveSafe("tmp");
	config.Swap(basicConfig);
	InitBasicConfigDefaults();
	RefreshProfiles();

	if (create_new)
		ResetProfileData();

	blog(LOG_INFO, "Created profile '%s' (%s, %s)", newName.c_str(),
			create_new ? "clean" : "duplicate", newDir.c_str());
	blog(LOG_INFO, "------------------------------------------------");

	config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
	UpdateTitleBar();
	return true;
}
int main(int argc, char **argv)
{
    int     cErrors = 0;                  /* error count. */

    RTR3InitExe(argc, &argv, RTR3INIT_FLAGS_SUPLIB);
    RTPrintf(TESTCASE ": TESTING...\n");

    /*
     * Create empty VM.
     */
    PVM pVM;
    PUVM pUVM;
    int rc = VMR3Create(1, NULL, NULL, NULL, NULL, NULL, &pVM, &pUVM);
    if (RT_SUCCESS(rc))
    {
        /*
         * Instantiate the debugger GUI bits and run them.
         */
        QApplication App(argc, argv);
        PDBGGUI pGui;
        PCDBGGUIVT pGuiVT;
        rc = DBGGuiCreateForVM(pUVM, &pGui, &pGuiVT);
        if (RT_SUCCESS(rc))
        {
            if (argc <= 1 || argc == 2)
            {
                RTPrintf(TESTCASE ": calling pfnShowCommandLine...\n");
                rc = pGuiVT->pfnShowCommandLine(pGui);
                if (RT_FAILURE(rc))
                {
                    RTPrintf(TESTCASE ": error: pfnShowCommandLine failed! rc=%Rrc\n", rc);
                    cErrors++;
                }
            }

            if (argc <= 1 || argc == 3)
            {
                RTPrintf(TESTCASE ": calling pfnShowStatistics...\n");
                pGuiVT->pfnShowStatistics(pGui);
                if (RT_FAILURE(rc))
                {
                    RTPrintf(TESTCASE ": error: pfnShowStatistics failed! rc=%Rrc\n", rc);
                    cErrors++;
                }
            }

            pGuiVT->pfnAdjustRelativePos(pGui, 0, 0, 640, 480);
            RTPrintf(TESTCASE ": calling App.exec()...\n");
            App.exec();
        }
        else
        {
            RTPrintf(TESTCASE ": error: DBGGuiCreateForVM failed! rc=%Rrc\n", rc);
            cErrors++;
        }

        /*
         * Cleanup.
         */
        rc = VMR3Destroy(pUVM);
        if (!RT_SUCCESS(rc))
        {
            RTPrintf(TESTCASE ": error: failed to destroy vm! rc=%Rrc\n", rc);
            cErrors++;
        }
        VMR3ReleaseUVM(pUVM);
    }
    else
    {
        RTPrintf(TESTCASE ": fatal error: failed to create vm! rc=%Rrc\n", rc);
        cErrors++;
    }

    /*
     * Summary and exit.
     */
    if (!cErrors)
        RTPrintf(TESTCASE ": SUCCESS\n");
    else
        RTPrintf(TESTCASE ": FAILURE - %d errors\n", cErrors);
    return !!cErrors;
}
Ejemplo n.º 25
0
int main(int argc, char **argv)
{
  QApplication App(argc, argv);
  DemosFramework *demos = new DemosFramework;
  return App.exec();
}
Ejemplo n.º 26
0
int main()
{
    // Create the main window
    sf::RenderWindow App(sf::VideoMode(800, 600), "SFML window");

    sf::Vector2f WindowSize(App.GetWidth(), App.GetHeight());

    Scene::initSingleton();

    WINDOW_X = App.GetWidth();
    WINDOW_Y = App.GetHeight();

    // Use circles for now.
    sf::Shape GreenCircle = sf::Shape::Circle(0, 0, 10, sf::Color(0, 255, 0));
    GreenCircle.Move(WindowSize.x/2, WindowSize.y/2);
    TestEntity GreenCirclePhysics(GreenCircle.GetPosition().x, GreenCircle.GetPosition().y, (Shape*)new Circle(10.0), GreenCircle);
    //GreenCirclePhysics.setGravity(0, 4.9);
    GreenCirclePhysics.Setdx(95);
    //GreenCirclePhysics.Setdy(4.9);

    Scene::singleton().addEntity((Entity*)&GreenCirclePhysics);

    sf::Shape RedCircle = sf::Shape::Circle(0, 0, 10, sf::Color(255, 0, 0));
    RedCircle.Move(WindowSize.x*(3/4), WindowSize.y/2);
    TestEntity RedCirclePhysics(RedCircle.GetPosition().x, RedCircle.GetPosition().y, (Shape*)new Circle(10.0), RedCircle);
    //RedCirclePhysics.setGravity(0, 4.9);
    RedCirclePhysics.Setdx(-95);
    //RedCirclePhysics.Setdy(4.9);

    Scene::singleton().addEntity((Entity*)&RedCirclePhysics);


    sf::Clock Clock;

	// Start the game loop
    while (App.IsOpened())
    {
        // Process events
        sf::Event Event;
        while (App.GetEvent(Event))
        {
            // Close window : exit
            if (Event.Type == sf::Event::Closed)
                App.Close();
            else if (Event.Type == sf::Event::KeyPressed)
            {
                if (Event.Key.Code == sf::Key::Escape)
                {
                    App.Close();
                }
                if (Event.Key.Code == sf::Key::Space)
                {
                    GreenCirclePhysics.Setdx(180);
                    //GreenCirclePhysics.Setdy(4.9);
                }
            }
        }

        // Clear screen
        App.Clear();

        float Time = Clock.GetElapsedTime();
        Clock.Reset();
        Scene::singleton().update(Time);
        /*
        if (GreenCirclePhysics.GetX() > WindowSize.x + 10)
        {
            GreenCirclePhysics.SetX(-10);
        }
        if (GreenCirclePhysics.GetX() < -10)
        {
            GreenCirclePhysics.SetX(WindowSize.x+10);
        }
        if (GreenCirclePhysics.GetY() > WindowSize.y - 10)
        {
            GreenCirclePhysics.SetY(WindowSize.y - 10);
            GreenCirclePhysics.Setdy(-0.5*GreenCirclePhysics.Getdy());
        }
        if (GreenCirclePhysics.GetY() < 0)
        {
            //GreenCirclePhysics.SetY(0);
            //GreenCirclePhysics.Setdy(-0.5*GreenCirclePhysics.Getdy());
        }
        //GreenCirclePhysics.setForce(-0.5*GreenCirclePhysics.Getdx()*GreenCirclePhysics.Getdx(), -0.5*GreenCirclePhysics.Getdy()*GreenCirclePhysics.Getdy());
        GreenCircle.SetPosition(GreenCirclePhysics.GetX(), GreenCirclePhysics.GetY());

        // Draw the GreenCircle
        App.Draw(GreenCircle);

        if (RedCirclePhysics.GetX() > WindowSize.x + 10)
        {
            RedCirclePhysics.SetX(-10);
        }
        if (RedCirclePhysics.GetX() < -10)
        {
            RedCirclePhysics.SetX(WindowSize.x+10);
        }
        if (RedCirclePhysics.GetY() > WindowSize.y - 10)
        {
            RedCirclePhysics.SetY(WindowSize.y - 10);
            RedCirclePhysics.Setdy(-0.5*RedCirclePhysics.Getdy());
        }
        if (RedCirclePhysics.GetY() < 0)
        {
            //RedCirclePhysics.SetY(0);
            //RedCirclePhysics.Setdy(-0.5*RedCirclePhysics.Getdy());
        }
        //RedCirclePhysics.setForce(-0.5*RedCirclePhysics.Getdx()*RedCirclePhysics.Getdx(), -0.5*RedCirclePhysics.Getdy()*RedCirclePhysics.Getdy());
        RedCircle.SetPosition(RedCirclePhysics.GetX(), RedCirclePhysics.GetY());

        // Draw the RedCircle
        App.Draw(RedCircle);*/
        for (std::map<unsigned int, Entity*>::iterator i = Scene::singleton()._entmap.begin(); i != Scene::singleton()._entmap.end(); i++)
        {
            TestEntity* ent = dynamic_cast<TestEntity*>((*i).second);
            if (ent)
            {
                App.Draw(ent->graphics);
            }
        }

        // Update the window
        App.Display();
    }

    return EXIT_SUCCESS;
}
Ejemplo n.º 27
0
////////////////////////////////////////////////////////////
/// Entry point of application
///
/// \return Application exit code
///
////////////////////////////////////////////////////////////
int main()
{
	// Defines PI
	const float PI = 3.14159f;

    // Create the window of the application
    sf::RenderWindow App(sf::VideoMode(800, 600, 32), "SFML Pong");

    // Load the sounds used in the game
    sf::SoundBuffer BallSoundBuffer;
    if (!BallSoundBuffer.LoadFromFile("datas/pong/ball.wav"))
    {
        return EXIT_FAILURE;
    }
    sf::Sound BallSound(BallSoundBuffer);

    // Load the images used in the game
    sf::Image BackgroundImage, LeftPaddleImage, RightPaddleImage, BallImage;
    if (!BackgroundImage.LoadFromFile("datas/pong/background.jpg")    ||
        !LeftPaddleImage.LoadFromFile("datas/pong/paddle_left.png")   ||
        !RightPaddleImage.LoadFromFile("datas/pong/paddle_right.png") ||
        !BallImage.LoadFromFile("datas/pong/ball.png"))
    {
        return EXIT_FAILURE;
    }

    // Load the text font
    sf::Font Cheeseburger;
    if (!Cheeseburger.LoadFromFile("datas/post-fx/cheeseburger.ttf"))
        return EXIT_FAILURE;

	// Initialize the end text
	sf::String End;
    End.SetFont(Cheeseburger);
	End.SetSize(60.f);
    End.Move(150.f, 200.f);
    End.SetColor(sf::Color(50, 50, 250));

    // Create the sprites of the background, the paddles and the ball
    sf::Sprite Background(BackgroundImage);
    sf::Sprite LeftPaddle(LeftPaddleImage);
    sf::Sprite RightPaddle(RightPaddleImage);
    sf::Sprite Ball(BallImage);

    LeftPaddle.Move(10, (App.GetView().GetRect().GetHeight() - LeftPaddle.GetSize().y) / 2);
    RightPaddle.Move(App.GetView().GetRect().GetWidth() - RightPaddle.GetSize().x - 10, (App.GetView().GetRect().GetHeight() - RightPaddle.GetSize().y) / 2);
    Ball.Move((App.GetView().GetRect().GetWidth() - Ball.GetSize().x) / 2, (App.GetView().GetRect().GetHeight() - Ball.GetSize().y) / 2);

    // Define the paddles properties
    sf::Clock AITimer;
	const float AITime     = 0.1f;
    float LeftPaddleSpeed  = 400.f;
    float RightPaddleSpeed = 400.f;

    // Define the ball properties
    float BallSpeed = 400.f;
    float BallAngle;
    do
    {
        // Make sure the ball initial angle is not too much vertical
        BallAngle = sf::Randomizer::Random(0.f, 2 * PI);
    } while (std::abs(std::cos(BallAngle)) < 0.7f);

	bool IsPlaying = true;
    while (App.IsOpened())
    {
        // Handle events
        sf::Event Event;
        while (App.GetEvent(Event))
        {
            // Window closed or escape key pressed : exit
            if ((Event.Type == sf::Event::Closed) || 
               ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::Escape)))
            {
                App.Close();
                break;
            }
        }

        if (IsPlaying)
		{
			// Move the player's paddle
            if (App.GetInput().IsKeyDown(sf::Key::Up) && (LeftPaddle.GetPosition().y > 5.f))
				LeftPaddle.Move(0.f, -LeftPaddleSpeed * App.GetFrameTime());
            if (App.GetInput().IsKeyDown(sf::Key::Down) && (LeftPaddle.GetPosition().y < App.GetView().GetRect().GetHeight() - LeftPaddle.GetSize().y - 5.f))
				LeftPaddle.Move(0.f, LeftPaddleSpeed * App.GetFrameTime());

			// Move the computer's paddle
            if (((RightPaddleSpeed < 0.f) && (RightPaddle.GetPosition().y > 5.f)) ||
                ((RightPaddleSpeed > 0.f) && (RightPaddle.GetPosition().y < App.GetView().GetRect().GetHeight() - RightPaddle.GetSize().y - 5.f)))
            {
                RightPaddle.Move(0.f, RightPaddleSpeed * App.GetFrameTime());
            }

            // Update the computer's paddle direction according to the ball position
            if (AITimer.GetElapsedTime() > AITime)
            {
                AITimer.Reset();
                if ((RightPaddleSpeed < 0) && (Ball.GetPosition().y + Ball.GetSize().y > RightPaddle.GetPosition().y + RightPaddle.GetSize().y))
                    RightPaddleSpeed = -RightPaddleSpeed;
                if ((RightPaddleSpeed > 0) && (Ball.GetPosition().y < RightPaddle.GetPosition().y))
                    RightPaddleSpeed = -RightPaddleSpeed;
            }

			// Move the ball
			float Factor = BallSpeed * App.GetFrameTime();
            Ball.Move(std::cos(BallAngle) * Factor, std::sin(BallAngle) * Factor);

			// Check collisions between the ball and the screen
			if (Ball.GetPosition().x < 0.f)
			{
				IsPlaying = false;
				End.SetText("You lost !\n(press escape to exit)");
			}
			if (Ball.GetPosition().x + Ball.GetSize().x > App.GetView().GetRect().GetWidth())
			{
				IsPlaying = false;
				End.SetText("You won !\n(press escape to exit)");
			}
			if (Ball.GetPosition().y < 0.f)
			{
				BallSound.Play();
				BallAngle = -BallAngle;
				Ball.SetY(0.1f);
			}
			if (Ball.GetPosition().y + Ball.GetSize().y > App.GetView().GetRect().GetHeight())
			{
				BallSound.Play();
				BallAngle = -BallAngle;
				Ball.SetY(App.GetView().GetRect().GetHeight() - Ball.GetSize().y - 0.1f);
			}

			// Check the collisions between the ball and the paddles
			// Left Paddle
			if (Ball.GetPosition().x < LeftPaddle.GetPosition().x + LeftPaddle.GetSize().x && 
				Ball.GetPosition().x > LeftPaddle.GetPosition().x + (LeftPaddle.GetSize().x / 2.0f) &&
				Ball.GetPosition().y + Ball.GetSize().y >= LeftPaddle.GetPosition().y &&
				Ball.GetPosition().y <= LeftPaddle.GetPosition().y + LeftPaddle.GetSize().y)
			{
				BallSound.Play();
				BallAngle = PI - BallAngle;
				Ball.SetX(LeftPaddle.GetPosition().x + LeftPaddle.GetSize().x + 0.1f);
			}

			// Right Paddle
			if (Ball.GetPosition().x + Ball.GetSize().x > RightPaddle.GetPosition().x &&
				Ball.GetPosition().x + Ball.GetSize().x < RightPaddle.GetPosition().x + (RightPaddle.GetSize().x / 2.0f) &&
				Ball.GetPosition().y + Ball.GetSize().y >= RightPaddle.GetPosition().y &&
				Ball.GetPosition().y <= RightPaddle.GetPosition().y + RightPaddle.GetSize().y)
			{
				BallSound.Play();
				BallAngle = PI - BallAngle;
				Ball.SetX(RightPaddle.GetPosition().x - Ball.GetSize().x - 0.1f);
			}
		}

        // Clear the window
        App.Clear();

        // Draw the background, paddles and ball sprites
        App.Draw(Background);
        App.Draw(LeftPaddle);
        App.Draw(RightPaddle);
        App.Draw(Ball);

        // If the game is over, display the end message
        if (!IsPlaying)
            App.Draw(End);

        // Display things on screen
        App.Display();
    }

    return EXIT_SUCCESS;
}
Ejemplo n.º 28
0
bool PGM_KICAD::OnPgmInit( wxApp* aWxApp )
{
    m_wx_app = aWxApp;      // first thing.

    wxString absoluteArgv0 = wxStandardPaths::Get().GetExecutablePath();

    if( !wxIsAbsolutePath( absoluteArgv0 ) )
    {
        wxLogError( wxT( "No meaningful argv[0]" ) );
        return false;
    }

    // Set LIB_ENV_VAR *before* loading the KIFACE DSOs, in case they have hard
    // dependencies on subsidiary DSOs below it.
    set_lib_env_var( absoluteArgv0 );

    if( !initPgm() )
        return false;

    m_bm.Init();

    // Add search paths to feed the PGM_KICAD::SysSearch() function,
    // currenly limited in support to only look for project templates
    {
        SEARCH_STACK bases;

        SystemDirsAppend( &bases );

        // DBG( bases.Show( (std::string(__func__) + " bases").c_str() );)

        for( unsigned i = 0; i < bases.GetCount(); ++i )
        {
            wxFileName fn( bases[i], wxEmptyString );

            // Add KiCad template file path to search path list.
            fn.AppendDir( wxT( "template" ) );
            m_bm.m_search.AddPaths( fn.GetPath() );
        }

        //DBG( m_bm.m_search.Show( (std::string( __func__ ) + " SysSearch()").c_str() );)
    }

    // Must be called before creating the main frame in order to
    // display the real hotkeys in menus or tool tips
    extern struct EDA_HOTKEY_CONFIG kicad_Manager_Hokeys_Descr[];
    ReadHotkeyConfig( KICAD_MANAGER_FRAME_NAME, kicad_Manager_Hokeys_Descr );

    KICAD_MANAGER_FRAME* frame = new KICAD_MANAGER_FRAME( NULL, wxT( "KiCad" ),
                                     wxDefaultPosition, wxDefaultSize );
    App().SetTopWindow( frame );

    Kiway.SetTop( frame );

    bool prjloaded = false;    // true when the project is loaded

    if( App().argc > 1 )
        frame->SetProjectFileName( App().argv[1] );

    else if( GetFileHistory().GetCount() )
    {
        wxString last_pro = GetFileHistory().GetHistoryFile( 0 );

        if( !wxFileExists( last_pro ) )
        {
            GetFileHistory().RemoveFileFromHistory( 0 );

            wxFileName namelessProject( wxStandardPaths::Get().GetDocumentsDir(), NAMELESS_PROJECT,
                                        ProjectFileExtension );

            frame->SetProjectFileName( namelessProject.GetFullPath() );
        }
        else
        {
            // Try to open the last opened project,
            // if a project name is not given when starting Kicad
            frame->SetProjectFileName( last_pro );

            wxCommandEvent cmd( 0, wxID_FILE1 );

            frame->OnFileHistory( cmd );
            prjloaded = true;    // OnFileHistory() loads the project
        }
    }
    else	// there is no history
    {
            wxFileName namelessProject( wxStandardPaths::Get().GetDocumentsDir(), NAMELESS_PROJECT,
                                        ProjectFileExtension );

            frame->SetProjectFileName( namelessProject.GetFullPath() );
    }

    if( !prjloaded )
    {
        wxCommandEvent cmd( 0, wxID_ANY );

        frame->OnLoadProject( cmd );
    }

    frame->Show( true );
    frame->Raise();

    return true;
}
Ejemplo n.º 29
0
int main()
{
    // Create the main window
    sf::Window App(sf::VideoMode(800, 600, 32), "SFML/NeHe OpenGL");

    InitGL();
    ReSizeGLScene(800, 600);

    // Start game loop
    while (App.IsOpened())
    {
        // Process events
        sf::Event Event;
        while (App.GetEvent(Event))
        {
            // Close window : exit
            if (Event.Type == sf::Event::Closed)
                App.Close();

            // Resize event : adjust viewport
            if (Event.Type == sf::Event::Resized)
                ReSizeGLScene(Event.Size.Width, Event.Size.Height);

            // Handle Keyboard Events
            if (Event.Type == sf::Event::KeyPressed) {
                switch (Event.Key.Code) {
                    case sf::Key::Escape:
                        App.Close();
                        break;
                    case sf::Key::F1:
                        fullscreen = !fullscreen;
                        App.Create(fullscreen ? sf::VideoMode::GetDesktopMode() : sf::VideoMode(800, 600, 32) , "SFML/NeHe OpenGL",
                        (fullscreen ? sf::Style::Fullscreen : sf::Style::Resize | sf::Style::Close));
                        ReSizeGLScene(App.GetWidth(),App.GetHeight());
                        break;
                    case sf::Key::F5:
                        vsync = !vsync;
                        break;
                    case sf::Key::F:
                        filter+=1;
                        if (filter>2) {
                            filter=0;
                        }
                        break;
                    case sf::Key::B:
                        blend = !blend;
                        if(blend) {
                            glEnable(GL_BLEND);			// Turn Blending On
                            glDisable(GL_DEPTH_TEST);	// Turn Depth Testing Off
                        } else {
                            glDisable(GL_BLEND);		// Turn Blending Off
                            glEnable(GL_DEPTH_TEST);	// Turn Depth Testing On
                        }
                        break;
                    default:
                        break;
                }
            }
        }

        //Handle movement keys
        const sf::Input& Input = App.GetInput();

        if (Input.IsKeyDown(sf::Key::PageUp)) {
            z-=0.02f;
            lookupdown-= 1.0f;
        }
        if (Input.IsKeyDown(sf::Key::PageDown)) {
            z+=0.02f;
            lookupdown+= 1.0f;
        }
        if (Input.IsKeyDown(sf::Key::Up)) {
            xpos -= (float)sin(heading*piover180) * 0.05f;
            zpos -= (float)cos(heading*piover180) * 0.05f;
            if (walkbiasangle >= 359.0f) {
                walkbiasangle = 0.0f;
            } else {
                walkbiasangle+= 10;
            }
            walkbias = (float)sin(walkbiasangle * piover180)/20.0f;
        }
        if (Input.IsKeyDown(sf::Key::Down)) {
            xpos += (float)sin(heading*piover180) * 0.05f;
            zpos += (float)cos(heading*piover180) * 0.05f;
            if (walkbiasangle <= 1.0f) {
                walkbiasangle = 359.0f;
            } else {
                walkbiasangle-= 10;
            }
            walkbias = (float)sin(walkbiasangle * piover180)/20.0f;
        }
        if (Input.IsKeyDown(sf::Key::Right)) {
            heading -= 1.0f;
            yrot = heading;
        }
        if (Input.IsKeyDown(sf::Key::Left)) {
            heading += 1.0f;
            yrot = heading;
        }

        // Turn VSYNC on so that animations run at a more reasonable speed on new CPU's/GPU's.
        App.UseVerticalSync(vsync);

        // Set the active window before using OpenGL commands
        // It's useless here because active window is always the same,
        // but don't forget it if you use multiple windows or controls
        App.SetActive();

        //Draw some pretty stuff
        DrawGLScene();

        // Finally, display rendered frame on screen
        App.Display();
    }

    return EXIT_SUCCESS;
}
Ejemplo n.º 30
0
////////////////////////////////////////////////////////////
/// Entry point of application
///
/// \return Application exit code
///
////////////////////////////////////////////////////////////
int main()
{
    // Create the main window
    sf::Window App(sf::VideoMode(800, 600, 32), "SFML OpenGL");

    // Create a clock for measuring time elapsed
    sf::Clock Clock;

    // Set color and depth clear value
    glClearDepth(1.f);
    glClearColor(0.f, 0.f, 0.f, 0.f);

    // Enable Z-buffer read and write
    glEnable(GL_DEPTH_TEST);
    glDepthMask(GL_TRUE);

    // Setup a perspective projection
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(90.f, 1.f, 1.f, 500.f);

    // Start game loop
    while (App.isOpen())
    {
        // Process events
        sf::Event Event;
        while (App.pollEvent(Event))
        {
            // Close window : exit
            if (Event.type == sf::Event::Closed)
                App.close();

            // Escape key : exit
            if ((Event.type == sf::Event::KeyPressed) && (Event.key.code == sf::Keyboard::Escape))
                App.close();

            // Resize event : adjust viewport
            if (Event.type == sf::Event::Resized)
                glViewport(0, 0, Event.size.width, Event.size.height);
        }

        // Set the active window before using OpenGL commands
        // It's useless here because active window is always the same,
        // but don't forget it if you use multiple windows or controls
        App.setActive();

        // Clear color and depth buffer
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        // Apply some transformations
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
        glTranslatef(0.f, 0.f, -200.f);
        glRotatef(Clock.getElapsedTime().asSeconds() * 50, 1.f, 0.f, 0.f);
        glRotatef(Clock.getElapsedTime().asSeconds() * 30, 0.f, 1.f, 0.f);
        glRotatef(Clock.getElapsedTime().asSeconds() * 90, 0.f, 0.f, 1.f);

        // Draw a cube
        glBegin(GL_QUADS);

        glVertex3f(-50.f, -50.f, -50.f);
        glVertex3f(-50.f,  50.f, -50.f);
        glVertex3f( 50.f,  50.f, -50.f);
        glVertex3f( 50.f, -50.f, -50.f);

        glVertex3f(-50.f, -50.f, 50.f);
        glVertex3f(-50.f,  50.f, 50.f);
        glVertex3f( 50.f,  50.f, 50.f);
        glVertex3f( 50.f, -50.f, 50.f);

        glVertex3f(-50.f, -50.f, -50.f);
        glVertex3f(-50.f,  50.f, -50.f);
        glVertex3f(-50.f,  50.f,  50.f);
        glVertex3f(-50.f, -50.f,  50.f);

        glVertex3f(50.f, -50.f, -50.f);
        glVertex3f(50.f,  50.f, -50.f);
        glVertex3f(50.f,  50.f,  50.f);
        glVertex3f(50.f, -50.f,  50.f);

        glVertex3f(-50.f, -50.f,  50.f);
        glVertex3f(-50.f, -50.f, -50.f);
        glVertex3f( 50.f, -50.f, -50.f);
        glVertex3f( 50.f, -50.f,  50.f);

        glVertex3f(-50.f, 50.f,  50.f);
        glVertex3f(-50.f, 50.f, -50.f);
        glVertex3f( 50.f, 50.f, -50.f);
        glVertex3f( 50.f, 50.f,  50.f);

        glEnd();

        // Finally, Display rendered frame on screen
        App.display();
    }

    return EXIT_SUCCESS;
}