Ejemplo n.º 1
0
possible_end_play_signal playmp_controller::play_human_turn(){
	LOG_NG << "playmp::play_human_turn...\n";

	remove_blindfold();
	int cur_ticks = SDL_GetTicks();
	show_turn_dialog();

	if (!preferences::disable_auto_moves()) {
		HANDLE_END_PLAY_SIGNAL(execute_gotos());
	}

	if (!linger_ || is_host()) {
		end_turn_enable(true);
	}
	while(!end_turn_) {
		turn_info_send send_safe(turn_data_);
			config cfg;

			if(network_reader_.read(cfg)) {
				turn_info::PROCESS_DATA_RESULT res;
				HANDLE_END_PLAY_SIGNAL( res = turn_data_.process_network_data(cfg, skip_replay_) );
				//PROCESS_RESTART_TURN_TEMPORARY_LOCAL should be impossible because that's means the currently active side (that's us) left.
				if (res == turn_info::PROCESS_RESTART_TURN || res == turn_info::PROCESS_RESTART_TURN_TEMPORARY_LOCAL)
				{
					// Clean undo stack if turn has to be restarted (losing control)
					if ( undo_stack_->can_undo() )
					{
						font::floating_label flabel(_("Undoing moves not yet transmitted to the server."));

						SDL_Color color = {255,255,255,255};
						flabel.set_color(color);
						SDL_Rect rect = gui_->map_area();
						flabel.set_position(rect.w/2, rect.h/2);
						flabel.set_lifetime(150);
						flabel.set_clip_rect(rect);

						font::add_floating_label(flabel);
					}

					while( undo_stack_->can_undo() )
						undo_stack_->undo();

					end_turn_struct ets = {static_cast<unsigned>(gui_->playing_side())};
					return possible_end_play_signal(ets);
					//throw end_turn_exception(gui_->playing_side());
				}
				else if(res == turn_info::PROCESS_END_LINGER)
				{
					if(!linger_)
						replay::process_error("Received unexpected next_scenario durign the game");
					else
					{
						//we end the turn immidiately to prevent receiving data of the next scenario while we are not playing it.
						end_turn();
					}
				}
			}

			HANDLE_END_PLAY_SIGNAL( play_slice() );
			HANDLE_END_PLAY_SIGNAL( check_end_level() );

		if (!linger_ && (current_team().countdown_time() > 0) && saved_game_.mp_settings().mp_countdown) {
			SDL_Delay(1);
			const int ticks = SDL_GetTicks();
			int new_time = current_team().countdown_time()-std::max<int>(1,(ticks - cur_ticks));
			if (new_time > 0 ){
				current_team().set_countdown_time(new_time);
				cur_ticks = ticks;
				if(current_team().is_human() && !beep_warning_time_) {
					beep_warning_time_ = new_time - WARNTIME + ticks;
				}
				if(counting_down()) {
					think_about_countdown(ticks);
				}
			} else {
				// Clock time ended
				// If no turn bonus or action bonus -> defeat
				const int action_increment = saved_game_.mp_settings().mp_countdown_action_bonus;
				if ( (saved_game_.mp_settings().mp_countdown_turn_bonus == 0 )
					&& (action_increment == 0 || current_team().action_bonus_count() == 0)) {
					// Not possible to end level in MP with throw end_level_exception(DEFEAT);
					// because remote players only notice network disconnection
					// Current solution end remaining turns automatically
					current_team().set_countdown_time(10);
				}

				return possible_end_play_signal(end_turn_exception().to_struct());
				//throw end_turn_exception();
			}
		}

		gui_->draw();
	}
	return boost::none;
}
Ejemplo n.º 2
0
void jhi_delay_seconds(int seconds)
{
	SDL_Delay(seconds * 1000.0);
}
Ejemplo n.º 3
0
int main(int argc, const char * argv[])
{
    int i;
    char deviceName[128];
    
    if (init() != true)
    {
        return 1;
    }
    
    SDL_Delay(2000);
    
    // try to get the dispatch queue for the GPU
    dispatch_queue_t queue = gcl_create_dispatch_queue(CL_DEVICE_TYPE_GPU, NULL);
    
    // in the event that the system does not have an OpenCL GPU, we can use the CPU instead
    if (queue == NULL)
    {
        queue = gcl_create_dispatch_queue(CL_DEVICE_TYPE_CPU, NULL);
    }
    
    // let's print some data on the device we're usng! かわいいです!
    cl_device_id gpu = gcl_get_device_id_with_dispatch_queue(queue);
    clGetDeviceInfo(gpu, CL_DEVICE_NAME, 128, deviceName, NULL);
    fprintf(stdout, "Created a dispatch queue using the %s\n", deviceName);
    
    // let's hardcode some handy test data that's easy to understand
    float* test_in = (float*)malloc(sizeof(cl_float) * NUM_VALUES);
    for (i = 0; i < NUM_VALUES; i++)
    {
        test_in[i] = (cl_float)i;
    }
    
    // Once the computation using the CL is done, we'll need space in RAM for the output
    float* test_out = (float*)malloc(sizeof(cl_float) * NUM_VALUES);
    
    // Now we're going to allocate the buffers again in the OpenCL device's memory space
    // CL_MEM_COPY_HOST_PTR will copy the values of test_in to mem_in
    void* mem_in = gcl_malloc(sizeof(cl_float) * NUM_VALUES, test_in, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR);
    void* mem_out = gcl_malloc(sizeof(cl_float) * NUM_VALUES, NULL, CL_MEM_WRITE_ONLY);
    
    // DISPATCH THE KERNEL PROGRAM
    dispatch_sync(queue, ^{
        
        //workgroup size, I think
        size_t wgs;
        
        //information on sizing of dimensions
        gcl_get_kernel_block_workgroup_info(square_kernel, CL_KERNEL_WORK_GROUP_SIZE, sizeof(wgs), &wgs, NULL);
        cl_ndrange range = {
            1,
            {0, 0, 0},
            {NUM_VALUES, 0, 0},
            {wgs, 0, 0}
        };
        
        // call the kernel
        square_kernel(&range, (cl_float*)mem_in, (cl_float*)mem_out);
        
        //copy the output into memory
        gcl_memcpy(test_out, mem_out, sizeof(cl_float) * NUM_VALUES);
    });
Ejemplo n.º 4
0
void I_uSleep(unsigned long usecs)
{
    SDL_Delay(usecs/1000);
}
Ejemplo n.º 5
0
int main(int argc, char *argv[])
{
	auto t_start = std::chrono::high_resolution_clock::now();
	GLfloat directionx, directiony, directionz;
	directionx = 0.0f;
	directiony = 0.0f;
	directionz = 1.0f;
	GLboolean quit = GL_FALSE;
	GLenum errorValue;

	// Initialize SDL
	if (SDL_Init(SDL_INIT_VIDEO) < 0)
	{
		std::cerr << "SDL video initialization failed! Error: " << SDL_GetError() << std::endl;
		quit = GL_TRUE;
		SDL_Delay(5000);
	}
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
	SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
	SDL_Window* window = SDL_CreateWindow("OpenGL tutorial", 100, 100, width, height, SDL_WINDOW_OPENGL);
	SDL_GLContext context = SDL_GL_CreateContext(window);

	// Initialize GLEW
	glewExperimental = GL_TRUE;
	glewInit();
	
	// Error checking
	errorValue = glGetError();
	if (errorValue != 0)
	{
		std::cerr << "GL_Error after GLEW init: " << errorValue << std::endl;
	}
	
	// Create Vertex Array Objects, don't bind yet
	/*
	VAOs are used to store all of the links between the vertex attributes and VBOs with raw vertex data.
	Since VBOs are just containers for the raw data that the graphics card reads and manipulates,
	the meaning and usage of the data has to be specified for each VBO & shader program.
	This might be quite cumbersome, if many shader programs are used, since the layout of the attributes would
	have to be specified every time. This is wheree VAOs come in: they can be used to store the links between
	VBO and the specified attributes. This way, a new VAO can be bound for each different shader program,
	which can then be changed easily at will by just calling glUseProgram(shaderProg1);.
	The graphics card then knows how to use the raw data in the VBO, since its usage and meaning has been
	specified beforehand and the links between VBOs and attributes has been saved to the VAO.

	As soon as VAO has been bound, all glVertexAttribPointer calls store the information to that VAO.
	*/
	GLuint vaoCube, vaoQuad;
	glGenVertexArrays(1, &vaoCube);
	glGenVertexArrays(1, &vaoQuad);

	// Create a Vertex Buffer Objects and upload vertex data
	/*
	VBOs are used to upload the vertex data to the graphics card.
	glGenBuffers(); creates a VBO, which can then be made active by binding it
	with glBindBuffer();. When the VBO has been set as active by binding it,
	the vertex data can be loaded to it with glBufferData();.

	Note that VBO/OpenGL doesn't know what the data means or is used for, it's just raw data.
	The usage of the data has to be specified, meaning which indices in the data correspond to which
	attribute (pos, color, texcoord, etc.).
	*/
	GLuint vboCube, vboQuad;
	glGenBuffers(1, &vboCube);
	glGenBuffers(1, &vboQuad);

	glBindBuffer(GL_ARRAY_BUFFER, vboCube);
	glBufferData(GL_ARRAY_BUFFER, sizeof(cubeVertices), cubeVertices, GL_STATIC_DRAW);

	glBindBuffer(GL_ARRAY_BUFFER, vboQuad);
	glBufferData(GL_ARRAY_BUFFER, sizeof(quadVertices), quadVertices, GL_STATIC_DRAW);

	// Error checking
	errorValue = glGetError();
	if (errorValue != 0)
	{
		std::cerr << "GL_Error after VBOs: " << errorValue << std::endl;
	}

	// Generate shader programs
	GLuint sceneVertexShader, sceneFragmentShader, sceneShaderProgram;
	createShaderprogram(sceneVertexSource, sceneFragmentSource, sceneVertexShader, sceneFragmentShader, sceneShaderProgram);

	GLuint screenVertexShader, screenFragmentShader, screenShaderProgram;
	createShaderprogram(screenVertexSource, screenFragmentSource, screenVertexShader, screenFragmentShader, screenShaderProgram);

	// Error checking
	errorValue = glGetError();
	if (errorValue != 0)
	{
		std::cerr << "GL_Error after generating shader programs: " << errorValue << std::endl;
	}

	// Specify the layout of the vertex data (bind vertex arrays)
	/*
	Since OpenGL doesn't know how the attributes of the vertices are
	specified in the arrays containing the vertex information (position, color, texture coordinates),
	they need to be specified by the user.
	Each attribute also saves the VBO that's been bound to the current GL_ARRAY_BUFFER.
	This means different VBOs can be used for each attribute if so desired.

	Only calls after a VAO has been bound will "stick" to it.
	As soon as VAO has been bound, all glVertexAttribPointer calls store the information to that VAO.
	See more complete explanation of VAO above.
	*/
	glBindVertexArray(vaoCube);
	glBindBuffer(GL_ARRAY_BUFFER, vboCube);
	specifySceneVertexAttributes(sceneShaderProgram);

	glBindVertexArray(vaoQuad);
	glBindBuffer(GL_ARRAY_BUFFER, vboQuad);
	specifyScreenVertexAttributes(screenShaderProgram);

	// Error checking
	errorValue = glGetError();
	if (errorValue != 0)
	{
		std::cerr << "GL_Error after specifying the layout of vertex data: " << errorValue << std::endl;
	}

	// Load textures
	GLuint texKitten = loadTexture("sample.png");
	GLuint texPuppy = loadTexture("sample2.png");

	glUseProgram(sceneShaderProgram);
	glUniform1i(glGetUniformLocation(sceneShaderProgram, "texKitten"), 0);
	glUniform1i(glGetUniformLocation(sceneShaderProgram, "texPuppy"), 1);

	glUseProgram(screenShaderProgram);
	glUniform1i(glGetUniformLocation(screenShaderProgram, "texFramebuffer"), 0);

	GLint uniModel = glGetUniformLocation(sceneShaderProgram, "model");

	// Error checking
	errorValue = glGetError();
	if (errorValue != 0)
	{
		std::cerr << "GL_Error after loading textures: " << errorValue << std::endl;
	}

	// Create frame buffer
	GLuint frameBuffer;
	glGenFramebuffers(1, &frameBuffer);
	glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer);

	// Error checking
	errorValue = glGetError();
	if (errorValue != 0)
	{
		std::cerr << "GL_Error after creating a frame buffer: " << errorValue << std::endl;
	}

	// Create texture to hold color buffer
	GLuint texColorBuffer;
	glGenTextures(1, &texColorBuffer);
	glBindTexture(GL_TEXTURE_2D, texColorBuffer);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texColorBuffer, 0);

	// Error checking
	errorValue = glGetError();
	if (errorValue != 0)
	{
		std::cerr << "GL_Error after color buffer texture creation: " << errorValue << std::endl;
	}

	// Create Renderbuffer Object to hold depth and stencil buffers
	GLuint rboDepthStencil;
	glGenRenderbuffers(1, &rboDepthStencil);
	glBindRenderbuffer(GL_RENDERBUFFER, rboDepthStencil);
	glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height);
	glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rboDepthStencil);


	// Error checking
	errorValue = glGetError();
	if (errorValue != 0)
	{
		std::cerr << "GL_Error after RBO: " << errorValue << std::endl;
	}

	/*
	Set up projection:
	View matrix:
	First vector gives the position of the camera
	Second vector gives the point where the camera is centered or looking at
	Third vector defines "up", here up is the z-axis, xy-plane is the "ground"
	*/
	glm::mat4 view = glm::lookAt(
		glm::vec3(2.5f, 2.5f, 2.0f),
		glm::vec3(0.0f, 0.0f, 0.0f),
		glm::vec3(0.0f, 0.0f, 1.0f)
		);

	glUseProgram(sceneShaderProgram);

	GLint uniView = glGetUniformLocation(sceneShaderProgram, "view");
	glUniformMatrix4fv(uniView, 1, GL_FALSE, glm::value_ptr(view));

	// Projection matrix
	glm::mat4 proj = glm::perspective(glm::radians(45.0f), GLfloat(width) / GLfloat(height), 1.0f, 10.0f);
	GLint uniProj = glGetUniformLocation(sceneShaderProgram, "proj");
	glUniformMatrix4fv(uniProj, 1, GL_FALSE, glm::value_ptr(proj));

	GLint uniColor = glGetUniformLocation(sceneShaderProgram, "overrideColor");

	// Final error check will write errors (if any are encountered at this point) to file
	GLint status, status2, status3, status4, OpenGLError;
	OpenGLError = glGetError();
	GLenum frameBufferStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER);
	glGetShaderiv(sceneVertexShader, GL_COMPILE_STATUS, &status);
	glGetShaderiv(sceneFragmentShader, GL_COMPILE_STATUS, &status2);
	glGetShaderiv(screenVertexShader, GL_COMPILE_STATUS, &status3);
	glGetShaderiv(screenFragmentShader, GL_COMPILE_STATUS, &status4);

	if (
		OpenGLError != 0
		|| status == 0
		|| status2 == 0
		|| status3 == 0
		|| status4 == 0
		|| frameBufferStatus != GL_FRAMEBUFFER_COMPLETE)
	{
		char buffer1[512], buffer2[512], buffer3[512], buffer4[512];
		glGetShaderInfoLog(sceneVertexShader, 512, NULL, buffer1);
		glGetShaderInfoLog(sceneFragmentShader, 512, NULL, buffer2);
		glGetShaderInfoLog(screenVertexShader, 512, NULL, buffer3);
		glGetShaderInfoLog(screenFragmentShader, 512, NULL, buffer4);

		std::ofstream errorOutput;
		GLchar* errorOutFilename = "shader_errors.txt";
		errorOutput.open(errorOutFilename);
		
		errorOutput
			<< "GL_Error: " << OpenGLError
			<< "\n Scene vertex shader status: " << status
			<< "\n Scene vertex shader log: " << buffer1
			<< "\n Scene fragment shader status: " << status2
			<< "\n Scene fragment shader log: " << buffer2
			<< "\n Screen vertex shader status: " << status3
			<< "\n Screen vertex shader log: " << buffer3
			<< "\n Screen fragment shader status: " << status4
			<< "\n Screen fragment shader log: " << buffer4
			<< "\n Frame buffer status: " << frameBufferStatus
			<< "\n OpenGL version: " << glGetString(GL_VERSION);
		
		errorOutput.close();
		
		std::cerr << "An error has occured with shaders or frame buffer! See "
			<< errorOutFilename
			<< " for more info!\n Terminating program in 10s!"
			<< std::endl;

		SDL_Delay(10000);
		quit = GL_TRUE;
	}

	SDL_Event e;

	while (!quit)
	{
		while (SDL_PollEvent(&e) != 0)
		{
			if (e.type == SDL_QUIT)
			{
				quit = GL_TRUE;
			}
			else if (e.type == SDL_KEYDOWN)
			{
				switch (e.key.keysym.sym)
				{
				case SDLK_RETURN:
					directionx = 1.0f;
					directiony = 0.0f;
					directionz = 0.0f;
					break;
				case SDLK_SPACE:
					directionx = 0.0f;
					directiony = 1.0f;
					directionz = 0.0f;
					break;
				case SDLK_LCTRL:
					directionx = 0.0f;
					directiony = 0.0f;
					directionz = 1.0f;
				default:
					directionx = 0.0f;
					directiony = 0.0f;
					directionz = 1.0f;
					break;
				}
			}
		}

		// Bind framebuffer and draw 3D scene
		glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer);
		glBindVertexArray(vaoCube);
		glEnable(GL_DEPTH_TEST);
		glUseProgram(sceneShaderProgram);
		
		glActiveTexture(GL_TEXTURE0);
		glBindTexture(GL_TEXTURE_2D, texKitten);
		glActiveTexture(GL_TEXTURE1);
		glBindTexture(GL_TEXTURE_2D, texPuppy);

		// Clear screen to greenish
		glClearColor(0.15f, 0.7f, 0.5f, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		// Calculate transformation
		auto t_now = std::chrono::high_resolution_clock::now();
		float time = std::chrono::duration_cast<std::chrono::duration<float>>(t_now - t_start).count();
		
		glm::mat4 model;
		model = glm::rotate(model, time * glm::radians(180.f), glm::vec3(directionx, directiony, directionz));
		glUniformMatrix4fv(uniModel, 1, GL_FALSE, glm::value_ptr(model));

		// Draw cube
		glDrawArrays(GL_TRIANGLES, 0, 36);

		glEnable(GL_STENCIL_TEST);

		// Draw floor
		glStencilFunc(GL_ALWAYS, 1, 0xFF); // Set any stencil to 1
		glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
		glStencilMask(0xFF); // Write to stencil buffer
		glDepthMask(GL_FALSE); // Don't write to depth buffer
		glClear(GL_STENCIL_BUFFER_BIT); // Clear stencil buffer (0 by default)

		glDrawArrays(GL_TRIANGLES, 36, 6);

		// Draw cube reflection

		glStencilFunc(GL_EQUAL, 1, 0xFF); // Pass test if stencil value is 1
		glStencilMask(0x00); // Don't write anything to stencil buffer
		glDepthMask(GL_TRUE); // Write to depth buffer

		model = glm::scale(glm::translate(model, glm::vec3(0, 0, -1)), glm::vec3(1, 1, -1));
		glUniformMatrix4fv(uniModel, 1, GL_FALSE, glm::value_ptr(model));

		glUniform3f(uniColor, 0.3f, 0.3f, 0.3f);
		glDrawArrays(GL_TRIANGLES, 0, 36);
		glUniform3f(uniColor, 1.0f, 1.0f, 1.0f);

		glDisable(GL_STENCIL_TEST);

		// Bind default framebuffer and draw contents of our framebuffer
		glBindFramebuffer(GL_FRAMEBUFFER, 0);
		glBindVertexArray(vaoQuad);
		glDisable(GL_DEPTH_TEST);
		glUseProgram(screenShaderProgram);

		glActiveTexture(GL_TEXTURE0);
		glBindTexture(GL_TEXTURE_2D, texColorBuffer);

		glDrawArrays(GL_TRIANGLES, 0, 6);

		// Swap buffers
		SDL_GL_SwapWindow(window);
		
	}
	glDeleteRenderbuffers(1, &rboDepthStencil);
	glDeleteTextures(1, &texColorBuffer);
	glDeleteFramebuffers(1, &frameBuffer);
	
	glDeleteTextures(1, &texKitten);
	glDeleteTextures(1, &texPuppy);

	glDeleteProgram(screenShaderProgram);
	glDeleteShader(screenFragmentShader);
	glDeleteShader(screenVertexShader);

	glDeleteProgram(sceneShaderProgram);
	glDeleteShader(sceneFragmentShader);
	glDeleteShader(sceneVertexShader);

	glDeleteBuffers(1, &vboCube);
	glDeleteBuffers(1, &vboQuad);

	glDeleteVertexArrays(1, &vaoCube);
	glDeleteVertexArrays(1, &vaoQuad);

	SDL_GL_DeleteContext(context);
	SDL_Quit();
	return 0;
}
Ejemplo n.º 6
0
void run(){
	
	SDL_Window* window;
	SDL_Renderer* renderer;
	SDL_Surface* temp;
	SDL_Texture* tbullet;
	SDL_Event e;
	int i, quit = 0;
	Bullet* bulletarray[MAXBULLETS];
	unsigned int lastshooting = 0;
	
	/* Initialise generic */
	SDL_Init(SDL_INIT_EVERYTHING);
	window = SDL_CreateWindow("Shoot", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_SHOWN);
	renderer = SDL_CreateRenderer(window, -1, 0);
	SDL_SetRenderDrawColor(renderer, 90, 90, 90, 0);
	
	temp = SDL_LoadBMP("bullet.bmp");
	tbullet = SDL_CreateTextureFromSurface(renderer, temp);
	SDL_FreeSurface(temp);
	temp = NULL;
	
	/* Initialise bulletarray */
	for(i = 0; i < MAXBULLETS ; i++){
		bulletarray[i] = NULL;
	}
	
	/* Event loop */
	do{
		SDL_PollEvent(&e);
		if(e.type == SDL_QUIT){
			quit = 1;
		}
		
		/* Fire bullet from centre*/
		if(e.type == SDL_MOUSEBUTTONDOWN){
			if(e.button.button == SDL_BUTTON_LEFT && (SDL_GetTicks() - lastshooting) > TIMEBETWEENSHOOT){
				for(i = 0; i <MAXBULLETS; i++){
					if(bulletarray[i] == NULL){
						bulletarray[i] = createbullet((WIDTH-BULLETSIZE)/2, (HEIGHT-BULLETSIZE)/2);
						i = MAXBULLETS;
					}
				}
				lastshooting = SDL_GetTicks();
			}
		}
		
		deletebulletatboundary(bulletarray);		
		bulletmovement(bulletarray);
		
		/* Update Screen */
		SDL_RenderClear(renderer);
		renderbullets(renderer, tbullet, bulletarray);
		SDL_RenderPresent(renderer);
		SDL_Delay(20);
		
	}while(quit == 0);
	
	/* Memory Cleanup */
	SDL_DestroyTexture(tbullet);
	SDL_DestroyRenderer(renderer);
	SDL_DestroyWindow(window);
	tbullet = NULL;
	renderer = NULL;
	window = NULL;
	SDL_Quit();
}
Ejemplo n.º 7
0
// This is how we're actually going to handle input events, SDL getch
// is simply a wrapper around this.
input_event input_manager::get_input_event(WINDOW *win) {
    // standards note: getch is sometimes required to call refresh
    // see, e.g., http://linux.die.net/man/3/getch
    // so although it's non-obvious, that refresh() call (and maybe InvalidateRect?) IS supposed to be there

    if(win == NULL) win = mainwin;

    wrefresh(win);
    lastchar=ERR;//ERR=-1
    input_event rval;

    if (inputdelay < 0)
    {
        do
        {
            rval.type = CATA_INPUT_ERROR;
            CheckMessages();
            if (lastchar!=ERR) break;
            SDL_Delay(1);
        }
        while (lastchar==ERR);
    }
    else if (inputdelay > 0)
    {
        unsigned long starttime=SDL_GetTicks();
        unsigned long endtime;
        bool timedout = false;
        do
        {
            rval.type = CATA_INPUT_ERROR;
            CheckMessages();
            endtime=SDL_GetTicks();
            if (lastchar!=ERR) break;
            SDL_Delay(1);
            timedout = endtime >= starttime + inputdelay;
            if (timedout) {
                rval.type = CATA_INPUT_TIMEOUT;
            }
        }
        while (!timedout);
    }
    else
    {
        CheckMessages();
    }

    if (rval.type != CATA_INPUT_TIMEOUT) {
        if (lastchar == ERR) {
            rval.type = CATA_INPUT_ERROR;
        } else if (lastchar_isbutton) {
            rval.type = CATA_INPUT_GAMEPAD;
            rval.add_input(lastchar);
        } else if (lastchar_is_mouse) {
            rval.type = CATA_INPUT_MOUSE;
            rval.add_input(lastchar);
            SDL_GetMouseState(&rval.mouse_x, &rval.mouse_y);
        } else {
            rval.type = CATA_INPUT_KEYBOARD;
            rval.add_input(lastchar);
        }
    }

    return rval;
}
Ejemplo n.º 8
0
int main(int argc, char *argv[])
{
	/* Initialize SDL */
	if ( SDL_Init(SDL_INIT_VIDEO) < 0 ) {
		fprintf(stderr, "Couldn't initialize SDL: %s\n",SDL_GetError());
		return(1);
	}

	/* Alpha blending doesn't work well at 8-bit color */
#ifdef _WIN32_WCE
	/* Pocket PC */
	w = 240;
	h = 320;
#else
	w = 640;
	h = 480;
#endif
	info = SDL_GetVideoInfo();
	if ( info->vfmt->BitsPerPixel > 8 ) {
		video_bpp = info->vfmt->BitsPerPixel;
	} else {
		video_bpp = 16;
                fprintf(stderr, "forced 16 bpp mode\n");
	}
	videoflags = SDL_SWSURFACE;
	for ( i = 1; argv[i]; ++i ) {
		if ( strcmp(argv[i], "-bpp") == 0 ) {
			video_bpp = atoi(argv[++i]);
                        if (video_bpp<=8) {
                            video_bpp=16;
                            fprintf(stderr, "forced 16 bpp mode\n");
                        }
		} else
		if ( strcmp(argv[i], "-hw") == 0 ) {
			videoflags |= SDL_HWSURFACE;
		} else
		if ( strcmp(argv[i], "-warp") == 0 ) {
			videoflags |= SDL_HWPALETTE;
		} else
		if ( strcmp(argv[i], "-width") == 0 && argv[i+1] ) {
			w = atoi(argv[++i]);
		} else
		if ( strcmp(argv[i], "-height") == 0 && argv[i+1] ) {
			h = atoi(argv[++i]);
		} else
		if ( strcmp(argv[i], "-resize") == 0 ) {
			videoflags |= SDL_RESIZABLE;
		} else
		if ( strcmp(argv[i], "-noframe") == 0 ) {
			videoflags |= SDL_NOFRAME;
		} else
		if ( strcmp(argv[i], "-fullscreen") == 0 ) {
			videoflags |= SDL_FULLSCREEN;
		} else {
			fprintf(stderr, 
			"Usage: %s [-width N] [-height N] [-bpp N] [-warp] [-hw] [-fullscreen]\n",
								argv[0]);
			quit(1);
		}
	}

	/* Set video mode */
	if ( (screen=SDL_SetVideoMode(w,h,video_bpp,videoflags)) == NULL ) {
		fprintf(stderr, "Couldn't set %dx%dx%d video mode: %s\n",
						w, h, video_bpp, SDL_GetError());
		quit(2);
	}
	FillBackground(screen);

	/* Create the light */
	light = CreateLight(82);
	if ( light == NULL ) {
		quit(1);
	}

	/* Load the sprite */
	if ( LoadSprite(screen, "icon.bmp") < 0 ) {
		SDL_FreeSurface(light);
		quit(1);
	}

	/* Print out information about our surfaces */
	printf("Screen is at %d bits per pixel\n",screen->format->BitsPerPixel);
	if ( (screen->flags & SDL_HWSURFACE) == SDL_HWSURFACE ) {
		printf("Screen is in video memory\n");
	} else {
		printf("Screen is in system memory\n");
	}
	if ( (screen->flags & SDL_DOUBLEBUF) == SDL_DOUBLEBUF ) {
		printf("Screen has double-buffering enabled\n");
	}
	if ( (sprite->flags & SDL_HWSURFACE) == SDL_HWSURFACE ) {
		printf("Sprite is in video memory\n");
	} else {
		printf("Sprite is in system memory\n");
	}

	/* Run a sample blit to trigger blit acceleration */
	MoveSprite(screen, NULL);
	if ( (sprite->flags & SDL_HWACCEL) == SDL_HWACCEL ) {
		printf("Sprite blit uses hardware alpha acceleration\n");
	} else {
		printf("Sprite blit dosn't uses hardware alpha acceleration\n");
	}

	/* Set a clipping rectangle to clip the outside edge of the screen */
	{ SDL_Rect clip;
		clip.x = 32;
		clip.y = 32;
		clip.w = screen->w-(2*32);
		clip.h = screen->h-(2*32);
		SDL_SetClipRect(screen, &clip);
	}

	/* Wait for a keystroke */
	lastticks = SDL_GetTicks();
	done = 0;
	mouse_pressed = 0;
#ifndef EMSCRIPTEN
	while ( !done ) {
#else
	emscripten_run_script("report(true);");
	emscripten_set_main_loop(&main_loop, 30, 1);
}

void main_loop() {
#endif
		/* Update the frame -- move the sprite */
		if ( mouse_pressed ) {
			MoveSprite(screen, light);
			mouse_pressed = 0;
		} else {
			MoveSprite(screen, NULL);
		}

#ifndef EMSCRIPTEN
		/* Slow down the loop to 30 frames/second */
		ticks = SDL_GetTicks();
		if ( (ticks-lastticks) < FRAME_TICKS ) {
#ifdef CHECK_SLEEP_GRANULARITY
fprintf(stderr, "Sleeping %d ticks\n", FRAME_TICKS-(ticks-lastticks));
#endif
			SDL_Delay(FRAME_TICKS-(ticks-lastticks));
#ifdef CHECK_SLEEP_GRANULARITY
fprintf(stderr, "Slept %d ticks\n", (SDL_GetTicks()-ticks));
#endif
		}
		lastticks = ticks;
#endif

		/* Check for events */
		while ( SDL_PollEvent(&event) ) {
			switch (event.type) {
				case SDL_VIDEORESIZE:
					screen = SDL_SetVideoMode(event.resize.w, event.resize.h, video_bpp, videoflags);
					if ( screen ) {
						FillBackground(screen);
					}
					break;
				/* Attract sprite while mouse is held down */
				case SDL_MOUSEMOTION:
					if (event.motion.state != 0) {
						AttractSprite(event.motion.x,
								event.motion.y);
						mouse_pressed = 1;
					}
					break;
				case SDL_MOUSEBUTTONDOWN:
					if ( event.button.button == 1 ) {
						AttractSprite(event.button.x,
						              event.button.y);
						mouse_pressed = 1;
					} else {
						SDL_Rect area;

						area.x = event.button.x-16;
						area.y = event.button.y-16;
						area.w = 32;
						area.h = 32;
						SDL_FillRect(screen, &area, 0);
						SDL_UpdateRects(screen,1,&area);
					}
					break;
				case SDL_KEYDOWN:
#ifdef _WIN32_WCE
					// there is no ESC key at all
					done = 1;
#else
					if ( event.key.keysym.sym == SDLK_ESCAPE ) {
						done = 1;
					} else if (event.key.keysym.sym == SDLK_t) {
						videoflags ^= SDL_FULLSCREEN;
						screen = SDL_SetVideoMode(w, h, video_bpp, videoflags);
						if ( screen == NULL ) {
							fprintf(stderr, "Couldn't toggle video mode: %s\n",
									SDL_GetError());
							quit(2);
						}
						FillBackground(screen);
					}
#endif

					break;
				case SDL_QUIT:
					done = 1;
					break;
				default:
					break;
			}
		}

#ifndef EMSCRIPTEN
	}
	
	SDL_FreeSurface(light);
	SDL_FreeSurface(sprite);
	SDL_FreeSurface(backing);

	/* Print out some timing information */
	if ( flashes > 0 ) {
		printf("%d alpha blits, ~%4.4f ms per blit\n", 
			flashes, (float)flashtime/flashes);
	}
	
	SDL_Quit();
	return(0);
#else
	if(done) {
		SDL_FreeSurface(light);
		SDL_FreeSurface(sprite);
		SDL_FreeSurface(backing);

		/* Print out some timing information */
		if ( flashes > 0 ) {
			printf("%d alpha blits, ~%4.4f ms per blit\n", 
				flashes, (float)flashtime/flashes);
		}
		
		SDL_Quit();
	}
#endif
}
Ejemplo n.º 9
0
void Sys_Sleep(void)
{
    SDL_Delay(1);
}
Ejemplo n.º 10
0
/*
====================================================================
Display a info message (gray screen a bit and display text), 
send a MSG_READY when player has clicked and wait for a remote answer
(timeout 10 secs). Waiting may be cancelled by pressing ESCAPE which
results in sending a MSG_GAME_EXITED.
Return Value: True if both peers clicked to continue, False if the
connection was cancelled for some reason.
====================================================================
*/
int display_info( StkFont *font, char *str, NetSocket *peer )
{
#if 0
    char error[128];
    Net_Msg msg;
    SDL_Event event;
    int ret = 0, leave = 0;
    SDL_Surface *buffer = 
        stk_surface_create( SDL_SWSURFACE, stk_display->w, stk_display->h );
    SDL_SetColorKey(buffer, 0, 0);

#ifdef AUDIO_ENABLED
    stk_sound_play( wav_click );
#endif

    event_clear_sdl_queue();

    stk_surface_blit( stk_display, 0,0,-1,-1, buffer, 0,0 );
	draw_confirm_screen( font, buffer, str );
    stk_display_update( STK_UPDATE_ALL );
    stk_wait_for_input();
    net_write_empty_msg( peer, MSG_READY ); 
	draw_confirm_screen( font, buffer, 
                         _("Waiting for remote answer...") );
    stk_display_update( STK_UPDATE_ALL );
    event_clear_sdl_queue();
    while ( !leave ) {
        if ( SDL_PollEvent( &event ) )
            if ( (event.type == SDL_KEYDOWN && 
                 event.key.keysym.sym == SDLK_ESCAPE) ||
                 event.type == SDL_QUIT ) {
                    net_write_empty_msg( peer, MSG_GAME_EXITED );
                    leave = 1;
                    break;
                }
        if ( net_read_msg( peer, &msg, 0 ) )
            switch ( msg.type ) {
                case MSG_READY:
                    ret = 1; leave = 1;
                    break;
                case MSG_GAME_EXITED:
                    ret = 0; leave = 1;
                    sprintf( error, /* xgettext:no-c-format */ _("remote player cancelled the game\n") );
                    confirm( font, error, CONFIRM_ANY_KEY );
                    break;
            }
        SDL_Delay( 10 );
    }
    
#ifdef AUDIO_ENABLED
    stk_sound_play( wav_click );
#endif
    
    stk_surface_blit( buffer, 0,0,-1,-1, stk_display, 0,0 );
    stk_display_update( STK_UPDATE_ALL );
    SDL_FreeSurface(buffer);
    
    /* reset the relative position so paddle wont jump */
    SDL_GetRelativeMouseState(0,0);

    return ret;
#endif
    return 1;
}
Ejemplo n.º 11
0
int decode_thread( void *thread_arg )
{
  VideoState *is = (VideoState *) thread_arg;
  AVFormatContext *pFormatCtx;
  AVPacket pkt1, *packet = &pkt1;
  //global_video_state = is;
  url_set_interrupt_cb(decode_interrupt_cb); // will interrupt blocking functions if we quit!

//  is->filename[0] = *"./foo.mkv";
  strcpy(is->filename, "./foo.mkv");

  int i;
  //AVCodecContext *pCodecCtx;
  //AVCodecContext *aCodecCtx;

  // Open video file
  if( av_open_input_file(&pFormatCtx, is->filename, NULL, 0, NULL) != 0 )
    return -1; // Couldn't open file
  is->pFormatCtx = pFormatCtx;

  // Retrieve stream information
  if(av_find_stream_info(pFormatCtx)<0)
    return -1; // Couldn't find stream information

  // Dump information about file onto standard error
  //dump_format(pFormatCtx, 0, is->filename, 0);

  // Find the video stream and audio stream
  int videoStream = -1;
  int audioStream = -1;
  is->videoStream = -1;
  is->audioStream = -1;
  for( i=0; i<pFormatCtx->nb_streams; i++ )
  {
    if( pFormatCtx->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO ) {
      videoStream = i;
    }
    if( pFormatCtx->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO && audioStream < 0 ) {
      audioStream = i;
    }
  }

  if(videoStream == -1)
    return -1; // Didn't find a video stream
  if(audioStream == -1)
    printf( "No audio stream\n" );
  else
    stream_component_open( is, audioStream );

  stream_component_open( is, videoStream );

  if(is->videoStream < 0 ) {
    fprintf(stderr, "%s: could not open codecs\n", is->filename);
    goto fail;
  } 

  // Decode loop
  for(;;) {
    if(is->quit) {
      break;
    }
    if(is->audioq.size > MAX_AUDIOQ_SIZE ||
       is->videoq.size > MAX_VIDEOQ_SIZE) {
      SDL_Delay(10);
      continue;
    }
/*
    if( av_read_frame(is->pFormatCtx, packet) < 0 ) {
      if( url_ferror((ByteIOContext *)&pFormatCtx->pb) == 0 ) {
        SDL_Delay(100); // no error; wait for user input
        continue;
      } else {
        break;
      }
    }

    // Queue the packets into the right queue
    if(packet->stream_index == is->videoStream) {
      packet_queue_put(&is->videoq, packet);
    } else if(packet->stream_index == is->audioStream) {
      packet_queue_put(&is->audioq, packet);
    } else {
      av_free_packet(packet);
    }
*/
  }

  while(!is->quit) {
    SDL_Delay(100);
  }

 fail:
  if(1){
    SDL_Event event;
    event.type = FF_QUIT_EVENT;
    event.user.data1 = is;
    SDL_PushEvent(&event);
  }
  return 0;

} // End decode_thread()
Ejemplo n.º 12
0
void main (){
    // Initialize everything
    if (SDL_Init(SDL_INIT_AUDIO) < 0) {
	fprintf(stderr, "Couldn't initialize SDL (%s)\n", SDL_GetError());
	exit(1);
    }
    atexit(quit);

    //    SDL_PauseAudio(false);

    //InitAll(1, "./be");

    cSIDInit();
    unsigned int now = 0;
    //    sid_write(uint32 adr, uint32 byte, cycle_t now, bool rmw);
  csid_write(0,0xd6, now, 123);
  now+=5;  
csid_write(1,0x1c, now, 123);
  now+=5;  
  csid_write(7,0x55, now, 123);
  now+=5;  
  csid_write(8,0x24, now, 123);
  now+=5;  
  csid_write(4,0x11, now, 123);
  now+=5;  
  csid_write(11,0x11, now, 123);
  SDL_Delay(1000);
  csid_write(4,0x10, now, 123);
  now+=5;  
  csid_write(11,0x10, now, 123);
  SDL_Delay(1000);


  csid_write(5,0xa8, now, 123);
  now+=5;  
  csid_write(6,0xff, now, 123);
  now+=5;  
  csid_write(12,0xa8, now, 123);
  now+=5;  
  csid_write(13,0xFF, now, 123);	

  now+=5;  
  csid_write(4,0x11, now, 123);
  now+=5;  
  csid_write(11,0x11, now, 123);
  SDL_Delay(1000);
  csid_write(4,0x10, now, 123);
  now+=5;  
  csid_write(11,0x10, now, 123);
  SDL_Delay(1000);


    while (true) {
	SDL_Event e;
	if (SDL_WaitEvent(&e)) {
	    if (e.type == SDL_QUIT)
		break;
	}
    }

    //    SIDInit()  ->  void SIDCalcBuffer(uint8 *buf, int count) -> calc_buffer ->	desired.callback = calc_buffer;
    //    ExitAll();
    cSIDExit();
    //    makefile: #define  SID_PLAYER 0
    //    make CFLAGS=-DMACRO
}
Ejemplo n.º 13
0
Archivo: main.cpp Proyecto: HuiD/ece590
int menu(SDL_Surface * screen) {
    SDL_Event event;
    Background * menuBackground = new Background("img/menu/menu.bmp");
    menuBackground->setCoords(0,0);
    Background * arrow = new Background("img/menu/arrow.bmp");
    menuMusic = Mix_LoadMUS("sound/menubgm.wav");
    menuSFX = Mix_LoadWAV("sound/arrow.wav");
    int arrowX = 250;
    int arrowY = 515;
    arrow->setCoords(arrowX,arrowY);
    int arrowPos = 0;
    int step = 83;
    while(1) {
        int stage;
        while (SDL_PollEvent(&event)) {
            switch (event.type) {
            case SDL_KEYDOWN:
                stage = handle_menu_key(event.key.keysym.sym, arrowPos);
                break;
            case SDL_KEYUP:
                stage = handle_menu_keyup(event.key.keysym.sym, arrowPos);
                break;
            }
            if (stage == EXIT) {
                delete menuBackground;
                delete arrow;
                Mix_FreeChunk(menuSFX);
                Mix_HaltMusic();
                Mix_FreeMusic(menuMusic);
                menuMusic = NULL;
                return EXIT;

            }
            else if (stage == MULTIPLE) {
                delete menuBackground;
                delete arrow;
                Mix_FreeChunk(menuSFX);
                Mix_HaltMusic();
                Mix_FreeMusic(menuMusic);
                menuMusic = NULL;
                return MULTIPLE;

            }

        }

        arrow->setCoords(arrowX, arrowY+arrowPos*step);
        menuBackground->setCoords(0,0);

        menuBackground->blit(screen);
        arrow->blit(screen);

        if (Mix_PlayingMusic() == 0) {
            if (Mix_PlayMusic(menuMusic, -1) == -1)
                fprintf(stderr, "Unable to play WAV file: %s\n", Mix_GetError());
        }

        SDL_Flip(screen);

        SDL_Delay(10);
    }
    return 0;
}
Ejemplo n.º 14
0
Archivo: main.cpp Proyecto: HuiD/ece590
int eventLoop(SDL_Surface * screen) {
    SDL_Event event;
    int animationCounter = 0;
    while(1) {
        while (SDL_PollEvent(&event)) {
            switch (event.type) {
            case SDL_KEYUP:
                if(handle_keyup(event.key.keysym.sym)==MENU) {
                    gameLoopCleanUp();
                    return MENU;
                }
                break;
            case SDL_KEYDOWN:
                handle_key(event.key.keysym.sym);
                break;
            }


        }

        handleNetwork();

        std::map<int, Hero*>::iterator it;
        for(it=heroGroup.begin(); it!=heroGroup.end(); ++it)
        {
            if (it->second->getVisible())
                it->second->update(blocks, colList, heroGroup, bombGroup, explosionGroup);
        }
        if(moved) {
            hero_pos newPos=heroGroup[myId]->getPos();
            heromessage msg;
            msg.LoadByte(newPos.x, newPos.y, newPos.id);
            udpclient->Send(msg,tcpclient->getIpAddress() ,-1);
            moved=false;
        }
        if(bombed)
        {
            int bombx, bomby, level;
            bombx=heroGroup[myId]->getBombx();
            bomby=heroGroup[myId]->getBomby();
            level=heroGroup[myId]->getBombLevel();
            bombmessage bmsg;
            bmsg.LoadByte(bombx, bomby, level);
            udpclient->Send(bmsg, tcpclient->getIpAddress(), -1);
            bombed=false;
        }
        for (int i = 0; i < blocks.size(); i++) {
            blocks[i]->update(colList, heroGroup, explosionGroup, upgradeGroup);
        }

        for (int i = 0; i < bombGroup.size(); i++) {
            bombGroup.at(i)->update(blocks, colList, heroGroup, bombGroup, explosionGroup);
        }
        for (int i = 0; i < explosionGroup.size(); i++) {
            explosionGroup.at(i)->update();
        }
        for (int i = 0; i < upgradeGroup.size(); i++) {
            upgradeGroup.at(i)->update();
        }

        for (int i = 0; i < colList.size(); i++) {
            CollisionPair * tmp = colList.at(i);
            if (tmp->isCollided()) {
                tmp->onCollision();
            }
        }

        background->blit(screen);

        if (Mix_PlayingMusic() == 0) {
            if (Mix_PlayMusic(mainMusic, -1) == -1)
                fprintf(stderr, "Unable to play WAV file: %s\n", Mix_GetError());
        }

        for (int j = 0; j < bombGroup.size(); j++) {
            bombGroup.at(j)->blit(screen);
        }
        for (int j = 0; j < explosionGroup.size(); j++) {
            SDL_Rect tmp = explosionGroup.at(j)->getShowPart();
            explosionGroup.at(j)->blit(screen, &tmp);
        }
        for (int i = 0; i < blocks.size(); i++) {
            blocks.at(i)->blit(screen);
        }

        for (int i = 0; i < upgradeGroup.size(); i++) {
            upgradeGroup.at(i)->blit(screen);
        }
        for(map<int, Hero* >::iterator it=heroGroup.begin(); it!=heroGroup.end(); ++it) {
            it->second->blit(screen);
        }

        for(map<int, Hero* >::iterator it=heroGroup.begin(); it!=heroGroup.end(); ++it) {
            sprintf(textbuf[it->first], "Player %d = %d", it->first+1, it->second->getLife());
            text_image[it->first] =  TTF_RenderText_Solid(text_font, textbuf[it->first], font_color);
            int offsetX = it->first<2 ? 0:1;
            int offsetY = it->first%2==0 ? 0:1;
            textDest[it->first].x = 50+750*offsetX;
            textDest[it->first].y = 10+50*offsetY;
            textDest[it->first].w = text_image[it->first]->w;
            textDest[it->first].h = text_image[it->first]->h;
            SDL_BlitSurface(text_image[it->first], NULL, screen, &(textDest[it->first]));
            SDL_FreeSurface(text_image[it->first]);
        }


        // game over
        bool iWin = false;
        if (heroGroup[myId]->getLife()!=0) {
            iWin = true;
            for(map<int, Hero* >::iterator it=heroGroup.begin(); it!=heroGroup.end(); ++it) {
                if (it->first != myId) {
                    if (it->second->getLife() != 0) {
                        iWin = false;
                        break;
                    }
                }
            }
        }
        bool iLose=false;
        if (heroGroup[myId]->getLife()==0) {
            iLose = true;
            int counter = 0;
            for(map<int, Hero* >::iterator it=heroGroup.begin(); it!=heroGroup.end(); ++it) {
                if (it->first != myId) {
                    if (it->second->getLife() != 0) {
                        counter++;
                        if (counter>1) {
                            iLose = false;
                            break;
                        }
                    }
                }
            }
        }

        if (iWin) {
            animationCounter++;
            if (animationCounter>20) {
                winScreen->blit(screen);
                SDL_Flip(screen);
                SDL_Delay(3000);
                gameLoopCleanUp();
                return MENU;
            }
        }
        else if (iLose) {
            animationCounter++;
            if (animationCounter>20) {
                loseScreen->blit(screen);
                SDL_Flip(screen);
                SDL_Delay(3000);
                gameLoopCleanUp();
                return MENU;
            }
        }

        /* since its double buffered, make
         the changes show up*/
        SDL_Flip(screen);

        SDL_Delay(50);
    }
    return 0;
}
Ejemplo n.º 15
0
int main ( int argc, char** argv )
{
    // initialize SDL video
    if ( SDL_Init( SDL_INIT_VIDEO ) < 0 )
    {
        printf( "Unable to init SDL: %s\n", SDL_GetError() );
        return 1;
    }

    // make sure SDL cleans up before exit
    atexit(SDL_Quit);

    // create a new window
    SDL_Surface* screen = SDL_SetVideoMode(800, 600, 24,
                                           SDL_SWSURFACE);
    if ( !screen )
    {
        printf("Unable to set 640x480 video: %s\n", SDL_GetError());
        return 1;
    }

    SDL_WM_SetCaption("Raw Viewer","Raw Viewer");

    // load an image
    SDL_Surface* buffer = SDL_CreateRGBSurface(SDL_SWSURFACE,600,524,32,0,0,0,0);

    fl=fopen(argv[1],"rb");
    fseek(fl,0,SEEK_END);
    Max=ftell(fl);

    Render(buffer,rejim,WIDT,HIGH,DX);


    // program main loop
    bool done = false;
    while (!done)
    {
        // message processing loop
        FlushHits();
        SDL_Event event;
        while (SDL_PollEvent(&event))
        {
            // check for messages
            switch (event.type)
            {
                // exit if the window is closed
            case SDL_QUIT:
                done = true;
                break;

                // check for keypresses
            case SDL_KEYDOWN:
            {
                SetHit(event.key.keysym.sym);
                break;
            }
            } // end switch
        } // end of message processing
        UpdateKeyboard();

        // DRAWING STARTS HERE

        if (KeyDown(SDLK_ESCAPE))
            done=true;


        // clear screen
        SDL_FillRect(screen, 0, SDL_MapRGB(screen->format, 0, 0, 0));

        SDL_BlitSurface(buffer,0,screen,0);

        lineColor(screen,0,524,600,524,0xFFFFFFFF);
        lineColor(screen,600,0,600,524,0xFFFFFFFF);

        char buf[255];
        sprintf(buf,"Offset:%X",Offs);
        stringColor(screen,700,10,buf,0xFFFFFFFF);
        sprintf(buf,"Width:%d",WIDT);
        stringColor(screen,700,20,buf,0xFFFFFFFF);

        rectangleColor(screen,663,7,670,509,0xFF0000FF);
        FillRect(screen,665,9,4,501*(Offs/(float)Max),0x00FF00);//rectangleColor(screen,664,8,669,8+500*Offs/Max,0x00FF00FF);
        if (WIDT>150)
        {
            rectangleColor(screen,9,549,511,556,0xFF0000FF); //Rect  9,549,502,7,0
            FillRect(screen,10,550,500*DX/(WIDT-150),5,0x00FF00);//	Rect  10,550,500*(Float(DX)/Float(widt-150)),5,1
        }

        switch (rejim)
        {
        case 1:
            sprintf(buf,"1 Bit mode");
            break;
        case 2:
            sprintf(buf,"2 Bit mode");
            break;
        case 3:
            sprintf(buf,"4 Bit mode");
            break;
        case 4:
            sprintf(buf,"8 Bit mode");
            break;
        case 5:
            sprintf(buf,"16 Bit mode RGBA5551");
            break;
        case 6:
            sprintf(buf,"16 Bit mode RGBA4444");
            break;
        case 7:
            sprintf(buf,"16 Bit mode RGB565");
            break;
        case 8:
            sprintf(buf,"16 Bit mode BGRA5551");
            break;
        case 9:
            sprintf(buf,"16 Bit mode BGRA4444");
            break;
        case 10:
            sprintf(buf,"16 Bit mode BGR565");
            break;
        case 11:
            sprintf(buf,"24 Bit mode RGB");
            break;
        case 12:
            sprintf(buf,"24 Bit mode BGR");
            break;
        }

        stringColor(screen,5,580,buf,0xFFFFFFFF);


        if (KeyHit(SDLK_SPACE))
        {
            setka=!setka;
            Render(buffer,rejim,WIDT,HIGH,DX);
        }



        if (KeyDown(SDLK_PERIOD))
        {
            WIDT++;
            DX=0;
            if (WIDT<1)
                WIDT =1;
            Render(buffer,rejim,WIDT,HIGH,DX);
        }
        if (KeyDown(SDLK_COMMA))
        {
            WIDT--;
            DX=0;
            if (WIDT<1)
                WIDT =1;
            Render(buffer,rejim,WIDT,HIGH,DX);
        }
        if (KeyDown(SDLK_SEMICOLON))
        {
            WIDT+=10;
            DX=0;
            if (WIDT<1)
                WIDT =1;
            Render(buffer,rejim,WIDT,HIGH,DX);
        }
        if (KeyDown(SDLK_l))
        {
            WIDT-=10;
            DX=0;
            if (WIDT<1)
                WIDT =1;
            Render(buffer,rejim,WIDT,HIGH,DX);
        }
        if (KeyDown(SDLK_LEFTBRACKET))
        {
            WIDT+=100;
            DX=0;
            if (WIDT<1)
                WIDT =1;
            Render(buffer,rejim,WIDT,HIGH,DX);
        }
        if (KeyDown(SDLK_p))
        {
            WIDT-=100;
            DX=0;
            if (WIDT<1)
                WIDT =1;
            Render(buffer,rejim,WIDT,HIGH,DX);
        }



        if (MouseDown(1))
        {

            if (MouseX()>663 && MouseX()<670 && MouseY()>7 && MouseY()<507)
            {
                Offs=(float)Max*((MouseY()-8.0))/500.0;
                Render(buffer,rejim,WIDT,HIGH,DX);
            }


            if (WIDT>150)
            {
                if (MouseX()>9 && MouseX()<511 && MouseY()>549 && MouseY()<556)
                {
                    DX=(WIDT -150)*((MouseX()-10)/500.0);
                    Render(buffer,rejim,WIDT,HIGH,DX);
                }
            }
        }
        if (MouseDown(3))
        {
            HIGH=MouseY()/4;
            if (HIGH<1)
                HIGH=1;

            if (HIGH> 130)
                HIGH=130;
            Render(buffer,rejim,WIDT,HIGH,DX);
        }


        if (KeyHit(SDLK_1))
        {
            rejim=1;
            Render(buffer,rejim,WIDT,HIGH,DX);
        }
        if (KeyHit(SDLK_2))
        {
            rejim=2;
            Render(buffer,rejim,WIDT,HIGH,DX);
        }
        if (KeyHit(SDLK_3))
        {
            rejim=3;
            Render(buffer,rejim,WIDT,HIGH,DX);
        }
        if (KeyHit(SDLK_4))
        {
            rejim=4;
            Render(buffer,rejim,WIDT,HIGH,DX);
        }
        if (KeyHit(SDLK_5))
        {
            rejim=5;
            Render(buffer,rejim,WIDT,HIGH,DX);
        }
        if (KeyHit(SDLK_6))
        {
            rejim=6;
            Render(buffer,rejim,WIDT,HIGH,DX);
        }
        if (KeyHit(SDLK_7))
        {
            rejim=7;
            Render(buffer,rejim,WIDT,HIGH,DX);
        }
        if (KeyHit(SDLK_8))
        {
            rejim=8;
            Render(buffer,rejim,WIDT,HIGH,DX);
        }
        if (KeyHit(SDLK_9))
        {
            rejim=9;
            Render(buffer,rejim,WIDT,HIGH,DX);
        }
        if (KeyHit(SDLK_0))
        {
            rejim=10;
            Render(buffer,rejim,WIDT,HIGH,DX);
        }

        if (KeyHit(SDLK_MINUS))
        {
            rejim=11;
            Render(buffer,rejim,WIDT,HIGH,DX);
        }

        if (KeyHit(SDLK_EQUALS))
        {
            rejim=12;
            Render(buffer,rejim,WIDT,HIGH,DX);
        }

        if (KeyDown(SDLK_RIGHT))
        {
            Offs++;
            Render(buffer,rejim,WIDT,HIGH,DX);
        }
        if (KeyDown(SDLK_LEFT))
        {
            Offs--;
            Render(buffer,rejim,WIDT,HIGH,DX);
        }

        if (rejim<5)
        {
            if (KeyDown(SDLK_DOWN))
            {
                Offs+=WIDT;
                Render(buffer,rejim,WIDT,HIGH,DX);
            }
            if (KeyDown(SDLK_UP))
            {
                Offs-=WIDT;
                Render(buffer,rejim,WIDT,HIGH,DX);
            }
            if (KeyDown(SDLK_PAGEUP))
            {
                Offs-=WIDT*10;
                Render(buffer,rejim,WIDT,HIGH,DX);
            }
            if (KeyDown(SDLK_PAGEDOWN))
            {
                Offs+=WIDT*10;
                Render(buffer,rejim,WIDT,HIGH,DX);
            }
            if (KeyDown(SDLK_HOME))
            {
                Offs-=WIDT*100;
                Render(buffer,rejim,WIDT,HIGH,DX);
            }
            if (KeyDown(SDLK_END))
            {
                Offs+=WIDT*100;
                Render(buffer,rejim,WIDT,HIGH,DX);
            }
        }
        else if (rejim < 11)
        {
            if (KeyDown(SDLK_DOWN))
            {
                Offs+=WIDT*2;
                Render(buffer,rejim,WIDT,HIGH,DX);
            }
            if (KeyDown(SDLK_UP))
            {
                Offs-=WIDT*2;
                Render(buffer,rejim,WIDT,HIGH,DX);
            }
            if (KeyDown(SDLK_PAGEUP))
            {
                Offs-=WIDT*20;
                Render(buffer,rejim,WIDT,HIGH,DX);
            }
            if (KeyDown(SDLK_PAGEDOWN))
            {
                Offs+=WIDT*20;
                Render(buffer,rejim,WIDT,HIGH,DX);
            }
            if (KeyDown(SDLK_HOME))
            {
                Offs-=WIDT*200;
                Render(buffer,rejim,WIDT,HIGH,DX);
            }
            if (KeyDown(SDLK_END))
            {
                Offs+=WIDT*200;
                Render(buffer,rejim,WIDT,HIGH,DX);
            }
        }
        else if (rejim < 13)
        {
            if (KeyDown(SDLK_DOWN))
            {
                Offs+=WIDT*3;
                Render(buffer,rejim,WIDT,HIGH,DX);
            }
            if (KeyDown(SDLK_UP))
            {
                Offs-=WIDT*3;
                Render(buffer,rejim,WIDT,HIGH,DX);
            }
            if (KeyDown(SDLK_PAGEUP))
            {
                Offs-=WIDT*30;
                Render(buffer,rejim,WIDT,HIGH,DX);
            }
            if (KeyDown(SDLK_PAGEDOWN))
            {
                Offs+=WIDT*30;
                Render(buffer,rejim,WIDT,HIGH,DX);
            }
            if (KeyDown(SDLK_HOME))
            {
                Offs-=WIDT*300;
                Render(buffer,rejim,WIDT,HIGH,DX);
            }
            if (KeyDown(SDLK_END))
            {
                Offs+=WIDT*300;
                Render(buffer,rejim,WIDT,HIGH,DX);
            }
        }


        // DRAWING ENDS HERE


        // finally, update the screen :)
        SDL_Flip(screen);
        SDL_Delay(10);
    } // end main loop

    fclose(fl);

    return 0;
}
Ejemplo n.º 16
0
void Time::Sleep(uint32 time) {
	SDL_Delay(time);
}
Ejemplo n.º 17
0
int main(int argc, char* args[])
{
  //quit flag
  bool quit = false;

  //frame rate regulator
  Timer fps;

  if(init() == false)
    return 1;
      
  if(load_files() == false)
    return 1;

  setButtons_and_Frames();
  create_Tooltips();

  //start frame counter
  frame = 0;

  //play music
  //Mix_PlayMusic(mainMusic, -1);

  //the player
  Player *player0 = NULL;

  //while in game
  while(quit == false)
    {
      //start frame timer
      fps.start();
      
      //while events to handle
      while(SDL_PollEvent(&event))
	{
	  //player0 ship movement/ shooting
	  if(isPaused == false)
	     player0->handle_input();
	  else
	    quit = handle_menu_input();

	  //if user closes window
	  if(event.type == SDL_QUIT)
	    {
	      quit = true;
	    }
	}

      if(isPaused == false)
	{
	  //background
	  apply_surface(0, 0, background, screen, &camera);

	  if(gameMode == 0)
	    {
	      doMainGame(player0);
	    }

	  else if(gameMode == 1)
	    doArcadeMode(player0);

	  //control units
	  player0->doUnit();
	  doGrunts();
	  doBoomers();
	  doStealths();
	  doCarriers();
	  
	  doExplosions();
	  
	  //HUD
	  renderHUD(player0);
	}
      else if(quit == false) //paused, show some sort of menu;
	{
	  switch(menu) //show menu based on menu variable
	    {
	    case 0:
	      quit = doMainMenu();
	      //going to mainMenu, reset everything
	      if(player0 != NULL)
		delete player0;
	      player0 = new Player;
	      reset();
	      break;
	    case 1: instructionsMenu(); break;
	    case 2: doPauseMenu(); break;
	    case 3: doSkillMenu(player0); break;
	    case 4: gameOverMenu(); break;
	      //case 5: doShopMenu(player0); break;
	      //if not valid menu, unpause game
	    case 6: victoryMenu(); break;
	    default: isPaused = false;
	    }
	}
      
      //update screen
      if(SDL_Flip(screen) == -1)
	return 1;

      //cap frame rate
      if(fps.get_ticks() < 1000 / FRAMES_PER_SECOND)
	{
	  SDL_Delay((1000 / FRAMES_PER_SECOND) - fps.get_ticks());
	}
	
      frame++;
    }

  clean_up();

  return 0;
}
Ejemplo n.º 18
0
bool GameThroneMode::doRun()
{
	SDL_Event event;
	if(SDL_PollEvent(&event))
	{
		switch(event.type)
		{
			case SDL_QUIT:
			{
				return false;
				break;
			}
			case SDL_KEYDOWN:
			{

				if ( event.key.keysym.sym == SDLK_ESCAPE ) 
				{
					m_mgr->SetActiveModule(MAINMENU);
					return true;
				} 
				if ( event.key.keysym.sym == SDLK_p || event.key.keysym.sym == SDLK_SPACE) 
				{
					doPause();
				} 
				if ( event.key.keysym.sym == SDLK_UP && snake1->GetDirection()!=Down) 
				{
					snake1->SetDirection(Up);
				} 
				if ( event.key.keysym.sym == SDLK_w && snake2->GetDirection()!=Down) 
				{
					snake2->SetDirection(Up);
				} 
				if ( event.key.keysym.sym == SDLK_DOWN && snake1->GetDirection()!=Up) 
				{
					snake1->SetDirection(Down);
				} 
				if ( event.key.keysym.sym == SDLK_s && snake2->GetDirection()!=Up) 
				{
					snake2->SetDirection(Down);
				} 
				if ( event.key.keysym.sym == SDLK_LEFT && snake1->GetDirection()!=Right) 
				{
					snake1->SetDirection(Left);
				} 
				if ( event.key.keysym.sym == SDLK_a && snake2->GetDirection()!=Right) 
				{
					snake2->SetDirection(Left);
				} 
				if ( event.key.keysym.sym == SDLK_RIGHT && snake1->GetDirection()!=Left) 
				{
					snake1->SetDirection(Right);
				} 
				if ( event.key.keysym.sym == SDLK_d && snake2->GetDirection()!=Left) 
				{
					snake2->SetDirection(Right);
				} 
				break;
			}
		}

	}
	if(snake1->Move()&&snake2->Move())
	{
		Converter.Convert();
		DrawField();
		DrawTop();
		SDL_Delay(50);
	}
	else
	{
		Converter.Convert();
		DrawField();	
		DrawTop();
		GameOver();
	}	
	return true;
}
Ejemplo n.º 19
0
void EventsManager::delay(uint32 ms) {
	SDL_Delay(ms);
}
Ejemplo n.º 20
0
int main(int argc, char *argv[])
{
	Uint32 flags;
	SDL_Surface *screen, *image;
	int depth, done;
	SDL_Event event;

	/* Check command line usage */
	if ( ! argv[1] ) {
		fprintf(stderr, "Usage: %s <image_file>, (int) size\n", argv[0]);
		return(1);
	}


	/* Initialize the SDL library */
	if ( SDL_Init(SDL_INIT_VIDEO) < 0 ) {
		fprintf(stderr, "Couldn't initialize SDL: %s\n",SDL_GetError());
		return(255);
	}

	flags = SDL_SWSURFACE;
	image = Load_image( argv[1] );
	//printf( "\n\nImage properts:\n" );
	//printf( "BitsPerPixel = %i \n", image->format->BitsPerPixel );
	printf( "BytesPerPixel = %i \n", image->format->BytesPerPixel );
	printf( "width %d ,height %d \n\n", image->w, image->h );	 	
	
	SDL_WM_SetCaption(argv[1], "showimage");
	
	/* Create a display for the image */
	depth = SDL_VideoModeOK(image->w, image->h, 32, flags);
	/* Use the deepest native mode, except that we emulate 32bpp
	   for viewing non-indexed images on 8bpp screens */
	if ( depth == 0 ) {
		if ( image->format->BytesPerPixel > 1 ) {
			depth = 32;
		} else {
			depth = 8;
		}
	} else
	if ( (image->format->BytesPerPixel > 1) && (depth == 8) ) {
    		depth = 32;
	}
	if(depth == 8)
		flags |= SDL_HWPALETTE;
	screen = SDL_SetVideoMode(image->w, image->h, depth, flags);
	if ( screen == NULL ) {
		fprintf(stderr,"Couldn't set %dx%dx%d video mode: %s\n",
			image->w, image->h, depth, SDL_GetError());
	}

	/* Set the palette, if one exists */
	if ( image->format->palette ) {
		SDL_SetColors(screen, image->format->palette->colors,
	              0, image->format->palette->ncolors);
	}


	/* Display the image */
	Paint(image, screen);

	done = 0;

	while ( ! done ) {
		if ( SDL_PollEvent(&event) ) {
			switch (event.type) {
			    case SDL_KEYUP:
				switch (event.key.keysym.sym) {
				    case SDLK_ESCAPE:
				    case SDLK_TAB:
				    case SDLK_q:
					done = 1;
					break;
				    case SDLK_SPACE:
				    case SDLK_k:
						SDL_LockSurface(image);
						
						printf("Start filtering...  ");
						rotateOY(image->pixels,image->w,image->h); 
						printf("Done.\n");

						SDL_UnlockSurface(image);
						
						printf("Repainting after filtered...  ");
						Paint(image, screen);
						printf("Done.\n");
						break;

				    case SDLK_l:
						SDL_LockSurface(image);
						
						printf("Start filtering...  ");
						rotateOX(image->pixels,image->w,image->h); 
						printf("Done.\n");

						SDL_UnlockSurface(image);
						
						printf("Repainting after filtered...  ");
						Paint(image, screen);
						printf("Done.\n");
						break;
				   	
				   	 case SDLK_n:
						SDL_LockSurface(image);
						
						printf("Start filtering...  ");
						int size = image->w * image->h*3 ;
						printf("%d\n", size);
						negatyw(image->pixels,size); 
						printf("Done.\n");

						SDL_UnlockSurface(image);
						
						printf("Repainting after filtered...  ");
						Paint(image, screen);
						printf("Done.\n");
						break;

				   case SDLK_s:
					printf("Saving surface at nowy.bmp ...");
					SDL_SaveBMP(image, "nowy.bmp" ); 
					printf("Done.\n");
				    default:
					break;
				}
				break;
//			    case  SDL_MOUSEBUTTONDOWN:
//				done = 1;
//				break;
                case SDL_QUIT:
				done = 1;
				break;
			    default:
				break;
			}
		} else {
			SDL_Delay(10);
		}
	}
	SDL_FreeSurface(image);
	/* We're done! */
	SDL_Quit();
	return(0);
}
Ejemplo n.º 21
0
void wait_delay( void )
{
	Sint32 delay = target - SDL_GetTicks();
	if (delay > 0)
		SDL_Delay(delay);
}
Ejemplo n.º 22
0
/**
 * Draws all points of the objects in OpenGl with SDL in cartesian coordinates
 */
void drawObjects(struct system *System,
                 struct tip *Tip,
                 struct space *Space,
                 struct graphene *Graphene,
                 struct substrate *Substrate)
{
	SDL_Event event;
	Uint8 running = 1;
	GLfloat angleH = 0.0f;
	GLfloat angleV = -90.0f;
	GLfloat rescaleX = WIDTH/System->size.x;
	GLfloat rescaleY = HEIGHT/System->size.z;

	while (running)
	{
		glMatrixMode (GL_PROJECTION);
		glLoadIdentity ();
		glClearColor(0.0, 0.0, 0.0, 0.0); // Black background color
		glClear(GL_COLOR_BUFFER_BIT); // Black screen
		glColor4f(1.0, 1.0, 1.0, 0.0); // White color for Objects
		glOrtho(-WIDTH/2, WIDTH/2, HEIGHT/2, -HEIGHT/2, HEIGHT/2, -HEIGHT/2);
		glRotatef(angleV, 1.0f, 0.0f, 0.0f); // Show the x-z plane of the system
		glRotatef(angleH, 0.0f, 0.0f, 1.0f); // Rotate around Z
		glTranslatef(-0.0f, -0.0f, -120.0f);
		glPointSize(1.0f);
		glLineWidth(2.0f);
		glMatrixMode (GL_MODELVIEW);

		// Draw objects
		glBegin(GL_POINTS);

		for (Uint32 i = 0; i < Tip->numPoints; i++)
		{
			glColor3f (Tip->points[i].potential/System->potential, 0.5f, 0.0f);
			glVertex3f(Tip->points[i].x * rescaleX,
			           Tip->points[i].y * rescaleY,
			           Tip->points[i].z * rescaleY);
		}

		for (Uint32 i = 0; i < Space->numPoints; i++)
		{
			glColor3f (Space->points[i].potential/System->potential, 0.5f, 0.5f);
			glVertex3f(Space->points[i].x * rescaleX,
			           Space->points[i].y * rescaleY,
			           Space->points[i].z * rescaleY);
		}

		for (Uint32 i = 0; i < Graphene->numPoints; i++)
		{
			glColor3f (Graphene->points[i].potential/System->potential, 0.5f, 0.5f);
			glVertex3f(Graphene->points[i].x * rescaleX,
			           Graphene->points[i].y * rescaleY,
			           Graphene->points[i].z * rescaleY);
		}

		for (Uint32 i = 0; i < Substrate->numPoints; i++)
		{
			glColor3f (Substrate->points[i].potential/System->potential, 0.0f, 0.5f);
			glVertex3f(Substrate->points[i].x * rescaleX,
			           Substrate->points[i].y * rescaleY,
			           Substrate->points[i].z * rescaleY);
		}

		glColor3f (1.0f, 1.0f, 1.0f);
		glVertex3f(0.0f, 0.0f, 0.0f); // Center of the System
		glEnd();

		SDL_GL_SwapBuffers();
		SDL_Delay(150);

		while (SDL_PollEvent (&event))
		{
			if(event.type == SDL_QUIT)
			{
				running = 0;
			}
			else if (event.key.keysym.sym == SDLK_ESCAPE)
			{
				running = 0;
			}
			else if(event.button.button == SDL_BUTTON_LEFT && event.button.state == SDL_PRESSED)
			{
				angleH += 10.0f;
			}
			else if(event.button.button == SDL_BUTTON_RIGHT && event.button.state == SDL_PRESSED)
			{
				angleH -= 10.0f;
			}
			else if(event.button.button == SDL_BUTTON_WHEELUP && event.button.state == SDL_PRESSED)
			{
				angleV += 5.0f;
			}
			else if(event.button.button == SDL_BUTTON_WHEELDOWN && event.button.state == SDL_PRESSED)
			{
				angleV -= 5.0f;
			}
		}
	}
}
Ejemplo n.º 23
0
/**
 * \brief Makes the program sleep during some time.
 *
 * Due to the OS scheduling, the real delay may be longer.
 *
 * \param duration duration of the sleep in milliseconds
 */
void System::sleep(uint32_t duration) {
  SDL_Delay(duration);
}
Ejemplo n.º 24
0
int main()
{
    core::logger::init();
    core::logger::addOutput(&std::cout);
    graphics::Graphics* gfx = new graphics::Graphics;

    events::Events ev;
    bool cont = true;

    if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
        std::cout << "Couldn't load SDL : " << SDL_GetError() << std::endl;
        return 1;
    }

    cont = gfx->openWindow("Test events::Events joysticks handling", 800, 600);
    if(!cont)
        return 1;

    /* Open all joysticks */
    std::cout << "There are " << ev.numJoysticks() << " joysticks available." << std::endl;
    for(int i = 0; i < ev.numJoysticks(); ++i) {
        if(ev.openJoystick(i) != NULL)
            std::cout << "Opened joystick #" << i << std::endl;
    }

    /* Background */
    geometry::AABB bgaabb(800.0f, 600.0f);
    graphics::Color bgc;
    bgc.r = bgc.g = 127;
    bgc.b = 255;

    ev.enableInput(true);
    while(cont) {
        ev.update();
        ev.clearInput();
        if(ev.closed() || ev.quit() || ev.isKeyPressed(events::Key('Q')))
            cont = false;

        if(ev.joysticksChanged()) {
            std::cout << "Joysticks changed !" << std::endl;
            std::vector<events::JoystickID> plugged  = ev.lastJoysticksAdded();
            for(events::JoystickID id : plugged) {
                if(ev.openJoystick(id) != NULL)
                    std::cout << "Opened joystick #" << id << std::endl;
            }
            dumpAddedJoysticks(plugged);
        }

        dumpAxis(ev.lastAxesMoved());
        dumpHats(ev.lastHatsMoved());
        dumpJoyButtons(ev.lastJoyButtonsPressed(), "pressed");
        dumpJoyButtons(ev.lastJoyButtonsReleased(), "released");

        gfx->beginDraw();
        gfx->draw(bgaabb, bgc);
        gfx->endDraw();

        SDL_Delay(1000/30);
    }

    delete gfx;
    core::logger::free();
    SDL_Quit();
    return 0;
}
Ejemplo n.º 25
0
void VideoState::init()
{
	State::init();

	bool wasLetterboxed = CutsceneState::initDisplay();

	bool ufoIntroSoundFileDosExists = false;
	bool ufoIntroSoundFileWinExists = false;
	int prevMusicVol = Options::musicVolume;
	int prevSoundVol = Options::soundVolume;
	if (_useUfoAudioSequence)
	{
		const std::set<std::string> &soundDir = FileMap::getVFolderContents("SOUND");
		ufoIntroSoundFileDosExists = soundDir.end() != soundDir.find("intro.cat");
		ufoIntroSoundFileWinExists = soundDir.end() != soundDir.find("sample3.cat");

		if (!ufoIntroSoundFileDosExists && !ufoIntroSoundFileWinExists)
		{
			_useUfoAudioSequence = false;
		}
		else
		{
			// ensure user can hear both music and sound effects for the
			// vanilla intro sequence
			Options::musicVolume = Options::soundVolume = std::max(prevMusicVol, prevSoundVol/8);
			_game->setVolume(Options::soundVolume, Options::musicVolume, -1);
		}
	}
	_game->getCursor()->setVisible(false);

	int dx = (Options::baseXResolution - Screen::ORIGINAL_WIDTH) / 2;
	int dy = (Options::baseYResolution - Screen::ORIGINAL_HEIGHT) / 2;

	FlcPlayer *flcPlayer = NULL;
	for (std::vector<std::string>::const_iterator it = _videos->begin(); it != _videos->end(); ++it)
	{
		std::string videoFileName = FileMap::getFilePath(*it);

		if (!CrossPlatform::fileExists(videoFileName))
		{
			continue;
		}

		if (!flcPlayer)
		{
			flcPlayer = new FlcPlayer();
		}

		if (_useUfoAudioSequence)
		{
			audioSequence = new AudioSequence(_game->getResourcePack(), flcPlayer);
		}

		flcPlayer->init(videoFileName.c_str(),
			 _useUfoAudioSequence ? &audioHandler : NULL,
			 _game, dx, dy);
		flcPlayer->play(_useUfoAudioSequence);
		if (_useUfoAudioSequence)
		{
			flcPlayer->delay(10000);
			delete audioSequence;
			audioSequence = NULL;
		}
		flcPlayer->deInit();

		if (flcPlayer->wasSkipped())
		{
			break;
		}
	}

	if (flcPlayer)
	{
		delete flcPlayer;
	}

#ifndef __NO_MUSIC
	// fade out!
	Mix_FadeOutChannel(-1, 45 * 20);
	if (Mix_GetMusicType(0) != MUS_MID)
	{
		// SDL_Mixer has trouble with native midi and volume on windows,
		// which is the most likely use case, so f@%# it.
		Mix_FadeOutMusic(45 * 20);
		func_fade();
	}
	else
	{
		Mix_HaltMusic();
	}
#endif

	SDL_Color pal[256];
	SDL_Color pal2[256];
	memcpy(pal, _game->getScreen()->getPalette(), sizeof(SDL_Color) * 256);
	for (int i = 20; i > 0; --i)
	{
		SDL_Event event;
		if (SDL_PollEvent(&event) && event.type == SDL_KEYDOWN) break;
		for (int color = 0; color < 256; ++color)
		{
			pal2[color].r = (((int)pal[color].r) * i) / 20;
			pal2[color].g = (((int)pal[color].g) * i) / 20;
			pal2[color].b = (((int)pal[color].b) * i) / 20;
			pal2[color].unused = pal[color].unused;
		}
		_game->getScreen()->setPalette(pal2, 0, 256, true);
		_game->getScreen()->flip();
		SDL_Delay(45);
	}
	_game->getScreen()->clear();
	_game->getScreen()->flip();

	if (_useUfoAudioSequence)
	{
		Options::musicVolume = prevMusicVol;
		Options::soundVolume = prevSoundVol;
		_game->setVolume(Options::soundVolume, Options::musicVolume, Options::uiVolume);
	}

#ifndef __NO_MUSIC
	Sound::stop();
	Music::stop();
#endif

	_game->getCursor()->setVisible(true);
	CutsceneState::resetDisplay(wasLetterboxed);
	_game->popState();
}
Ejemplo n.º 26
0
int main(int argc, char *argv[]){
    //#ifdef WIN
        string appDir = argv[0];
        int pos = appDir.rfind(Constant::getFileSep());
        if (pos == string::npos){
            FILE_SEPARATOR = FILE_SEPARATOR_UNIX;
            pos = appDir.rfind(FILE_SEPARATOR);
            tempFileSep[0] = FILE_SEPARATOR;
        }
        appDir = appDir.substr(0, pos);
        if (appDir[appDir.length()-1] == '.'){
            appDir.substr(0, appDir.rfind(Constant::getFileSep()));
        }
        Constant::setAppDir(appDir);
    //#endif // WIN

    //#ifdef UNIX
    //    Dirutil dir;
    //    Constant::setAppDir(dir.getDirActual());
    //#endif // UNIX

    string rutaTraza = appDir + Constant::getFileSep() + "Traza.txt";

    Traza *traza = new Traza(rutaTraza.c_str());
    Iofrontend *ioFront = new Iofrontend();
    srand(time(NULL));

    try{

        bool salir = false;
        long delay = 0;
        unsigned long before = 0;
        ioFront->setCanFlip(true);
        atexit (Terminate);

        if (argc > 1){
            string fichParm = argv[1];
            ioFront->addLocalAlbum(fichParm);
            Traza::print("Parameter: " + fichParm, W_DEBUG);
        } else {
            //ioFront->actualizaciones(); // Ya no son necesarias las actualizaciones
            ioFront->autenticateAndRefresh();
            tEvento evento;
            ioFront->drawMenu(evento);
            ioFront->bienvenida();
        }



        while (!salir){

            tEvento evento = ioFront->WaitForKey();
            procesarTeclado(&evento, ioFront);

            before = SDL_GetTicks();
            salir = evento.quit;

            if (!salir){
                salir = ioFront->drawMenu(evento);

                if (LIMITFPS){
                //Calculamos el tiempo que deberia pasar de frame a frame en un lapso de 1 seg (TIMETOLIMITFRAME) y le restamos
                //el tiempo que realmente ha pasado (before - SDL_GetTicks()), para esperar el tiempo que indique
                //esta diferencia. No es el mejor m�todo pero es sencillo de implementar
                    delay = before - SDL_GetTicks() + TIMETOLIMITFRAME;
                    if(delay > 0) SDL_Delay(delay);
                }
            }
        }
    } catch(Excepcion &e) {
        Traza::print("Error capturado en hilo principal:",e.getCode(), W_FATAL);
        //exit(e.getCode());
    }

    Traza::print("Eliminando iofront", W_DEBUG);
    delete ioFront;
    Traza::print("Eliminando traza", W_DEBUG);
    delete traza;
    exit(0);
}
Ejemplo n.º 27
0
void jhi_delay_mili_seconds(int ms)
{
	SDL_Delay(ms);
}
Ejemplo n.º 28
0
void SHPView::run_anim(Uint32 sframe, Uint32 eframe)
{
    SDL_Event event;
    Uint8 done = 0;

    Uint32 frame = sframe;
    if (frame > max) {
        logger->warning("Supplied start frame was greater than number of frames\n");
        sframe = frame = 0;
    }
    if (eframe > max) {
        logger->warning("Supplied end frame was greater than number of frames\n");

        eframe = max-1;
    }
    if (eframe < sframe) {
        eframe ^= sframe;
        sframe ^= eframe;
        eframe ^= sframe;
        frame = sframe;
    }
    while(!done) {
        if(SDL_PollEvent(&event)) {
            switch(event.type) {
            case SDL_KEYDOWN:
                if( event.key.state != SDL_PRESSED )
                    break;
                switch( event.key.keysym.sym ) {
                case SDLK_ESCAPE:
                case SDLK_q:
                    done = 1;
                    break;
                default:
                    break;
                }
                break;
            case SDL_QUIT:
                done = 1;
                break;
            default:
                break;
            }
        }
        if (frame < eframe) {
            ++frame;
        } else {
            frame = sframe;
        }
        switch (mode) {
        case 0:
            gfx->draw(shp, fnt, frame,max);
            break;
        case 1:
            gfx->draw(tem, fnt, frame,max);
            break;
        case 2:
            gfx->draw(d2i, fnt, frame,max);
            break;
        default:
            logger->error("Unknown mode: %i\n",mode);
            done = 1;
            break;
        }

        SDL_Delay(100);
    }
}
Ejemplo n.º 29
0
void GfxGlEngine::delay( const unsigned int msec )
{
  SDL_Delay( msec );
}
/* This function waits until it is possible to write a full sound buffer */
static void
DMA_WaitDevice(_THIS)
{
    fd_set fdset;

    /* Check to see if the thread-parent process is still alive */
    {
        static int cnt = 0;
        /* Note that this only works with thread implementations 
           that use a different process id for each thread.
         */
        if (parent && (((++cnt) % 10) == 0)) {  /* Check every 10 loops */
            if (kill(parent, 0) < 0 && errno == ESRCH) {
                this->enabled = 0;
            }
        }
    }

    /* See if we need to use timed audio synchronization */
    if (frame_ticks) {
        /* Use timer for general audio synchronization */
        Sint32 ticks;

        ticks = ((Sint32) (next_frame - SDL_GetTicks())) - FUDGE_TICKS;
        if (ticks > 0) {
            SDL_Delay(ticks);
        }
    } else {
        /* Use select() for audio synchronization */
        struct timeval timeout;
        FD_ZERO(&fdset);
        FD_SET(audio_fd, &fdset);
        timeout.tv_sec = 10;
        timeout.tv_usec = 0;
#ifdef DEBUG_AUDIO
        fprintf(stderr, "Waiting for audio to get ready\n");
#endif
        if (select(audio_fd + 1, NULL, &fdset, NULL, &timeout) <= 0) {
            const char *message =
#ifdef AUDIO_OSPACE_HACK
                "Audio timeout - buggy audio driver? (trying ospace)";
#else
                "Audio timeout - buggy audio driver? (disabled)";
#endif
            /* In general we should never print to the screen,
               but in this case we have no other way of letting
               the user know what happened.
             */
            fprintf(stderr, "SDL: %s\n", message);
#ifdef AUDIO_OSPACE_HACK
            /* We may be able to use GET_OSPACE trick */
            frame_ticks = (float) (this->spec.samples * 1000) /
                this->spec.freq;
            next_frame = SDL_GetTicks() + frame_ticks;
#else
            this->enabled = 0;
            /* Don't try to close - may hang */
            audio_fd = -1;
#ifdef DEBUG_AUDIO
            fprintf(stderr, "Done disabling audio\n");
#endif
#endif /* AUDIO_OSPACE_HACK */
        }
#ifdef DEBUG_AUDIO
        fprintf(stderr, "Ready!\n");
#endif
    }
}