Exemplo n.º 1
0
void ShaderImpl::begin(CL_GraphicContext &p_gc)
{
	G_ASSERT(m_initialized);
	G_ASSERT(!m_began);

	// new texture
	m_drawRect = m_parent->getDrawRect(m_boundRect);
	m_texture = CL_Texture(p_gc, m_drawRect.get_width(), m_drawRect.get_height());

	// attach frame buffer
	m_frameBuffer.attach_color_buffer(0, m_texture);
	p_gc.set_frame_buffer(m_frameBuffer);

	// clear to transparent
	p_gc.clear(CL_Colorf::transparent);

	// set proper matrix
	p_gc.push_modelview();

	// get scaling in count
	const CL_Mat4f &matrix = p_gc.get_modelview();
	const float scaleX = matrix[0];
	const float scaleY = matrix[5];

	p_gc.mult_translate(-m_drawRect.left / scaleX, -m_drawRect.top / scaleY);

	m_began = true;
}
Exemplo n.º 2
0
void App::render(CL_GraphicContext &gc)
{
	gc.clear(CL_Colorf(0.0f, 0.0f, 0.0f, 1.0f));

	scene.gs->image_grid.draw(gc, 420.0f, 120.0f);	// Draw a grid in the backgound

	gc.set_map_mode(cl_user_projection);
	CL_Rect viewport_rect(0, 0, CL_Size(gc.get_width(), gc.get_height()));
	gc.set_viewport(viewport_rect);

	gc.set_projection(scene.gs->camera_projection);

	CL_BufferControl buffer_control;
	buffer_control.set_depth_compare_function(cl_comparefunc_lequal);
	buffer_control.enable_depth_write(true);
	buffer_control.enable_depth_test(true);
	buffer_control.enable_stencil_test(false);
	buffer_control.enable_color_write(true);
	gc.set_buffer_control(buffer_control);

	gc.clear_depth(1.0f);

	CL_Mat4f modelview_matrix = scene.gs->camera_modelview;
	scene.Draw(modelview_matrix, gc);
	gc.reset_program_object();
}
Exemplo n.º 3
0
	static int main(const std::vector<CL_String> &args)
	{
		try
		{
			CL_SetupCore setup_core; 
			CL_SetupDisplay setup_disp;
			CL_SetupGL setup_gl;

			CL_DisplayWindow window("Viewport Grid Test", 640, 480, false, true);
			CL_GraphicContext gc = window.get_gc();
			
			CL_BlendMode blend_mode1;
			blend_mode1.enable_blending(true);
			gc.set_blend_mode(blend_mode1);

			gc.set_map_mode(cl_map_2d_upper_left);

			while(!window.get_ic().get_keyboard().get_keycode(CL_KEY_ESCAPE))
			{
				gc.clear(CL_Colorf::white);
				CL_Rect viewport = window.get_viewport();
				for (int y = viewport.top; y < viewport.bottom; y+=2)
				{
					CL_Draw::line(gc, viewport.left, y, viewport.right, y, CL_Colorf::black);
				}
				for (int x = viewport.left; x < viewport.right; x+=2)
				{
					CL_Draw::line(gc, x, viewport.top, x, viewport.bottom, CL_Colorf::black);
				}

				window.flip(1);
				CL_KeepAlive::process();

				CL_System::sleep(10);
			}

			return 0;
		}
		catch(CL_Exception error)
		{
			CL_ConsoleWindow console("Console");
			CL_Console::write_line("Exception caught:");
			CL_Console::write_line(error.message);
			console.display_close_message();

			return -1;
		}

		return 0;
	}
Exemplo n.º 4
0
// The start of the Application
int App::start(const std::vector<CL_String> &args)
{
	CL_DisplayWindowDescription win_desc;
	win_desc.set_allow_resize(true);
	win_desc.set_title("ColorWheel Example");
	win_desc.set_size(CL_Size( 800, 600 ), false);

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

	CL_String theme;
	if (CL_FileHelp::file_exists("../../../Resources/GUIThemeAero/theme.css"))
		theme = "../../../Resources/GUIThemeAero";
	else if (CL_FileHelp::file_exists("../../../Resources/GUIThemeBasic/theme.css"))
		theme = "../../../Resources/GUIThemeBasic";
	else
		throw CL_Exception("No themes found");

	CL_GUIWindowManagerTexture wm(window);
	CL_GUIManager gui(wm, theme);

	CL_GraphicContext gc = window.get_gc();

	// Deleted automatically by the GUI
	new ColorWheel(gc, gui, CL_Rect(32, 32, CL_Size(512, 512)));


	unsigned int time_last = CL_System::get_time();

	while (!quit)
	{
		unsigned int time_now = CL_System::get_time();
		float time_diff = (float) (time_now - time_last);
		time_last = time_now;

		gc.clear(CL_Colorf(0.0f,0.0f,0.0f));

		wm.process();
		wm.draw_windows(gc);

		window.flip(1);

		CL_KeepAlive::process();
	}

	return 0;
}
Exemplo n.º 5
0
void WorkerGC::worker_thread_loop()
{
	CL_DisplayWindowDescription desc;
	desc.set_title("ClanLib Worker Thread");
	desc.set_size(CL_Size(320, 320), true);
	//desc.set_visible(false);
	window = CL_DisplayWindow(desc);

	while (true)
	{
		int wakeup_reason = CL_Event::wait(event_start, event_stop);

		if (wakeup_reason != 0)
			break;

		event_start.reset();
	
		try
		{

			CL_GraphicContext gc = window.get_gc();

			// Test code 
			unsigned int time_ms = CL_System::get_time();
			while((CL_System::get_time() - time_ms) < 2000)
			{
				gc.clear(CL_Colorf(1.0f,0.0f,0.2f));
				CL_KeepAlive::process();
				window.flip(0);
			}
			window.set_visible(false, false);
			retrieved_sprite = CL_Sprite(gc, sprite_name);
			CL_OpenGL::set_active(gc);
			glFlush();
		}
		catch (CL_Exception &error)
		{
			exception_set = true;
			exception = error;
		}

		event_completed.set();
	}
	window = CL_DisplayWindow();
}
Exemplo n.º 6
0
int App::start(const std::vector<CL_String> &args)
{
	CL_OpenGLWindowDescription description;
	description.set_title("NightVision Shader");
	description.set_size(CL_Size(1024, 768), true);

	CL_DisplayWindow window(description);
	CL_InputDevice keyboard = window.get_ic().get_keyboard();
	CL_GraphicContext gc = window.get_gc();

	CL_Slot slot_input_up = (window.get_ic().get_keyboard()).sig_key_up().connect(this, &App::on_input_up);

	CL_Slot slot_window_close = window.sig_window_close().connect(this, &App::window_close);

	// Create offscreen texture
	CL_Texture texture_offscreen(gc, gc.get_width(), gc.get_height());
	texture_offscreen.set_min_filter(cl_filter_nearest);
	texture_offscreen.set_mag_filter(cl_filter_nearest);

	CL_Texture texture_mask(gc, gc.get_width(), gc.get_height());
	texture_mask.set_min_filter(cl_filter_nearest);
	texture_mask.set_mag_filter(cl_filter_nearest);

	// Create offscreen framebuffer
	CL_FrameBuffer framebuffer_offscreen(gc);
	framebuffer_offscreen.attach_color_buffer(0, texture_offscreen);

	CL_FrameBuffer framebuffer_mask(gc);
	framebuffer_mask.attach_color_buffer(0, texture_mask);

	CL_Image background(gc, "../PostProcessing/Resources/background.png");
	CL_Image ball(gc, "../PostProcessing/Resources/ball.png");
	ball.set_alignment(origin_center);
	CL_Texture noise_texture(gc, "Resources/noise_texture_0001.png");
	noise_texture.set_wrap_mode(cl_wrap_repeat, cl_wrap_repeat);

	// Load and link shaders
	CL_ProgramObject shader = CL_ProgramObject::load(gc, "Resources/vertex_shader.glsl", "Resources/fragment_shader.glsl");
	shader.bind_attribute_location(0, "Position");
	shader.bind_attribute_location(2, "TexCoord0");
	if (!shader.link())
		throw CL_Exception("Unable to link shader program: Error:" + shader.get_info_log());

	quit = false;

	float amount = 0.0f;
	float timer = 0.0f;

	float scale = 1.0f;

	CL_Font font(gc, "tahoma", 32);

	// Shader based on: http://www.geeks3d.com/20091009/shader-library-night-vision-post-processing-filter-glsl/

	elapsedTime = 0.0f; // seconds
	luminanceThreshold = 0.2f;
	colorAmplification = 4.0f;
	effectCoverage = 0.65f;

	// Render the mask
	gc.set_frame_buffer(framebuffer_mask);
	gc.clear();
	for (float offset=0.0f; offset<=1.0f; offset+=0.01f)
	{
		CL_Draw::circle(gc, gc.get_width() / 2.0f,  gc.get_height() / 2.0f, 400.0f - offset * 64.0f, CL_Colorf(offset, offset, offset, 1.0f));
	}
	gc.reset_frame_buffer();

	unsigned int startTime = CL_System::get_time();

	while (!quit)
	{
		timer = (CL_System::get_time() - startTime) / 1000.0f;

		elapsedTime = timer;

		// Render standard image to offscreen buffer
		gc.set_frame_buffer(framebuffer_offscreen);
		background.draw(gc, 0, 0);
		ball.draw(gc, gc.get_width() / 2 + 200 * sinf(timer / 2.0f), gc.get_height() / 2 + 200 * cosf(timer / 2.0f));
		gc.reset_frame_buffer();

		render_night_vision(gc, texture_offscreen, texture_mask, noise_texture, shader);

		const int gap = 32;
		font.draw_text(gc, 10, 64+gap*0, CL_String("luminanceThreshold : " + CL_StringHelp::float_to_text(luminanceThreshold) + " (Press Q,W)" ));
		font.draw_text(gc, 10, 64+gap*1, CL_String("colorAmplification : " + CL_StringHelp::float_to_text(colorAmplification) + " (Press A,S)" ));
		font.draw_text(gc, 10, 64+gap*2, CL_String("effectCoverage : " + CL_StringHelp::float_to_text(effectCoverage) + " (Press Z,X)" ));

		window.flip();

		CL_System::sleep(10);

		CL_KeepAlive::process();
	}

	return 0;
}
Exemplo n.º 7
0
// The start of the Application
int App::start(const std::vector<CL_String> &args)
{
	quit = false;

	running_test = 0;

	// Create a console window for text-output if not available
	CL_ConsoleWindow console("Console", 80, 200);
	
	CL_Console::write_line("Press 1-5 for different tests! (Test 3 and 5 not applicable for ClanLib 0.8)");			

	try
	{
		// This opens a window, including the frame size
		// If you want more control over the window, pass CL_DisplayWindowDescription to CL_DisplayWindow
		// (This is useful to create a borderless window of a specific size)
		// If you require target specific control over the window, use the derived CL_OpenGLWindowDescription
		// (This contains the multisampling options)
		CL_DisplayWindow window("ClanLib SpriteSpeed Test", 1000, 1000);

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

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

		// Get the graphic context
		CL_GraphicContext gc = window.get_gc();

		CL_ResourceManager resources("resources.xml");

		explosion1 = CL_Sprite(gc, "Explosion1", &resources);
		explosion2 = CL_Sprite(gc, "Explosion2", &resources);

		explosions_same_tex.reserve(10000);
		for(int i=0; i<10000; i++)
		{
			explosions_same_tex.push_back(CL_Sprite(explosion1));

			if(i % 2 == 0)
				explosions_diff_tex.push_back(CL_Sprite(explosion1));
			else
				explosions_diff_tex.push_back(CL_Sprite(explosion2));
		}

		// Run until someone presses escape
		while (!quit)
		{
			float delta_time = dump_fps() / 1000.0f;

			gc.clear(CL_Colorf(0.0f,0.0f,0.2f));

			if(running_test == 0)
				CL_System::sleep(100);
			if(running_test == 1)
				draw_equal_tex_equal_sprites(gc, 10000, delta_time);
			if(running_test == 2)
				draw_equal_tex_diff_sprites(gc, 10000, delta_time);
			if(running_test == 3)
				draw_equal_tex_diff_sprites_batch(gc, 10000, delta_time);
			if(running_test == 4)
				draw_diff_tex_diff_sprites(gc, 10000, delta_time);
			if(running_test == 5)
				draw_diff_tex_diff_sprites_batch(gc, 10000, delta_time);

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

			// This call processes user input and other events
			CL_KeepAlive::process();
		}

		explosions_same_tex.clear();
		explosions_diff_tex.clear();
		explosion1 = CL_Sprite();
		explosion2 = CL_Sprite();
	}
	catch(CL_Exception& exception)
	{
		CL_Console::write_line("Exception caught:");
		CL_Console::write_line(exception.message);

		// Display the stack trace (if available)
		std::vector<CL_String> stacktrace = exception.get_stack_trace();
		int size = stacktrace.size();
		if (size > 0)
		{
			CL_Console::write_line("Stack Trace:");
			for (int cnt=0; cnt < size; cnt++)
			{
				CL_Console::write_line(stacktrace[cnt]);
			}
		}

		console.display_close_message();

		return -1;
	}
	return 0;
}
Exemplo n.º 8
0
// The start of the Application
int App::start(const std::vector<CL_String> &args)
{
	quit = false;

	// Set the window
	CL_DisplayWindowDescription desc;
	desc.set_title("ClanLib App Example");
	desc.set_size(CL_Size(1200, 500), true);
	desc.set_allow_resize(true);

	CL_DisplayWindow window(desc);

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

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

	// Get the graphic context
	CL_GraphicContext gc = window.get_gc();

	// Load a sprite from a png-file
	tux = CL_PixelBuffer("Resources/tux.png");

	tux_original = CL_Image(gc, tux, tux.get_size());
	current_format = cl_rgba8;

	//current_format = cl_rgba8;
	//current_format = cl_rgb8;
	//current_format = cl_bgra8;
	//current_format = cl_bgr8;
	//current_format = cl_r8;
	//current_format = cl_r8_snorm;
	//current_format = cl_r16;
	//current_format = cl_r16_snorm;
	//current_format = cl_rg8;
	//current_format = cl_rg8_snorm;
	//current_format = cl_rg16;
	//current_format = cl_rg16_snorm;
	//current_format = cl_r3_g3_b2;
	//current_format = cl_rgb4;
	//current_format = cl_rgb5;
	//current_format = cl_rgb8_snorm;
	//current_format = cl_rgb10;
	//current_format = cl_rgb12;		// XX
	//current_format = cl_rgb16;
	//current_format = cl_rgb16_snorm;
	//current_format = cl_rgba2;		// XX
	//current_format = cl_rgba4;
	//current_format = cl_rgb5_a1;
	//current_format = cl_rgba8_snorm;
	//current_format = cl_rgb10_a2;
	//current_format = cl_rgba12;		// X
	//current_format = cl_rgba16;
	//current_format = cl_rgba16_snorm;
	//current_format = cl_srgb8;
	//current_format = cl_srgb8_alpha8;
	//current_format = cl_r16f;
	//current_format = cl_rg16f;
	//current_format = cl_rgb16f;
	//current_format = cl_rgba16f;
	//current_format = cl_r32f;
	current_format = cl_rg32f;
	//current_format = cl_rgb32f;
	//current_format = cl_rgba32f;
	//current_format = cl_r11f_g11f_b10f;	// X
	//current_format = cl_rgb9_e5;	// X
	//current_format = cl_r8i;
	//current_format = cl_r8ui;
	//current_format = cl_r16i;
	//current_format = cl_r16ui;
	//current_format = cl_r32i;
	//current_format = cl_r32ui;
	//current_format = cl_rg8i;
	//current_format = cl_rg8ui;
	//current_format = cl_rg16i;
	//current_format = cl_rg16ui;
	//current_format = cl_rg32i;
	//current_format = cl_rg32ui;
	//current_format = cl_rgb8i;
	//current_format = cl_rgb8ui;
	//current_format = cl_rgb16i;
	//current_format = cl_rgb16ui;
	//current_format = cl_rgb32i;
	//current_format = cl_rgb32ui;
	//current_format = cl_rgba8i;
	//current_format = cl_rgba8ui;
	//current_format = cl_rgba16i;
	//current_format = cl_rgba16ui;
	//current_format = cl_rgba32i;
	//current_format = cl_rgba32ui;
	//current_format = cl_depth_component16;
	//current_format = cl_depth_component24;
	//current_format = cl_depth_component32;
	//current_format = cl_depth_component32f;
	//current_format = cl_depth24_stencil8;
	//current_format = cl_depth32f_stencil8;
	//current_format = cl_compressed_red;
	//current_format = cl_compressed_rg;
	//current_format = cl_compressed_rgb;
	//current_format = cl_compressed_rgba;
	//current_format = cl_compressed_srgb;
	//current_format = cl_compressed_srgb_alpha;
	//current_format = cl_compressed_red_rgtc1;
	//current_format = cl_compressed_signed_red_rgtc1;
	//current_format = cl_compressed_rg_rgtc2;
	//current_format = cl_compressed_signed_rg_rgtc2;
	//current_format = cl_compressed_rgb_s3tc_dxt1;
	//current_format = cl_compressed_rgba_s3tc_dxt1;
	//current_format = cl_compressed_rgba_s3tc_dxt3;
	//current_format = cl_compressed_rgba_s3tc_dxt5;
	//current_format = cl_compressed_srgb_s3tc_dxt1;
	//current_format = cl_compressed_srgb_alpha_s3tc_dxt1;
	//current_format = cl_compressed_srgb_alpha_s3tc_dxt3;
	//current_format = cl_compressed_srgb_alpha_s3tc_dxt5;


	display_gc = &gc;
	update_images();

	CL_Font font(gc, "tahoma", 24);

	// Run until someone presses escape
	while (!quit)
	{

		gc.clear(CL_Colorf(0.0f,0.0f,0.2f));

		tux_original.draw(gc, 0, 0);
		tux_convert.draw(gc, 400, 0);
		tux_unconvert.draw(gc, 800, 0);

		font.draw_text(gc, 10, 400, "cl_rgba8");

		if (gl_supported)
		{
			font.draw_text(gc, 410, 400, "converted");
		}
		else
		{
			font.draw_text(gc, 410, 400, "NOT SUPPORTED BY clanGL");
		}

		font.draw_text(gc, 810, 400, "converted back to cl_rgba8");

		window.flip(1);

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

	return 0;
}
Exemplo n.º 9
0
void ContainerRenderer::render(CL_GraphicContext& gc) {
    renderQueue_->preRender();

    gc.clear(CL_Colorf(0.f, 0.f, 0.f, 0.f));

    boost::shared_ptr<CL_ProgramObject> shader = ui::Manager::getShaderManager()->getGumpShader();
    gc.set_program_object(*shader, cl_program_matrix_modelview_projection);

    CL_Texture huesTexture = data::Manager::getHuesLoader()->getHuesTexture();
    gc.set_texture(0, huesTexture);
    // set texture unit 1 active to avoid overriding the hue texture with newly loaded object textures
    gc.set_texture(1, huesTexture);

    shader->set_uniform1i("HueTexture", 0);
    shader->set_uniform1i("ObjectTexture", 1);

    RenderQueue::const_iterator igIter = renderQueue_->begin();
    RenderQueue::const_iterator igEnd = renderQueue_->end();

    CL_Vec2f vertexCoords[6];

    bool renderingComplete = true;

    // draw background container texture
    boost::shared_ptr<ui::Texture> bgTex = containerView_->getBackgroundTexture();
    if (bgTex && bgTex->isReadComplete()) {
        CL_Vec3f hueInfo(0, 0, 1);

        CL_Rectf rect(0, 0, CL_Sizef(bgTex->getWidth(), bgTex->getHeight()));

        vertexCoords[0] = CL_Vec2f(rect.left, rect.top);
        vertexCoords[1] = CL_Vec2f(rect.right, rect.top);
        vertexCoords[2] = CL_Vec2f(rect.left, rect.bottom);
        vertexCoords[3] = CL_Vec2f(rect.right, rect.top);
        vertexCoords[4] = CL_Vec2f(rect.left, rect.bottom);
        vertexCoords[5] = CL_Vec2f(rect.right, rect.bottom);

        CL_Rectf texCoordHelper = bgTex->getNormalizedTextureCoords();

        CL_Vec2f texCoords[6] = {
            CL_Vec2f(texCoordHelper.left, texCoordHelper.top),
            CL_Vec2f(texCoordHelper.right, texCoordHelper.top),
            CL_Vec2f(texCoordHelper.left, texCoordHelper.bottom),
            CL_Vec2f(texCoordHelper.right, texCoordHelper.top),
            CL_Vec2f(texCoordHelper.left, texCoordHelper.bottom),
            CL_Vec2f(texCoordHelper.right, texCoordHelper.bottom)
        };

        CL_PrimitivesArray primarray(gc);
        primarray.set_attributes(0, vertexCoords);
        primarray.set_attributes(1, texCoords);

        primarray.set_attribute(2, hueInfo);

        gc.set_texture(1, bgTex->getTexture());
        gc.draw_primitives(cl_triangles, 6, primarray);
    } else {
        renderingComplete = false;
    }

    for (; igIter != igEnd; ++igIter) {
        boost::shared_ptr<world::IngameObject> curObj = *igIter;

        // just items in a container
        if (!curObj->isDynamicItem()) {
            continue;
        }

        // check if texture is ready to be drawn
        boost::shared_ptr<ui::Texture> tex = curObj->getIngameTexture();

        if (!tex) {
            continue;
        }

        if (!tex->isReadComplete()) {
            renderingComplete = false;
            continue;
        }

        CL_Rectf rect(curObj->getLocXDraw(), curObj->getLocYDraw(), CL_Sizef(tex->getWidth(), tex->getHeight()));

        vertexCoords[0] = CL_Vec2f(rect.left, rect.top);
        vertexCoords[1] = CL_Vec2f(rect.right, rect.top);
        vertexCoords[2] = CL_Vec2f(rect.left, rect.bottom);
        vertexCoords[3] = CL_Vec2f(rect.right, rect.top);
        vertexCoords[4] = CL_Vec2f(rect.left, rect.bottom);
        vertexCoords[5] = CL_Vec2f(rect.right, rect.bottom);

        CL_Rectf texCoordHelper = tex->getNormalizedTextureCoords();

        CL_Vec2f texCoords[6] = {
            CL_Vec2f(texCoordHelper.left, texCoordHelper.top),
            CL_Vec2f(texCoordHelper.right, texCoordHelper.top),
            CL_Vec2f(texCoordHelper.left, texCoordHelper.bottom),
            CL_Vec2f(texCoordHelper.right, texCoordHelper.top),
            CL_Vec2f(texCoordHelper.left, texCoordHelper.bottom),
            CL_Vec2f(texCoordHelper.right, texCoordHelper.bottom)
        };

        CL_PrimitivesArray primarray(gc);
        primarray.set_attributes(0, vertexCoords);
        primarray.set_attributes(1, texCoords);

        primarray.set_attribute(2, curObj->getHueInfo(false));

        gc.set_texture(1, tex->getTexture());
        gc.draw_primitives(cl_triangles, 6, primarray);
    }

    gc.reset_textures();
    gc.reset_program_object();

    renderQueue_->postRender(renderingComplete);

    if (!renderingComplete) {
        ui::Manager::getSingleton()->queueComponentRepaint(containerView_);
    }
}
Exemplo n.º 10
0
int App::start(const std::vector<CL_String> &args)
{
	CL_OpenGLWindowDescription description;
	description.set_title("GLSL Test");
	description.set_size(CL_Size(1024, 768), true);

	CL_DisplayWindow window(description);
	CL_InputDevice keyboard = window.get_ic().get_keyboard();
	CL_GraphicContext gc = window.get_gc();

	CL_Slot slot_window_close = window.sig_window_close().connect(this, &App::window_close);

	// Load and link shaders
	CL_ProgramObject shader = CL_ProgramObject::load(gc, "Resources/vertex_shader.glsl", "Resources/fragment_shader.glsl");
	shader.bind_attribute_location(0, "Position");
	if (!shader.link())
		throw CL_Exception("Unable to link shader program: Error:" + shader.get_info_log());

	quit = false;

	while (!keyboard.get_keycode(CL_KEY_ESCAPE) && !quit )
	{
		gc.clear();
		gc.set_program_object(shader, cl_program_matrix_modelview_projection);
		//shader.set_uniform1i("SourceTexture", 0);

		int xpos = 0;
		int size = 16;
		int gap = size + 2;

		//-------- Test 1
		CL_Mat2f matrix2_a = CL_Mat2f(3, 1, 2, 4);
		CL_Mat2f matrix2_b = CL_Mat2f(-3, 7, 2, 5);
		CL_Mat2f matrix2_result = CL_Mat2f::multiply(matrix2_a, matrix2_b);

		CL_Mat2f matrix2_a_temp = matrix2_a;
		if (CL_Mat2i(matrix2_result) != CL_Mat2i(matrix2_a * matrix2_b))
			throw CL_Exception("Failure");

		shader.set_uniform1i("test_id", 1);
		shader.set_uniform_matrix("matrix2_a", matrix2_a);
		shader.set_uniform_matrix("matrix2_b", matrix2_b);
		shader.set_uniform_matrix("matrix2_result", matrix2_result);
		draw(gc, CL_Rect(xpos, 0, CL_Size(size, size)));
		xpos+=gap;

		//-------- Test 2
		CL_Mat3f matrix3_a = CL_Mat3f(3, 1, 2, 4, 5 ,6, 4, 2, 1);
		CL_Mat3f matrix3_b = CL_Mat3f(4, 7, 2, 5, 3, 5, 2, 9, 3);
		CL_Mat3f matrix3_result = CL_Mat3f::multiply(matrix3_a, matrix3_b);

		CL_Mat3f matrix3_a_temp = matrix3_a;
		if (CL_Mat3i(matrix3_result) != CL_Mat3i(matrix3_a * matrix3_b))
			throw CL_Exception("Failure");

		shader.set_uniform1i("test_id", 2);
		shader.set_uniform_matrix("matrix3_a", matrix3_a);
		shader.set_uniform_matrix("matrix3_b", matrix3_b);
		shader.set_uniform_matrix("matrix3_result", matrix3_result);
		draw(gc, CL_Rect(xpos, 0, CL_Size(size, size)));
		xpos+=gap;

		//-------- Test 3
		static float test_a_values[] = {3, 1, 2, 4, 5 ,6, 4, 2, 1, 4, 6, 7, 6, 3, 7, 2};
		static float test_b_values[] = {4, 7, 2, 5, 3, 5, 2, 9, 3, 3, 6, 9, 2, 4, 6, 2};

		CL_Mat4f matrix4_a = CL_Mat4f(test_a_values);
		CL_Mat4f matrix4_b = CL_Mat4f(test_b_values);
		CL_Mat4f matrix4_result = CL_Mat4f::multiply(matrix4_a, matrix4_b);

		CL_Mat4f matrix4_a_temp = matrix4_a;
		if (CL_Mat4i(matrix4_result) != CL_Mat4i(matrix4_a * matrix4_b))
			throw CL_Exception("Failure");

		shader.set_uniform1i("test_id", 3);
		shader.set_uniform_matrix("matrix4_a", matrix4_a);
		shader.set_uniform_matrix("matrix4_b", matrix4_b);
		shader.set_uniform_matrix("matrix4_result", matrix4_result);
		draw(gc, CL_Rect(xpos, 0, CL_Size(size, size)));
		xpos+=gap;

		//-------- Test 4
		matrix2_result = CL_Mat2f::subtract(matrix2_a, matrix2_b);

		matrix2_a_temp = matrix2_a;
		if (CL_Mat2i(matrix2_result) != CL_Mat2i(matrix2_a - matrix2_b))
			throw CL_Exception("Failure");

		shader.set_uniform1i("test_id", 4);
		shader.set_uniform_matrix("matrix2_a", matrix2_a);
		shader.set_uniform_matrix("matrix2_b", matrix2_b);
		shader.set_uniform_matrix("matrix2_result", matrix2_result);
		draw(gc, CL_Rect(xpos, 0, CL_Size(size, size)));
		xpos+=gap;

		//-------- Test 5
		matrix3_result = CL_Mat3f::subtract(matrix3_a, matrix3_b);

		matrix3_a_temp = matrix3_a;
		if (CL_Mat3i(matrix3_result) != CL_Mat3i(matrix3_a - matrix3_b))
			throw CL_Exception("Failure");

		shader.set_uniform1i("test_id", 5);
		shader.set_uniform_matrix("matrix3_a", matrix3_a);
		shader.set_uniform_matrix("matrix3_b", matrix3_b);
		shader.set_uniform_matrix("matrix3_result", matrix3_result);
		draw(gc, CL_Rect(xpos, 0, CL_Size(size, size)));
		xpos+=gap;

		//-------- Test 6

		matrix4_result = CL_Mat4f::subtract(matrix4_a, matrix4_b);

		matrix4_a_temp = matrix4_a;
		if (CL_Mat4i(matrix4_result) != CL_Mat4i(matrix4_a - matrix4_b))
			throw CL_Exception("Failure");

		shader.set_uniform1i("test_id", 6);
		shader.set_uniform_matrix("matrix4_a", matrix4_a);
		shader.set_uniform_matrix("matrix4_b", matrix4_b);
		shader.set_uniform_matrix("matrix4_result", matrix4_result);
		draw(gc, CL_Rect(xpos, 0, CL_Size(size, size)));
		xpos+=gap;

		//-------- Test 7
		CL_Vec2f vector2_a(2,3);
		CL_Vec2f vector2_result = vector2_a * matrix2_a;

		shader.set_uniform1i("test_id", 7);
		shader.set_uniform_matrix("matrix2_a", matrix2_a);
		shader.set_uniform2f("vector2_a", vector2_a);
		shader.set_uniform2f("vector2_result", vector2_result);
		draw(gc, CL_Rect(xpos, 0, CL_Size(size, size)));
		xpos+=gap;

		//-------- Test 8
		vector2_result = matrix2_a * vector2_a;

		shader.set_uniform1i("test_id", 8);
		shader.set_uniform_matrix("matrix2_a", matrix2_a);
		shader.set_uniform2f("vector2_a", vector2_a);
		shader.set_uniform2f("vector2_result", vector2_result);
		draw(gc, CL_Rect(xpos, 0, CL_Size(size, size)));
		xpos+=gap;


		//-------- Test 9
		CL_Vec3f vector3_a(3,5,6);
		CL_Vec3f vector3_result = vector3_a * matrix3_a;

		shader.set_uniform1i("test_id", 9);
		shader.set_uniform_matrix("matrix3_a", matrix3_a);
		shader.set_uniform3f("vector3_a", vector3_a);
		shader.set_uniform3f("vector3_result", vector3_result);
		draw(gc, CL_Rect(xpos, 0, CL_Size(size, size)));
		xpos+=gap;

		//-------- Test 10
		vector3_result = matrix3_a * vector3_a;

		shader.set_uniform1i("test_id", 10);
		shader.set_uniform_matrix("matrix3_a", matrix3_a);
		shader.set_uniform3f("vector3_a", vector3_a);
		shader.set_uniform3f("vector3_result", vector3_result);
		draw(gc, CL_Rect(xpos, 0, CL_Size(size, size)));
		xpos+=gap;
		//-------- Test 11
		CL_Vec4f vector4_a(4,3,5,6);
		CL_Vec4f vector4_result = vector4_a * matrix4_a;

		shader.set_uniform1i("test_id", 11);
		shader.set_uniform_matrix("matrix4_a", matrix4_a);
		shader.set_uniform4f("vector4_a", vector4_a);
		shader.set_uniform4f("vector4_result", vector4_result);
		draw(gc, CL_Rect(xpos, 0, CL_Size(size, size)));
		xpos+=gap;

		//-------- Test 12
		vector4_result = matrix4_a * vector4_a;

		shader.set_uniform1i("test_id", 12);
		shader.set_uniform_matrix("matrix4_a", matrix4_a);
		shader.set_uniform4f("vector4_a", vector4_a);
		shader.set_uniform4f("vector4_result", vector4_result);
		draw(gc, CL_Rect(xpos, 0, CL_Size(size, size)));
		xpos+=gap;


		gc.reset_program_object();
		window.flip();

		CL_System::sleep(10);

		CL_KeepAlive::process();
	}

	return 0;
}
Exemplo n.º 11
0
// The start of the Application
int App::start(const std::vector<CL_String> &args)
{
	quit = false;

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

	try
	{
		// Set the window
		// This opens a 640 x 480 window, including the frame size
		// If you want more control over the window, pass CL_DisplayWindowDescription to CL_DisplayWindow
		// (This is useful to create a borderless window of a specific size)
		// If you require target specific control over the window, use the derived CL_OpenGLWindowDescription
		// (This contains the multisampling options)
#ifdef USE_SWRENDER
		CL_DisplayWindowDescription desc;
#else
		CL_OpenGLWindowDescription desc;
//		desc.set_multisampling(4);
#endif
		desc.set_title("ClanLib 2D Test");
		desc.set_size(CL_Size(800, 600), true);
		CL_DisplayWindow window(desc);

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

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

		// Get the graphic context
		CL_GraphicContext gc = window.get_gc();

		CL_Texture texture_image(gc, "tux.png");
		texture_image.set_wrap_mode(cl_wrap_repeat, cl_wrap_repeat, cl_wrap_repeat);
		texture_image.set_min_filter(cl_filter_linear);
		texture_image.set_mag_filter(cl_filter_linear);

		CL_ResourceManager resources("resources.xml");
		CL_Sprite sprite(gc, "test", &resources);
		//sprite.set_linear_filter(true);

		CL_Font small_font = CL_Font(gc, "Tahoma", 12);

		float test_base_angle = 0.0f;
		float test_angle = 0.0f;
		float test_angle_pitch = 0.0f;
		float test_angle_yaw = 0.0f;
		float test_scale = 1.0f;
		bool test_scale_dir = false;

		// Run until someone presses escape
		while (!quit)
		{
			gc.clear(CL_Colorf(0.0f,0.0f,0.2f));

			gc.set_map_mode(CL_MapMode(cl_map_2d_upper_left));

	// CL_Draw::point()
			for (int xcnt=0; xcnt<8; xcnt++)
			{
				for (int ycnt=0; ycnt<6; ycnt++)
				{
					CL_Draw::point(gc, xcnt*2, ycnt*2, CL_Colorf(1.0f, 1.0f, 1.0f, 1.0f));
				}
			}
			small_font.draw_text(gc, 32, 10, "8*6 Points (0 + 2x), (0 + 2y)");

	// CL_Draw::line()
			for (int xcnt=0; xcnt<4; xcnt++)
			{
				for (int ycnt=0; ycnt<3; ycnt++)
				{
					const int offset_y = 16;
					const int line_length = 6;
					const int spacing = 8;
					CL_Draw::line(gc, xcnt*spacing, (ycnt*spacing) + offset_y, line_length + (xcnt*spacing), (line_length + (ycnt*spacing)) + offset_y, CL_Colorf(1.0f, 1.0f, 1.0f, 1.0f));
				}
			}
			small_font.draw_text(gc, 48, 30, "4*3 Lines (0 + 8x), (32 + 8y), (6 + 8x), (38 + 8y)");

	// CL_Draw::box()
			for (int xcnt=0; xcnt<4; xcnt++)
			{
				for (int ycnt=0; ycnt<3; ycnt++)
				{
					const int offset_y = 48;
					const int line_length = 6;
					const int spacing = 8;
					CL_Draw::box(gc, xcnt*spacing, (ycnt*spacing) + offset_y, line_length + (xcnt*spacing), (line_length + (ycnt*spacing)) + offset_y, CL_Colorf(1.0f, 1.0f, 1.0f, 1.0f));
				}
			}
			small_font.draw_text(gc, 48, 66, "4*3 Box (0 + 8x), (32 + 8y), (6 + 8x), (38 + 8y)");

	// CL_Draw::fill()
			for (int xcnt=0; xcnt<4; xcnt++)
			{
				for (int ycnt=0; ycnt<3; ycnt++)
				{
					const int offset_y = 80;
					const int line_length = 6;
					const int spacing = 8;
					CL_Draw::fill(gc, xcnt*spacing, (ycnt*spacing) + offset_y, line_length + (xcnt*spacing), (line_length + (ycnt*spacing)) + offset_y, CL_Colorf(1.0f, 1.0f, 1.0f, 1.0f));
				}
			}
			small_font.draw_text(gc, 48, 90, "4*3 Fill (0 + 8x), (32 + 8y), (6 + 8x), (38 + 8y)");

	// CL_Draw::gradient_fill()
			CL_Gradient gradient;
			gradient.top_left = CL_Colorf(1.0f, 1.0f, 1.0f, 1.0f);
			gradient.top_right = CL_Colorf(1.0f, 0.0f, 0.0f, 1.0f);
			gradient.bottom_left = CL_Colorf(0.0f, 0.0f, 1.0f, 1.0f);
			gradient.bottom_right = CL_Colorf(0.0f, 1.0f, 0.0f, 1.0f);
			for (int xcnt=0; xcnt<4; xcnt++)
			{
				for (int ycnt=0; ycnt<3; ycnt++)
				{
					const int offset_y = 110;
					const int line_length = 6;
					const int spacing = 8;
					CL_Draw::gradient_fill(gc, xcnt*spacing, (ycnt*spacing) + offset_y, line_length + (xcnt*spacing), (line_length + (ycnt*spacing)) + offset_y, gradient);
				}
			}
			small_font.draw_text(gc, 48, 115, "4*3 GradientFill (0 + 8x), (32 + 8y), (6 + 8x), (38 + 8y)");
			small_font.draw_text(gc, 48, 125, "top left = white. top right = red");
			small_font.draw_text(gc, 48, 135, "bottom left = blue. bottom right = green");

	// CL_Draw::circle()
			{
				const int offset_y = 140;
				int radius = 5;
				CL_Draw::circle(gc, radius, offset_y + radius, radius, CL_Colorf(1.0f, 1.0f, 1.0f, 1.0f));

				const int offset_x = 16;
				radius = 16;
				CL_Draw::circle(gc, offset_x + radius, offset_y + radius, radius, CL_Colorf(1.0f, 1.0f, 1.0f, 1.0f));
			}
			small_font.draw_text(gc, 54, 149, "Circle (5, 145) Radius = 5");
			small_font.draw_text(gc, 54, 159, "Circle (32, 156) Radius = 16");

	// CL_Draw::gradient_circle()
			{
				CL_Gradient gradient;
				gradient.top_left = CL_Colorf(1.0f, 1.0f, 1.0f, 1.0f);
				gradient.top_right = CL_Colorf(0.0f, 0.0f, 0.0f, 1.0f);
				gradient.bottom_left = CL_Colorf(0.0f, 0.0f, 0.0f, 1.0f);
				gradient.bottom_right = CL_Colorf(1.0f, 0.0f, 0.0f, 1.0f);

				const int offset_y = 180;
				float radius = 17.0;
				float xpos = radius;
				float ypos = offset_y + radius;
				CL_Draw::gradient_circle(gc, CL_Pointf( xpos, ypos ), CL_Pointf(radius/2.0, 0.0f), radius, gradient);

				const int offset_x = 40;
				radius = 17.0;
				xpos = offset_x + radius;
				ypos = offset_y + radius;
				CL_Draw::gradient_circle(gc, CL_Pointf( xpos, ypos), CL_Pointf(0.0f, radius/2.0), radius, gradient);
			}

			small_font.draw_text(gc, 80, 189, "Gradient Circle (16, 196) Radius = 17. Gradient right");
			small_font.draw_text(gc, 80, 199, "Gradient Circle (56, 196) Radius = 17. Gradient up");
			small_font.draw_text(gc, 80, 209, "centre = white, outer = red");

	// CL_Draw::triangle()
			{
				const float offset_y = 220.0f;
				const float size = 12.0f;
				CL_Draw::triangle(gc, CL_Pointf(0.0f, offset_y), CL_Pointf(0.0f, offset_y + size), CL_Pointf(size, offset_y + size), CL_Colorf(1.0f, 1.0f, 1.0f, 1.0f));

				float offset_x = 16.0f;
				CL_Draw::triangle(gc, CL_Pointf(offset_x + 0.0f, offset_y + size), CL_Pointf(offset_x + size, offset_y + size), CL_Pointf(offset_x + 0.0f, offset_y), CL_Colorf(1.0f, 1.0f, 1.0f, 1.0f));

				offset_x = 32.0f;
				CL_Draw::triangle(gc, CL_Pointf(offset_x + size, offset_y + size), CL_Pointf(offset_x + 0.0f, offset_y), CL_Pointf(offset_x + 0.0f, offset_y + size), CL_Colorf(1.0f, 1.0f, 1.0f, 1.0f));
			}
			small_font.draw_text(gc, 48, 229, "3 Triangles (12 pixel size) (Left vertical edge).");
			small_font.draw_text(gc, 48, 239, "Top Left: (0,220)  (16,220)  (32,220)");

	// CL_Draw::texture()
			gc.set_texture(0, texture_image);
			{
				float offset_x = 0.0f;
				float offset_y = 250.0f;
				CL_Rectf src_rect(offset_x, offset_y, CL_Sizef(31, 47));
				CL_Rectf texture_coords(0.0, 0.0, 1.0f, 1.0f);
				CL_Colorf color(1.0f, 1.0f, 1.0f, 1.0f);
				CL_Draw::texture(gc, src_rect, color, texture_coords);

				offset_x = 33.0f;
				src_rect = CL_Rectf(offset_x, offset_y, CL_Sizef(31, 47));
				texture_coords = CL_Rectf(0.25f, 0.25f, 0.75f, 0.75f);
				color = CL_Colorf(1.0f, 0.0f, 0.0f, 1.0f);
				CL_Draw::texture(gc, src_rect, color, texture_coords);
			}
			gc.reset_texture(0);
			small_font.draw_text(gc, 76, 260, "Texture (0, 250) size=(31,47)");
			small_font.draw_text(gc, 76, 275, "Texture (33, 250) size=(31,47) (red, magnify*2)");

	// CL_RoundedRect
			{
				CL_RoundedRect roundedrect(CL_Sizef(64.0f, 32.0f), 15.0f);

				float offset_x = 0.0f;
				float offset_y = 300.0f;
				CL_Origin origin = origin_top_left;
				roundedrect.draw(gc, CL_Pointf(offset_x, offset_y), CL_Colorf(1.0f, 1.0f, 1.0f, 1.0f), origin);

				offset_y = 340.0f;
				roundedrect.fill(gc, CL_Pointf(offset_x, offset_y), CL_Colorf(1.0f, 1.0f, 1.0f, 1.0f), origin);

				offset_y = 380.0f;
				CL_Gradient gradient;
				gradient.top_left = CL_Colorf(1.0f, 1.0f, 1.0f, 1.0f);
				gradient.top_right = CL_Colorf(1.0f, 0.0f, 0.0f, 1.0f);
				gradient.bottom_left = CL_Colorf(0.0f, 0.0f, 1.0f, 1.0f);
				gradient.bottom_right = CL_Colorf(0.0f, 1.0f, 0.0f, 1.0f);
				roundedrect.fill(gc, CL_Pointf(offset_x, offset_y), gradient, origin);

				offset_y = 420.0f;
				roundedrect.set_control_point_bl(CL_Pointf(0.4f, 0.8f));
				roundedrect.set_rounding_bottom_left(CL_Sizef(0.2f, 0.6f));

				roundedrect.set_control_point_tl(CL_Pointf(0.2f, 0.4f));
				roundedrect.set_rounding_top_left(CL_Sizef(0.4f, 0.2f));

				roundedrect.set_control_point_tr(CL_Pointf(0.6f, 0.2f));
				roundedrect.set_rounding_top_right(CL_Sizef(0.8f, 0.4f));
				roundedrect.set_control_point_br(CL_Pointf(0.6f, 0.8f));
				roundedrect.set_rounding_bottom_right(CL_Sizef(0.8f, 0.6f));

				roundedrect.fill(gc, CL_Pointf(offset_x, offset_y), gradient, origin);

			}
			small_font.draw_text(gc, 76, 310, "RoundedRect - draw (0, 300) size=(64,32)");
			small_font.draw_text(gc, 76, 325, "(RoundedRect - draw gradient - is not implemented)");
			small_font.draw_text(gc, 76, 350, "RoundedRect - fill (0, 340) size=(64,32)");
			small_font.draw_text(gc, 76, 390, "RoundedRect - fill gradient (0, 380) size=(64,32)");
			small_font.draw_text(gc, 76, 400, "top left = white. top right = red");
			small_font.draw_text(gc, 76, 410, "bottom left = blue. bottom right = green");
			small_font.draw_text(gc, 76, 430, "RoundedRect - fill gradient (0, 420) size=(64,32)");
			small_font.draw_text(gc, 76, 440, "Controling control / rounding points");

	// CL_Sprite
			{
				test_base_angle+=5.0f;
				if (test_base_angle >= 360.0f)
				{
					test_base_angle = 0.0f;
				}
#ifndef USE_SWRENDER
				clEnable(GL_MULTISAMPLE);
#endif
				sprite.set_base_angle(CL_Angle(test_base_angle, cl_degrees));
				sprite.draw(gc, 350, 20);
				sprite.set_base_angle(CL_Angle(0, cl_degrees));

#ifndef USE_SWRENDER
				clDisable(GL_MULTISAMPLE);
#endif
			}
			small_font.draw_text(gc, 370, 20, "Sprite - Base angle");
			small_font.draw_text(gc, 370, 35, "Multisampling enabled");

			{
				test_angle+=5.0f;
				if (test_angle >= 360.0f)
				{
					test_angle = 0.0f;
				}

				sprite.set_angle(CL_Angle(test_angle, cl_degrees));
				sprite.draw(gc, 350, 60);
				sprite.set_angle(CL_Angle(0, cl_degrees));
			}
			small_font.draw_text(gc, 370, 60, "Sprite - Angle");

			{
				test_angle_pitch+=5.0f;
				if (test_angle_pitch >= 360.0f)
				{
					test_angle_pitch = 0.0f;
				}

				sprite.set_angle_pitch(CL_Angle(test_angle_pitch, cl_degrees));
				sprite.draw(gc, 350, 100);
				sprite.set_angle_pitch(CL_Angle(0, cl_degrees));
			}
			small_font.draw_text(gc, 370, 100, "Sprite - Angle Pitch");

			{
				test_angle_yaw+=5.0f;
				if (test_angle_yaw >= 360.0f)
				{
					test_angle_yaw = 0.0f;
				}

				sprite.set_angle_yaw(CL_Angle(test_angle_yaw, cl_degrees));
				sprite.draw(gc, 350, 140);
				sprite.set_angle_yaw(CL_Angle(0, cl_degrees));
			}
			small_font.draw_text(gc, 370, 140, "Sprite - Angle Yaw");

			{
				if (test_scale_dir)
				{
					test_scale += 0.1f;
					if (test_scale >= 2.0f)
					{
						test_scale = 2.0f;
						test_scale_dir = false;
					}
				}else
				{
					test_scale -= 0.1f;
					if (test_scale <= -2.0f)
					{
						test_scale = -2.0f;
						test_scale_dir = true;
					}
				}

				sprite.set_scale(test_scale, 1.0f);
				sprite.draw(gc, 350, 180);
				sprite.set_scale(1.0f, test_scale);
				sprite.draw(gc, 390, 180);
				sprite.set_scale(1.0f, 1.0f);
			}
			small_font.draw_text(gc, 420, 180, "Sprite - Set Scale (x), (y)");

			// 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
			CL_KeepAlive::process();
		}
		small_font = CL_Font();
	}
	catch(CL_Exception& exception)
	{
		CL_Console::write_line("Exception caught:");
		CL_Console::write_line(exception.message);

		// Display the stack trace (if available)
		std::vector<CL_String> stacktrace = exception.get_stack_trace();
		int size = stacktrace.size();
		if (size > 0)
		{
			CL_Console::write_line("Stack Trace:");
			for (int cnt=0; cnt < size; cnt++)
			{
				CL_Console::write_line(stacktrace[cnt]);
			}
		}

		console.display_close_message();

		return -1;
	}
	return 0;
}
Exemplo n.º 12
0
// The start of the Application
int Basic::start(const std::vector<CL_String> &args)
{
	quit = false;

	// Set the window
	CL_DisplayWindowDescription desc;
	desc.set_title("ClanLib OpenCL Basic Example");
	desc.set_size(CL_Size(640, 480), true);
	desc.set_allow_resize(true);

	CL_DisplayWindow window(desc);

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

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

	// Get the graphic context
	CL_GraphicContext gc = window.get_gc();

	cl_int error;
	cl_platform_id platform;
	cl_uint platforms;
	
	error = clGetPlatformIDs(1, &platform, &platforms);
	if (error != CL_SUCCESS)
		throw CL_Exception("clGetPlatformIDs failed");

	cl_device_id device;
	cl_uint devices;
	error = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, &devices);
	if (error != CL_SUCCESS)
		throw CL_Exception("clGetDeviceIDs failed");
	
	cl_context_properties properties[]={CL_CONTEXT_PLATFORM, (cl_context_properties)platform, 0};
	cl_context context;
	context = clCreateContext(properties, 1, &device, NULL, NULL, &error);
	if (error != CL_SUCCESS)
		throw CL_Exception("clCreateContext failed");

	cl_command_queue cq;
	cq = clCreateCommandQueue(context, device, 0, &error);
	if (error != CL_SUCCESS)
		throw CL_Exception("clCreateCommandQueue failed");

	static const char source_code[] = 
		""
		"__kernel void simple_test(__global float *vals)"
		"{"
		"	const uint i = get_global_id(0);"
		""
		"vals[i] = 1.23;"
		"}"
		"";


	const char *src[] = {source_code};

	cl_program prog;
	prog = clCreateProgramWithSource(context, 1, src, NULL, &error);
	if (error != CL_SUCCESS)
		throw CL_Exception("clCreateProgramWithSource failed");

	error = clBuildProgram(prog, 0, NULL, "", NULL, NULL);
	if (error != CL_SUCCESS)
		throw CL_Exception("clBuildProgram failed");

	cl_kernel k_simple_test;
	k_simple_test = clCreateKernel(prog, "simple_test", &error);
	if (error != CL_SUCCESS)
		throw CL_Exception("clCreateKernel failed");

	static const int buffer_length = 64;
	cl_mem ref_buffer;
	ref_buffer = clCreateBuffer(context, CL_MEM_READ_WRITE, sizeof(float) *  buffer_length, NULL, &error);
	if (error != CL_SUCCESS)
		throw CL_Exception("clCreateBuffer failed");

	error = clSetKernelArg(k_simple_test, 0, sizeof(ref_buffer), &ref_buffer);
	if (error != CL_SUCCESS)
		throw CL_Exception("clSetKernelArg failed");

	const size_t worksize = buffer_length;
	error = clEnqueueNDRangeKernel(cq, k_simple_test, 1, NULL, &worksize, NULL, 0, NULL, NULL);
	if (error != CL_SUCCESS)
		throw CL_Exception("clEnqueueNDRangeKernel failed");

	error = clFinish(cq);
	if (error != CL_SUCCESS)
		throw CL_Exception("clFinish failed");

	float ram_buffer[buffer_length];
	error=clEnqueueReadBuffer(cq, ref_buffer, CL_TRUE, 0, sizeof(float) * buffer_length, ram_buffer, 0, NULL, NULL);
	if (error != CL_SUCCESS)
		throw CL_Exception("clEnqueueReadBuffer failed");

	error=clFinish(cq);
	if (error != CL_SUCCESS)
		throw CL_Exception("clFinish failed");

	// Clean up
	clReleaseKernel(k_simple_test);
	clReleaseProgram(prog);
	clReleaseCommandQueue(cq);
	clReleaseContext(context);
	clReleaseMemObject(ref_buffer);

	// Test output
	for (int cnt=0;cnt < buffer_length; cnt++)
	{
		if (ram_buffer[cnt] != 1.23f)
			throw CL_Exception("It did not work!");
	}

	CL_Font font(gc, "tahoma", 24);

	// Run until someone presses escape
	while (!quit)
	{
		gc.clear(CL_Colorf(0.0f,0.0f,0.2f));
		font.draw_text(gc, 32, 32, "Success");
		window.flip(1);
		CL_KeepAlive::process(0);
	}

	return 0;
}
Exemplo n.º 13
0
// The start of the Application
int App::start(const std::vector<CL_String> &args)
{
	quit = false;
    CL_GL1WindowDescription desc;

	desc.set_title("ClanLib Object 3D Example");
	desc.set_size(CL_Size(640, 480), true);
	desc.set_multisampling(4);
	desc.set_depth_size(16);

	CL_DisplayWindow window(desc);

#ifdef _DEBUG
	//struct aiLogStream stream;
	//stream = aiGetPredefinedLogStream(aiDefaultLogStream_STDOUT,NULL);
	//aiAttachLogStream(&stream);
	//stream = aiGetPredefinedLogStream(aiDefaultLogStream_FILE,"assimp_log.txt");
	//aiAttachLogStream(&stream);
#endif

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

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

	// Get the graphic context
	CL_GraphicContext gc = window.get_gc();

#ifdef USE_OPENGL_1
    CL_GraphicContext_GL1 gc_gl1 = gc;
#endif

	// Prepare the display
	gc.set_map_mode(cl_user_projection);

	CL_PolygonRasterizer polygon_rasterizer;
	polygon_rasterizer.set_culled(true);
	polygon_rasterizer.set_face_cull_mode(cl_cull_back);
	polygon_rasterizer.set_front_face(cl_face_side_clockwise);
	gc.set_polygon_rasterizer(polygon_rasterizer);

	CL_BufferControl buffer_control;
	buffer_control.enable_depth_test(true);
	buffer_control.set_depth_compare_function(cl_comparefunc_lequal);
	buffer_control.enable_depth_write(true);
	gc.set_buffer_control(buffer_control);

#ifdef USE_OPENGL_1
	// Set the lights
	CL_LightModel_GL1 light_model;
	light_model.enable_lighting(true);
	light_model.set_flat_shading(false);
	light_model.set_scene_ambient_light(CL_Colorf(0.2f, 0.2f, 0.2f, 1.0f));
	gc_gl1.set_light_model(light_model);

	CL_LightSource_GL1 light_distant;
	light_distant.set_spot_cutoff(180.0f);
	light_distant.set_diffuse_intensity(CL_Colorf(1.0f, 1.0f, 1.0f, 1.0f));
	light_distant.set_position(CL_Vec4f(0.0f, -2.0f, 30.0f, 0.0f).normalize3());
	gc_gl1.set_light(0, light_distant);

	cl1Enable(GL_NORMALIZE);
#endif

#ifdef USE_OPENGL_2
    Shader shader(gc);
#endif

	// Create the objects

	aiSetImportPropertyFloat(AI_CONFIG_PP_GSN_MAX_SMOOTHING_ANGLE,89.53f);

	const struct aiScene* scene_teapot = aiImportFile("../Clan3D/Resources/teapot.dae",aiProcessPreset_TargetRealtime_MaxQuality);
	if (!scene_teapot)
		throw CL_Exception("Cannot load the teapot model");

	const struct aiScene* scene_clanlib = aiImportFile("../Clan3D/Resources/clanlib.dae",aiProcessPreset_TargetRealtime_MaxQuality);
	if (!scene_clanlib)
		throw CL_Exception("Cannot load the clanlib model");

	const struct aiScene* scene_tuxball = aiImportFile("../Clan3D/Resources/tux_ball.dae",aiProcessPreset_TargetRealtime_MaxQuality | aiProcess_FlipUVs);
	if (!scene_tuxball)
		throw CL_Exception("Cannot load the tux ball model");

	// Load the texture
	CL_Texture tux(gc, "../Clan3D/Resources/tux.png");

	float angle = 0.0f;
	// Run until someone presses escape
	while (!quit)
	{

		CL_Mat4f perp = CL_Mat4f::perspective(45.0f, ((float) gc.get_width()) / ((float) gc.get_height()), 0.1f, 1000.0f);
		gc.set_projection(perp);

		gc.clear(CL_Colorf::black);
		gc.clear_depth(1.0f);

		angle += 1.0f;
		if (angle >= 360.0f)
			angle -= 360.0f;


#ifdef USE_OPENGL_2
        shader.Set(gc);
        shader.Use(gc);
#else
        gc.set_program_object(cl_program_color_only);
#endif

		CL_PrimitivesArray prim_array(gc);

		gc.set_modelview(CL_Mat4f::identity());
		gc.mult_scale(1.0f,1.0f, -1.0f);	// So +'ve Z goes into the screen
		gc.mult_translate(0.0f, 0.0f, 2.0f);
		gc.mult_rotate(CL_Angle(angle, cl_degrees), 0.0f, 1.0f, 0.0f, false);

		gc.push_modelview();
		recursive_render(gc, scene_teapot, scene_teapot->mRootNode, false);
		gc.pop_modelview();

		gc.push_modelview();
		gc.mult_scale(0.5f, 0.5f, 0.5f);
		gc.mult_translate(0.0f, -0.5f, 0.0f);
		recursive_render(gc, scene_clanlib, scene_clanlib->mRootNode, false);
		gc.pop_modelview();

#ifdef USE_OPENGL_2
        shader.Set(gc, 0);
        shader.Use(gc);
#else
        gc.set_program_object(cl_program_single_texture);
#endif

		gc.set_texture(0, tux);
 		gc.set_modelview(CL_Mat4f::identity());
		gc.mult_scale(1.0f,1.0f, -1.0f);	// So +'ve Z goes into the screen
		gc.mult_translate(0.7f, 0.5f, 2.0f);
		gc.mult_scale(0.05f, 0.05f, 0.05f);
		gc.mult_rotate(CL_Angle(angle * 4.0f, cl_degrees), 0.0f, 1.0f, 0.0f, false);
		recursive_render(gc, scene_tuxball, scene_tuxball->mRootNode, true);
		gc.reset_texture(0);

		gc.reset_program_object();
		
		// 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
		CL_KeepAlive::process();
	}

	aiReleaseImport(scene_tuxball);
	aiReleaseImport(scene_clanlib);
	aiReleaseImport(scene_teapot);
	aiDetachAllLogStreams();

	return 0;
}
Exemplo n.º 14
0
// The start of the Application
int App::start(const std::vector<CL_String> &args)
{
	CL_DisplayWindowDescription win_desc;
	win_desc.set_allow_resize(true);
	win_desc.set_title("Vertex Buffer Object Example");
	win_desc.set_depth_size(16);

	win_desc.set_size(CL_Size( 800, 600 ), false);

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

	CL_GraphicContext gc = window.get_gc();

	Shader shader(gc);

	// Prepare the display
	gc.set_map_mode(cl_user_projection);

	CL_PolygonRasterizer polygon_rasterizer;
	polygon_rasterizer.set_culled(true);
	polygon_rasterizer.set_face_cull_mode(cl_cull_back);
	polygon_rasterizer.set_front_face(cl_face_side_clockwise);
	gc.set_polygon_rasterizer(polygon_rasterizer);

	CL_BufferControl buffer_control;
	buffer_control.enable_depth_test(true);
	buffer_control.set_depth_compare_function(cl_comparefunc_lequal);
	buffer_control.enable_depth_write(true);
	gc.set_buffer_control(buffer_control);

	std::vector<CL_Vec3f> object_positions;
	std::vector<CL_Vec3f> object_normals;
	std::vector<CL_Vec4f> object_material_ambient;

	const int num_cubes = 20000;
	object_positions.reserve(num_cubes * 6 * 6);	// 6 faces, and 6 vertices per face
	object_normals.reserve(num_cubes * 6 * 6);
	object_material_ambient.reserve(num_cubes * 6 * 6);

	for (int cnt=0; cnt < num_cubes; cnt++)
	{
		create_cube(object_positions, object_normals, object_material_ambient);
	}

	CL_VertexArrayBuffer vb_positions(gc, &object_positions[0], sizeof(CL_Vec3f) * object_positions.size());
	CL_VertexArrayBuffer vb_normals(gc, &object_normals[0], sizeof(CL_Vec3f) * object_normals.size());
	CL_VertexArrayBuffer vb_material_ambient(gc, &object_material_ambient[0], sizeof(CL_Vec4f) * object_material_ambient.size());

	// ** Note, at this point "object_positions, object_normals and object_material_ambient"
	// ** can be destroyed. But for the purpose of this example, is it kept

	CL_Font fps_font(gc, "tahoma", 20);

	FramerateCounter frameratecounter;
	unsigned int time_last = CL_System::get_time();

	float angle = 0.0f;
	is_vertex_buffer_on = true;

	while (!quit)
	{
		unsigned int time_now = CL_System::get_time();
		float time_diff = (float) (time_now - time_last);
		time_last = time_now;

		gc.clear(CL_Colorf(0.0f, 0.0f, 0.0f, 1.0f));
		gc.clear_depth(1.0f);

		gc.set_map_mode(cl_map_2d_upper_left);
		CL_String fps = cl_format("%1 fps", frameratecounter.get_framerate());
		fps_font.draw_text(gc, gc.get_width() - 100, 30, fps);
		CL_String info = cl_format("%1 vertices", (int) object_positions.size());
		fps_font.draw_text(gc, 30, 30, info);

		fps_font.draw_text(gc, 30, gc.get_height() - 8, "Press any key to toggle the Vertex Buffer option");

		if (is_vertex_buffer_on)
		{
			fps_font.draw_text(gc, 200, 30, "Vertex Buffer = ON");
		}
		else
		{
			fps_font.draw_text(gc, 200, 30, "Vertex Buffer = OFF");
		}

		gc.set_map_mode(cl_user_projection);
		CL_Mat4f perp = CL_Mat4f::perspective(45.0f, ((float) gc.get_width()) / ((float) gc.get_height()), 0.1f, 100000.0f);
		gc.set_projection(perp);

		angle += time_diff / 20.0f;
		if (angle >= 360.0f)
			angle -= 360.0f;

		gc.push_modelview();
		gc.set_modelview(CL_Mat4f::identity());
		gc.mult_scale(1.0f,1.0f, -1.0f);	// So +'ve Z goes into the screen
		gc.mult_translate(0.0f, 0.0f, 800.0f);
		gc.mult_rotate(CL_Angle(angle*2.0f, cl_degrees), 0.0f, 1.0f, 0.0f, false);
		gc.mult_rotate(CL_Angle(angle, cl_degrees), 1.0f, 0.0f, 0.0f, false);

		shader.Set(gc);
		shader.Use(gc);

		CL_PrimitivesArray prim_array(gc);

		if (is_vertex_buffer_on)
		{
			prim_array.set_attributes(0, vb_positions, 3, cl_type_float, (void *) 0);
			prim_array.set_attributes(1, vb_normals, 3, cl_type_float, (void *) 0);
			prim_array.set_attributes(2, vb_material_ambient, 4, cl_type_float, (void *) 0);
		}
		else
		{
			prim_array.set_attributes(0, &object_positions[0]);
			prim_array.set_attributes(1, &object_normals[0]);
			prim_array.set_attributes(2, &object_material_ambient[0]);
		}
		gc.draw_primitives(cl_triangles, object_positions.size(), prim_array);

		gc.pop_modelview();

		gc.reset_program_object();

		window.flip(0);
		frameratecounter.frame_shown();

		CL_KeepAlive::process();
	}

	return 0;
}
Exemplo n.º 15
0
// The start of the Application
int Tetris::start(const std::vector<CL_String> &args)
{
    quit = false;
    finish = false;

//    leftborderlist = new LeftBordeList();
 //   rightbordelist = new RightBordeList();

    // Set the window
    CL_DisplayWindowDescription desc;
    desc.set_title("Tetris");
    desc.set_size(CL_Size(320, 640), true);
    desc.set_allow_resize(true);

    CL_DisplayWindow window(desc);

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

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

    // Get the graphic context
    CL_GraphicContext gc = window.get_gc();

    // Load a sprite from a png-file
    //CL_Sprite spr_logo(gc, "Resources/logo.png");

    float sin_count = 0.0f;
    float ypos = 0.0f;
    float ydir = 0.3f;

    unsigned int last_time = CL_System::get_time();

    CL_Font font(gc, "Utopia", 40);
    linesRemoved = 0;

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

        //std::cout << "shift = " << shift << std::endl;

        // Clear the display in a dark blue nuance
        // The four arguments are red, green, blue and alpha
        gc.clear(CL_Colorf(25.0f,25.0f,25.0f));
        std::string s;
        std::stringstream out;
        out << linesRemoved;
        s = out.str();
        font.draw_text(gc, 250,40, s.c_str(), CL_Colorf::blue);

        int l = bottomborderlist.getLineNumberToDelete();

        while (l != -1)
        {
            l = bottomborderlist.getLineNumberToDelete();
            if (l!= -1)
            {
                if (!bottomborderlist.isFullHeight())
                {
                    linesRemoved++;
                }

            }
            bottomborderlist.removeLine(l);


        }



        if (!figlist.checkCollisionDown(bottomborderlist))
        {
            figlist.moveDown(shift);


        }
        else
        {
            FigureList newfl = figlist;
            newfl.setStablePosition();

            if (!finish)
            {
                bottomborderlist.addList(newfl.getFigureList());
                if (figlist.checkCollisionDown(bottomborderlist))
                {
                   figlist.reset();


                }
                else
                {
                    figlist.reset();
                    figlist.clearFigureList();

                }

            }


            if (figlist.checkCollisionDown(bottomborderlist))
            {

                finish  = true;

            }



        }

        leftborderlist.draw(gc);
         rightborderlist.draw(gc);
         bottomborderlist.draw(gc);

        if (finish == false  && !figlist.checkCollisionDown(bottomborderlist))
        {
            figlist.draw(gc);
        }
        else
        {
             if (linesRemoved < 5)
                    {
                        font.draw_text(gc, 10,40, "You Lost", CL_Colorf::black);
                    }
                    else
                    {
                        font.draw_text(gc, 10,40, "You Won", CL_Colorf::black);
                    }

        }












        // 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
        CL_KeepAlive::process(0);
    }
    return 0;
}
Exemplo n.º 16
0
	void run()
	{
		quit = false;

		CL_DisplayWindowDescription window_desc;
		window_desc.set_size(CL_Size(1920, 1080), true);
		window_desc.set_title("Luna");
		CL_DisplayWindow window(window_desc);

		CL_Slot slot_quit = window.sig_window_close().connect(this, &RootWindow::on_window_close);

		CL_GraphicContext gc = window.get_gc();
		CL_InputDevice keyboard = window.get_ic().get_keyboard();

		CL_FontDescription font_desc;
		font_desc.set_typeface_name("Monospace");
		font_desc.set_height(16);
		CL_Font_System font(gc, font_desc);
		CL_FontMetrics fmetrics = font.get_font_metrics();
		int fntWidth = fmetrics.get_max_character_width();

		CL_SpriteDescription spr_desc;
		spr_desc.add_frame(CL_ImageProviderFactory::load("spaceship.png"));
		CL_Sprite node(gc, spr_desc);
		node.set_play_loop(true);
		node.set_play_pingpong(false);
		node.set_frame(0);

		CL_Image pict(gc,"stars.jpg");

		x = gc.get_width() / 2 ;
		y = gc.get_height() / 2 ;
		U = 0;
		W = 0;
		V = 0;
		H = 0;
		step = 0.2;

		while (!quit)
		{
			if(keyboard.get_keycode(CL_KEY_ESCAPE) == true)
				quit = true;
			if(keyboard.get_keycode(CL_KEY_LEFT) == true)
			    U -= step ;
			if(keyboard.get_keycode(CL_KEY_RIGHT) == true)
			    U += step ;
			if(keyboard.get_keycode(CL_KEY_UP) == true)
			    V -= step ;
			if(keyboard.get_keycode(CL_KEY_DOWN) == true)
			    V += step ;

			if(x < -node.get_width()) {
				x = gc.get_width();
			}
			else if(x > gc.get_width()) {
				x = -node.get_width();
			}
			else
				x += U ;

			if(y < step) {
				y = step;
				V = 0;
			}
			else if(y > gc.get_height()-node.get_height()) {
				y = gc.get_height()-node.get_height();
				V = 0;
			}
			else
				y += V;

			gc.clear();

			pict.draw(gc,W,H);
			pict.draw(gc,W,H-gc.get_height() );
			pict.draw(gc,W-gc.get_width(),H );
				H++ ;

			if( H > gc.get_height() ) H = 0;

			node.draw(gc, x, y);

			CL_String velocity = cl_format("Velocity U[%1] V[%2] --- Coordinate X[%3] Y[%4] --- Origin W[%5] H[%6]",U,V,x,y,W,H);
			font.draw_text(gc, gc.get_width()/2 - (velocity.length() * fntWidth)/2, 16, velocity);

			window.flip();
			CL_KeepAlive::process();
			CL_System::sleep(10);
		}
	}
Exemplo n.º 17
0
// The start of the Application
int App::start(const std::vector<CL_String> &args)
{
	quit = false;

	try
	{

		CL_OpenGLWindowDescription desc;

		desc.set_title("ClanLib AnimCursor Test");
		desc.set_size(CL_Size(800, 600), true);
		CL_DisplayWindow window(desc);

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

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

		// Get the graphic context
		CL_GraphicContext gc = window.get_gc();

		CL_Font font = CL_Font(gc, "Tahoma", 20);

		CL_PixelBuffer pacman("pacman.png");

		CL_SpriteDescription description;
		CL_Size size(22, 22);

		for (int frame_cnt=0; frame_cnt < 6; frame_cnt++)
		{
			CL_PixelBuffer frame(size.width, size.height, cl_rgba8);
			pacman.convert(frame, size, CL_Rect((frame_cnt * 28) + 4, 4, size));
			description.add_frame(frame);
			description.set_frame_delay(frame_cnt, 0.1);
		}

		CL_Point hotspot(0,0);
		CL_Cursor cursor(window, description, hotspot);
		window.set_cursor(cursor);

		// Run until someone presses escape
		while (!quit)
		{
			gc.clear(CL_Colorf(0.0f,0.0f,0.5f));

			font.draw_text(gc, 32, 32, "Observe the animated cursor");

			// 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
			CL_KeepAlive::process();
		}
	}
	catch(CL_Exception& exception)
	{
		// Create a console window for text-output if not available
		CL_ConsoleWindow console("Console", 80, 200);

		CL_Console::write_line("Exception caught:");
		CL_Console::write_line(exception.message);

		// Display the stack trace (if available)
		std::vector<CL_String> stacktrace = exception.get_stack_trace();
		int size = stacktrace.size();
		if (size > 0)
		{
			CL_Console::write_line("Stack Trace:");
			for (int cnt=0; cnt < size; cnt++)
			{
				CL_Console::write_line(stacktrace[cnt]);
			}
		}

		console.display_close_message();

		return -1;
	}
	return 0;
}
Exemplo n.º 18
0
// The start of the Application
int App::start(const std::vector<CL_String> &args)
{
	quit = false;

	// Create a console window for text-output if not available
	CL_ConsoleWindow console("Console");

	try
	{
		CL_DisplayWindow window("ClanLib Font Sprite Test", 1024, 480);

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

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

		// Get the graphic context
		CL_GraphicContext gc = window.get_gc();

		// Load some fonts from the resource file
		CL_ResourceManager resources("font.xml");
		CL_Font_Sprite font1(gc, "Font1", &resources);
		CL_Font_Sprite font2(gc, "Font2", &resources);

		// Run until someone presses escape
		while (!quit)
		{
			gc.set_map_mode(CL_MapMode(cl_map_2d_upper_left));
			gc.clear(CL_Colorf::red);

			font1.draw_text(gc, 25, 25, "ClanLib: Phear the Power!");
			
			font2.draw_text(gc, 3, 155, "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZzÆæØøÅå0123456789[]()!#$&%/\\=-+~'`\".,:;*?");

			font2.draw_text(gc, 10.0f, 200.0f, 2.0f, 2.0f, "Hello World\nMy Message");

			// 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
			CL_KeepAlive::process();
		}
	}
	catch(CL_Exception& exception)
	{
		CL_Console::write_line("Exception caught:");
		CL_Console::write_line(exception.message);

		// Display the stack trace (if available)
		std::vector<CL_String> stacktrace = exception.get_stack_trace();
		int size = stacktrace.size();
		if (size > 0)
		{
			CL_Console::write_line("Stack Trace:");
			for (int cnt=0; cnt < size; cnt++)
			{
				CL_Console::write_line(stacktrace[cnt]);
			}
		}

		console.display_close_message();

		return -1;
	}
	return 0;
}
Exemplo n.º 19
0
// The start of the Application
int App::start(const std::vector<CL_String> &args)
{
	quit = false;

	// Set the window
	CL_DisplayWindowDescription desc;
	desc.set_title("ClanLib Worker GC Example");
	desc.set_size(CL_Size(640, 480), true);
	desc.set_allow_resize(true);

	CL_DisplayWindow window(desc);
	CL_OpenGL::set_active(NULL);	//  wglCreateContextAttribsARB will fail if the shared context is current in a different thread.
	WorkerGC worker_gc;
	CL_System::sleep(200);	// Fixme

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

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

	// Get the graphic context
	CL_GraphicContext gc = window.get_gc();

	worker_gc.Start("../../../Examples/Game/DiceWar/Resources/lobby_background1.png");

	CL_Sprite spr_logo;

	float sin_count = 0.0f;
	float ypos = 0.0f;
	float ydir = 0.3f;

	unsigned int last_time = CL_System::get_time();

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

		if (!spr_logo.is_null())
		{
			gc.clear(CL_Colorf(0.0f,0.0f,0.2f));
			spr_logo.draw(gc, 
				(float) gc.get_width()-spr_logo.get_width(),
				(float) gc.get_height()-spr_logo.get_height());
		}
		else
		{
			gc.clear(CL_Colorf(0.5f,0.0f,0.0f));
		}

		// Move the lines
		ypos += ydir * time_delta_ms;
		if (ydir > 0.0f)
		{
			if ((ypos+200.0f) >= gc.get_height())
			{
				ypos = (float) (gc.get_height() - 200);
				ydir *= -1.0f;
			}
		}
		else
		{
			if (ypos <= 0.0f)
			{
				ypos = 0.0f;
				ydir *= -1.0f;
			}
		}
			
		CL_Draw::fill(gc, 0, ypos-1.0f, (float) gc.get_width(), ypos-8.0f,CL_Colorf(1.0f, 1.0f, 1.0f));
		CL_Draw::fill(gc, 0, ypos+198.0f, (float) gc.get_width(), ypos+190.0f, CL_Colorf(1.0f, 1.0f, 1.0f));


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

		if (worker_gc.IsReady())
		{
				spr_logo = worker_gc.Get();
		}

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



	}

	return 0;
}
Exemplo n.º 20
0
int GameRunner::main(const std::vector<CL_String> &args) {
  // Initialise clanlib by instanciating these classes.
  // when the get destroyed after scope goes away, they clean
  // themselves up (I think) so no need to deinitialise.
  // We never actually use these variables again.

  CL_SetupCore setup_core;
  CL_SetupDisplay setup_display;

  std::vector<CL_String> my_args = args;

  CL_String device = "GL";
  for(std::vector<CL_String>::iterator arg = my_args.begin(); arg != my_args.end(); ++arg) {
    CL_Console::write_line(*arg);
    if(*arg == "-d") {
      device = *++arg;
    }
  }

  CL_Console::write_line(device);


  // setup clanlib correctly (doesn't work)

  CL_SetupGL* setup_gl = 0;
  CL_SetupGL1* setup_gl1 = 0;
  CL_SetupSDL* setup_sdl = 0;
  CL_SetupGDI* setup_gdi = 0;

  if(device == "GL") {
     setup_gl = new CL_SetupGL();
  }
  if(device == "GL1") {
     setup_gl1 = new CL_SetupGL1();
  }
  if(device == "SDL") {
     setup_sdl = new CL_SetupSDL();
  }
  if(device == "GDI") {
     setup_gdi = new CL_SetupGDI();
  }


  // command line argument handling
  //CL_CommandLine argp;
  //argp.add_doc("Play Drillboy!");
  //argp.add_option('d', "device", "DEVICE", "Choose a device from GL1, GL, SDL or GDI");
  //argp.parse_args(args);

  //CL_SetupGL1 setup_gl1; // use gl1 as opengl2 target breaks for me
//  CL_SetupSDL setup_sdl; // use sdl as render target
  //CL_SetupGDI setup_gdi; // use gdi as render target
  //CL_SetupGL setup_gl;

  try {
    // Set the window description
    CL_DisplayWindowDescription desc;
    desc.set_title("Drillboy");
    desc.set_size(CL_Size(800, 600), true);

    // Lets actually make a window now called Drillboy 800x600
    CL_DisplayWindow window(desc);

    // Grab the graphics context so we have a handle to call
    // drawing functions on
    CL_GraphicContext graphics = window.get_gc();

    // Grab the keyboard so we can ask it about key presses
    CL_InputDevice keyboard = window.get_ic().get_keyboard();

    // Tell console (as in, text-based debug output) we are good to go
    CL_Console::write_line("ClanLib init complete...");

    // Before game loop begins, set screen to black via graphics context
    graphics.clear(CL_Colorf::black); // shortcut for CL_Colorf c(0,0,0)

    GameEngine engine(window, graphics, keyboard);

    bool running = true;

    // infinite loop to run the game
    while(running) {
      // Run the game engine
      running = engine.run();
    }

    if(setup_gl) delete setup_gl;
    if(setup_gl1) delete setup_gl1;
    if(setup_sdl) delete setup_sdl;
    if(setup_gdi) delete setup_gdi;

    // if we're this far, game finished running successfully, bye bye
    return 0;
  } catch(CL_Exception exception) {
    // output the exception's message
    CL_Console::write_line("ClanLib Exception caught:");
    CL_Console::write_line(exception.message);

    // Display the stack trace associated with the exception (it's an array of strings)
    std::vector<CL_String> stacktrace = exception.get_stack_trace();
    // if there is a stacktrace (because it has at least 1 line)
    // then iterate through the vector and output each line
    if (stacktrace.size() > 0) {
      CL_Console::write_line("Stack Trace:");
      for(std::vector<CL_String>::iterator line = stacktrace.begin();
          line != stacktrace.end(); ++line) {
        CL_Console::write_line(*line);
      }
    }

    return -1;
  }
}
Exemplo n.º 21
0
int DemoSimple::run(CL_DisplayWindow &window)
{
	quit = false;

	// Set the window
	window.set_title("LinearParticle Example - Simple ");

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

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

	// Get the graphic context
	CL_GraphicContext gc = window.get_gc();

	// initialize LinearParticle
	L_ParticleSystem::init();

	// create surface to be used for particle and set the alignment
	CL_Sprite surface(gc,"Resources/light16p.png");
	surface.set_alignment(origin_center);

	// create a sample of particle with life of 5000
	L_Particle particle(&surface,5000);

	// create dropping effect with period of 16
	L_DroppingEffect dropper(0,0,16);

	// add the particle to dropper effect
	dropper.add(&particle);

	// initialize particle effect
	dropper.initialize();

	float x_pos = 320;
	float y_pos = 240;
	float x_vel = 3.0f;
	float y_vel = 3.0f;

	CL_Font font(gc, "tahoma", 16 );

	FramerateCounter frameratecounter;

	// Run until someone presses escape
	while (!quit)
	{
		gc.clear();

		x_pos += x_vel;
		y_pos += y_vel;

		if( x_pos > 640 || x_pos < 0 )
			x_vel = -x_vel;

		if( y_pos > 480 || y_pos < 0 )
			y_vel = -y_vel;

		dropper.set_position(x_pos, y_pos);
			dropper.trigger();

		/* pass frame time to L_ParticleEffect::run(int) for time based system,
			a constant number would be a reference time unit for frame based system. */
		dropper.run(16);

		// draw dropping effect
		L_DrawParticle(gc,dropper);

		frameratecounter.show_fps(gc, font);
		window.flip(0);	// Set to "1" to lock to screen refresh rate
		frameratecounter.frame_shown();

		CL_KeepAlive::process(0);
	}

	// deinitialize LinearParticle
	L_ParticleSystem::deinit();

	return 0;
}
Exemplo n.º 22
0
	int start(const std::vector<CL_String> &args)
	{
		CL_ConsoleWindow console("Console");

		try
		{
			CL_DisplayWindow window("Image test", 1024, 768);
			CL_GraphicContext gc = window.get_gc();

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

			CL_BlendMode blend_mode1;
			blend_mode1.enable_blending(true);
			gc.set_blend_mode(blend_mode1);

			quit = false;

			CL_ResourceManager resources("resources.xml");

			CL_Texture texture(gc, "Images/square.png");

			CL_Image image_texture(gc, texture, CL_Rect(0, 0, texture.get_size()));
			CL_Image image_loaded(gc, "Images/square.png");
			CL_Image image_resources(gc, "entire_image", &resources);
			CL_Image image_copy(image_texture);
			CL_Image image_top_right(gc, "image_top_right", &resources);
			CL_Image image_bottom_right(gc, "image_bottom_right", &resources);
			CL_Image image_black(gc, "image_black", &resources);

			CL_Font small_font = CL_Font(gc, "Tahoma", 12);

			//CL_Console::write_line("Color: %1,%2,%3,%4", image_resources.get_color().r, image_resources.get_color().g, image_resources.get_color().b, image_resources.get_color().a);
			//CL_Console::write_line("Scale: %1,%2", image_resources.get_scale_x(), image_resources.get_scale_y());
			//CL_Console::write_line("Translation: %1,%2,%3", image_resources.get_alignment());

			while((!quit) && (!window.get_ic().get_keyboard().get_keycode(CL_KEY_ESCAPE)))
			{
				gc.clear(CL_Colorf(0.5f,0.5f,0.5f));

				small_font.draw_text(gc, 10, 40, "Image From Texture (10,60)");
				image_texture.draw(gc, 10, 60);

				small_font.draw_text(gc, 150, 40, "Image From Load (150,60)");
				image_loaded.draw(gc, 150, 60);

				small_font.draw_text(gc, 300, 40, "Image From Resources (300,60)");
				image_resources.draw(gc, 300, 60);

				small_font.draw_text(gc, 450, 40, "Image Copied (450,60)");
				image_copy.draw(gc, 450, 60);

				small_font.draw_text(gc, 10, 190, "Image - Top Right (10,200)");
				image_top_right.draw(gc, 10, 200);

				small_font.draw_text(gc, 150, 190, "Image - Top Right (150,200)");
				image_texture.draw(gc, CL_Rect(32, 0, CL_Size(32, 32)), CL_Rect(150, 200, CL_Size(32, 32)));

				small_font.draw_text(gc, 300, 190, "Image - Bottom Right (300,200)");
				image_bottom_right.draw(gc, 300, 200);

				small_font.draw_text(gc, 450, 190, "Image - Bottom Right (450,200)");
				image_texture.draw(gc, CL_Rect(32, 32, CL_Size(32, 32)), CL_Rect(450, 200, CL_Size(32, 32)));

				small_font.draw_text(gc, 10, 290, "700 Images (10,300)");
				for(int i=0;i<700;i++)
					image_texture.draw(gc, 10, 300);

				small_font.draw_text(gc, 150, 290, "br image (150,400) Size(128,256)");
				image_bottom_right.draw(gc, CL_Rect(150, 300, CL_Size(128, 256)));

				small_font.draw_text(gc, 300, 290, "Image - black");
				image_black.draw(gc, 300, 300);

				small_font.draw_text(gc, 300, 490, "Image - Scale (1.5, 2.5)");
				image_texture.set_scale(1.5f, 2.5f);
				image_texture.draw(gc, 300, 500);
				image_texture.set_scale(1.0f, 1.0f);

				small_font.draw_text(gc, 450, 460, "Image - Alignment (4 images with 8 pixel offset)");
				small_font.draw_text(gc, 450, 475, "(top left, top right, bottom left, bottom right)");
				small_font.draw_text(gc, 450, 490, "(Circle denotes the draw origin)");
				const int offset = 96;

				image_texture.set_alignment(origin_top_left, 8, 8);
				image_texture.draw(gc, 450+offset, 500+offset);
				image_texture.set_alignment(origin_top_right, -8, 8);
				image_texture.draw(gc, 450+offset, 500+offset);

				image_texture.set_alignment(origin_bottom_left, 8, -8);
				image_texture.draw(gc, 450+offset, 500+offset);
				image_texture.set_alignment(origin_bottom_right, -8, -8);
				image_texture.draw(gc, 450+offset, 500+offset);

				CL_Draw::circle(gc, 450+offset, 500+offset, 4, CL_Colorf(1.0f, 1.0f, 1.0f, 0.9f));

				small_font.draw_text(gc, 700, 460, "Image - Center Alignment (4 images with 8 pixel offset)");
				small_font.draw_text(gc, 700, 475, "(top center, right center, bottom center, left center)");
				small_font.draw_text(gc, 700, 490, "(Circle denotes the draw origin)");

				image_texture.set_alignment(origin_top_center, 0, 8);
				image_texture.draw(gc, 700+offset, 500+offset);
				image_texture.set_alignment(origin_bottom_center, 0, -8);
				image_texture.draw(gc, 700+offset, 500+offset);

				image_texture.set_alignment(origin_center_left, 8, 0);
				image_texture.draw(gc, 700+offset, 500+offset);
				image_texture.set_alignment(origin_center_right, -8, 0);
				image_texture.draw(gc, 700+offset, 500+offset);

				CL_Draw::circle(gc, 700+offset, 500+offset, 4, CL_Colorf(1.0f, 1.0f, 1.0f, 0.9f));

				small_font.draw_text(gc, 700, 160, "Image - Center Align (4 images with 64 pixel offset)");
				small_font.draw_text(gc, 700, 175, "Also Includes a centered image (Without offset)");
				small_font.draw_text(gc, 700, 190, "(Circle denotes the draw origin)");

				const int center_image_offset = 64;

				image_texture.set_alignment(origin_center, 0, 0);
				image_texture.draw(gc, 700+offset, 200+offset);

				image_texture.set_alignment(origin_center, 0, center_image_offset);
				image_texture.draw(gc, 700+offset, 200+offset);
				image_texture.set_alignment(origin_center, 0, -center_image_offset);
				image_texture.draw(gc, 700+offset, 200+offset);

				image_texture.set_alignment(origin_center, center_image_offset, 0);
				image_texture.draw(gc, 700+offset, 200+offset);
				image_texture.set_alignment(origin_center, -center_image_offset, 0);
				image_texture.draw(gc, 700+offset, 200+offset);

				CL_Draw::circle(gc, 700+offset, 200+offset, 4, CL_Colorf(1.0f, 1.0f, 1.0f, 0.9f));

				// Restore alignment
				image_texture.set_alignment(origin_top_left, 0, 0);

				dump_fps();

				window.flip(1);
				CL_KeepAlive::process();
			}

			return 0;
		}
		catch(CL_Exception error)
		{
			CL_Console::write_line("Exception caught:");
			CL_Console::write_line(error.message);
			console.display_close_message();

			return -1;
		}

		return 0;
	}