void SWRenderDisplayWindowProvider::create(DisplayWindowSite *new_site, const DisplayWindowDescription &description)
{
	site = new_site;
	flip_timer_set = false;

	refresh_rate = description.get_refresh_rate();
	if (!refresh_rate)	// Default the refresh rate to 100 if not defined
		refresh_rate = 100;
	swap_interval = description.get_swap_interval();

#ifdef WIN32
	window.create(site, description);
#elif !defined(__APPLE__)
	::Display *disp = window.get_display();

	int bpp = 24;
	XVisualInfo visual_info;
	int screen =  DefaultScreen(disp); //RootWindow(disp,  0);

	if (XMatchVisualInfo(disp, screen, 24, TrueColor, &visual_info)) {bpp = 24;} 
	else if (XMatchVisualInfo(disp, screen, 16, TrueColor, &visual_info)) {bpp = 16;}
	else if (XMatchVisualInfo(disp, screen, 15, TrueColor, &visual_info)) {bpp = 15;}
	else if (XMatchVisualInfo(disp, screen, 32, TrueColor, &visual_info)) {bpp = 32;}
	else if (XMatchVisualInfo(disp, screen, 8, PseudoColor, &visual_info)) {bpp = 8;}
	else if (XMatchVisualInfo(disp, screen, 8, GrayScale, &visual_info)) {bpp = 8;}
	else if (XMatchVisualInfo(disp, screen, 8, StaticGray, &visual_info)) {bpp = 8;}
	else if (XMatchVisualInfo(disp, screen, 1, StaticGray, &visual_info)) {bpp = 1;}
	else { throw Exception("Cannot match visual info"); }

	window.create(&visual_info, site, description);
#endif
	gc = GraphicContext(new SWRenderGraphicContextProvider(this));
}
示例#2
0
		static DisplayWindowDescription get_window_desc()
		{
			DisplayWindowDescription desc;
			desc.set_type(WindowType::popup);
			desc.set_visible(false);
			desc.set_topmost(true);
			return desc;
		}
示例#3
0
ClientGUI::ClientGUI()
{
	DisplayWindowDescription desc;
	desc.set_title("ClanLib - Dice War");
	desc.set_size(Size(1024, 768), true);
//	desc.set_allow_resize(true);
//	desc.set_multisampling(4);
	display_window = DisplayWindow(desc);

	//FIXME: Font_System::register_font("Resources\\bitstream_vera_sans\\VeraBd.ttf", "VeraBd");

	slot_quit = display_window.sig_window_close().connect(this, &ClientGUI::on_window_close);

	gui = GUIManager(display_window, "Resources/GUITheme");
}
示例#4
0
文件: game.cpp 项目: Cassie90/ClanLib
void Game::run()
{
	quit = false;

	DisplayWindowDescription desc;
	desc.set_title("ClanLib TileMap Example");
	desc.set_size(Size(640, 480), true);
	desc.set_allow_resize(false);

	DisplayWindow window(desc);

	Slot slot_quit = window.sig_window_close().connect(this, &Game::on_window_close);
	Slot slot_input_up = (window.get_ic().get_keyboard()).sig_key_up().connect(this, &Game::on_input_up);

	Canvas canvas(window);

	clan::XMLResourceDocument xml_resource_document("resources.xml");
	ResourceManager resources = clan::XMLResourceManager::create(xml_resource_document);

	TileMap map;
	map.load(canvas, "tavern", resources, xml_resource_document);

	// Run until someone presses escape, or closes the window
	while (!quit)
	{
		int x = window.get_ic().get_mouse().get_x() - canvas.get_width();
		int y = window.get_ic().get_mouse().get_y() - canvas.get_height();

		// ** Enable these 3 lines to display the example magnified **
		//Mat4f matrix = Mat4f::scale( 2.0f, 2.0f, 1.0f);
		//x /= 2; y /= 2;
		//canvas.set_modelview(matrix);

		map.set_scroll(x, y);

		canvas.clear(Colorf::black);

		map.draw(canvas);


		// Flip the display, showing on the screen what we have drawed since last call to flip()
		window.flip(1);

		// This call processes user input and other events
		KeepAlive::process(0);
	}
}
示例#5
0
	int main(const std::vector<std::string> &args)
	{
		try
		{
			DisplayWindowDescription desc;
			desc.set_title("Custom Component");
			desc.set_size(Size(1024, 768), true);
			DisplayWindow displaywindow(desc);

			Slot slotWindowClose = displaywindow.sig_window_close().connect(this, &App::on_close);

			DisplayCache resources("../../../Resources/GUIThemeAero/resources.xml");

			GUIWindowManagerTexture wm(displaywindow);

			GUIThemeDefault theme;
			theme.set_resources(resources);

			GUIManager gui;
			gui.set_window_manager(wm);
			gui.set_theme(theme); 
			gui.set_css_document("../../../Resources/GUIThemeAero/theme.css");

			CustomComponent comp1(Rect(10, 10, 400, 200), &gui, Colorf::beige);
//			CustomComponent comp2(Rect(20, 210, 500, 400), &gui, Colorf::green);
//			CustomComponent comp3(Rect(50, 20, 600, 300), &gui, Colorf::blue);
			CustomComponent comp3(Rect(87, 200, 600, 300), &gui, Colorf::blue);
//			CustomComponent comp3(Rect(88, 200, 600, 300), &gui, Colorf::blue);

			gui.exec();
		}
		catch (Exception e)
		{
			ConsoleWindow console("Console");
			Console::write_line(e.message);
			console.display_close_message();
		}

		return 0;
	}
示例#6
0
int TestApp::main(const std::vector<std::string> &args)
{
	// Create a console window for text-output if not available
	ConsoleWindow console("Console");

	try
	{
		DisplayWindowDescription desc;
		desc.set_size(Size(800,600), true);
		desc.set_title("Fullscreen test");
		DisplayWindow window(desc);
		
		while (!window.get_ic().get_keyboard().get_keycode(keycode_escape))
		{
			if (window.get_ic().get_keyboard().get_keycode(keycode_f11))
			{
				desc.set_fullscreen(!desc.is_fullscreen());
				window = DisplayWindow(desc);
			}

			window.get_gc().clear(Colorf::gray30);

			window.flip();
			KeepAlive::process();
			System::sleep(50);
		}
	}
	catch(Exception error)
	{
		Console::write_line("Exception caught:");
		Console::write_line(error.message);

		console.display_close_message();
		return -1;
	}

	return 0;
}
D3DGraphicContextProvider::D3DGraphicContextProvider(D3DDisplayWindowProvider *window, const DisplayWindowDescription &display_desc)
:	window(window),
	current_prim_array_provider(0),
	current_program_provider(0),
	input_layout_set(false)
{
//	set_blend_color(Colorf::black);
//	set_blend_function(blend_one, blend_zero, blend_one, blend_zero);
//	enable_blending(false);

	default_depth = display_desc.get_depth_size();

	Size viewport_size = get_display_window_size();
	for (int i = 0; i < D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT; i++)
	{
		viewports[i].Width = viewport_size.width;
		viewports[i].Height = viewport_size.height;
		viewports[i].TopLeftX = 0;
		viewports[i].TopLeftY = 0;
		viewports[i].MinDepth = 0.0f;
		viewports[i].MaxDepth = 1.0f;
	}
	window->get_device_context()->RSSetViewports(D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT, viewports);

	for (int i = 0; i < D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT; i++)
	{
		scissor_rects[i].left = 0;
		scissor_rects[i].top = 0;
		scissor_rects[i].right = 0;
		scissor_rects[i].bottom = 0;
	}

	for (int i = 0; i < shadertype_num_types; i++)
		shader_bound[i] = false;

	set_default_dsv();

	SharedGCData::add_provider(this);
}
示例#8
0
DisplayWindow::DisplayWindow(
	const std::string &title,
	int width,
	int height,
	bool start_fullscreen,
	bool allow_resize,
	int flipping_buffers)
{
	DisplayWindowDescription description;
	description.set_title(title);
	description.set_size(Size(width, height), false);
	description.set_fullscreen(start_fullscreen);

	if (start_fullscreen)
	{
		description.show_caption(false);
	}

	description.set_allow_resize(allow_resize);
	description.set_flipping_buffers(flipping_buffers);

	*this = DisplayWindow(description);
}
示例#9
0
	virtual int main(const std::vector<std::string> &args)
	{

		DisplayWindowDescription desc;
		desc.set_size(Size(800,600), true);
		desc.set_title("Span Layout Test");
		DisplayWindow window(desc);

		Canvas canvas(window);
		GraphicContext gc = window.get_gc();

		FontDescription font_desc1;
		font_desc1.set_typeface_name("Verdana");
		font_desc1.set_height(-13);
		Font font1(canvas, font_desc1);

		Image smiley(canvas, "smiley.png");

		SpanLayout span;
		span.add_text(" This is a ", font1, Colorf::white, 1);
		span.add_text("red", font1, Colorf::red, 2);
		span.add_text(" text! ", font1, Colorf::white, 3);
		span.add_text("And this   complete   text   is   green with non-blocking space..", font1, Colorf::green, 4);
		span.add_image(smiley, 10, 5);
		span.add_text("This is a really long descriptive and interesting text. ", font1, Colorf::yellow, 6);
		span.add_text("[", font1, Colorf::black, 7);
		span.add_text("15:35", font1, Colorf::white, 8);
		span.add_text("]", font1, Colorf::black, 9);
		span.add_image(smiley, 0, 10);
		span.add_image(smiley, 2, 11);
		span.add_text("kthxbye!", font1, Colorf::blue, 12);

		span.layout(gc, 200);
		span.set_position(Point(10, 10));

		while (!window.get_ic().get_keyboard().get_keycode(keycode_escape))
		{
			gc.clear(Colorf::gray70);

			span.draw_layout(canvas);

			Point mouse_pos = window.get_ic().get_mouse().get_position();
			SpanLayout::HitTestResult result = span.hit_test(gc, mouse_pos);

			std::string type;
			switch(result.type)
			{
				case SpanLayout::HitTestResult::no_objects_available:
					type = "no_objects_available";
					break;
				case SpanLayout::HitTestResult::outside_top:
					type = "outside_top";
					break;
				case SpanLayout::HitTestResult::outside_left:
					type = "outside_left";
					break;
				case SpanLayout::HitTestResult::outside_right:
					type = "outside_right";
					break;
				case SpanLayout::HitTestResult::outside_bottom:
					type = "outside_bottom";
					break;
				case SpanLayout::HitTestResult::inside:
					type = "inside";
					break;
			}
			std::string result_text = string_format("HitTestResult: Type:%1 ID:%2 Offset:%3", type, result.object_id, result.offset);

			font1.draw_text(canvas, 10, 300, result_text);

			window.flip();
			KeepAlive::process();
			System::sleep(50);
		}

		return 0;
	}
示例#10
0
FlexTable::FlexTable()
{
#if defined(WIN32) && !defined(__MINGW32__)
	clan::D3DTarget::set_current();
#else
	clan::OpenGLTarget::set_current();
#endif

	// Create a source for our resources
	FileResourceDocument doc(FileSystem("../../ThemeAero"));
	ResourceManager resources = FileResourceManager::create(doc);

	// Mark this thread as the UI thread
	ui_thread = UIThread(resources);

	// Create a window:
	DisplayWindowDescription desc;
	desc.set_title("UICore: Flex Table");
	desc.set_allow_resize(true);
	desc.set_size(Sizef(1400, 800), false);
	window = std::make_shared<TopLevelWindow>(desc);

	// Exit run loop when close is clicked or ESC pressed.
	auto pRootView = window->root_view();
	pRootView->slots.connect(pRootView->sig_close(), [&](CloseEvent &e) { RunLoop::exit(); });
	pRootView->slots.connect(pRootView->sig_key_press(), [&](clan::KeyEvent &e) 
		{ if (e.key() == clan::Key::escape) RunLoop::exit(); }
	);

	// Need for receive a keyboard events.
	pRootView->set_focus();
	window->root_view()->style()->set("background-color: white;");

	// Main window icons
	window->display_window().set_small_icon(clan::PixelBuffer("Resources/app_icon_16x16.png", doc.get_file_system()));
	window->display_window().set_large_icon(clan::PixelBuffer("Resources/app_icon_32x32.png", doc.get_file_system()));

	auto outer_view = window->root_view()->add_child<clan::View>();
	outer_view->style()->set("border: 20px solid blue; padding: 15px; margin: 0px; background-color: black; width: 1000px; height: 500px;");

	auto column_flex_view = outer_view->add_child<clan::View>();
	column_flex_view->style()->set("border: 8px solid yellow; padding: 15px; margin: 0px; display:flex; align-items:flex-start; flex-direction:column; height:400px; background-color: #666666;");

	std::string row_flex_style("border: 8px solid red; padding: 15px; margin: 0px; width:100%; box-sizing: border-box;	display:flex; align-items:flex-start; background-color: #444444;");
	std::string row_view_style("color: white; height:60px; border: 8px solid white;	background: black;");

	for (int cnt = 0; cnt < 2; cnt++)
	{
		auto row_flex_view = column_flex_view->add_child<clan::View>();
		row_flex_view->style()->set(row_flex_style);

		auto row_view1 = row_flex_view->add_child<clan::View>();
		row_view1->style()->set(row_view_style);
		row_view1->style()->set("flex: 0 0 400px;");

		auto row_view2 = row_flex_view->add_child<clan::View>();
		row_view2->style()->set(row_view_style);
		row_view2->style()->set("flex: 1 0 auto;");

		auto row_view3 = row_flex_view->add_child<clan::View>();
		row_view3->style()->set(row_view_style);
		row_view3->style()->set("flex: 0 0 200px;");
	}

	// Prevent close program when hint or modal windows closes.
	window_manager.set_exit_on_last_close(false);
	
	// Make our window visible
	window->show();
}
示例#11
0
文件: test.cpp 项目: rombust/ClanLib
int App::start(const std::vector<std::string> &args)
{
    quit = false;

    ConsoleWindow console("Console", 80, 200);

    print_usage();

    DisplayWindowDescription desc;
    desc.set_title("ClanLib Collision Test");
    desc.set_size(Size(950, 700), true);
    DisplayWindow window(desc);
    Canvas canvas(window);

    Slot slot_quit = window.sig_window_close().connect(this, &App::on_window_close);
    Slot slot_input_up = window.get_ic().get_keyboard().sig_key_up().connect(this, &App::on_input_up);

    Font font(canvas, "Tahoma", 16);

//////////////////////////////////////////////////////////////////////////
    std::string file1("images/triangle.png");
    //std::string file2("images/triangle.png");
    std::string file2("images/weird.png");
    //std::string file2("images/edge_test2.png");
    //std::string file2("images/inside_test5.png");

    if( args.size() == 3 )
    {
        file1 = args[1];
        file2 = args[2];
    }

    double tri_x_pos = 0;
    double tri_y_pos = 0;
    double other_x_pos = canvas.get_width()/2;
    double other_y_pos = canvas.get_height()/2;

    // draw_limit = 0;

    bool draw_min_on_co1 = false;
    bool draw_min_on_co2 = false;
    bool draw_sub_on_co1 = false;
    bool draw_sub_on_co2 = false;
    bool draw_surfaces = false;
    bool draw_deep_point = false;
    float sub_circle_multiplier = 3.5f;

    ////////////////////////////////////////////
    // load resources:

    Sprite surface(canvas, file1);
    Sprite surface2(canvas, file2);

    surface.set_rotation_hotspot(origin_center);
    surface.set_alignment(origin_center);

    surface2.set_rotation_hotspot(origin_center);
    surface2.set_alignment(origin_center);

    ////////////////////////////////////////////
    // Collision code

    // load outlines
    FileSystem vfs(".");
    CollisionOutline co1(file1);
    CollisionOutline co2(file2, vfs, 128, accuracy_medium, true);

    // Save now before alignment and positions have been applied
    co1.save("collision_1_test_outline_file.out");
    co2.save("collision_2_test_outline_file.out");

    // print some info about the outlines:
    unsigned int size = co1.get_contours().size();

    Console::write_line(string_format("outline 1: %1 contour(s)", (int) co1.get_contours().size()));
    Console::write_line(string_format("outline 2: %1 contour(s)", (int) co2.get_contours().size()));

    std::vector<Contour>::const_iterator it;

    Console::write_line("outline 1:");
    int i=1;
    for( it = co1.get_contours().begin(); it!=co1.get_contours().end(); ++it )
    {
        Console::write_line(string_format("\tcontour %1: %2 points", i, (int) (*it).get_points().size()));
        i++;
    }

    Console::write_line("outline 2:");
    i=1;
    for( it = co2.get_contours().begin(); it!=co2.get_contours().end(); ++it )
    {
        Console::write_line("\tcontour %1: %2 points", i, (int) (*it).get_points().size());
        i++;
    }

    co1.set_alignment(origin_center);
    co1.set_rotation_hotspot(origin_center);
    co1.enable_collision_info(true,true,true,true);
    co1.set_inside_test(true);

    co2.set_alignment(origin_center);
    co2.set_rotation_hotspot(origin_center);
    co2.enable_collision_info(true,true,true,true);
    co2.set_inside_test(true);

    print_usage();

    InputDevice keyboard = window.get_ic().get_keyboard();

    // Loop until the user hits escape:
    while (!quit)
    {
        canvas.clear(Colorf::ghostwhite);

        if (keyboard.get_keycode(keycode_shift))
        {
            // Control Other
            if( keyboard.get_keycode(keycode_right) )
                other_x_pos+=0.25;
            if( keyboard.get_keycode(keycode_left) )
                other_x_pos-=0.25;

            if( keyboard.get_keycode(keycode_up) )
                other_y_pos-=0.25;
            if( keyboard.get_keycode(keycode_down) )
                other_y_pos+=0.25;
        }
        else
        {
            // Control Triangle
            if( keyboard.get_keycode(keycode_right) )
                tri_x_pos+=0.25;
            if( keyboard.get_keycode(keycode_left) )
                tri_x_pos-=0.25;

            if( keyboard.get_keycode(keycode_up) )
                tri_y_pos-=0.25;
            if( keyboard.get_keycode(keycode_down) )
                tri_y_pos+=0.25;
        }

        if( keyboard.get_keycode(keycode_e) )
        {
            surface.rotate(Angle(0.1f, angle_degrees));
            co1.rotate(Angle(0.1f, angle_degrees));
        }
        if( keyboard.get_keycode(keycode_r) )
        {
            co2.rotate(Angle(0.1f, angle_degrees));
            surface2.rotate(Angle(0.1f, angle_degrees));
        }
        if( keyboard.get_keycode(keycode_1) )
        {
            co2.set_scale(1.0f, 1.0f);
            surface2.set_scale(1.0f, 1.0f);
            System::sleep(100);
        }
        if( keyboard.get_keycode(keycode_2) )
        {
            co2.set_scale(2.0f, 2.0f);
            surface2.set_scale(2.0f, 2.0f);
            System::sleep(100);
        }
        if( keyboard.get_keycode(keycode_3) )
        {
            co2.set_scale(3.0f, 3.0f);
            surface2.set_scale(3.0f, 3.0f);
            System::sleep(100);
        }
        if( keyboard.get_keycode(keycode_4) )
        {
            co2.set_scale(4.0f, 4.0f);
            surface2.set_scale(4.0f, 4.0f);
            System::sleep(100);
        }
        if( keyboard.get_keycode(keycode_5) )
        {
            co2.set_scale(5.0f, 5.0f);
            surface2.set_scale(5.0f, 5.0f);
            System::sleep(100);
        }
        if( keyboard.get_keycode(keycode_6) )
        {
            co2.set_scale(6.0f, 6.0f);
            surface2.set_scale(6.0f, 6.0f);
            System::sleep(100);
        }
        if( keyboard.get_keycode(keycode_7) )
        {
            co2.set_scale(7.0f, 7.0f);
            surface2.set_scale(7.0f, 7.0f);
            System::sleep(100);
        }
        if( keyboard.get_keycode(keycode_8) )
        {
            co2.set_scale(8.0f, 8.0f);
            surface2.set_scale(8.0f, 8.0f);
            System::sleep(100);
        }
        if( keyboard.get_keycode(keycode_i) )
        {
            draw_sub_on_co1 = !draw_sub_on_co1;
            System::sleep(100);
        }
        if( keyboard.get_keycode(keycode_o) )
        {
            draw_sub_on_co2 = !draw_sub_on_co2;
            System::sleep(100);
        }
        if( keyboard.get_keycode(keycode_t) )
        {
            draw_min_on_co1 = !draw_min_on_co1;
            System::sleep(100);
        }
        if( keyboard.get_keycode(keycode_y) )
        {
            draw_min_on_co2 = !draw_min_on_co2;
            System::sleep(100);
        }
        if( keyboard.get_keycode(keycode_d) )
        {
            draw_deep_point = !draw_deep_point;
            System::sleep(100);
        }
        if( keyboard.get_keycode(keycode_s) )
        {
            draw_surfaces = !draw_surfaces;
            System::sleep(100);
        }
        if( keyboard.get_keycode(keycode_x) )
        {
            // Load, ensuring recreated
            co1 = CollisionOutline("collision_1_test_outline_file.out");
            co2 = CollisionOutline("collision_2_test_outline_file.out");

            // Reset the options
            co1.set_alignment(origin_center);
            co1.set_rotation_hotspot(origin_center);
            co1.enable_collision_info(true,true,true,true);
            co1.set_inside_test(true);
            co2.set_alignment(origin_center);
            co2.set_rotation_hotspot(origin_center);
            co2.enable_collision_info(true,true,true,true);
            co2.set_inside_test(true);

            System::sleep(100);
        }

        if( keyboard.get_keycode(keycode_subtract) )
        {
            sub_circle_multiplier -= 0.2f;
            co1.calculate_sub_circles(sub_circle_multiplier);
            co2.calculate_sub_circles(sub_circle_multiplier);
            System::sleep(50);
        }
        if( keyboard.get_keycode(keycode_add) )
        {
            sub_circle_multiplier += 0.2f;
            co1.calculate_sub_circles(sub_circle_multiplier);
            co2.calculate_sub_circles(sub_circle_multiplier);
            System::sleep(50);
        }
        if( keyboard.get_keycode(keycode_g) )
        {
            co1.calculate_smallest_enclosing_discs();
            co2.calculate_smallest_enclosing_discs();
            System::sleep(50);
        }
        if( keyboard.get_keycode(keycode_c) )
        {
            co1.calculate_convex_hulls();
            co2.calculate_convex_hulls();
            System::sleep(200);
        }
        if( keyboard.get_keycode(keycode_h) )
        {
            print_usage();
            System::sleep(200);
        }

        // -----------------------------------
        // surfaces
        if(draw_surfaces)
        {
            surface.draw(canvas, (float)tri_x_pos, (float)tri_y_pos);
            surface2.draw(canvas, (float)other_x_pos, (float)other_y_pos);
        }

        // -----------------------------------
        // co1
        co1.set_translation((float)tri_x_pos, (float)tri_y_pos);
        co1.draw(0.0, 0.0, Colorf::limegreen, canvas);
        if(draw_sub_on_co1)
            co1.draw_sub_circles(0.0, 0.0, Colorf::blue, canvas);

        // -----------------------------------
        // co2
        co2.set_translation((float)other_x_pos, (float)other_y_pos);
        co2.draw(0.0, 0.0, Colorf::red, canvas );
        if(draw_sub_on_co2)
            co2.draw_sub_circles(0.0, 0.0, Colorf::blue, canvas);
        if(draw_min_on_co1)
            canvas.fill_circle(co1.get_minimum_enclosing_disc().position, co1.get_minimum_enclosing_disc().radius, Colorf(0.4f, 0.0f, 0.0f, 0.5f));

        if(draw_min_on_co2)
            canvas.fill_circle(co2.get_minimum_enclosing_disc().position, co2.get_minimum_enclosing_disc().radius, Colorf(0.0f, 0.4f, 0.0f, 0.5f));

        int font_ypos = 20;

        // -----------------------------------
        // collision testing
        if( co2.collide(co1) )
        {
            canvas.fill_rect(canvas.get_size(), Colorf(Color(55,40,250,20)));

            const std::vector<CollidingContours> &colpointinfo = co2.get_collision_info();
            for(unsigned int c = 0; c < colpointinfo.size(); c++)
            {
                // Console::write_line(string_format("c1: %1 c2: %2 inside: %3", colpointinfo[c].contour1, colpointinfo[c].contour2, colpointinfo[c].inside));

                for(unsigned int p = 0; p < colpointinfo[c].points.size(); p++)
                {
                    const CollisionPoint &collision_point = colpointinfo[c].points[p];
                    draw_point_normal(canvas, collision_point.point, collision_point.normal, collision_point.is_entry ? Colorf::green : Colorf::red);

                    // Draw information
                    std::string output(string_format("Collision(%1). Point Number (%2). ", c, p));
                    output = output + string_format("Point(%1,%2). Normal(%3,%4). ", collision_point.point.x, collision_point.point.y, collision_point.normal.x, collision_point.normal.y);
                    if (collision_point.is_entry)
                    {
                        output = output + string_format("Entry(true). ");
                    }
                    else
                    {
                        output = output + string_format("Entry(false). ");
                    }

                    output = output + string_format("Contour1(%1,%2), Contour2(%3,%4).", collision_point.contour1_line_start, collision_point.contour1_line_end, collision_point.contour2_line_start, collision_point.contour2_line_end);

                    font.draw_text(canvas, 0, font_ypos, output, Colorf(0.0f, 0.0f, 0.0f, 0.5f));
                    font_ypos += 20;
                }
                // Paint the pen-depth and normal from the deepest points
                {
                    if (draw_deep_point)
                    {
                        draw_point_normal(canvas, colpointinfo[c].contour1_deep_point, colpointinfo[c].penetration_normal, Colorf::blue);
                        draw_point_normal(canvas, colpointinfo[c].contour2_deep_point, colpointinfo[c].penetration_normal, Colorf::blue);
                    }

                    // Draw information

                    std::string output(string_format("Collision(%1). ", c));
                    if (colpointinfo[c].inside)
                    {
                        output = output + string_format("Inside(true). ");
                    }
                    else
                    {
                        output = output + string_format("Inside(false). ");
                    }
                    output = output + string_format("PenNormal(%1,%2). ", colpointinfo[c].penetration_normal.x, colpointinfo[c].penetration_normal.y);
                    output = output + string_format("PenDepth(%1). ", colpointinfo[c].penetration_depth);
                    output = output + string_format("DeepPoint1(%1,%2). ", colpointinfo[c].contour1_deep_point.x, colpointinfo[c].contour1_deep_point.y);
                    output = output + string_format("DeepPoint2(%1,%2). ", colpointinfo[c].contour2_deep_point.x, colpointinfo[c].contour2_deep_point.y);
                    font.draw_text(canvas, 0, font_ypos, output, Colorf(0.0f, 0.0f, 0.0f, 0.5f));
                    font_ypos += 20;

                }
            }
        }

        // Update keyboard input and handle system events:
        window.flip(1);
        KeepAlive::process();
    }


//////////////////////////////////////////////////////////////////////////

    return 0;
}
	void OpenGLWindowProvider::create(DisplayWindowSite *new_site, const DisplayWindowDescription &desc)
	{
		window_handle = desc.get_handle();
		if (window_handle.window == nullptr)
			throw Exception("Window handle must exist in the display description");

		ANativeWindow *window = window_handle.window;

		const EGLint attribs[] = {
			EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
			EGL_BLUE_SIZE, 8,
			EGL_GREEN_SIZE, 8,
			EGL_RED_SIZE, 8,
			EGL_NONE
		};
		EGLint format;
		EGLint numConfigs;
		EGLConfig config;

		display = eglGetDisplay(EGL_DEFAULT_DISPLAY);

		eglInitialize(display, 0, 0);

		/* Here, the application chooses the configuration it desires. In this
		* sample, we have a very simplified selection process, where we pick
		* the first EGLConfig that matches our criteria */
		if (!eglChooseConfig(display, attribs, &config, 1, &numConfigs))
			throw Exception("eglChooseConfig failed");
		if (numConfigs < 1)
			throw Exception("Found configs failed");

		/* EGL_NATIVE_VISUAL_ID is an attribute of the EGLConfig that is
		* guaranteed to be accepted by ANativeWindow_setBuffersGeometry().
		* As soon as we picked a EGLConfig, we can safely reconfigure the
		* ANativeWindow buffers to match, using EGL_NATIVE_VISUAL_ID. */
		eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format);

		ANativeWindow_setBuffersGeometry(window, 0, 0, format);

		surface = eglCreateWindowSurface(display, config, window, NULL);
		if (surface == EGL_NO_SURFACE)
			throw Exception("eglCreateWindowSurface failed");

		context = eglCreateContext(display, config, NULL, NULL);
		if (context == EGL_NO_CONTEXT)
			throw Exception("eglCreateWindowSurface failed");

		if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE)
		{
			throw Exception("Unable to eglMakeCurrent");
		}
		bool use_gl3;
		int desc_version_major = opengl_desc.get_version_major();
		int desc_version_minor = opengl_desc.get_version_minor();

		// Do not attempt GL3, if not requested that version
		if (desc_version_major < 3)
		{
			use_gl3 = false;
		}
		else if (!opengl_desc.get_allow_lower_versions())	// Else, if we do not allow lower versions, only attempt GL3
		{
			use_gl3 = true;
		}
		else
		{
			// Choose the target depending on the current opengl version
			int gl_version_major;
			int gl_version_minor;
			get_opengl_version(gl_version_major, gl_version_minor);
			if (gl_version_major < 3)
			{
				use_gl3 = false;
			}
			else
			{
				use_gl3 = true;
			}

		}

		if (use_gl3)
		{
			using_gl3 = true;
			gc = GraphicContext(new GL3GraphicContextProvider(this));
		}
		else
		{
			using_gl3 = false;
			gc = GraphicContext(new GL1GraphicContextProvider(this));
		}
		swap_interval = desc.get_swap_interval();
		if (swap_interval != -1)
			eglSwapInterval(display, swap_interval);

	}
示例#13
0
// The start of the Application
int Joints::start(const std::vector<std::string> &args)
{
	//Remove the need to send physic world to every object. Instead send just the description.

	//Fix having two fixtures working weirdly.
	quit = false;

	// Set the window
	DisplayWindowDescription desc;
	desc.set_title("ClanLib Joints Example");
	desc.set_size(Size(window_x_size, window_y_size), true);
	desc.set_allow_resize(false);

	DisplayWindow window(desc);
	
	// Connect the Window close event
	Slot slot_quit = window.sig_window_close().connect(this, &Joints::on_window_close);

	// Connect a keyboard handler to on_key_up()
	Slot slot_input_up = (window.get_ic().get_keyboard()).sig_key_up().connect(this, &Joints::on_input_up);

	// Create the canvas
	Canvas canvas(window);

	//Setup physic world
	PhysicsWorldDescription phys_desc;
	phys_desc.set_gravity(0.0f,10.0f);
	phys_desc.set_sleep(true);
	phys_desc.set_physic_scale(100);

	PhysicsWorld phys_world(phys_desc);

	//Setup ground body
	Body ground = create_ground_body(phys_world);

	unsigned int last_time = System::get_time();

	//Setup debug draw.
	PhysicsDebugDraw debug_draw(phys_world);
	debug_draw.set_flags(f_shape|f_aabb|f_joint);

	GraphicContext gc = canvas.get_gc();
	//Setup joints

	const int number_of_joints = 3;
	std::vector<Body> bodies_A(number_of_joints);
	std::vector<Body> bodies_B(number_of_joints);
	std::vector<std::shared_ptr<Joint>> Joints(number_of_joints);
	

	for(int i=0; i<number_of_joints; i++)
	{
		bodies_A[i] = create_box_body(phys_world);
		bodies_A[i].set_position(Vec2f(80.0f+80.0f*i,280.0f));

		bodies_B[i] = create_box_body(phys_world);
		bodies_B[i].set_position(Vec2f(80.0f+80.0f*i,440.0f));

		Joints[i] = create_joint(phys_world, bodies_A[i], bodies_B[i], i);
	}

	// Run until someone presses escape
	while (!quit)
	{
		unsigned int current_time = System::get_time();
		float time_delta_ms = static_cast<float> (current_time - last_time);
		last_time = current_time;

		canvas.clear();
		
		phys_world.step();
		debug_draw.draw(canvas);

		canvas.flush();
		window.flip(1);

		// This call processes user input and other events
		KeepAlive::process(0);

		System::sleep(10);
	}

	return 0;
}
示例#14
0
HelloWorld::HelloWorld()
{
#if defined(WIN32) && !defined(__MINGW32__)
	clan::D3DTarget::set_current();
#else
	clan::OpenGLTarget::set_current();
#endif

	// Create a source for our resources
	FileResourceDocument doc(FileSystem("../../ThemeAero"));
	ResourceManager resources = FileResourceManager::create(doc);

	// Mark this thread as the UI thread
	ui_thread = UIThread(resources);

	// Create a window:
	DisplayWindowDescription desc;
	desc.set_title("UICore: Hello World");
	desc.set_allow_resize(true);
	desc.set_size(Sizef(640, 600), false);
	window = std::make_shared<TopLevelWindow>(desc);

	// Exit run loop when close is clicked or ESC pressed.
	auto pRootView = window->root_view();
	pRootView->slots.connect(pRootView->sig_close(), [&](CloseEvent &e) { RunLoop::exit(); });
	pRootView->slots.connect(pRootView->sig_key_press(), [&](clan::KeyEvent &e) 
		{ if (e.key() == clan::Key::escape) RunLoop::exit(); }
	);

	// Need for receive a keyboard events.
	pRootView->set_focus();

	// Style the root view to use rounded corners and a bit of drop shadow
	window->root_view()->style()->set("padding: 11px");
	window->root_view()->style()->set("background: #efefef");
	window->root_view()->style()->set("flex-direction: column");

	// Main window icons
	window->display_window().set_small_icon(clan::PixelBuffer("Resources/app_icon_16x16.png", doc.get_file_system()));
	window->display_window().set_large_icon(clan::PixelBuffer("Resources/app_icon_32x32.png", doc.get_file_system()));

	auto body = std::make_shared<View>();
	body->style()->set("background: white");
	body->style()->set("padding: 11px");
	body->style()->set("border-top: 5px solid #DD3B2A");
	body->style()->set("border-bottom: 5px solid #DD3B2A");
	body->style()->set("flex-direction: column");
	body->style()->set("flex: auto");
	window->root_view()->add_child(body);

	// Create a label with some text to have some content
	label = std::make_shared<LabelView>();
	label->style()->set("flex: none");
	label->style()->set("font: 20px/40px 'Ravie'");
	label->style()->set("color: #DD3B2A");
	label->set_text("Hello World!");
	body->add_child(label);

	// React to clicking
	label->slots.connect(label->sig_pointer_press(), [&](PointerEvent &e) {
		label->set_text(label->text() + " CLICK!");
	});

	auto scrollarea = std::make_shared<ScrollView>();
	scrollarea->style()->set("margin: 5px 0; border: 1px solid black; padding: 5px 0px 5px 5px;");
	scrollarea->content_view()->style()->set("flex-direction: column; background: white;");
	Theme::initialize_scrollbar(scrollarea->scrollbar_y_view(), false);
	scrollarea->scrollbar_y_view()->style()->set("padding: 0 0 0 3px; background: white;");
	body->add_child(scrollarea);

	// Create a text field for our span layout
	std::shared_ptr<TextFieldView> edit = std::make_shared<TextFieldView>();
	edit->style()->set("font: 11px/20px 'Segoe UI'");
	edit->style()->set("margin: 5px");
	edit->style()->set("background: #efefef");
	edit->style()->set("border: 1px solid black");
	edit->style()->set("border-radius: 3px");
	edit->style()->set("padding: 2px 5px 2px 5px");
	edit->style()->set("width: 128px");
	edit->style()->set("box-shadow: 0 0 5px rgba(100,100,200,0.2)");
	edit->set_text("amazing!");

	// Create a span layout views with some more complex inline formatting
	std::shared_ptr<SpanLayoutView> p1 = std::make_shared<SpanLayoutView>();
	p1->style()->set("font: 13px/25px 'Segoe UI'");
	p1->text_style("bold")->set("font-weight: bold");
	p1->text_style("italic")->set("font-style: italic");
	p1->add_text("This is an example of why Sphair should never ever make fun of my ");
	p1->add_text("BEAUTIFUL", "bold");
	p1->add_text(" green 13.37deg gradients because he will never know what it is replaced with!");
	scrollarea->content_view()->add_child(p1);

	std::shared_ptr<SpanLayoutView> p2 = std::make_shared<SpanLayoutView>();
	p2->style()->set("margin: 15px 0 5px 0");
	p2->style()->set("padding: 7px");
	p2->style()->set("border-top: 5px solid #CCE4FB");
	p2->style()->set("border-bottom: 5px solid #CCE4FB");
	p2->style()->set("background: #EDF6FF");
	p2->style()->set("font: 13px/25px 'Segoe UI'");
	p2->text_style("bold")->set("font-weight: bold");
	p2->text_style("italic")->set("font-style: italic");
	p2->add_text("If you also think Sphair made a ");
	p2->add_text("BIG MISTAKE", "bold");
	p2->add_text(" please consider typing ");
	p2->add_text("Yes, yes, yes, yes, yes, yes, yes yes, YES!", "italic");
	p2->add_text(" in the text field: ");
	p2->add_child(edit);
	p2->add_text(" You know you want to!", "bold");
	scrollarea->content_view()->add_child(p2);
	
	std::shared_ptr<SpanLayoutView> p3 = std::make_shared<SpanLayoutView>();
	p3->style()->set("font: 13px/25px 'Segoe UI'");
	p3->text_style("bold")->set("font-weight: bold");
	p3->text_style("italic")->set("font-style: italic");
	p3->add_text("Since we both know you typed ");
	p3->add_text("Yes, yes, yes..", "italic");
	p3->add_text(" into the text field (who wouldn't!?), here's the amazing gradient:");
	scrollarea->content_view()->add_child(p3);
	
	std::shared_ptr<View> gradient_box = std::make_shared<View>();
	gradient_box->style()->set("margin: 15px auto; width: 120px; height: 75px;");
	gradient_box->style()->set("border: 1px solid #777");
	gradient_box->style()->set("background: linear-gradient(13.37deg, #f0f0f0, rgb(120,240,120) 50%, #f0f0f0)");
	gradient_box->style()->set("box-shadow: 7px 7px 7px rgba(0,0,0,0.2)");
	scrollarea->content_view()->add_child(gradient_box);
	
	auto listbox = Theme::create_listbox();
	listbox->style()->set("flex: none; height: 60px; margin: 7px 0; border: 1px solid black; padding: 5px; background: #f0f0f0");
	listbox->set_items<std::string>(
		{ "Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "More items", "Even more items!!", "No more items!!!!!" },
		[](const std::string &s) -> std::shared_ptr<View>
		{
			auto item = Theme::create_listbox_label(s);
			return item;
		});
	scrollarea->content_view()->add_child(listbox);

	auto scrollbar = Theme::create_scrollbar();
	//scrollbar->set_disabled();
	scrollbar->set_range(0.0, 1.0);
	scrollbar->set_position(0.5);
	scrollbar->set_page_step(0.1);
	scrollbar->set_line_step(0.01);
	scrollarea->content_view()->add_child(scrollbar);

	auto button = Theme::create_button();
	button->label()->set_text("This is a button");
	scrollarea->content_view()->add_child(button);

	std::shared_ptr<clan::SliderView> slider = Theme::create_slider();
	//slider->set_disabled();
	slider->set_min_position(0);
	slider->set_max_position(1000);
	slider->set_tick_count(100);
	slider->set_lock_to_ticks(false);
	slider->set_page_step(100);
	slider->set_position(slider->max_position()/2);
	scrollarea->content_view()->add_child(slider);

	auto checkbox = Theme::create_checkbox();
	//checkbox->set_disabled();
	checkbox->style()->set("margin: 12px");
	checkbox->label()->set_text("Checkbox");
	scrollarea->content_view()->add_child(checkbox);

	// Hint - parent of the radiobutton must have an opaque background due to sub-pixel rendering effect.
	for (int cnt = 0; cnt < 3; cnt++)
	{
		auto radio = Theme::create_radiobutton();
		//radio->set_disabled(true);
		scrollarea->content_view()->add_child(radio);
	}

	// Create a popup window
	pRootView->slots.connect(button->sig_pointer_enter(), [=](PointerEvent &e)
	{
		auto popup = std::make_shared<WindowController>();
		popup->root_view()->style()->set("flex-direction: column");
		popup->root_view()->style()->set("background: #FFFFE0");
		popup->root_view()->style()->set("margin: 5px");
		popup->root_view()->style()->set("border: 1px solid black");
		popup->root_view()->style()->set("border-radius: 2px");
		popup->root_view()->style()->set("padding: 2px 5px 2px 5px");
		popup->root_view()->style()->set("box-shadow: 0 0 3px rgba(0,0,0,0.2)");

		auto text = Theme::create_label(true);
		text->style()->set("font: 12px Tahoma; color: black");
		text->set_text("This is an awesome popup");
		popup->root_view()->add_child(text);

		std::weak_ptr<WindowController> popup_weak = popup;
		popup->slots.connect(button->sig_pointer_leave(), [=](PointerEvent &e)
		{
			auto p = popup_weak.lock();
			if (p)
				p->dismiss();
		});

		window_manager.present_popup(button.get(), e.pos(button) + Pointf(10.0f, -10.0f), popup);
	});

	// Show a modal dialog
	button->func_clicked() = [=]()
	{
		auto dialog = std::make_shared<WindowController>();
		dialog->set_title("Alarm!!");
		dialog->root_view()->style()->set("flex-direction: column");
		dialog->root_view()->style()->set("background: rgb(240,240,240)");
		dialog->root_view()->style()->set("padding: 11px");
		dialog->root_view()->style()->set("width: 250px");

		auto text = Theme::create_label(true);
		text->style()->set("margin-bottom: 7px");
		text->style()->set("font: 12px Tahoma; color: black");
		text->set_text("This a modal dialog");
		dialog->root_view()->add_child(text);

		auto ok_button = Theme::create_button();
		ok_button->label()->set_text("OK");
		dialog->root_view()->add_child(ok_button);

		std::weak_ptr<WindowController> dialog_weak = dialog;
		ok_button->func_clicked() = [=]()
		{
			auto d = dialog_weak.lock();
			if (d)
				d->dismiss();
		};

		window_manager.present_modal(window->root_view().get(), dialog);
	};

	// Prevent close program when hint or modal windows closes.
	window_manager.set_exit_on_last_close(false);
	
	// Make our window visible
	window->show();
}
示例#15
0
// The start of the Application
int Collision::start(const std::vector<std::string> &args)
{
	//Remove the need to send physic world to every object. Instead send just the description.

	//Fix having two fixtures working weirdly.
	quit = false;

	// Set the window
	DisplayWindowDescription desc;
	desc.set_title("ClanLib Collision Example");
	desc.set_size(Size(window_x_size, window_y_size), true);
	desc.set_allow_resize(false);

	DisplayWindow window(desc);
	
	// Connect the Window close event
	window.sig_window_close().connect(this, &Collision::on_window_close);

	// Connect a keyboard handler to on_key_up()
	window.get_ic().get_keyboard().sig_key_up().connect(this, &Collision::on_input_up);

	// Create the canvas
	Canvas canvas(window);

	//Setup physic world
	PhysicsWorldDescription phys_desc;
	phys_desc.set_gravity(0.0f,10.0f);
	phys_desc.set_sleep(true);
	phys_desc.set_physic_scale(100);
	phys_desc.set_timestep(1.0f/60.0f);
	phys_desc.set_velocity_iterations(8);
	phys_desc.set_position_iterations(3);

	PhysicsWorld phys_world(phys_desc);

	//Setup ground body
	Body ground = create_ground_body(phys_world);

	unsigned int last_time = System::get_time();

	//Setup outline body
	Body outline_body = create_outline_body(phys_world);
	outline_body.set_position(Vec2f(200.0f,200.0f));

	//Setup debug draw.
	PhysicsDebugDraw debug_draw(phys_world);
	debug_draw.set_flags(f_shape);

	GraphicContext gc = canvas.get_gc();
	
	// Run until someone presses escape
	while (!quit)
	{
		unsigned int current_time = System::get_time();
		float time_delta_ms = static_cast<float> (current_time - last_time);
		last_time = current_time;

		canvas.clear();
		
		phys_world.step();
		debug_draw.draw(canvas);

		canvas.flush();
		window.flip(1);
		
		// This call processes user input and other events
		KeepAlive::process(0);

		System::sleep(10);
	}

	return 0;
}
示例#16
0
文件: test.cpp 项目: punkkeks/ClanLib
int TestApp::main(const std::vector<std::string> &args)
{
	quit = false;

	// Create a console window for text-output if not available
	ConsoleWindow console("Console", 80, 200);

	try
	{

		DisplayWindowDescription desc;

		desc.set_title("Image clipboard test");
		desc.set_size(Size(800,600), true);
		DisplayWindow window(desc);

		// Connect the Window close event
		Slot slot_quit = window.sig_window_close().connect(this, &TestApp::on_window_close);

		// Connect a keyboard handler to on_key_up()
		Slot slot_input_up = (window.get_ic().get_keyboard()).sig_key_up().connect(this, &TestApp::on_input_up);
		
		//Create the Canvas
		Canvas canvas(window);

		//Set the reference to GraphicContext
		GraphicContext &gc = canvas.get_gc();

		PixelBuffer to_clipboard = ImageProviderFactory::load("copy.png");
		window.set_clipboard_image(to_clipboard);

		/*		while (!window.get_ic().get_keyboard().get_keycode(KEY_ESCAPE))
		{
			window.get_gc().clear(Colorf::gray70);
			window.flip();
			KeepAlive::process();
			System::sleep(50);
		}*/

/*		// Save to file
		PNGProvider::save(to_clipboard, "copy2.png");

		// Save to IODevice_Memory memory buffer
		DataBuffer data(1024*8); // 8 kb
		IODevice_Memory mem(data);
		PNGProvider::save(to_clipboard, mem);
		File file("copy3.png", File::create_always);
		DataBuffer mem_data = mem.get_data();
		file.write(mem_data.get_data(), mem_data.get_size());
*/	

		PixelBuffer from_clipboard;
		if (window.is_clipboard_image_available())
		{
			from_clipboard = window.get_clipboard_image();
			PNGProvider::save(from_clipboard, "from_clipboard.png");
		} 

		if (!from_clipboard.is_null())
		{
			Texture2D texture_image(gc,
									from_clipboard.get_width(),
									from_clipboard.get_height(),
									from_clipboard.get_format());
			texture_image.set_image(gc,from_clipboard);
			texture_image.set_min_filter(filter_linear);
			texture_image.set_mag_filter(filter_linear);

			Image image(texture_image,texture_image.get_size());

			while (!quit)
			{
				canvas.clear(Colorf(0.0f,0.0f,0.2f));

				canvas.set_map_mode(MapMode(map_2d_upper_left));

				image.draw(canvas,0,0);

				// Flip the display, showing on the screen what we have drawed
				// since last call to flip()
				window.flip(1);
				
				// This call processes user input and other events
				KeepAlive::process();
			}
		}
	}
	catch(Exception error)
	{
		Console::write_line("Exception caught:");
		Console::write_line(error.message);

		console.display_close_message();
		return -1;
	}

	return 0;
}
	void OpenGLWindowProvider::create(DisplayWindowSite *new_site, const DisplayWindowDescription &desc)
	{
		site = new_site;
		fullscreen = desc.is_fullscreen();

		win32_window.create(site, desc);

		if (!opengl_context)
		{
			HWND handle = win32_window.get_hwnd();
			dwm_layered = false;

			if (desc.is_layered() && !DwmFunctions::is_composition_enabled())
			{
				create_shadow_window(handle);
			}
			else
			{
				if (desc.is_layered())
					dwm_layered = true;
			}

			desc.is_layered() ? double_buffered = false : double_buffered = true;	// Only can use Layered windows that are single buffered with OpenGL (via shadow window) ( PFD_DOUBLEBUFFER_DONTCARE set in OpenGLCreationHelper::set_multisampling_pixel_format)

			device_context = GetDC(handle);

			HGLRC share_context = get_share_context();

			OpenGLCreationHelper helper(handle, device_context);
			helper.set_multisampling_pixel_format(desc);

			int gl_major = opengl_desc.get_version_major();
			int gl_minor = opengl_desc.get_version_minor();
			if (opengl_desc.get_allow_lower_versions() == false)
			{
				opengl_context = helper.create_opengl3_context(share_context, gl_major, gl_minor, opengl_desc);
				if (!opengl_context)
					throw Exception(string_format("This application requires OpenGL %1.%2 or above. Try updating your drivers, or upgrade to a newer graphics card.", gl_major, gl_minor));
			}
			else
			{
				static const char opengl_version_list[] =
				{
					// Clanlib supported version pairs
					4, 5,
					4, 4,
					4, 3,
					4, 2,
					4, 1,
					4, 0,
					3, 3,
					3, 2,
					3, 1,
					3, 0,
					0, 0,	// End of list
				};

				const char *opengl_version_list_ptr = opengl_version_list;
				do
				{
					int major = *(opengl_version_list_ptr++);
					if (major == 0)
						break;

					int minor = *(opengl_version_list_ptr++);

					// Find the appropriate version in the list
					if (major > gl_major)
						continue;

					if (major == gl_major)
					{
						if (minor > gl_minor)
							continue;
					}

					opengl_context = helper.create_opengl3_context(share_context, major, minor, opengl_desc);
				} while (!opengl_context);

				if (!opengl_context)
					opengl_context = helper.create_opengl2_context(share_context);

				if (!opengl_context)
					throw Exception("This application requires OpenGL. Try updating your drivers, or upgrade to a newer graphics card.");

			}

			bool use_gl3;
			int desc_version_major = opengl_desc.get_version_major();
			int desc_version_minor = opengl_desc.get_version_minor();

			// Do not attempt GL3, if not requested that version
			if (desc_version_major < 3)
			{
				use_gl3 = false;
			}
			else if (!opengl_desc.get_allow_lower_versions())	// Else, if we do not allow lower versions, only attempt GL3
			{
				use_gl3 = true;
			}
			else
			{
				// Choose the target depending on the current opengl version
				int gl_version_major;
				int gl_version_minor;
				get_opengl_version(gl_version_major, gl_version_minor);
				if (gl_version_major < 3)
				{
					use_gl3 = false;
				}
				else
				{
					use_gl3 = true;
				}

			}

			if (use_gl3)
			{
				using_gl3 = true;
				gc = GraphicContext(new GL3GraphicContextProvider(this));
			}
			else
			{
				using_gl3 = false;
				gc = GraphicContext(new GL1GraphicContextProvider(this));
			}
		}

		wglSwapIntervalEXT = (ptr_wglSwapIntervalEXT)OpenGL::get_proc_address("wglSwapIntervalEXT");
		swap_interval = desc.get_swap_interval();
		if (wglSwapIntervalEXT && swap_interval != -1)
			wglSwapIntervalEXT(swap_interval);
	}
示例#18
0
	void X11Window::create(XVisualInfo *visual, DisplayWindowSite *new_site, const DisplayWindowDescription &desc)
	{
		site = new_site;

		// Reset all variables
		close_window();

		handle.screen = visual->screen;
		atoms = X11Atoms(handle.display);

		int disp_width_px = XDisplayWidth(handle.display, handle.screen);
		int disp_height_px = XDisplayHeight(handle.display, handle.screen);
		int disp_width_mm = XDisplayWidthMM(handle.display, handle.screen);

		// Get DPI of screen or use 96.0f if Xlib doesn't have a value.
		ppi = (disp_width_mm < 24) ? 96.0f : (25.4f * static_cast<float>(disp_width_px) / static_cast<float>(disp_width_mm));

		// Update pixel ratio.
		set_pixel_ratio(pixel_ratio);

		// Get X11 root window.
		auto _root_window = RootWindow(handle.display, handle.screen);

		// Get and validate initial window position and size.
		int win_x = desc.get_position().left * pixel_ratio;
		int win_y = desc.get_position().top * pixel_ratio;
		int win_width = desc.get_size().width * pixel_ratio;
		int win_height = desc.get_size().height * pixel_ratio;

		if (win_width <= 0)
			throw Exception("Invalid window width.");

		if (win_height <= 0)
			throw Exception("Invalid window height.");

		// Set values if fullscreen requested.
		if (desc.is_fullscreen())
		{
			win_x = 0;
			win_y = 0;
			win_width = disp_width_px;
			win_height = disp_height_px;
		}

		// Center window if position supplied is (-1, -1)
		if (win_x == -1 && win_y == -1)
		{
			win_x = (disp_width_px - win_width)/2 - 1;
			win_y = (disp_height_px - win_height)/2 - 1;
		}

		// Set minimum and maximum size
		this->resize_allowed = desc.get_allow_resize() || desc.is_fullscreen(); // Fullscreen mode needs a resizable window.
		if (resize_allowed)
		{
			minimum_size = Size(_ResizeMinimumSize_, _ResizeMinimumSize_);
			maximum_size = Size(0, 0); // No maximum size by default.
		}
		else
		{
			minimum_size = Size(win_width, win_height);
			maximum_size = Size(win_width, win_height);
		}

		// Setup X11 size hints.
		this->size_hints = XAllocSizeHints();
		if (size_hints == NULL)
			throw Exception("Failed to allocate X11 XSizeHints structure.");

		size_hints->flags       = PMinSize | (resize_allowed ? 0 : PMaxSize);
		size_hints->flags      |= PResizeInc | PBaseSize | PWinGravity;

		// x, y, width, height are obsolete.
		size_hints->flags      |= USSize | USPosition;	// See http://standards.freedesktop.org/wm-spec/wm-spec-latest.html#idm140200472522864

		size_hints->min_width   = minimum_size.width;
		size_hints->min_height  = minimum_size.height;
		size_hints->max_width   = maximum_size.width;
		size_hints->max_height  = maximum_size.height;
		size_hints->width_inc   = 1;
		size_hints->height_inc  = 1;
		size_hints->base_width  = win_width;
		size_hints->base_height = win_height;
		size_hints->win_gravity = NorthWestGravity;

		// Setup X11 colormap.
		//
		// The X.Org XServer implementation used on most systems requires that
		// a color-map be set for the window. Additionally, windows with a
		// different color-depth than its parent must have the border-pixel flag
		// set when creating them. Failure to do either will cause XCreateWindow()
		// to result in a BadMatch error.
		//
		// Source: stackoverflow.com/questions/3645632
		color_map = XCreateColormap(handle.display, _root_window, visual->visual, AllocNone);

		// Static popups are unresizable captionless popup windows.
		// These windows should not be decorated.
		bool is_static_popup = desc.is_popup() && !desc.has_caption() && !desc.get_allow_resize();

		// Tell X11 to perserve graphical content under small popup windows to avoid redraws.
		bool save_under = desc.is_popup() && ( (win_width * win_height) < (256 * 256 * pixel_ratio * pixel_ratio) );

		// Setup window attributes.
		XSetWindowAttributes attr = XSetWindowAttributes {
			.background_pixmap  = None, /* default */
			.background_pixel   =  0ul, /* default: undefined */
			.border_pixmap      = CopyFromParent, /* default */
			.border_pixel       =  0ul, /* see color_map details above */
			.bit_gravity        = ForgetGravity, /* default */
			.win_gravity        = NorthWestGravity, /* default */
			.backing_store      = NotUseful, /* default */
			.backing_planes     = -1ul, /* default */
			.backing_pixel      =  0ul, /* default */
			.save_under         = save_under ? True : False,
			.event_mask         = KeyPressMask
								| KeyReleaseMask
								| ButtonPressMask
								| ButtonReleaseMask
								| EnterWindowMask
								| LeaveWindowMask
								| PointerMotionMask
								| KeymapStateMask
								| ExposureMask
								// | VisibilityChangeMask
								| StructureNotifyMask
								| FocusChangeMask
								| PropertyChangeMask ,
			.do_not_propagate_mask  = NoEventMask, /* default */
			.override_redirect      = is_static_popup ? True : False,
			.colormap               = color_map, /* see color_map details above */
			.cursor                 = None /* default; Let X11 handle the cursor for now. */
		};

		this->system_cursor = XCreateFontCursor(handle.display, XC_left_ptr); // This is allowed to fail

		log_event("debug", "clan::X11Window::create(): Creating window...");
		log_event("debug", "    x%1 y%2 w%3 h%4 b%5 d%6", win_x, win_y, win_width, win_height, border_width, visual->depth);
		log_event("debug", "    a.su%1, a.od%2", save_under, is_static_popup);

		// Create window
		handle.window = XCreateWindow(
				handle.display, _root_window,
				win_x, win_y, win_width, win_height, border_width,
				visual->depth, InputOutput, visual->visual,
				CWBorderPixel | CWOverrideRedirect | CWSaveUnder | CWEventMask | CWColormap,
				&attr
				);

		if (!handle.window)
			throw Exception("Unable to create the X11 window");

		if (!desc.get_owner().is_null())
		{
			DisplayWindow owner = desc.get_owner();
			XSetTransientForHint(handle.display, handle.window, owner.get_handle().window);
		}

		// Setup the hidden cursor (Maybe this should be done only once when required)
		char data[64]; // 8x8
		memset(data, 0, 64);

		XColor black_color;
		memset(&black_color, 0, sizeof(black_color));

		cursor_bitmap = XCreateBitmapFromData(handle.display, handle.window, data, 8, 8);
		hidden_cursor = XCreatePixmapCursor(handle.display, cursor_bitmap, cursor_bitmap, &black_color, &black_color, 0,0);

		// Set title of window:
		set_title(desc.get_title());

		{   // Inform the window manager who we are, so it can kill us if we're not good for its universe.
			Atom atom;
			int32_t pid = getpid();
			if (pid > 0)
			{
				atom = atoms.get_atom(handle.display, "_NET_WM_PID", False);
				XChangeProperty(handle.display, handle.window, atom, XA_CARDINAL, 32, PropModeReplace, (unsigned char *) &pid, 1);
			}

			char hostname[256];
			if (gethostname(hostname, sizeof(hostname)) > -1)
			{
				hostname[255] = 0;
				atom = atoms.get_atom(handle.display, "WM_CLIENT_MACHINE", False);
				XChangeProperty(handle.display, handle.window, atom, XA_STRING, 8, PropModeReplace, (unsigned char *) hostname, strlen(hostname));
			}
		}

		// Set-up window type/styling.
		// TODO Support more window types, broaden ClanLib window type support, etc.
		if (atoms["_NET_WM_WINDOW_TYPE"] != None)
		{
			Atom type = None;
			std::string name;

			if (desc.is_dialog())
			{
				name = "_NET_WM_WINDOW_TYPE_DIALOG";
				type = atoms[name];
			}
			else if (desc.is_popup())
			{
				if (is_static_popup)
				{
					name = "_NET_WM_WINDOW_TYPE_TOOLTIP";
					type = atoms[name];
				}
				else if (desc.has_caption()) // A pop-up with title bar -> utility
				{
					name = "_NET_WM_WINDOW_TYPE_UTILITY";
					type = atoms[name];
				} // else, a pop-up without a title bar -> popup-menu, combo, dropdown, tooltip, ...

				if (type == None) { name = "_NET_WM_WINDOW_TYPE_POPUP_MENU"; type = atoms[name]; }
				if (type == None) { name = "_NET_WM_WINDOW_TYPE_COMBO"; type = atoms[name]; }
				if (type == None) { name = "_NET_WM_WINDOW_TYPE_DROPDOWN_MENU"; type = atoms[name]; }
			} // else if (desc.is_normal())

			// Fallback to normal window type if WM doesn't support what we want.
			if (type == None) { name = "_NET_WM_WINDOW_TYPE_NORMAL"; type = atoms[name]; }

			if (type != None) // Ensure selected type exists.
			{
				XChangeProperty(handle.display, handle.window, atoms["_NET_WM_WINDOW_TYPE"], XA_ATOM, 32, PropModeReplace, (unsigned char *)&type, 1);
				log_event("debug", "clan::X11Window::create(): Creating window of type '%1'.", name);
			}
			else
			{
				log_event("debug", "clan::X11Window::create(): Failed to find a suitable window type.");
			}
		}
		else
		{
			log_event("debug", "clan::X11Window::create(): _NET_WM_WINDOW_TYPE does not exist.");
		}

		// Set size hints
		XSetWMNormalHints(handle.display, handle.window, size_hints);

		{	// Subscribe to WM events.
			Atom protocol = atoms["WM_DELETE_WINDOW"];
			Status result = XSetWMProtocols(handle.display, handle.window, &protocol, 1);
			if (result == 0)
				log_event("debug", "clan::X11Window::create(): Failed to set WM_PROTOCOLS.");
		}

		{	// Make auto-repeat keys detectable.
			Bool supports_detectable_autorepeat;
			XkbSetDetectableAutoRepeat(handle.display, True, &supports_detectable_autorepeat);
		}

		{	// Make window full-screen if requested.
			if (atoms["_NET_WM_STATE"] == None && atoms["_NET_WM_STATE_FULLSCREEN"])
			{
				fullscreen = false;
				log_event("debug", "clan::X11Window: Fullscreen not supported by WM.");
			}
			else
			{
				fullscreen = desc.is_fullscreen();
			}

			if (fullscreen)
			{
				Atom state = atoms["_NET_WM_STATE_FULLSCREEN"];
				XChangeProperty(handle.display, handle.window, atoms["_NET_WM_STATE"], XA_ATOM, 32, PropModeReplace, (unsigned char *)&state, 1);
			}
		}

		update_frame_extents();

		auto new_client_area = desc.get_position_client_area() // supplied position is at ? client area : window area;
			? Rect::xywh(win_x, win_y, win_width, win_height)
			: Rect::xywh(win_x + frame_extents.left, win_y + frame_extents.right, win_width, win_height)
			;

		process_window_resize(new_client_area);

		// Set window visibility
		if (desc.is_visible())
		{
			show(false);
		}

		// Setup the clipboard
		clipboard.setup();

		// Go looking for joysticks:
		setup_joysticks();
	}

	void X11Window::update_frame_extents()
	{
		frame_extents = Rect { border_width, border_width, border_width, border_width };

		if (atoms["_NET_FRAME_EXTENTS"] == None)
			return;

		// Request frame extents from WM.
		if (atoms["_NET_REQUEST_FRAME_EXTENTS"] != None)
		{
			XEvent event;
			memset(&event, 0, sizeof(event));

			event.type = ClientMessage;
			event.xclient.window = handle.window;
			event.xclient.format = 32;
			event.xclient.message_type = atoms["_NET_REQUEST_FRAME_EXTENTS"];

			XSendEvent(handle.display, RootWindow(handle.display, handle.screen), False, SubstructureNotifyMask | SubstructureRedirectMask, &event);

			int timer = 10;
			while(true)
			{
				if (timer < 0)
				{
					log_event("debug", "clan::X11Window: Your window manager has a broken _NET_REQUEST_FRAME_EXTENTS implementation.");
					break;
				}

				if (XCheckMaskEvent(handle.display, PropertyNotify, &event))
				{
					break;
				}

				clan::System::sleep(5);
				timer--;
			}
		}

		unsigned long  item_count;
		// _NET_FRAME_EXTENTS, left, right, top, bottom, CARDINAL[4]/32
		unsigned char *data = atoms.get_property(handle.window, "_NET_FRAME_EXTENTS", item_count);
		if (data == NULL)
			return;

		if (item_count >= 4)
		{
			long *cardinal = (long *)data;
			frame_extents.left   = cardinal[0];
			frame_extents.right  = cardinal[1];
			frame_extents.top    = cardinal[2];
			frame_extents.bottom = cardinal[3];
		}

		XFree(data);
	}
示例#19
0
HelloWorld::HelloWorld()
{
	// We support all display targets, in order listed here
	//clan::D3DTarget::enable();
	clan::OpenGLTarget::enable();

	// Create a source for our resources
	FileResourceDocument doc(FileSystem("../../ThemeAero"));
	ResourceManager resources = FileResourceManager::create(doc);

	// Mark this thread as the UI thread
	ui_thread = UIThread(resources);

	// Create root view and window:
	DisplayWindowDescription desc;
	desc.set_title("UICore: Hello World");
	desc.set_allow_resize(true);
	desc.set_size(Sizef(640, 600), false);
	root = std::make_shared<WindowView>(desc);

	// Exit run loop when close is clicked.
	// We have to store the return Slot because if it is destroyed the lambda function is disconnected from the signal.
	slot_close = root->sig_close().connect([&](CloseEvent &e) { RunLoop::exit(); });

	// Style the root view to use rounded corners and a bit of drop shadow
	root->style()->set("padding: 11px");
	root->style()->set("background: #efefef");
	root->style()->set("flex-direction: column");

	auto body = std::make_shared<View>();
	body->style()->set("background: white");
	body->style()->set("padding: 11px");
	body->style()->set("border-top: 5px solid #DD3B2A");
	body->style()->set("border-bottom: 5px solid #DD3B2A");
	body->style()->set("flex-direction: column");
	body->style()->set("flex: auto");
	root->add_subview(body);

	// Create a label with some text to have some content
	label = std::make_shared<LabelView>();
	label->style()->set("flex: none");
	label->style()->set("font: 20px/40px 'Ravie'");
	label->style()->set("color: #DD3B2A");
	label->set_text("Hello World!");
	body->add_subview(label);

	// React to clicking
	label->slots.connect(label->sig_pointer_press(), [&](PointerEvent &e) {
		label->set_text(label->text() + " CLICK!");
	});

	auto scrollarea = std::make_shared<ScrollView>();
	scrollarea->style()->set("margin: 5px 0; border: 1px solid black; padding: 5px 5px;");
	scrollarea->scrollbar_x_view()->thumb()->style()->set("background: #c8c8c8");
	scrollarea->scrollbar_y_view()->thumb()->style()->set("background: #c8c8c8");
	scrollarea->content_view()->style()->set("flex-direction: column");
	body->add_subview(scrollarea);

	// Create a text field for our span layout
	std::shared_ptr<TextFieldView> edit = std::make_shared<TextFieldView>();
	edit->style()->set("font: 11px/20px 'Segoe UI'");
	edit->style()->set("margin: 5px");
	edit->style()->set("background: #efefef");
	edit->style()->set("border: 1px solid black");
	edit->style()->set("border-radius: 3px");
	edit->style()->set("padding: 2px 5px 2px 5px");
	edit->style()->set("width: 128px");
	edit->style()->set("box-shadow: 0 0 5px rgba(100,100,200,0.2)");
	edit->set_text("amazing!");

	// Create some text styles for the text we will write
	std::shared_ptr<Style> normal = std::make_shared<Style>();
	std::shared_ptr<Style> bold = std::make_shared<Style>();
	std::shared_ptr<Style> italic = std::make_shared<Style>();
	normal->set("font: 13px/25px 'Segoe UI'");
	bold->set("font: 13px/25px 'Segoe UI'; font-weight: bold");
	italic->set("font: 13px/25px 'Segoe UI'; font-style: italic");

	// Create a span layout views with some more complex inline formatting
	std::shared_ptr<SpanLayoutView> p1 = std::make_shared<SpanLayoutView>();
	p1->add_text("This is an example of why Sphair should never ever make fun of my ", normal);
	p1->add_text("BEAUTIFUL", bold);
	p1->add_text(" green 13.37deg gradients because he will never know what it is replaced with!", normal);
	scrollarea->content_view()->add_subview(p1);

	std::shared_ptr<SpanLayoutView> p2 = std::make_shared<SpanLayoutView>();
	p2->style()->set("margin: 15px 0 5px 0");
	p2->style()->set("padding: 7px");
	p2->style()->set("border-top: 5px solid #CCE4FB");
	p2->style()->set("border-bottom: 5px solid #CCE4FB");
	p2->style()->set("background: #EDF6FF");
	p2->add_text("If you also think Sphair made a ", normal);
	p2->add_text("BIG MISTAKE", bold);
	p2->add_text(" please consider typing ", normal);
	p2->add_text("Yes, yes, yes, yes, yes, yes, yes yes, YES!", italic);
	p2->add_text(" in the text field: ", normal);
	p2->add_subview(edit);
	p2->add_text(" You know you want to!", bold);
	scrollarea->content_view()->add_subview(p2);
	
	std::shared_ptr<SpanLayoutView> p3 = std::make_shared<SpanLayoutView>();
	p3->add_text("Since we both know you typed ", normal);
	p3->add_text("Yes, yes, yes..", italic);
	p3->add_text(" into the text field (who wouldn't!?), here's the amazing gradient:", normal);
	scrollarea->content_view()->add_subview(p3);
	
	std::shared_ptr<View> gradient_box = std::make_shared<View>();
	gradient_box->style()->set("margin: 15px auto; width: 120px; height: 75px;");
	gradient_box->style()->set("border: 1px solid #777");
	gradient_box->style()->set("background: linear-gradient(13.37deg, #f0f0f0, rgb(120,240,120) 50%, #f0f0f0)");
	gradient_box->style()->set("box-shadow: 7px 7px 7px rgba(0,0,0,0.2)");
	scrollarea->content_view()->add_subview(gradient_box);

	auto scrollbar = Theme::create_scrollbar();
	//scrollbar->set_disabled();
	scrollbar->set_range(0.0, 1.0);
	scrollbar->set_position(0.5);
	scrollbar->set_page_step(0.1);
	scrollbar->set_line_step(0.01);
	scrollarea->content_view()->add_subview(scrollbar);

	auto button = Theme::create_button();
	button->label()->set_text("This is a button");
	scrollarea->content_view()->add_subview(button);

	std::shared_ptr<clan::SliderView> slider = Theme::create_slider();
	//slider->set_disabled();
	slider->set_min_position(0);
	slider->set_max_position(1000);
	slider->set_tick_count(100);
	slider->set_lock_to_ticks(false);
	slider->set_page_step(100);
	slider->set_position(slider->max_position()/2);
	scrollarea->content_view()->add_subview(slider);

	auto checkbox = Theme::create_checkbox();
	//checkbox->set_disabled();
	scrollarea->content_view()->add_subview(checkbox);

	for (int cnt = 0; cnt < 3; cnt++)
	{
		auto radio = Theme::create_radiobutton();
		//radio->set_disabled(true);
		scrollarea->content_view()->add_subview(radio);
	}

	// Make our window visible
	root->show();
}
示例#20
0
// The start of the Application
int Raycasting::start(const std::vector<std::string> &args)
{
	//Remove the need to send physic world to every object. Instead send just the description.

	//Fix having two fixtures working weirdly.
	quit = false;

	int window_x_size = 640;
	int window_y_size = 480;
	// Set the window
	DisplayWindowDescription desc;
	desc.set_title("ClanLib Raycasting Example");
	desc.set_size(Size(window_x_size, window_y_size), true);
	desc.set_allow_resize(false);

	DisplayWindow window(desc);
	
	// Connect the Window close event
	Slot slot_quit = window.sig_window_close().connect(this, &Raycasting::on_window_close);

	// Connect a keyboard handler to on_key_up()
	Slot slot_input_up = (window.get_ic().get_keyboard()).sig_key_up().connect(this, &Raycasting::on_input_up);

	// Create the canvas
	Canvas canvas(window);

	//Setup physic world
	PhysicsWorldDescription phys_desc;
	phys_desc.set_gravity(0.0f,10.0f);
	phys_desc.set_sleep(true);
	phys_desc.set_physic_scale(100);
	phys_desc.set_timestep(1.0f/200.0f);

	PhysicsWorld phys_world(phys_desc);

	//Get the Physics Context
	PhysicsContext pc = phys_world.get_pc();

	//Setup ground body
	BodyDescription ground_desc(phys_world);
	ground_desc.set_position(Vec2f((float)window_x_size/2.0f,(float)window_y_size));
	ground_desc.set_type(body_static);

	Body ground(pc, ground_desc);
	//Setup ground fixture
	PolygonShape ground_shape(phys_world);
	ground_shape.set_as_box((float)window_x_size/2,20.0f);

	FixtureDescription fixture_desc(phys_world);
	fixture_desc.set_shape(ground_shape);
	
	Fixture ground_fixture(pc, ground, fixture_desc);

	//Setup box body
	BodyDescription box_desc(phys_world);
	box_desc.set_position(Vec2f(10.0f,10.0f));
	box_desc.set_type(body_dynamic);
	box_desc.set_linear_velocity(Vec2f(100.0f,0.0f));
	Body box(pc, box_desc);

	box_desc.set_position(Vec2f((float)window_x_size-50.0f,100.0f));
	box_desc.set_linear_velocity(Vec2f(-80.0f,0.0f));
	Body box2(pc, box_desc);

	//Setup box fixture
	PolygonShape box_shape(phys_world);
	box_shape.set_as_box(30.0f, 30.0f);

	FixtureDescription fixture_desc2(phys_world);
	fixture_desc2.set_shape(box_shape);
	fixture_desc2.set_restitution(0.6f);
	fixture_desc2.set_friction(0.0005f);

	Fixture box_fixture(pc, box, fixture_desc2);
	Fixture box_fixture2(pc, box2, fixture_desc2);

	Vec2f ground_pos = ground.get_position();

	unsigned int last_time = System::get_time();
	
	//Setup debug draw.
	PhysicsDebugDraw debug_draw(phys_world);
	debug_draw.set_flags(f_shape|f_aabb);

	GraphicContext gc = canvas.get_gc();
	PhysicsQueryAssistant qa = phys_world.get_qa();

	clan::Font font(canvas, "Tahoma", 12);

	// Set raycast points
	Pointf p1(300,500);
	Pointf p2(100,100);

	// Set query rect;
	Rectf rect1(400.0f, 380.0f, Sizef(50.0f,50.0f));

	// Run until someone presses escape
	while (!quit)
	{
		unsigned int current_time = System::get_time();
		float time_delta_ms = static_cast<float> (current_time - last_time);
		last_time = current_time;

		canvas.clear();
		
		//Raycast
		
		font.draw_text(canvas, 10,20, "Raycasting...");
		
		qa.raycast_first(p1, p2);
		if(qa.has_query_result())
		{
			font.draw_text(canvas, 100,20, "Found object !");
			canvas.draw_line(p1,p2, Colorf::green);
		}
		else canvas.draw_line(p1, p2, Colorf::red);
		
		//Raycast

		//Query
		
		font.draw_text(canvas, 10,35, "Querying...");

		qa.query_any(rect1);

		if(qa.has_query_result())
		{
			font.draw_text(canvas, 100,35, "Found object !");
			canvas.draw_box(rect1, Colorf::green);

		}
		else canvas.draw_box(rect1, Colorf::red);
		//Query

		phys_world.step();
		debug_draw.draw(canvas);
		
		canvas.flush();
		window.flip(1);

		// This call processes user input and other events
		KeepAlive::process(0);

		System::sleep(10);
	}

	return 0;
}
示例#21
0
// The start of the Application
int HelloWorld::start(const std::vector<std::string> &args)
{
	// Create a source for our resources
	ResourceManager resources;
	DisplayCache::set(resources, std::make_shared<DisplayResources>());

	// Mark this thread as the UI thread
	UIThread ui_thread(resources);

	// Create root view and window:
	DisplayWindowDescription desc;
	desc.set_title("UICore: Hello World");
	desc.set_allow_resize(true);
	desc.set_type(WindowType::custom);
	desc.set_extend_frame(16, 40, 16, 16);
	std::shared_ptr<WindowView> root = std::make_shared<WindowView>(desc);

	// Exit run loop when close is clicked.
	// We have to store the return Slot because if it is destroyed the lambda function is disconnected from the signal.
	Slot slot_close = root->sig_close().connect([&](CloseEvent &e) { exit(); });

	Canvas canvas = UIThread::get_resource_canvas();

	// Style the root view to use rounded corners and a bit of drop shadow
	root->box_style.set_background(Colorf(240, 240, 240, 255));
	root->box_style.set_padding(11.0f);
	root->box_style.set_border_radius(15.0f);
	root->box_style.set_border(Colorf(0, 0, 0), 1.0f);
	root->box_style.set_margin(10.0f, 35.0f, 10.0f, 10.0f);
	root->box_style.set_box_shadow(Colorf(0, 0, 0, 50), 0.0f, 0.0f, 20.0f);

	// Create a label with some text to have some content
	std::shared_ptr<LabelView> label = std::make_shared<LabelView>();
	label->text_style().set_font("Ravie", 20.0f, 40.0f);
	label->set_text("Hello World!");
	root->add_subview(label);

	// React to clicking
	label->slots.connect(label->sig_pointer_press(), [&](PointerEvent &e) {
		label->set_text(label->text() + " CLICK!");
	});

	// Create a text field for our span layout
	std::shared_ptr<TextFieldView> edit = std::make_shared<TextFieldView>();
	edit->text_style().set_font("Ravie", 11.0f, 20.0f);
	edit->set_text("42");
	edit->box_style.set_margin(0.0f, 5.0f);
	edit->box_style.set_background(Colorf(255, 255, 255));
	edit->box_style.set_border(Colorf(0.0f, 0.0f, 0.0f), 1.0f);
	edit->box_style.set_border_radius(3.0f);
	edit->box_style.set_padding(5.0f, 2.0f, 5.0f, 3.0f);
	edit->box_style.set_width(35.0f);

	// Create a span layout view with some more complex inline formatting
	std::shared_ptr<SpanLayoutView> span = std::make_shared<SpanLayoutView>();
	TextStyle font_desc2;
	font_desc2.set_font_family("Segoe UI");
	font_desc2.set_size(13.0f);
	font_desc2.set_line_height(40.0f);
	span->add_text("This is the UI core ", font_desc2);
	TextStyle font_desc3;
	font_desc3.set_font_family("Segoe UI");
	font_desc3.set_size(18.0f);
	font_desc3.set_line_height(40.0f);
	span->add_text("Hello World!", font_desc3);
	TextStyle font_desc4;
	font_desc4.set_font_family("Segoe UI");
	font_desc4.set_size(13.0f);
	font_desc4.set_line_height(40.0f);
	span->add_text(" example! Here's a text field: ", font_desc4);
	span->add_subview(edit);
	TextStyle font_desc5;
	font_desc5.set_font_family("Segoe UI");
	font_desc5.set_size(16.0f);
	font_desc5.set_line_height(40.0f);
	font_desc5.set_weight(800);
	span->add_text(" units! sdfjghsdkfj hkjsdfhg jksdhfj gkshdfk gsjdkfghsjkdfh kgjshdfkg sjkdfh gjskhf gskjdfg hkjsdfh kgjsdhfkgjhsdkjfhgksjdfhg kjsdfhgjkshdfkhgskjdf ghkjsdfsg kdfhg skjdfhgjksdh fgsdfhg kjsdhfjkghsdkjfh gkjsdhfjkgsdhfkgjhsdkfj hgksj.", font_desc5);
	root->add_subview(span);

	// Create a popup window placed where the edit field is at
	std::shared_ptr<PopupView> popup = std::make_shared<PopupView>();
	popup->box_style.set_background(Colorf::lightyellow);
	popup->box_style.set_margin(5.0f);
	popup->box_style.set_box_shadow(Colorf(0, 0, 0, 40), 2.0f, 2.0f, 3.0f);
	popup->box_style.set_border_radius(2.0f);
	popup->box_style.set_border(Colorf::black, 1.0f);
	popup->box_style.set_padding(5.0f, 2.0f);
	popup->box_style.set_absolute();
	popup->box_style.set_bottom(28.0f);
	popup->box_style.set_left(0.0f);
	popup->box_style.set_layout_vbox();
	edit->add_subview(popup);

	// Write some text in the popup
	std::shared_ptr<LabelView> popup_label = std::make_shared<LabelView>();
	popup_label->text_style().set_font("Consolas", 12.0f, 14.0f);
	popup_label->set_text("Hey, this popup looks like a tooltip!");
	popup->add_subview(popup_label);

	// Make our window visible
	root->show();
	popup->show(WindowShowType::show_no_activate);

	// Process messages until user exits
	run();


	return 0;
}
示例#22
0
// The start of the Application
int App::start(const std::vector<std::string> &args)
{
	quit = false;

	DisplayWindowDescription desc;
	desc.set_title("ClanLib Quaternion's Example");
	desc.set_size(Size(900, 700), true);
	desc.set_multisampling(4);
	desc.set_allow_resize(true);
	desc.set_depth_size(16);

	DisplayWindow window(desc);

	// Connect the Window close event
	Slot slot_quit = window.sig_window_close().connect(this, &App::on_window_close);

	// Connect a keyboard handler to on_key_up()
	Slot slot_input_up = (window.get_ic().get_keyboard()).sig_key_up().connect(this, &App::on_input_up);

	// Set up GUI
	std::string theme;
	if (FileHelp::file_exists("../../../Resources/GUIThemeAero/theme.css"))
		theme = "../../../Resources/GUIThemeAero";
	else if (FileHelp::file_exists("../../../Resources/GUIThemeBasic/theme.css"))
		theme = "../../../Resources/GUIThemeBasic";
	else
		throw Exception("No themes found");

	GUIWindowManagerTexture wm(window);
	GUIManager gui(wm, theme);

	Canvas canvas(window);

	// Deleted automatically by the GUI
	Options *options = new Options(gui, Rect(8, 8, Size(canvas.get_width()-16, 170)));
	options->request_repaint();

	// Setup graphic store
	GraphicStore graphic_store(canvas);
	scene.gs = &graphic_store;

	RasterizerStateDescription rasterizer_state_desc;
	rasterizer_state_desc.set_culled(true);
	rasterizer_state_desc.set_face_cull_mode(cull_back);
	rasterizer_state_desc.set_front_face(face_clockwise);
	RasterizerState raster_state(canvas, rasterizer_state_desc);

	DepthStencilStateDescription depth_state_desc;
	depth_state_desc.enable_depth_write(true);
	depth_state_desc.enable_depth_test(true);
	depth_state_desc.enable_stencil_test(false);
	depth_state_desc.set_depth_compare_function(compare_lequal);
	DepthStencilState depth_write_enabled(canvas, depth_state_desc);

	create_scene(canvas);

	clan::Font font(canvas, "tahoma", 24);

	FramerateCounter framerate_counter;

	active_lerp = false;
	ubyte64 time_last = System::get_time();
	ubyte64 time_start = time_last;

	// Run until someone presses escape
	while (!quit)
	{
		framerate_counter.frame_shown();

		// Calculate time since last frame
		ubyte64 time_now = System::get_time();
		current_time = time_now - time_start;
		time_delta = time_now - time_last;
		time_last = time_now;

		// Control the target options
		control_target(options);

		// Use the euler angle options
		rotation_euler_a->rotation_y = options->rotation_y;
		rotation_euler_b->rotation_x = options->rotation_x;
		rotation_euler_c->rotation_z = options->rotation_z;

		teapot_euler->rotation_x = options->rotation_x;
		teapot_euler->rotation_y = options->rotation_y;
		teapot_euler->rotation_z = options->rotation_z;

		// Use the target angle options
		rotation_target_a->rotation_y = options->target_y;
		rotation_target_b->rotation_x = options->target_x;
		rotation_target_c->rotation_z = options->target_z;

		teapot_target->rotation_x = options->target_x;
		teapot_target->rotation_y = options->target_y;
		teapot_target->rotation_z = options->target_z;

		// Render the scene using euler angles
		calculate_matricies(canvas);
		update_light(canvas, options);

		canvas.set_depth_stencil_state(depth_write_enabled);
		canvas.set_rasterizer_state(raster_state);
		render(canvas);

		// Show the quaternion teapot
		Mat4f modelview_matrix = scene.gs->camera_modelview;
		modelview_matrix.translate_self(0.0f, 0.0f, 0.0f);
		modelview_matrix = modelview_matrix * options->quaternion.to_matrix();
		modelview_matrix.scale_self(5.0f, 5.0f, 5.0f);
		model_teapot.Draw(canvas, scene.gs, modelview_matrix);

		// Draw information boxes
		canvas.reset_rasterizer_state();
		canvas.reset_depth_stencil_state();
	
		std::string fps(string_format("%1 fps", framerate_counter.get_framerate()));
		font.draw_text(canvas, 16-2, canvas.get_height()-16-2, fps, Colorf(0.0f, 0.0f, 0.0f, 1.0f));
		font.draw_text(canvas, 16, canvas.get_height()-16-2, fps, Colorf(1.0f, 1.0f, 1.0f, 1.0f));

		font.draw_text(canvas, 60, 250, "Euler Orientation");
		font.draw_text(canvas, 330, 250, "Quaternion Orientation");
		font.draw_text(canvas, 600, 250, "Target Euler Orientation");
		font.draw_text(canvas, 16, 630, "(Using YXZ rotation order)");

		wm.process();
		wm.draw_windows(canvas);

		// Use flip(1) to lock the fps
		window.flip(0);

		KeepAlive::process();
	}

	return 0;
}
示例#23
0
文件: app.cpp 项目: ArtHome12/ClanLib
App::App()
{
#if defined(WIN32) && !defined(__MINGW32__)
	clan::D3DTarget::set_current();
#else
	clan::OpenGLTarget::set_current();
#endif

	// Create a window:
	DisplayWindowDescription desc;
	desc.set_title("UICore: Hello World");
	desc.set_allow_resize(true);
	window = std::make_shared<TopLevelWindow>(desc);
	auto pRootView = window->root_view();
	pRootView->slots.connect(window->root_view()->sig_close(), [&](CloseEvent &e) { RunLoop::exit(); });
	pRootView->slots.connect(pRootView->sig_key_press(), [&](clan::KeyEvent &e)
	{ if (e.key() == clan::Key::escape) RunLoop::exit(); }
	);

	// Need for receive a keyboard events.
	pRootView->set_focus();

	// Create a source for our resources
	FileResourceDocument doc(FileSystem("../../ThemeAero"));
	ResourceManager resources = FileResourceManager::create(doc);

	// Mark this thread as the UI thread
	ui_thread = UIThread(resources);

	// Style the root view to use rounded corners and a bit of drop shadow
	pRootView->style()->set("padding: 11px");
	pRootView->style()->set("background: #efefef");
	pRootView->style()->set("flex-direction: column");

	// First (top) panel with button and text
	//
	auto panel1 = std::make_shared<View>();
	panel1->style()->set("background: white");
	panel1->style()->set("padding: 11px");
	panel1->style()->set("flex-direction: row");
	panel1->style()->set("flex: auto");
	pRootView->add_child(panel1);

	auto button1 = Theme::create_button();
	button1->style()->set("height: 40px");
	button1->style()->set("width: 120px");
	button1->label()->set_text("Folder browse");
	button1->style()->set("flex: none");
	button1->image_view()->set_image(clan::Image(pRootView->canvas(), "./document_open.png"));
	button1->func_clicked() = clan::bind_member(this, &App::on_button1_down);
	panel1->add_child(button1);

	label1 = std::make_shared<LabelView>();
	label1->style()->set("font: 20px/40px 'Ravie'");
	label1->style()->set("padding: 0px 10px");
	label1->set_text("Press the button for select a folder");
	panel1->add_child(label1);

	// Second panel with button and text
	//
	auto panel2 = std::make_shared<View>();
	panel2->style()->set("background: white");
	panel2->style()->set("padding: 11px");
	panel2->style()->set("flex-direction: row");
	panel2->style()->set("flex: auto");
	pRootView->add_child(panel2);

	auto button2 = Theme::create_button();
	button2->style()->set("height: 40px");
	button2->style()->set("width: 120px");
	button2->label()->set_text("Open file");
	button2->style()->set("flex: none");
	button2->func_clicked() = clan::bind_member(this, &App::on_button2_down);
	panel2->add_child(button2);

	label2 = std::make_shared<LabelView>();
	label2->style()->set("font: 20px/40px 'Ravie'");
	label2->style()->set("padding: 0px 10px");
	label2->set_text("Press the button for select only existing file");
	panel2->add_child(label2);

	// Third panel with button and text
	//
	auto panel3 = std::make_shared<View>();
	panel3->style()->set("background: white");
	panel3->style()->set("padding: 11px");
	panel3->style()->set("flex-direction: row");
	panel3->style()->set("flex: auto");
	pRootView->add_child(panel3);

	auto button3 = Theme::create_button();
	button3->style()->set("height: 40px");
	button3->style()->set("width: 120px");
	button3->label()->set_text("Save file");
	button3->style()->set("flex: none");
	button3->func_clicked() = clan::bind_member(this, &App::on_button3_down);
	panel3->add_child(button3);

	label3 = std::make_shared<LabelView>();
	label3->style()->set("font: 20px/40px 'Ravie'");
	label3->style()->set("padding: 0px 10px");
	label3->set_text("Press the button for select existing or new file");
	panel3->add_child(label3);

	// Fourth panel with button and text
	//
	auto panel4 = std::make_shared<View>();
	panel4->style()->set("background: white");
	panel4->style()->set("padding: 11px");
	panel4->style()->set("flex-direction: row");
	panel4->style()->set("flex: auto");
	pRootView->add_child(panel4);

	button4 = Theme::create_button();
	button4->style()->set("height: 40px");
	button4->style()->set("width: 120px");
	button4->label()->set_text("Sticky button");
	button4->style()->set("flex: none");
	button4->func_clicked() = clan::bind_member(this, &App::on_button4_down);
	button4->set_sticky(true);
	button4->set_pressed(true);
	panel4->add_child(button4);

	label4 = std::make_shared<LabelView>();
	label4->style()->set("font: 20px/40px 'Ravie'");
	label4->style()->set("padding: 0px 10px");
	panel4->add_child(label4);
	on_button4_down();	// Manual setting button's "pressed" property doesn't call user event handler automatically.

}
示例#24
0
HelloWorld::HelloWorld()
{
	clan::Application::use_timeout_timing(std::numeric_limits<int>::max());	// The update() loop is not required for this application

	//clan::D3DTarget::set_current();
	clan::OpenGLTarget::set_current();

	// Create a source for our resources
	FileResourceDocument doc(FileSystem("../../ThemeAero"));
	ResourceManager resources = FileResourceManager::create(doc);

	// Mark this thread as the UI thread
	ui_thread = UIThread(resources);

	// Create a window:
	DisplayWindowDescription desc;
	desc.set_title("UICore: Hello World");
	desc.set_allow_resize(true);
	desc.set_size(Sizef(640, 600), false);
	window = std::make_shared<TopLevelWindow>(desc);

	// Exit run loop when close is clicked.
	// We have to store the return Slot because if it is destroyed the lambda function is disconnected from the signal.
	slots.connect(window->root_view()->sig_close(), [&](CloseEvent &e) { RunLoop::exit(); });

	// Style the root view to use rounded corners and a bit of drop shadow
	window->root_view()->style()->set("padding: 11px");
	window->root_view()->style()->set("background: #efefef");
	window->root_view()->style()->set("flex-direction: column");

	auto body = std::make_shared<View>();
	body->style()->set("background: white");
	body->style()->set("padding: 11px");
	body->style()->set("border-top: 5px solid #DD3B2A");
	body->style()->set("border-bottom: 5px solid #DD3B2A");
	body->style()->set("flex-direction: column");
	body->style()->set("flex: auto");
	window->root_view()->add_subview(body);

	// Create a label with some text to have some content
	label = std::make_shared<LabelView>();
	label->style()->set("flex: none");
	label->style()->set("font: 20px/40px 'Ravie'");
	label->style()->set("color: #DD3B2A");
	label->set_text("Hello World!");
	body->add_subview(label);

	// React to clicking
	label->slots.connect(label->sig_pointer_press(), [&](PointerEvent &e) {
		label->set_text(label->text() + " CLICK!");
	});

	auto scrollarea = std::make_shared<ScrollView>();
	scrollarea->style()->set("margin: 5px 0; border: 1px solid black; padding: 5px 5px;");
	scrollarea->scrollbar_x_view()->style()->set("background: rgb(232,232,236); margin-top: 5px");
	scrollarea->scrollbar_x_view()->track()->style()->set("padding: 0 4px");
	scrollarea->scrollbar_x_view()->thumb()->style()->set("background: rgb(208,209,215)");
	scrollarea->scrollbar_y_view()->style()->set("background: rgb(232,232,236); margin-left: 5px");
	scrollarea->scrollbar_y_view()->track()->style()->set("padding: 0 4px");
	scrollarea->scrollbar_y_view()->thumb()->style()->set("background: rgb(208,209,215)");
	scrollarea->content_view()->style()->set("flex-direction: column");
	body->add_subview(scrollarea);

	// Create a text field for our span layout
	std::shared_ptr<TextFieldView> edit = std::make_shared<TextFieldView>();
	edit->style()->set("font: 11px/20px 'Segoe UI'");
	edit->style()->set("margin: 5px");
	edit->style()->set("background: #efefef");
	edit->style()->set("border: 1px solid black");
	edit->style()->set("border-radius: 3px");
	edit->style()->set("padding: 2px 5px 2px 5px");
	edit->style()->set("width: 128px");
	edit->style()->set("box-shadow: 0 0 5px rgba(100,100,200,0.2)");
	edit->set_text("amazing!");

	// Create a span layout views with some more complex inline formatting
	std::shared_ptr<SpanLayoutView> p1 = std::make_shared<SpanLayoutView>();
	p1->style()->set("font: 13px/25px 'Segoe UI'");
	p1->text_style("bold")->set("font-weight: bold");
	p1->text_style("italic")->set("font-style: italic");
	p1->add_text("This is an example of why Sphair should never ever make fun of my ");
	p1->add_text("BEAUTIFUL", "bold");
	p1->add_text(" green 13.37deg gradients because he will never know what it is replaced with!");
	scrollarea->content_view()->add_subview(p1);

	std::shared_ptr<SpanLayoutView> p2 = std::make_shared<SpanLayoutView>();
	p2->style()->set("margin: 15px 0 5px 0");
	p2->style()->set("padding: 7px");
	p2->style()->set("border-top: 5px solid #CCE4FB");
	p2->style()->set("border-bottom: 5px solid #CCE4FB");
	p2->style()->set("background: #EDF6FF");
	p2->style()->set("font: 13px/25px 'Segoe UI'");
	p2->text_style("bold")->set("font-weight: bold");
	p2->text_style("italic")->set("font-style: italic");
	p2->add_text("If you also think Sphair made a ");
	p2->add_text("BIG MISTAKE", "bold");
	p2->add_text(" please consider typing ");
	p2->add_text("Yes, yes, yes, yes, yes, yes, yes yes, YES!", "italic");
	p2->add_text(" in the text field: ");
	p2->add_subview(edit);
	p2->add_text(" You know you want to!", "bold");
	scrollarea->content_view()->add_subview(p2);
	
	std::shared_ptr<SpanLayoutView> p3 = std::make_shared<SpanLayoutView>();
	p3->style()->set("font: 13px/25px 'Segoe UI'");
	p3->text_style("bold")->set("font-weight: bold");
	p3->text_style("italic")->set("font-style: italic");
	p3->add_text("Since we both know you typed ");
	p3->add_text("Yes, yes, yes..", "italic");
	p3->add_text(" into the text field (who wouldn't!?), here's the amazing gradient:");
	scrollarea->content_view()->add_subview(p3);
	
	std::shared_ptr<View> gradient_box = std::make_shared<View>();
	gradient_box->style()->set("margin: 15px auto; width: 120px; height: 75px;");
	gradient_box->style()->set("border: 1px solid #777");
	gradient_box->style()->set("background: linear-gradient(13.37deg, #f0f0f0, rgb(120,240,120) 50%, #f0f0f0)");
	gradient_box->style()->set("box-shadow: 7px 7px 7px rgba(0,0,0,0.2)");
	scrollarea->content_view()->add_subview(gradient_box);
	
	auto listbox = std::make_shared<ListBoxView>();
	listbox->style()->set("flex: none; height: 60px; margin: 7px 0; border: 1px solid black; padding: 5px; background: #f0f0f0");
	listbox->set_items<std::string>(
		{ "Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "More items", "Even more items!!", "No more items!!!!!" },
		[](const std::string &s) -> std::shared_ptr<View>
		{
			auto item = std::make_shared<LabelView>();
			item->style()->set("font: 13px/17px 'Segoe UI'; color: black; margin: 1px 0; padding: 0 2px");
			item->style("selected")->set("background: #7777f0; color: white");
			item->style("hot")->set("background: #ccccf0; color: black");

			item->set_text(s);
			return item;
		});
	scrollarea->content_view()->add_subview(listbox);

	auto scrollbar = Theme::create_scrollbar();
	//scrollbar->set_disabled();
	scrollbar->set_range(0.0, 1.0);
	scrollbar->set_position(0.5);
	scrollbar->set_page_step(0.1);
	scrollbar->set_line_step(0.01);
	scrollarea->content_view()->add_subview(scrollbar);

	auto button = Theme::create_button();
	button->label()->set_text("This is a button");
	scrollarea->content_view()->add_subview(button);

	std::shared_ptr<clan::SliderView> slider = Theme::create_slider();
	//slider->set_disabled();
	slider->set_min_position(0);
	slider->set_max_position(1000);
	slider->set_tick_count(100);
	slider->set_lock_to_ticks(false);
	slider->set_page_step(100);
	slider->set_position(slider->max_position()/2);
	scrollarea->content_view()->add_subview(slider);

	auto checkbox = Theme::create_checkbox();
	//checkbox->set_disabled();
	scrollarea->content_view()->add_subview(checkbox);

	for (int cnt = 0; cnt < 3; cnt++)
	{
		auto radio = Theme::create_radiobutton();
		//radio->set_disabled(true);
		scrollarea->content_view()->add_subview(radio);
	}

	// Create a popup window
	slots.connect(button->sig_pointer_enter(), [=](PointerEvent &e)
	{
		auto popup = std::make_shared<WindowController>();
		popup->root_view()->style()->set("flex-direction: column");
		popup->root_view()->style()->set("background: #FFFFE0");
		popup->root_view()->style()->set("margin: 5px");
		popup->root_view()->style()->set("border: 1px solid black");
		popup->root_view()->style()->set("border-radius: 2px");
		popup->root_view()->style()->set("padding: 2px 5px 2px 5px");
		popup->root_view()->style()->set("box-shadow: 0 0 3px rgba(0,0,0,0.2)");

		auto text = Theme::create_label(true);
		text->style()->set("font: 12px Tahoma; color: black");
		text->set_text("This is an awesome popup");
		popup->root_view()->add_subview(text);

		std::weak_ptr<WindowController> popup_weak = popup;
		popup->slots.connect(button->sig_pointer_leave(), [=](PointerEvent &e)
		{
			auto p = popup_weak.lock();
			if (p)
				p->dismiss();
		});

		window_manager.present_popup(button.get(), e.pos(button) + Pointf(10.0f, -10.0f), popup);
	});

	// Show a modal dialog
	button->func_clicked() = [=]()
	{
		auto dialog = std::make_shared<WindowController>();
		dialog->set_title("Alarm!!");
		dialog->root_view()->style()->set("flex-direction: column");
		dialog->root_view()->style()->set("background: rgb(240,240,240)");
		dialog->root_view()->style()->set("padding: 11px");
		dialog->root_view()->style()->set("width: 250px");

		auto text = Theme::create_label(true);
		text->style()->set("margin-bottom: 7px");
		text->style()->set("font: 12px Tahoma; color: black");
		text->set_text("This a modal dialog");
		dialog->root_view()->add_subview(text);

		auto ok_button = Theme::create_button();
		ok_button->label()->set_text("OK");
		dialog->root_view()->add_subview(ok_button);

		std::weak_ptr<WindowController> dialog_weak = dialog;
		ok_button->func_clicked() = [=]()
		{
			auto d = dialog_weak.lock();
			if (d)
				d->dismiss();
		};

		window_manager.present_modal(window->root_view().get(), dialog);
	};

	// Make our window visible
	window->show();
}
void D3DDisplayWindowProvider::create(DisplayWindowSite *new_site, const DisplayWindowDescription &description)
{
	site = new_site;

	if (device)
		D3DShareList::device_destroyed(device);
	info_queue.clear();
	debug.clear();
	back_buffer_rtv.clear();
	fake_front_buffer.clear();
	back_buffer.clear();
	swap_chain.clear();
	device_context.clear();
	device.clear();

	window.create(site, description);

	use_fake_front_buffer = description.is_update_supported();

	D3D_FEATURE_LEVEL request_levels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0 };
	DXGI_SWAP_CHAIN_DESC swap_chain_description;
	swap_chain_description.BufferCount = description.get_flipping_buffers();
	swap_chain_description.BufferDesc.Width = 0;
	swap_chain_description.BufferDesc.Height = 0;
	swap_chain_description.BufferDesc.RefreshRate.Numerator = 60;
	swap_chain_description.BufferDesc.RefreshRate.Denominator = 1;
	swap_chain_description.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; // DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
	swap_chain_description.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
	swap_chain_description.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
	swap_chain_description.SampleDesc.Count = 1;
	swap_chain_description.SampleDesc.Quality = 0;
	swap_chain_description.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
	swap_chain_description.OutputWindow = window.get_hwnd();
	swap_chain_description.Windowed = TRUE; // Seems the documentation wants us to call IDXGISwapChain::SetFullscreenState afterwards
	swap_chain_description.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
	swap_chain_description.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;

	bool debug_mode = false; // To do: fetch this from DisplayWindowDescription using same method as clanGL (or maybe promote debug flag to clanDisplay?)

	UINT device_flags = 0;
	if (debug_mode)
		device_flags |= D3D11_CREATE_DEVICE_DEBUG;

	MutexSection mutex_lock(&d3d11_mutex);
	if (d3d11_dll == 0)
	{
		d3d11_dll = LoadLibrary(L"d3d11.dll");
		if (d3d11_dll == 0)
			throw Exception("Unable to load d3d11.dll");

		try
		{
			d3d11_createdeviceandswapchain = reinterpret_cast<FuncD3D11CreateDeviceAndSwapChain>(GetProcAddress(d3d11_dll, "D3D11CreateDeviceAndSwapChain"));
			if (d3d11_createdeviceandswapchain == 0)
				throw Exception("D3D11CreateDeviceAndSwapChain function not found!");

		}
		catch (...)
		{
			CloseHandle(d3d11_dll);
			d3d11_dll = 0;
			d3d11_createdeviceandswapchain = 0;
			throw;
		}
	}
	HRESULT result = d3d11_createdeviceandswapchain(
		0,
		D3D_DRIVER_TYPE_HARDWARE,
		0,
		device_flags,
		request_levels, 3,
		D3D11_SDK_VERSION,
		&swap_chain_description,
		swap_chain.output_variable(),
		device.output_variable(),
		&feature_level,
		device_context.output_variable());
	D3DTarget::throw_if_failed("D3D11CreateDeviceAndSwapChain failed", result);

	if (debug_mode)
	{
		result = device->QueryInterface(__uuidof(ID3D11Debug), (void**)debug.output_variable());
		if (FAILED(result))
			debug.clear(); // No debug info available.  Should this throw an exception instead?
		result = device->QueryInterface(__uuidof(ID3D11InfoQueue), (void**)info_queue.output_variable());
		if (FAILED(result))
			info_queue.clear(); // No debug messages available.
	}

	// Disable mouse lag (no, 3 frames rendered ahead is NOT a good default Microsoft):
	ComPtr<IDXGIDevice1> dxgi_device;
	result = swap_chain->GetDevice(__uuidof(IDXGIDevice1), (void**)dxgi_device.output_variable());
	D3DTarget::throw_if_failed("Unable to retrieve IDXGIDevice1 from swap chain", result);
	dxgi_device->SetMaximumFrameLatency(1);

	create_swap_chain_buffers();

	gc = GraphicContext(new D3DGraphicContextProvider(this, description));

	if (description.is_fullscreen())
		swap_chain->SetFullscreenState(TRUE, 0);

	D3DGraphicContextProvider *d3d_gc = static_cast<D3DGraphicContextProvider*>(gc.get_provider());
	d3d_gc->standard_programs = StandardPrograms(gc);
}
	void OpenGLCreationHelper::set_multisampling_pixel_format(const DisplayWindowDescription &desc)
	{
		PIXELFORMATDESCRIPTOR pfd;
		memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR));
		pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
		pfd.nVersion = 1;
		pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL;
		pfd.iPixelType = PFD_TYPE_RGBA;
		pfd.dwFlags |= PFD_DOUBLEBUFFER;
		pfd.cColorBits = 24;
		pfd.cRedBits = 4;
		pfd.cGreenBits = 4;
		pfd.cBlueBits = 4;
		pfd.cAlphaBits = 4;
		pfd.cDepthBits = desc.get_depth_size();
		pfd.cStencilBits = desc.get_stencil_size();
		if (desc.is_layered())
		{
			pfd.cAlphaBits = 8;
			pfd.dwFlags |= PFD_DOUBLEBUFFER_DONTCARE; // | PFD_DRAW_TO_BITMAP
		}

		if (desc.get_multisampling() < 1)
		{
			int pixelformat = ChoosePixelFormat(hdc, &pfd);
			SetPixelFormat(hdc, pixelformat, &pfd);
		}
		else
		{
			int pixelformat = ChoosePixelFormat(hdc, &pfd);

			set_active();
			ptr_wglChoosePixelFormatEXT wglChoosePixelFormatEXT = (ptr_wglChoosePixelFormatEXT)wglGetProcAddress("wglChoosePixelFormatEXT");
			if (wglChoosePixelFormatEXT == 0)
				wglChoosePixelFormatEXT = (ptr_wglChoosePixelFormatEXT)wglGetProcAddress("wglChoosePixelFormatARB");
			reset_active();

			if (wglChoosePixelFormatEXT)
			{
				std::vector<FLOAT> float_attributes;
				std::vector<int> int_attributes;

				int_attributes.push_back(WGL_DRAW_TO_WINDOW);
				int_attributes.push_back(GL_TRUE);
				int_attributes.push_back(WGL_ACCELERATION);
				int_attributes.push_back(WGL_FULL_ACCELERATION);

				int_attributes.push_back(WGL_DOUBLE_BUFFER);
				int_attributes.push_back(GL_TRUE);

				int_attributes.push_back(WGL_COLOR_BITS);
				int_attributes.push_back(4 + 4 + 4);

				int_attributes.push_back(WGL_ALPHA_BITS);
				int_attributes.push_back(4);

				int_attributes.push_back(WGL_DEPTH_BITS);
				int_attributes.push_back(desc.get_depth_size());

				int_attributes.push_back(WGL_STENCIL_BITS);
				int_attributes.push_back(desc.get_stencil_size());

				int_attributes.push_back(WGL_SAMPLE_BUFFERS);
				int_attributes.push_back(GL_TRUE);
				int_attributes.push_back(WGL_SAMPLES);
				int_attributes.push_back(desc.get_multisampling());

				float_attributes.push_back(0.0f);
				float_attributes.push_back(0.0f);
				int_attributes.push_back(0);
				int_attributes.push_back(0);
				int new_pixelformat = pixelformat;
				UINT num_formats = 0;
				BOOL result = wglChoosePixelFormatEXT(hdc, &int_attributes[0], &float_attributes[0], 1, &new_pixelformat, &num_formats);
				if (result == TRUE && num_formats > 0)
					pixelformat = new_pixelformat;
			}

			SetPixelFormat(hdc, pixelformat, &pfd);
		}
	}