int main(int, char**) {
    // This section is the initialization for SDL2
    if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {
        logSDLError(std::cout, "SDL_Init");
        return 1;
    }
    SDL_Window *window = SDL_CreateWindow("Moving Window", 100, 100, 1440, 810, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
    if (window == nullptr) {
        logSDLError(std::cout, "CreateWindow");
        SDL_Quit();
        return 1;
    }
    SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
    if (renderer == nullptr) {
        logSDLError(std::cout, "CreateRenderer");
        SDL_DestroyWindow(window);
        SDL_Quit();
        return 1;
    }

    // Initialize all the Images and Texts Pointers
    const std::string resPath = getResourcePath("FeedbackDisplay");
    SDL_Texture *instruction = loadTexture(resPath + "instruction.png", renderer);
    SDL_Texture *trial_background = loadTexture(resPath + "background.png", renderer);
    SDL_Texture *background = loadTexture(resPath + "SyncStart.png", renderer);
    SDL_Texture *background2 = loadTexture(resPath + "SyncEnd.png", renderer);
    SDL_Texture *instruction2 = loadTexture(resPath + "instruction2.png", renderer);
    SDL_Texture *sphere = loadTexture(resPath + "sphere.png", renderer);
    SDL_Texture *Target = loadTexture(resPath + "Target.png", renderer);
    SDL_Texture *sphere2 = loadTexture(resPath + "sphere2.png", renderer);
    SDL_Texture *Target2 = loadTexture(resPath + "Target2.png", renderer);
    SDL_Texture *trialStart = loadTexture(resPath + "trialStart.png", renderer);
    SDL_Texture *trialEnd = loadTexture(resPath + "trialEnd.png", renderer);
    SDL_Event event;

    if (background == nullptr || background2 == nullptr || sphere == nullptr || instruction2 == nullptr || Target == nullptr || sphere2 == nullptr || Target2 == nullptr ||
            trialStart == nullptr || trialEnd == nullptr || instruction == nullptr || trial_background == nullptr )
    {
        SDL_DestroyWindow(window);
        SDL_DestroyRenderer(renderer);
        SDL_DestroyTexture(background);
        SDL_DestroyTexture(trial_background);
        SDL_DestroyTexture(instruction);
        SDL_DestroyTexture(sphere);
        SDL_DestroyTexture(background2);
        SDL_DestroyTexture(sphere2);
        SDL_DestroyTexture(Target2);
        SDL_DestroyTexture(Target);
        SDL_DestroyTexture(instruction2);
        SDL_Quit();
        SDL_Quit();
        return 1;
    }

    SDL_GetWindowSize(window, &SCREEN_WIDTH, &SCREEN_HEIGHT);
    // Wait for Synchronization between OpenBCI and Feedback Display
    SDL_RenderClear(renderer);
    renderTexture(background, renderer, (SCREEN_WIDTH - SCREEN_HEIGHT) / 2, 0, SCREEN_HEIGHT, SCREEN_HEIGHT);
    SDL_RenderPresent(renderer);

    // Obtain the timer as well as the logging files
    const std::string Feature1 = getResourcePath("FIFO") + "X_Direction.txt";
    const std::string Feature2 = getResourcePath("FIFO") + "Y_Direction.txt";
    const std::string Trial_Info = getResourcePath("FIFO") + "Trial_Information.txt";
    const std::string Trigger_Log = getResourcePath("FIFO") + "Trigger_Log.txt";
    const std::string Feedback = getResourcePath("FIFO") + "Feedback_Log_0.txt";
    Sync_Send(Feedback, "Timer on");
    Sync_Wait(Trigger_Log, "All Set", "ALL FINISH", event);
    SDL_RenderClear(renderer);
    renderTexture(background2, renderer, (SCREEN_WIDTH - SCREEN_HEIGHT) / 2, 0, SCREEN_HEIGHT, SCREEN_HEIGHT);
    SDL_RenderPresent(renderer);

    // flag used to stop the program execution
    bool Next_Trial, Finishing;
    Finishing = false;

    // Obtain Screen Size, Create position values for objects
    Position Centroid, Ball, Goal;
    const int SPHERE_SIZE = SCREEN_HEIGHT / 10;
    const int TARGET_WIDTH = SCREEN_HEIGHT / 10;
    const int TARGET_HEIGHT = TARGET_WIDTH;
    int Margin;
    Centroid.Set(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, 0, 0);
    std::string Previous_X, Previous_Y, Current_X, Current_Y;
    Feature X_Direction,Y_Direction;
    X_Direction.Set(1,0);
    Y_Direction.Set(1,0);


    // Maintain the Field of movement within Square
    if (SCREEN_HEIGHT < SCREEN_WIDTH)
        Margin = (SCREEN_WIDTH - SCREEN_HEIGHT) / 2;
    else
        Margin = 0;

    // Calibration
    if (!Sync_Wait(Trigger_Log, "Calibration On", "ALL FINISH", event)) {
        Sync_Send(Feedback,"Display End");
        SDL_DestroyWindow(window);
        SDL_DestroyRenderer(renderer);
        SDL_DestroyTexture(background);
        SDL_DestroyTexture(trial_background);
        SDL_DestroyTexture(instruction);
        SDL_DestroyTexture(sphere);
        SDL_DestroyTexture(background2);
        SDL_DestroyTexture(sphere2);
        SDL_DestroyTexture(Target2);
        SDL_DestroyTexture(Target);
        SDL_DestroyTexture(instruction2);
        SDL_Quit();
        return 1;
    }

    SDL_RenderClear(renderer);
    renderTexture(instruction, renderer, (SCREEN_WIDTH - SCREEN_HEIGHT) / 2, 0, SCREEN_HEIGHT, SCREEN_HEIGHT);
    SDL_RenderPresent(renderer);
    if (!Sync_Wait(Trigger_Log, "Calibration Stage2", "ALL FINISH", event)) {
        Sync_Send(Feedback,"Display End");
        SDL_DestroyWindow(window);
        SDL_DestroyRenderer(renderer);
        SDL_DestroyTexture(background);
        SDL_DestroyTexture(instruction);
        SDL_DestroyTexture(sphere);
        SDL_DestroyTexture(trial_background);
        SDL_DestroyTexture(background2);
        SDL_DestroyTexture(sphere2);
        SDL_DestroyTexture(Target2);
        SDL_DestroyTexture(Target);
        SDL_DestroyTexture(instruction2);
        SDL_Quit();
        return 1;
    }

    SDL_RenderClear(renderer);
    renderTexture(instruction2, renderer, (SCREEN_WIDTH - SCREEN_HEIGHT) / 2, 0, SCREEN_HEIGHT, SCREEN_HEIGHT);
    SDL_RenderPresent(renderer);
    if (!Sync_Wait(Trigger_Log, "Calibration End", "ALL FINISH", event)) {
        Sync_Send(Feedback,"Display End");
        SDL_DestroyWindow(window);
        SDL_DestroyRenderer(renderer);
        SDL_DestroyTexture(background);
        SDL_DestroyTexture(instruction);
        SDL_DestroyTexture(sphere);
        SDL_DestroyTexture(background2);
        SDL_DestroyTexture(sphere2);
        SDL_DestroyTexture(trial_background);
        SDL_DestroyTexture(Target2);
        SDL_DestroyTexture(Target);
        SDL_DestroyTexture(instruction2);
        SDL_Quit();
        return 1;
    }


    /******************************
     * The Actual Experiment Part *
    ******************************/

    while(!(Sync_Check(Trigger_Log,"ALL FINISH")||Finishing)) {
        // Determine the type of Trial
        if (!Sync_Wait(Trigger_Log, "Ready", "ALL FINISH", event)) {
            Sync_Send(Feedback,"Display End");
            SDL_DestroyWindow(window);
            SDL_DestroyRenderer(renderer);
            SDL_DestroyTexture(background);
            SDL_DestroyTexture(instruction);
            SDL_DestroyTexture(sphere);
            SDL_DestroyTexture(trial_background);
            SDL_DestroyTexture(background2);
            SDL_DestroyTexture(sphere2);
            SDL_DestroyTexture(Target2);
            SDL_DestroyTexture(Target);
            SDL_DestroyTexture(instruction2);
            SDL_Quit();
            return 1;
        }
        switch (Read_Trial(Trial_Info)) {
        case 0:
            Goal.Set(Margin, 0, TARGET_HEIGHT, TARGET_WIDTH);
            break;
        case 1:
            Goal.Set(SCREEN_WIDTH - Margin - TARGET_WIDTH, 0, TARGET_HEIGHT, TARGET_WIDTH);
            break;
        case 2:
            Goal.Set(Margin, SCREEN_HEIGHT - TARGET_HEIGHT, TARGET_WIDTH, TARGET_HEIGHT);
            break;
        case 3:
            Goal.Set(SCREEN_WIDTH - Margin - TARGET_WIDTH, SCREEN_HEIGHT - TARGET_HEIGHT, TARGET_WIDTH, TARGET_HEIGHT);
            break;
        }

        // Signal Trial Begin
        SDL_RenderClear(renderer);
        renderTexture(trialStart, renderer, (SCREEN_WIDTH-SCREEN_HEIGHT)/2, 0, SCREEN_HEIGHT, SCREEN_HEIGHT);
        SDL_RenderPresent(renderer);
        if (!Sync_Wait(Trigger_Log,"Trial Start", "ALL FINISH", event)) {
            Sync_Send(Feedback,"Display End");
            SDL_DestroyWindow(window);
            SDL_DestroyRenderer(renderer);
            SDL_DestroyTexture(background);
            SDL_DestroyTexture(instruction);
            SDL_DestroyTexture(sphere);
            SDL_DestroyTexture(trial_background);
            SDL_DestroyTexture(background2);
            SDL_DestroyTexture(sphere2);
            SDL_DestroyTexture(Target2);
            SDL_DestroyTexture(Target);
            SDL_DestroyTexture(instruction2);
            SDL_Quit();
            return 1;
        }

        Ball.Set(Centroid.X - SPHERE_SIZE / 2, Centroid.Y - SPHERE_SIZE / 2, SPHERE_SIZE, SPHERE_SIZE);

        Next_Trial = false;
        while (!Next_Trial) {
            // Listen to OpenBCI for Location Data
            Current_X = DirectionalReader(Feature1, Previous_X);
            Current_Y = DirectionalReader(Feature2, Previous_Y);

            if (Current_X != "No Update" && Current_Y != "No Update") {
                Y_Direction = DecodeString(Current_Y);
                X_Direction = DecodeString(Current_X);
                Previous_X = Current_X;
                Previous_Y = Current_Y;

                for (int rate = 0; rate < 10; rate++) {
                    Ball.Translocation(X_Direction.Results[0],Y_Direction.Results[0]);
                    Ball.rangeCheck(Margin, SCREEN_WIDTH - Margin, 0, SCREEN_HEIGHT);
                    SDL_RenderClear(renderer);
                    renderTexture(trial_background, renderer, Margin, 0, SCREEN_HEIGHT, SCREEN_HEIGHT);
                    renderTexture(sphere, renderer, Ball.X, Ball.Y, Ball.W, Ball.H);
                    renderTexture(Target, renderer, Goal.X, Goal.Y, Goal.W, Goal.H);
                    SDL_RenderPresent(renderer);
                    if (Determine_Location(Ball,Goal)) {
                        Next_Trial = true;
                        rate = 10;
                        SDL_RenderClear(renderer);
                        renderTexture(trial_background, renderer, Margin, 0, SCREEN_HEIGHT, SCREEN_HEIGHT);
                        renderTexture(sphere2, renderer, Ball.X, Ball.Y, Ball.W, Ball.H);
                        renderTexture(Target2, renderer, Goal.X, Goal.Y, Goal.W, Goal.H);
                        SDL_RenderPresent(renderer);
                        Sync_Send(Feedback,"Complete");
                        SDL_Delay(1000);
                    }
                    if (EventDetection(event) == SDL_SCANCODE_Q) {
                        Next_Trial = true;
                        Finishing = true;
                        Sync_Send(Feedback,"Complete");
                    }
                }
            }

            if (Sync_Check(Trigger_Log,"Trial End")) {
                Next_Trial = true;
            }
            // Check for Break or other commands
            if (EventDetection(event) == SDL_SCANCODE_Q) {
                Next_Trial = true;
                Finishing = true;
                Sync_Send(Feedback,"Complete");
            }
        }

        SDL_RenderClear(renderer);
        renderTexture(trialEnd, renderer, (SCREEN_WIDTH-SCREEN_HEIGHT)/2, 0, SCREEN_HEIGHT, SCREEN_HEIGHT);
        SDL_RenderPresent(renderer);
        if (!Sync_Wait(Trigger_Log,"Trial End", "ALL FINISH", event)) {
            Sync_Send(Feedback,"Display End");
            SDL_DestroyWindow(window);
            SDL_DestroyRenderer(renderer);
            SDL_DestroyTexture(background);
            SDL_DestroyTexture(instruction);
            SDL_DestroyTexture(sphere);
            SDL_DestroyTexture(trial_background);
            SDL_DestroyTexture(background2);
            SDL_DestroyTexture(sphere2);
            SDL_DestroyTexture(Target2);
            SDL_DestroyTexture(Target);
            SDL_DestroyTexture(instruction2);
            SDL_Quit();
            return 1;
        }
    }

    // Cleanning up
    Sync_Send(Feedback,"Display End");
    SDL_DestroyWindow(window);
    SDL_DestroyRenderer(renderer);
    SDL_DestroyTexture(background);
    SDL_DestroyTexture(instruction);
    SDL_DestroyTexture(sphere);
    SDL_DestroyTexture(trial_background);
    SDL_DestroyTexture(background2);
    SDL_DestroyTexture(sphere2);
    SDL_DestroyTexture(Target2);
    SDL_DestroyTexture(Target);
    SDL_DestroyTexture(instruction2);
    SDL_Quit();
    return 0;
}
示例#2
0
int main(void)
{
    if(SDL_Init(SDL_INIT_VIDEO) != 0)
    {
        fprintf(stderr, "SDL_Init( Error : %s\n", SDL_GetError());
        exit(1);
    }

    SDL_Window *win = SDL_CreateWindow("Hello World !", 100, 100, 700, 700, SDL_WINDOW_SHOWN);

    if(win == NULL)
    {
        fprintf(stderr, "SDL_CreateWindow Error : %s\n", SDL_GetError());
        exit(1);
    }

    SDL_Renderer *ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);

    if(ren == NULL)
    {
        SDL_DestroyWindow(win);
        fprintf(stderr, "SDL_CreateRenderer Error: %s\n", SDL_GetError());
        SDL_Quit();
        exit(1);
    }

    SDL_Surface *bmp = SDL_LoadBMP("../media/wtf.bmp");

    if(bmp == NULL)
    {
        SDL_DestroyRenderer(ren);
        SDL_DestroyWindow(win);
        fprintf(stderr, "SDL_LoadBMP Error: %s \n", SDL_GetError());
        SDL_Quit();
        exit(1);
    }

    SDL_Texture *tex = SDL_CreateTextureFromSurface(ren, bmp);
    SDL_FreeSurface(bmp);

    if(tex == NULL)
    {
        SDL_DestroyRenderer(ren);
        SDL_DestroyWindow(win);
        fprintf(stderr, "SDL_CreateTextureFromSurface Error :%s \n", SDL_GetError());
        SDL_Quit();
        exit(1);
    }

    if(Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 4096) == -1)

        return false;

    SDL_RenderClear(ren);
    SDL_RenderCopy(ren, tex, NULL, NULL);
    SDL_RenderPresent(ren);

    Mix_Music *music = NULL;

    SDL_Event event;
    bool running = false;
    int x = 0, y = 0;
    bool re = true;

    while(!running)
    {
        if(!re)
            exit(0);

        //  execl("finalProject", NULL);

        if(SDL_PollEvent(&event))
        {
            if(event.type == SDL_QUIT)  running = true;

            if(event.type == SDL_MOUSEMOTION)
            {
                SDL_GetMouseState(&x, &y);


                if((x >= 66) && (x <= 550) && (y >= 638) && (y <= 700))
                {
                    re = true;
                }

                /*first sqr
                x - 66 y - 638         x - 550 y 638
                x - 66 y - 700         x - 550 y - 700
                */
                else if((x >= 550) && (x <= 582) && (y >= 536) && (y <= 800))
                {
                    re = true;
                }

                /*second
                x - 550 y - 536        x 582  y 536
                x - 550 y - 700        x 582  y 700
                */
                else if((x >= 66) && (x <= 550) && (y >= 536) && (y <= 590))
                {
                    re = true;
                }
                /*
                next
                x - 66 y - 536         x - 550 y - 536
                x - 66 y - 590         x - 550 y - 590
                */
                else if((x >= 66) && (x <= 105) && (y >= 300) && (y <= 536))
                {
                    re = true;
                }
                /*
                next
                x - 66 y - 300         x - 105 y - 300
                x - 66 y - 536         x - 105 y - 536
                */
                else if((x >= 105) && (x <= 335) && (y >= 300) && (y <= 342))
                {
                    re = true;
                }
                /*
                next
                x - 105 y - 300        x - 335 y - 300
                x - 105 y - 342        x - 335 y - 342
                */
                else if((x >= 335) && (x <= 354) && (y >= 300) && (y <= 311))
                {
                    re = true;
                }
                /*
                next
                x - 335  y - 300       x - 354 y - 300
                x - 335  y - 311       x - 354 y - 311
                */
                else if((x >= 346) && (x <= 354) && (y >= 237) && (y <= 300))
                {
                    re = true;
                }
                /*
                next
                x - 346 y - 237        x - 354 y - 237
                x - 346 y - 300        x - 354 y - 300
                */
                else if((x >= 322) && (x <= 346) && (y >= 237) && (y <= 243))
                {
                    re = true;
                }
                /*
                next
                x - 322 y - 237        x - 346 y - 237
                x - 322 y - 243        x - 346 y - 243
                */
                else if((x >= 322) && (x <= 330) && (y >= 200) && (y <= 237))
                {
                    re = true;
                }
                /*
                next
                x - 322 y - 200        x - 330 y - 200
                x - 322 y - 237        x - 330 y - 237
                */
                else if((x >= 330) && (x <= 355) && (y >= 200) && (y <= 214))
                {
                    re = true;
                }
                /*
                next
                x - 330 y - 200        x - 355 y - 200
                x - 330 y - 214        x - 355 y - 214
                */
                else if((x >= 346) && (x <= 355) && (y >= 180) && (y <= 200))
                {
                    re = true;
                }
                /*
                next
                x - 346 y - 180        x - 355 y - 180
                x - 346 y - 200        x - 355 y - 200
                */
                else if((x >= 328) && (x <= 370) && (y >= 100) && (y <= 180))
                {

                    music = Mix_LoadMUS("../media/0111.wav");

                    if(music == NULL)
                    {
                        return false;
                    }

                    if(Mix_PlayMusic(music, -1) == -1)
                    {
                        return 1;
                    }
                    bmp = SDL_LoadBMP("../media/nice.bmp");

                    if(bmp == NULL)
                    {
                        SDL_DestroyRenderer(ren);
                        SDL_DestroyWindow(win);
                        fprintf(stderr, "SDL_LoadBMP Error: %s \n", SDL_GetError());
                        SDL_Quit();
                        exit(1);
                    }

                    tex = SDL_CreateTextureFromSurface(ren, bmp);
                    SDL_FreeSurface(bmp);

                    if(tex == NULL)
                    {
                        SDL_DestroyRenderer(ren);
                        SDL_DestroyWindow(win);
                        fprintf(stderr, "SDL_CreateTextureFromSurface Error :%s \n", SDL_GetError());
                        SDL_Quit();
                        exit(1);
                    }

                    //Mix_FreeMusic(music);
                    SDL_RenderClear(ren);
                    SDL_RenderCopy(ren, tex, NULL, NULL);
                    SDL_RenderPresent(ren);
                    SDL_Delay(10000);
                    running = true;

                }
                else re = false;

                /*
                topchik
                x - 328 y - 100        x - 370 y - 100
                x - 328 y - 178        x - 370 y - 178*/

            }

        }
    }




    SDL_DestroyTexture(tex);
    SDL_DestroyRenderer(ren);
    SDL_DestroyWindow(win);
    SDL_Quit();

    return 0;
}
示例#3
0
int main() 
{
    SDL_Init(SDL_INIT_VIDEO);

    // SDL Initialization
    SDL_Window *window = SDL_CreateWindow("Roguelike", 
                                          SDL_WINDOWPOS_UNDEFINED, 
                                          SDL_WINDOWPOS_UNDEFINED,
                                          SCREEN_WIDTH, SCREEN_HEIGHT,
                                          0);//SDL_WINDOW_FULLSCREEN_DESKTOP);
    SDL_Renderer *renderer = SDL_CreateRenderer(window, 0, SDL_RENDERER_SOFTWARE);

    SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear");
    SDL_RenderSetLogicalSize(renderer, SCREEN_WIDTH, SCREEN_HEIGHT);

    SDL_Texture *screen = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888,
                                            SDL_TEXTUREACCESS_STREAMING,
                                            SCREEN_WIDTH, SCREEN_HEIGHT);

    // Set up our console
    PT_Console *console = PT_ConsoleInit(SCREEN_WIDTH, SCREEN_HEIGHT,
                                         GRID_ROW_COUNT, GRID_COL_COUNT);
    PT_ConsoleSetBitmapFont(console, "./terminal16x16.png", 0, 16, 16);

    game_init();

    // Main game loop
    u32 delayTime = 1000 / FPS_LIMIT;
    u32 frameStart, frameTime = 0;
    i32 spareTime = 0;
    bool done = false;
    while (!done) {
        frameStart = SDL_GetTicks();

        // Handle all events in the queue
        SDL_Event event;
        while (SDL_PollEvent(&event) != 0) {

            if (event.type == SDL_QUIT) {
                done = true;
                break;
            }

            if (event.type == SDL_KEYDOWN) {
                SDL_Keycode key = event.key.keysym.sym;

                switch (key) {
                    case SDLK_UP:
                        object_move(player, 0, -1);
                        break;
                    case SDLK_DOWN:
                        object_move(player, 0, 1);
                        break;
                    case SDLK_LEFT:
                        object_move(player, -1, 0);
                        break;
                    case SDLK_RIGHT:
                        object_move(player, 1, 0);
                        break;
                    default:
                        break;
                }
            }

        }

        // Render the current frame
        render_all(renderer, screen, console);

        // Avoid pegging the CPU at 100% by sleeping for a bit
        frameTime = SDL_GetTicks() - frameStart;
        spareTime = delayTime - frameTime;
        if (spareTime > 0) {
            SDL_Delay(spareTime);
        }
    }

    // Clean up
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);

    SDL_Quit();
    return 0;
}
示例#4
0
extern "C" int main(int argcount, char** argvec)
{

	#ifdef NO_STDERR
	std::freopen("/dev/null", "w", stderr);
	std::cerr.sync_with_stdio(true);
	#endif

	std::cerr << "Frogatto engine version " << preferences::version() << "\n";
	LOG( "After print engine version" );

	#if defined(TARGET_BLACKBERRY)
		chdir("app/native");
		std::cout<< "Changed working directory to: " << getcwd(0, 0) << std::endl;
	#endif

	std::string level_cfg = "titlescreen.cfg";
	bool unit_tests_only = false, skip_tests = false;
	bool run_benchmarks = false;
	std::vector<std::string> benchmarks_list;
	std::string utility_program;
	std::vector<std::string> util_args;
	std::string server = "wesnoth.org";

	const char* profile_output = NULL;
	std::string profile_output_buf;

	std::string orig_level_cfg = level_cfg;
	std::string override_level_cfg = "";

	int modules_loaded = 0;

	std::vector<std::string> argv;
	for(int n = 1; n < argcount; ++n) {
		argv.push_back(argvec[n]);
        
        if(argv.size() >= 2 && argv[argv.size()-2] == "-NSDocumentRevisionsDebugMode" && argv.back() == "YES") {
            //XCode passes these arguments by default when debugging -- make sure they are ignored.
            argv.resize(argv.size()-2);
        }
	}

	if(sys::file_exists("./master-config.cfg")) {
		variant cfg = json::parse_from_file("./master-config.cfg");
		if(cfg.is_map()) {
			if(cfg["name"].is_null() == false) {
				preferences::set_preferences_path_from_module(cfg["name"].as_string());
				//XXX module::set_module_name(cfg["name"].as_string(), cfg["name"].as_string());
			} else if( cfg["id"].is_null() == false) {
				preferences::set_preferences_path_from_module(cfg["id"].as_string());
				//XXX module::set_module_name(cfg["id"].as_string(), cfg["id"].as_string());
			}
			if(cfg["arguments"].is_null() == false) {
				std::vector<std::string> additional_args = cfg["arguments"].as_list_string();
				argv.insert(argv.begin(), additional_args.begin(), additional_args.end());
			}
		}
	}

	for(int n = 0; n < argv.size(); ++n) {
		const int argc = argv.size();
		const std::string arg(argv[n]);
		std::string arg_name, arg_value;
		std::string::const_iterator equal = std::find(arg.begin(), arg.end(), '=');
		if(equal != arg.end()) {
			arg_name = std::string(arg.begin(), equal);
			arg_value = std::string(equal+1, arg.end());
		}
		if(arg_name == "--module") {
			if(load_module(arg_value, &argv) != 0) {
				std::cerr << "FAILED TO LOAD MODULE: " << arg_value << "\n";
				return -1;
			}
			++modules_loaded;
		}
	}

	if(modules_loaded == 0) {
		if(load_module(DEFAULT_MODULE, &argv) != 0) {
			std::cerr << "FAILED TO LOAD MODULE: " << DEFAULT_MODULE << "\n";
			return -1;
		}
	}

	preferences::load_preferences();
	LOG( "After load_preferences()" );

	// load difficulty settings after module, before rest of args.
	difficulty::manager();

	for(int n = 0; n < argv.size(); ++n) {
		const int argc = argv.size();
		const std::string arg(argv[n]);
		std::string arg_name, arg_value;
		std::string::const_iterator equal = std::find(arg.begin(), arg.end(), '=');
		if(equal != arg.end()) {
			arg_name = std::string(arg.begin(), equal);
			arg_value = std::string(equal+1, arg.end());
		}
		
		if(arg_name == "--module") {
			// ignore already processed.
		} else if(arg_name == "--profile" || arg == "--profile") {
			profile_output_buf = arg_value;
			profile_output = profile_output_buf.c_str();
		} else if(arg_name == "--utility") {
			utility_program = arg_value;
			for(++n; n < argc; ++n) {
				const std::string arg(argv[n]);
				util_args.push_back(arg);
			}

			break;
		} else if(arg == "--benchmarks") {
			run_benchmarks = true;
		} else if(arg_name == "--benchmarks") {
			run_benchmarks = true;
			benchmarks_list = util::split(arg_value);
		} else if(arg == "--tests") {
			unit_tests_only = true;
		} else if(arg == "--no-tests") {
			skip_tests = true;
		} else if(arg == "--width" && n+1 < argc) {
			std::string w(argv[++n]);
			preferences::set_actual_screen_width(boost::lexical_cast<int>(w));
		} else if(arg == "--height" && n+1 < argc) {
			std::string h(argv[++n]);
			preferences::set_actual_screen_height(boost::lexical_cast<int>(h));
		} else if(arg == "--level" && n+1 < argc) {
			override_level_cfg = argv[++n];
		} else if(arg == "--host" && n+1 < argc) {
			server = argv[++n];
		} else if(arg == "--compiled") {
			preferences::set_load_compiled(true);
#ifndef NO_EDITOR
		} else if(arg == "--edit") {
			preferences::set_edit_on_start(true);
#endif
		} else if(arg == "--no-compiled") {
			preferences::set_load_compiled(false);
#if defined(TARGET_PANDORA)
		} else if(arg == "--no-fbo") {
			preferences::set_fbo(false);
		} else if(arg == "--no-bequ") {
			preferences::set_bequ(false);
#endif
		} else if(arg == "--help" || arg == "-h") {
			print_help(std::string(argvec[0]));
			return 0;
		} else {
			const bool res = preferences::parse_arg(argv[n].c_str());
			if(!res) {
				std::cerr << "unrecognized arg: '" << arg << "'\n";
				return -1;
			}
		}
	}

	checksum::manager checksum_manager;

	preferences::expand_data_paths();
	LOG( "After expand_data_paths()" );

	std::cerr << "Preferences dir: " << preferences::user_data_path() << '\n';

	//make sure that the user data path exists.
	if(!preferences::setup_preferences_dir()) {
		std::cerr << "cannot create preferences dir!\n";
	}

	std::cerr << "\n";

	if(utility_program.empty() == false && test::utility_needs_video(utility_program) == false) {
		test::run_utility(utility_program, util_args);
		return 0;
	}

#if defined(TARGET_PANDORA)
    EGL_Open();
#endif

#if defined(__ANDROID__)
	std::freopen("stdout.txt","w",stdout);
	std::freopen("stderr.txt","w",stderr);
	std::cerr.sync_with_stdio(true);
#endif

	LOG( "Start of main" );
	
	Uint32 sdl_init_flags = SDL_INIT_VIDEO | SDL_INIT_JOYSTICK;
#ifdef _WINDOWS
	sdl_init_flags |= SDL_INIT_TIMER;
#endif
	if(SDL_Init(sdl_init_flags) < 0) {
		std::cerr << "could not init SDL\n";
		return -1;
	}
	LOG( "After SDL_Init" );

#ifdef TARGET_OS_HARMATTAN
	g_type_init();
#endif
	i18n::init ();
	LOG( "After i18n::init()" );

//	SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);

#if defined(TARGET_OS_IPHONE) || defined(TARGET_BLACKBERRY) || defined(__ANDROID__)
	//on the iPhone and PlayBook, try to restore the auto-save if it exists
	if(sys::file_exists(preferences::auto_save_file_path()) && sys::read_file(std::string(preferences::auto_save_file_path()) + ".stat") == "1") {
		level_cfg = "autosave.cfg";
		sys::write_file(std::string(preferences::auto_save_file_path()) + ".stat", "0");

	}
#endif

	if(override_level_cfg.empty() != true) {
		level_cfg = override_level_cfg;
		orig_level_cfg = level_cfg;
	}

#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
	int width, height;
	iphone_screen_res(&width, &height);
	preferences::set_actual_screen_width(width);
	preferences::set_actual_screen_height(height);
	int multiplier = 2;
	if (width > 320)
	{
		//preferences::set_use_pretty_scaling(true);
		multiplier = 1;
	}
	preferences::set_virtual_screen_width(height*multiplier);
	preferences::set_virtual_screen_height(width*multiplier);
	preferences::set_control_scheme(height % 1024 ? "iphone_2d" : "ipad_2d");
	
	SDL_WindowID windowID = SDL_CreateWindow (NULL, 0, 0, preferences::actual_screen_width(), preferences::actual_screen_height(),
		SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN |
		SDL_WINDOW_BORDERLESS);
	if (windowID == 0) { 
		std::cerr << "Could not create window: " << SDL_GetError() << "\n"; 
		return -1;
	}
	
	//	if (SDL_GL_CreateContext(windowID) == 0) {
	//		std::cerr << "Could not create GL context: " << SDL_GetError() << "\n";
	//		return -1;
	//	}
	if (SDL_CreateRenderer(windowID, -1, 0) != 0) {
		std::cerr << "Could not create renderer\n";
		return -1;
	}
	
#else
#ifdef TARGET_OS_HARMATTAN
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 1);
	if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),0,SDL_OPENGLES | SDL_FULLSCREEN) == NULL) {
		std::cerr << "could not set video mode\n";
		return -1;
	}

	preferences::init_oes();
	SDL_ShowCursor(0);
#else
#ifndef __APPLE__
	graphics::surface wm_icon = graphics::surface_cache::get("window-icon.png");
	if(!wm_icon.null()) {
		SDL_WM_SetIcon(wm_icon, NULL);
	}
#endif

#if defined(TARGET_PANDORA)
	if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),16,SDL_FULLSCREEN) == NULL) {
		std::cerr << "could not set video mode\n";
		return -1;
	}
    EGL_Init();
    preferences::init_oes();
#elif defined(TARGET_TEGRA)
	//if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),0,preferences::resizable() ? SDL_RESIZABLE : 0|preferences::fullscreen() ? SDL_FULLSCREEN : 0) == NULL) {
	if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),0,SDL_FULLSCREEN) == NULL) {
		std::cerr << "could not set video mode\n";
		return -1;
	}
    EGL_Init();
    preferences::init_oes();
#elif defined(TARGET_BLACKBERRY)
	if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),0,SDL_OPENGL|SDL_FULLSCREEN) == NULL) {
		std::cerr << "could not set video mode\n";
		return -1;
	}
	preferences::init_oes();
#elif defined(__ANDROID__)
    SDL_Rect** r = SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_OPENGL);
    if( r != (SDL_Rect**)0 && r != (SDL_Rect**)-1 ) {
        preferences::set_actual_screen_width(r[0]->w);
        preferences::set_actual_screen_height(r[0]->h);
		if(r[0]->w < 640) {
        	preferences::set_virtual_screen_width(r[0]->w*2);
        	preferences::set_virtual_screen_height(r[0]->h*2);
		} else {
			preferences::set_virtual_screen_width(r[0]->w);
			preferences::set_virtual_screen_height(r[0]->h);
		}
		preferences::set_control_scheme(r[0]->h >= 1024 ? "ipad_2d" : "android_med");
    }

    if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),16,SDL_FULLSCREEN|SDL_OPENGL) == NULL) {
		std::cerr << "could not set video mode\n";
		return -1;
    }
#else
	if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),0,SDL_OPENGL|(preferences::resizable() ? SDL_RESIZABLE : 0)|(preferences::fullscreen() ? SDL_FULLSCREEN : 0)) == NULL) {
		std::cerr << "could not set video mode\n";
		return -1;
	}
#endif
#endif

#endif

//	srand(time(NULL));

	const stats::manager stats_manager;
#ifndef NO_EDITOR
	const external_text_editor::manager editor_manager;
#endif // NO_EDITOR

	std::cerr
		<< "\n"
		<< "OpenGL vendor: " << reinterpret_cast<const char *>(glGetString(GL_VENDOR)) << "\n"
		<< "OpenGL version: " << reinterpret_cast<const char *>(glGetString(GL_VERSION)) << "\n"
		<< "OpenGL extensions: " << reinterpret_cast<const char *>(glGetString(GL_EXTENSIONS)) << "\n"
		<< "\n";
	glShadeModel(GL_SMOOTH);
	glEnable(GL_BLEND);
	glEnable(GL_TEXTURE_2D);
	glEnableClientState(GL_VERTEX_ARRAY);
	glEnableClientState(GL_TEXTURE_COORD_ARRAY);
	
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	SDL_WM_SetCaption(module::get_module_pretty_name().c_str(), module::get_module_pretty_name().c_str());

	std::cerr << "JOYSTICKS: " << SDL_NumJoysticks() << "\n";

	const load_level_manager load_manager;

	{ //manager scope
	const font::manager font_manager;
	const sound::manager sound_manager;
	const joystick::manager joystick_manager;
		
	#if !TARGET_OS_IPHONE && !TARGET_IPHONE_SIMULATOR
	const SDL_Surface* fb = SDL_GetVideoSurface();
	if(fb == NULL) {
		return 0;
	}
	#endif

	graphics::texture::manager texture_manager;

#ifndef NO_EDITOR
	editor::manager editor_manager;
#endif

	variant preloads;
	loading_screen loader;
	try {
		sound::init_music(json::parse_from_file(module::map_file("data/music.cfg")));

		std::string filename = "data/fonts." + i18n::get_locale() + ".cfg";
		if (!sys::file_exists(filename))
			filename = "data/fonts.cfg";
		graphical_font::init(json::parse_from_file(module::map_file(filename)));

		preloads = json::parse_from_file(module::map_file("data/preload.cfg"));
		int preload_items = preloads["preload"].num_elements();
		loader.set_number_of_items(preload_items+7); // 7 is the number of items that will be loaded below
		custom_object::init();
		loader.draw_and_increment(_("Initializing custom object functions"));
		init_custom_object_functions(json::parse_from_file(module::map_file("data/functions.cfg")));
		loader.draw_and_increment(_("Initializing textures"));
		loader.load(preloads);
		loader.draw_and_increment(_("Initializing tiles"));
		tile_map::init(json::parse_from_file(module::map_file("data/tiles.cfg")));
		loader.draw_and_increment(_("Initializing GUI"));

		variant gui_node = json::parse_from_file(module::map_file(preferences::load_compiled() ? "data/compiled/gui.cfg" : "data/gui.cfg"));
		gui_section::init(gui_node);
		loader.draw_and_increment(_("Initializing GUI"));
		framed_gui_element::init(gui_node);

	} catch(const json::parse_error& e) {
		std::cerr << "ERROR PARSING: " << e.error_message() << "\n";
		return 0;
	}
	loader.draw(_("Loading level"));

	if(!skip_tests && !test::run_tests()) {
		return -1;
	}

	if(unit_tests_only) {
		return 0;
	}
#if defined(__APPLE__) && !(TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE)
	GLint swapInterval = 1;
	CGLSetParameter(CGLGetCurrentContext(), kCGLCPSwapInterval, &swapInterval);
#endif

#ifndef SDL_VIDEO_OPENGL_ES
	GLenum glew_status = glewInit();
	ASSERT_EQ(glew_status, GLEW_OK);
#endif

	loader.finish_loading();
	//look to see if we got any quit events while loading.
	{
	SDL_Event event;
	while(SDL_PollEvent(&event)) {
		if(event.type == SDL_QUIT) {
			return 0;
		}
	}
	}

	formula_profiler::manager profiler(profile_output);
	texture_frame_buffer::init();

	if(run_benchmarks) {
		if(benchmarks_list.empty() == false) {
			test::run_benchmarks(&benchmarks_list);
		} else {
			test::run_benchmarks();
		}
		return 0;
	} else if(utility_program.empty() == false) {
		test::run_utility(utility_program, util_args);
		return 0;
	}

	bool quit = false;
	bool of_initialized = false;

	while(!quit && !show_title_screen(level_cfg)) {
		boost::intrusive_ptr<level> lvl(load_level(level_cfg));
		
#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
		if (!of_initialized)
		{
			of_init();
			of_initialized = true;
		}
#endif

		//see if we're loading a multiplayer level, in which case we
		//connect to the server.
		multiplayer::manager mp_manager(lvl->is_multiplayer());
		if(lvl->is_multiplayer()) {
			multiplayer::setup_networked_game(server);
		}

		if(lvl->is_multiplayer()) {
			last_draw_position() = screen_position();
			std::string level_cfg = "waiting-room.cfg";
			boost::intrusive_ptr<level> wait_lvl(load_level(level_cfg));
			wait_lvl->finish_loading();
			wait_lvl->set_multiplayer_slot(0);
			if(wait_lvl->player()) {
				wait_lvl->player()->set_current_level(level_cfg);
			}
			wait_lvl->set_as_current_level();

			level_runner runner(wait_lvl, level_cfg, orig_level_cfg);

			multiplayer::sync_start_time(*lvl, boost::bind(&level_runner::play_cycle, &runner));

			lvl->set_multiplayer_slot(multiplayer::slot());
		}

		last_draw_position() = screen_position();

		assert(lvl.get());
		if(!lvl->music().empty()) {
			sound::play_music(lvl->music());
		}

		if(lvl->player() && level_cfg != "autosave.cfg") {
			lvl->player()->set_current_level(level_cfg);
			lvl->player()->get_entity().save_game();
		}

		set_scene_title(lvl->title());

		try {
			quit = level_runner(lvl, level_cfg, orig_level_cfg).play_level();
			level_cfg = orig_level_cfg;
		} catch(multiplayer_exception&) {
		}
	}

	level::clear_current_level();

	} //end manager scope, make managers destruct before calling SDL_Quit
//	controls::debug_dump_controls();
#if defined(TARGET_PANDORA) || defined(TARGET_TEGRA)
    EGL_Destroy();
#endif

	SDL_Quit();
	
	preferences::save_preferences();
	std::cerr << SDL_GetError() << "\n";
#if !defined(TARGET_OS_HARMATTAN) && !defined(TARGET_TEGRA) && !defined(TARGET_BLACKBERRY) && !defined(__ANDROID__)
	std::cerr << gluErrorString(glGetError()) << "\n";
#endif
	return 0;
}
示例#5
0
bool Game::Init(const char* title, int xpos, int ypos, int width, int height,
                int flags) {

    // attempt to initialize SDL
    if (SDL_Init(SDL_INIT_EVERYTHING) == 0) {
        Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 4097);

        std::cout << "SDL init success\n";
//		 init the window

        m_pWindow = SDL_CreateWindow(title, xpos, ypos, width, height, flags);
        if (m_pWindow != 0) // window init success
        {
            std::cout << "window creation success\n";
            m_pRenderer = SDL_CreateRenderer(m_pWindow, -1, 0);
            if (m_pRenderer != 0) // renderer init success
            {
                std::cout << "renderer creation success\n";
                SDL_SetRenderDrawColor(m_pRenderer, 255, 255, 255, 255);

            } else {
                std::cout << "renderer init fail\n";
                return false; // renderer init fail
            }
        } else {
            std::cout << "window init fail\n";
            return false; // window init fail
        }
    } else {
        std::cout << "SDL init fail\n";
        return false; // SDL init fail
    }

    std::cout << "init success\n";

    m_bRunning = true; // everything inited successfully,
//		start the main loop
    //initial game State

    SoundsBank::sound = new SoundsBank();
    SoundsBank::sound->initSoundEffect("sounds/hover.wav");
    SoundsBank::sound->initSoundEffect("sounds/connect.wav");
    SoundsBank::sound->initSoundEffect("sounds/button-24.wav");
    SoundsBank::sound->initSoundEffect("sounds/no_time.wav");
    SoundsBank::sound->initMusic("sounds/removeCards.mp3");

    StateManager::stateMachine = new StateManager();
    StateManager::stateMachine->setCurrentGameStates(MENU);

    Timer::g_Timer = new Timer();

    StartMenu.InitSatistics(m_pRenderer);
    StartMenu.Init(m_pRenderer);
    StartMenu.InitRules(m_pRenderer);

    m_buttonsMenu.Init(m_pRenderer);
    for (int iter = 0; iter < 5; iter++) {
        m_buttonsMenu.setSource(iter * 232, 0, 232, 52);
        m_buttonsMenu.setDestination(100, (250 + 60 * iter), 260, 50);

        m_buttonSet.push_back(m_buttonsMenu);
    }
    PlayButton = m_buttonSet.at(0);
    PlayButton.setSource(0, 0, 232, 52);
    PlayButton.setDestination(410, 684, 240, 60);

    m_buttonSet.at(4).setDestination(25, 699, 150, 45);

//	Buttons MenuButton;
    texture.Init(m_pRenderer);
    m_cardLogic.Init(m_pRenderer);

    txt.Set(450, 60, 60, 45, " ");
    txt.setTextColor(255, 255, 0, 255);

    level.Set(756, 60, 60, 45, " ");
    level.setTextColor(255, 255, 0, 255);

//	**************
    bet.Set(920, 690, 60, 44, " ");
    bet.setTextColor(255, 255, 0, 255);
    bet.IntToTextMessage(5);

    credit.Set(270, 690, 60, 45, " ");
    credit.setTextColor(255, 255, 0, 255);

    profit.Set(756, 690, 60, 44, " ");
    profit.setTextColor(255, 255, 0, 255);

    m_stat.createFile();
    m_Recovery.createRecoverFile();
    return true;

}/*end of Init*/
示例#6
0
int main(int argc, char **argv){
    if(IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG != IMG_INIT_PNG){
        err_msg("IMG_INIT");
        return 1;
    }
    
    if (SDL_Init(SDL_INIT_EVERYTHING)){
        //std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl;
        err_msg("SDL_Init");
        return 1;
    }
    SDL_Window *win = SDL_CreateWindow("Hello World!", 100, 100, SCREEN_WIDTH, SCREEN_HEIGHT,
            SDL_WINDOW_SHOWN);
    if (!win){
        //std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl;
        err_msg("CreateWindow");
        return 1;
    }
    SDL_Renderer *ren = SDL_CreateRenderer(win, -1, 
            SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
    if (!ren){
        //std::cout << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl;
        err_msg("CreateRenderer");
        return 1;
    }
    
    SDL_Texture *background = load_texture("background.png", ren);
    SDL_Texture *image = load_texture("image.png", ren);
    if(!((long)background & (long)image)){
        err_msg("Load Images");
        return 1;
    }
    SDL_RenderClear(ren);
    int w, h;
    SDL_QueryTexture(background, NULL, NULL, &w, &h);
    /*for(int i = 0; i < 4; i++){
        render_texture(background, ren, (i & 1) * w, ((i >> 1) & 1) * h);
    }*/
    int tile_x = SCREEN_WIDTH / TILE_SIZE;
    int tile_y = SCREEN_HEIGHT / TILE_SIZE;

    for(int i = 0; i < tile_x * tile_y; i++){
        int x = i % tile_x;
        int y = i / tile_x;
        render_texture(background, ren, x * TILE_SIZE, y * TILE_SIZE, TILE_SIZE, TILE_SIZE);
    }
   
    int iW, iH;
    SDL_QueryTexture(image, NULL, NULL, &iW, &iH);
    int x = SCREEN_WIDTH / 2 - iW / 2;
    int y = SCREEN_HEIGHT / 2 - iH / 2;
    render_texture(image, ren, x, y);

    SDL_RenderPresent(ren);
    SDL_Delay(2000);
    SDL_DestroyTexture(background);
    SDL_DestroyTexture(image);
    SDL_DestroyRenderer(ren);
    SDL_DestroyWindow(win);
    SDL_Quit();






}   
//-----------------------------------------------------------------
// Game Engine General Methods
//-----------------------------------------------------------------
bool GameEngine::Initialize(const char* szTitle, const char* szIcon, int iWidth, int iHeight)
{
  // Set the member variables for the game engine
  m_pGameEngine = this;
  m_hWindow = NULL;
  if (strlen(szTitle) > 0)
    strcpy(m_szTitle, szTitle);
  if (strlen(szTitle) > 0)
    strcpy(m_szIcon, szIcon);
  
  m_iWidth = iWidth;
  m_iHeight = iHeight;
  m_iFrameDelay = 50;         // 20 FPS default
  m_bSleep = true;
  
  SDL_Init(SDL_INIT_VIDEO |
	   SDL_INIT_AUDIO |
	   SDL_INIT_GAMECONTROLLER);   // Initialize SDL2

  //Initialize SDL2 Mixer
  if (Mix_OpenAudio(22050, AUDIO_U8, 2, 512) < 0){
    std::cout << "Unable to init sound engine: " << SDL_GetError() << std::endl;
  }
    
  //Initialize SDL2 TTF
  if(TTF_Init()==-1) {
    std::cout << "TTF_Init: " << TTF_GetError() << std::endl;
    exit(EXIT_FAILURE);
  }

  //create the window
  m_hWindow = SDL_CreateWindow(m_szTitle,                  // window title
			       SDL_WINDOWPOS_UNDEFINED,    // initial x position
			       SDL_WINDOWPOS_UNDEFINED,    // initial y position
			       m_iWidth,                   // width, in pixels
			       m_iHeight,                  // height, in pixels
			       SDL_RENDERER_ACCELERATED |
			       SDL_RENDERER_PRESENTVSYNC    // flags
			       );
  if (!m_hWindow)
    return false;
  
  //set the window icon from the .ico file
  // The icon is attached to the window pointer
  SDL_Surface *icone_surface = IMG_Load(szIcon);
  SDL_SetWindowIcon(m_hWindow, icone_surface);
  
  //the surface containing the icon pixel data is no longer required.
  SDL_FreeSurface(icone_surface);
  
  //Create a Renderer
  m_renderer = SDL_CreateRenderer(m_hWindow,
				  0,
				  SDL_RENDERER_ACCELERATED |
				  SDL_RENDERER_PRESENTVSYNC);
  
  //Clear the screen
  SDL_SetRenderDrawColor(m_renderer, 255, 255, 255, 255);
  SDL_RenderClear(m_renderer);
  SDL_RenderPresent(m_renderer);
  
  return true;
}
示例#8
0
int
main(
        int argc,
        char ** argv
        ) {
    int width = 600;
    int height = 600;
    bool running = true;
    float (* state_current)[NVER][NHOR] = &state_buffer_a;
    float (* state_next)[NVER][NHOR] = &state_buffer_b;
    float (* dstate_current)[NVER][NHOR] = &dstate_buffer_a;
    float (* dstate_next)[NVER][NHOR] = &dstate_buffer_b;
    float (* state_swap_temp)[NVER][NHOR];
    int mouse_x, mouse_y;
    bool ismousedown = false;
    SDL_Event event;
    SDL_Window * window = SDL_CreateWindow(
            "CO",
            SDL_WINDOWPOS_CENTERED,
            SDL_WINDOWPOS_CENTERED,
            width,
            height,
            SDL_WINDOW_SHOWN
            );
    SDL_Renderer * renderer = SDL_CreateRenderer(
            window,
            -1,
            SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC
            );
    SDL_SetRenderDrawBlendMode(
            renderer,
            SDL_BLENDMODE_BLEND
            );
    int dt, now, tick_begin = SDL_GetTicks();
    init(state_current, dstate_current);
    draw(renderer, width, height, state_current);
    SDL_RenderPresent(renderer);
    for (;;) {
        while (SDL_PollEvent(&event)) {
            switch (event.type) {
                case SDL_QUIT:
                    running = false;
                    break;
                case SDL_KEYDOWN:
                    if (event.key.keysym.sym == SDLK_ESCAPE) {
                        running = false;
                    }
                    break;
                case SDL_MOUSEBUTTONDOWN:
                    ismousedown = true;
                    break;
                case SDL_MOUSEBUTTONUP:
                    ismousedown = false;
                    break;
                default:
                    break;
            }
        }
        if (ismousedown) {
            SDL_GetMouseState(&mouse_x, &mouse_y);
            input(state_current, dstate_current,
                    mouse_x * NHOR / width, mouse_y * NVER / height);
        }
        if (!running) {
            break;
        }
        now = SDL_GetTicks();
        if ((dt = now - tick_begin) > DT) {
            tick_begin = now;
            update(state_current, state_next, dstate_current, dstate_next);
            swap(&state_current, &state_next);
            swap(&dstate_current, &dstate_next);
            draw(renderer, width, height, state_current);
            SDL_RenderPresent(renderer);
        }
    }
    SDL_DestroyRenderer(renderer);
    SDL_Quit();
}
// WINDOWS MAIN FUNCTION
// hInst = current instance of the program
// hPrevInst = previous instance which is not used anymore.
// cmdLine = holds command line arguments to be passed in to the program
// cmdShow = holds an integer to specify if we want to show this window.
int CALLBACK WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR cmdLine, int cmdShow)
{
    WNDCLASS wc = {0};
    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.hInstance = hInst;
    wc.hbrBackground = (HBRUSH)COLOR_WINDOW;
    wc.lpszClassName = wndClassName;
    wc.hCursor = 0; //TODO: Add cursors and icons to this program.
    wc.hIcon = 0;
    wc.lpfnWndProc = (WNDPROC)wndProc;

    RegisterClass(&wc);

    HWND window = CreateWindow(wndClassName, wndTitle,
                               WS_OVERLAPPEDWINDOW,
                               CW_USEDEFAULT, CW_USEDEFAULT,
                               wndWidth, wndHeight,
                               0, 0, hInst, 0);
    
    if(window)
    {
        ShowWindow(window, SW_SHOW);
        UpdateWindow(window);

        // NOTE: Initializing SDL
        if(SDL_Init(SDL_INIT_VIDEO) != 0 )
        {
            DestroyWindow(window);
            return -2;
        }

        IMG_Init(IMG_INIT_JPG | IMG_INIT_PNG);
        
        sdlWindow = SDL_CreateWindowFrom((void*)window);

        char error[MAX_PATH];
        stringCopy(error, SDL_GetError());
        OutputDebugStringA(error);

        if(!sdlWindow)
        {
            SDL_Quit();
            DestroyWindow(window);
            return -3;
        }
        
        renderer = SDL_CreateRenderer(sdlWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);

        if(!renderer)
        {
            SDL_DestroyWindow(sdlWindow);
            SDL_Quit();
            DestroyWindow(window);
            return -4;
        }

        i32 RefreshRate = 0;
        HDC dc = GetDC(window);
        i32 winRefreshRate = GetDeviceCaps(dc, VREFRESH);

        if( winRefreshRate > 1 )
        {
            RefreshRate = winRefreshRate / 2;
        }
        else
        {
            RefreshRate = 30;
        }

        r32 targetSecsPerFrame = 1.0f / RefreshRate;

        GameMemory memory = {};
        memory.permanentSize = Megabytes(64);
        memory.transientSize = Megabytes(64);
        memory.totalSize = memory.permanentSize + memory.transientSize;
        
        gameMemoryBlock = VirtualAlloc( 0, memory.totalSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);

        if(!gameMemoryBlock)
        {
            SDL_DestroyRenderer(renderer);
            SDL_DestroyWindow(sdlWindow);
            SDL_Quit();
            DestroyWindow(window);
            return -5;
        }

        memory.permanentBlock = gameMemoryBlock;
        memory.transientBlock = (i8*)gameMemoryBlock + memory.permanentSize;
        memory.readEntireFile = ReadEntireFile;
        memory.freeFile = FreeFile;
        memory.writeEntireFile = WriteEntireFile;

        Win32Dims windowDims = GetWindowDimensions(window);
        
        Render render = {};
        render.renderer = renderer;
        render.screenW = windowDims.width;
        render.screenH = windowDims.height;
        
        GameController input = {0};
        input.dt = targetSecsPerFrame;
        
        Win32State state = {0};
        state.memoryBlock = gameMemoryBlock;
        state.memorySize = memory.totalSize;

        GameCodeDLL gameCode =  Win32LoadGameCode("Game.dll", "Game_temp.dll", "lock.tmp");
        
        isRunning = true;

        r32 sleepIsGranular = (timeBeginPeriod(1) == TIMERR_NOERROR);
        
        LARGE_INTEGER lastCounter = Win32GetClock();

        i64 lastCycles = __rdtsc();
        
        LARGE_INTEGER performanceFreqPerSecRes;
        QueryPerformanceFrequency(&performanceFreqPerSecRes);
        globalPerformanceCountFreq = performanceFreqPerSecRes.QuadPart;
        
        // NOTE: PROGRAM LOOP!!
        while(isRunning)
        {
            // NOTE: compare File times for us to be able to reload the new game code
            FILETIME currentFileTime = Win32GetLastWriteTime("Game.dll");
            if(CompareFileTime(&currentFileTime, &gameCode.lastWriteTime) != 0)
            {
                Win32UnloadGameCode(&gameCode);
                gameCode = Win32LoadGameCode("Game.dll", "Game_temp.dll", "lock.tmp");
            }
            
            MSG msg = {0};
            while(PeekMessage(&msg, window, 0, 0, PM_REMOVE))
            {
                switch(msg.message)
                {
                    case WM_CLOSE:
                    {
                        isRunning = false;
                    }break;

                    case WM_KEYUP:
                    case WM_KEYDOWN:
                    case WM_SYSKEYUP:
                    case WM_SYSKEYDOWN:
                    {
                        u32 vkCode = (u32)msg.wParam;   // This contains the keycode for the key that the user pressed.
                        bool isDown = ((msg.lParam & (1 << 31)) == 0);  // Check to see if the key is down now.
                        bool wasDown = ((msg.lParam & (1 << 30)) != 0); // Check to see if the key was down previously.

                        if(isDown != wasDown)
                        {
                            if(vkCode == 'W')
                            {
                                input.moveUp.isDown = isDown;
                            }
                            else if(vkCode == 'S')
                            {
                                input.moveDown.isDown = isDown;
                            }
                            else if(vkCode == 'A')
                            {
                                input.moveLeft.isDown = isDown;
                            }
                            else if(vkCode == 'D')
                            {
                                input.moveRight.isDown = isDown;
                            }
                            if(vkCode == VK_UP)
                            {
                                input.actionUp.isDown = isDown;
                            }
                            else if(vkCode == VK_DOWN)
                            {
                                input.actionDown.isDown = isDown;
                            }
                            else if(vkCode == VK_LEFT)
                            {
                                input.actionLeft.isDown = isDown;
                            }
                            else if(vkCode == VK_RIGHT)
                            {
                                input.actionRight.isDown = isDown;
                            }
                            else if(vkCode == VK_ESCAPE)
                            {
                                input.back.isDown = isDown;
                            }
                            else if(vkCode == 'O')
                            {
                                if(isDown)
                                {
                                    if(state.recordingIndex == 0)
                                    {
                                        BeginRecording(&state, 1);
                                    }
                                    else
                                    {
                                        EndRecording(&state);
                                        BeginPlayback(&state, 1);
                                    }
                                }
                            }
                            else if(vkCode == 'P')
                            {
                                if(isDown)
                                {
                                    if(state.playbackIndex > 0)
                                    {
                                        EndPlayback(&state);
                                        ZeroMemory(&input, sizeof(input));
                                    }
                                }
                            }
                        }

                        if(isDown)
                        {
                            bool AltKeyWasDown = ((msg.lParam & (1 << 29)) != 0);
                            if(vkCode == VK_RETURN && AltKeyWasDown)
                            {
                                if(msg.hwnd)
                                {
                                    isFullscreen = !isFullscreen;
                                    Win32FullscreenToggle(msg.hwnd);
                                }
                            }
                        }

                    }break;

                    default:
                    {
                        TranslateMessage(&msg);
                        DispatchMessage(&msg);
                    }
                }
            }

            if(input.back.isDown)
            {
                isRunning = false;
                PostQuitMessage(0);
            }

            if(state.recordingIndex > 0)
            {
                RecordingInput(&state, &input);
            }
            else if(state.playbackIndex > 0)
            {
                PlaybackInput(&state, &input);
            }

            Win32Dims windowDims = GetWindowDimensions(window);
            Win32UpdateWindow(windowDims, (i32*)&render.screenW, (i32*)&render.screenH);
            
            if(gameCode.UpdateRender)
            {
                gameCode.UpdateRender(&memory, &input, &render);
            }

            LARGE_INTEGER workCounter = Win32GetClock();
            r32 workSecsElapsed = Win32GetSecondsElapsed(lastCounter, workCounter);

            r32 secondsElapsed = workSecsElapsed;
            if(secondsElapsed < targetSecsPerFrame)
            {
                if(sleepIsGranular)
                {
                    DWORD sleepMS = (DWORD)(1000.0f * (targetSecsPerFrame - secondsElapsed));
                    if(sleepMS > 0)
                    {
                        Sleep(sleepMS);
                    }
                }

                r32 testSecsElapsed = Win32GetSecondsElapsed(lastCounter, Win32GetClock());
                if(testSecsElapsed < targetSecsPerFrame)
                {
                    //TODO: LOG MISSED SLEEP HERE!!
                }

                while(secondsElapsed < targetSecsPerFrame)
                {
                    secondsElapsed = Win32GetSecondsElapsed(lastCounter, Win32GetClock());
                }
            }
            else
            {
                //TODO: MISSED FRAME RATE!!
            }
            
            LARGE_INTEGER endCounter = Win32GetClock();

            i64 endCycles = __rdtsc();
            
            r64 elapsedCounts = (r64)(endCounter.QuadPart - lastCounter.QuadPart);
            r64 elapsedCycles = (r64)(endCycles - lastCycles);

            r32 MSperFrame = ((1000.0f * Win32GetSecondsElapsed(lastCounter, endCounter)));
            r32 FPS = (r32)(globalPerformanceCountFreq / elapsedCounts);
            r32 MegaCyclesPerFrame = (r32)(elapsedCycles / (1000.0f * 1000.0f));
            
            char buffer[256];
            sprintf_s(buffer, "%.02fms, %.02ffps, %.02fmcpf\n", MSperFrame, FPS, MegaCyclesPerFrame);            
            OutputDebugStringA(buffer);
            
            lastCounter = endCounter;
            lastCycles = endCycles;
            
        } // NOTE: END OF WHILE LOOP

        //IMPORTANT: Unload this when we exit the program.
        Win32UnloadGameCode(&gameCode);        
    }
    else
    {
        // TODO: Handle Error Loggin here!!
        return -1;
    }

    if(gameMemoryBlock)
    {
        VirtualFree(gameMemoryBlock, 0, MEM_RELEASE);
    }
    
    //Close
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(sdlWindow);
    IMG_Quit();
    SDL_Quit();
    DestroyWindow(window);

    return 0;
}
示例#10
0
int main(void) 
{
SDL_Window *wind;
SDL_Renderer *ren;
VIEW view={0, 400, 0, 400};
WIN win={-1.0, 1.0, -1.0, 1.0};
int n,i,j;
int x[DIM],y[DIM]; 
float step,s,c,scx,scy;
float x0,y0,xi,yi;
clock_t start, endt;

  if(SDL_Init(SDL_INIT_VIDEO)<0)
  {
    fprintf(stderr,"Couldn't init video: %s\n",SDL_GetError());
    return(1);
  }

  wind= SDL_CreateWindow("Polygonf", 100, 100,view.vxmax,view.vymax, SDL_WINDOW_SHOWN);
  if(wind==NULL){
	fprintf(stderr,"SDL_CreateWindow Error: %s\n",SDL_GetError());
	SDL_Quit();
	return 1;
  }

  ren = SDL_CreateRenderer(wind, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
  if (ren == NULL){
	SDL_DestroyWindow(wind);
	fprintf(stderr,"SDL_CreateRenderer Error: %s\n",SDL_GetError());
	SDL_Quit();
	return 1;
  }

  SDL_SetRenderDrawColor(ren, 50, 50, 50, 255);
  SDL_RenderClear(ren);
  SDL_RenderPresent(ren);

  scx=(view.vxmax-view.vxmin)/(win.wxmax-win.wxmin);
  scy=(view.vymax-view.vymin)/(win.wymax-win.wymin);
  printf("\nDisegno di un poligono regolare: \n");
  printf("Dai il numero di vertici: \n");
  scanf("%d",&n);
  step=6.28/n;
  s=sin(step);
  c=cos(step);
  x0=1.0;
  y0=0.0;
  wind_view(x0,y0,&x[0],&y[0],scx,scy,&view,&win);
  for (i=0; i<=n; i++)
  {
      xi=x0*c-y0*s;
      yi=x0*s+y0*c;
      wind_view(xi,yi,&x[i],&y[i],scx,scy,&view,&win);
      x0=xi;
      y0=yi;
  }

start=clock();
/* disegna poligono */
  SDL_SetRenderDrawColor(ren, 255, 255, 255, 255);
  SDL_RenderDrawLine(ren, x[n-1], y[n-1], x[0], y[0]);
  for (i=0; i<n-1; i++)
	SDL_RenderDrawLine(ren, x[i], y[i], x[i+1], y[i+1]);
  SDL_RenderPresent(ren);  
#ifdef DEBUG
/* disegno artistico: definire DEBUG nel Makefile*/
  SDL_SetRenderDrawColor(ren, 255, 255, 0, 255);
  for (i=0; i<n; i++)
    for (j=i+1; j<n; j++)
       SDL_RenderDrawLine(ren, x[i], y[i], x[j], y[j]);
  SDL_RenderPresent(ren);
#endif
endt=clock();
  printf("\n Tempo: %f \n", (double)(endt-start)/CLOCKS_PER_SEC);
  press();
  SDL_Quit();
  return(0);
}
示例#11
0
文件: planet.c 项目: bigml/emoon
int main(int argc, char **argv)
{
    mtc_init("planet", 7);

    if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {
        mtc_err("sdl init error: %s", SDL_GetError());
        return 1;
    }

    if (TTF_Init() == -1) {
        mtc_err("ttf init error: %s", TTF_GetError());
        return 1;
    }

	SDL_Window *win = SDL_CreateWindow("Hello OpenGL!",
                                       100, 100, WIN_WIDTH, WIN_HEIGHT, SDL_WINDOW_SHOWN);
	if (!win) {
        mtc_err("SDL_CreateWindow Error: %s", SDL_GetError());
		return 1;
	}

	m_render = SDL_CreateRenderer(win, -1,
                                  SDL_RENDERER_ACCELERATED |
                                  SDL_RENDERER_PRESENTVSYNC);
	if (!m_render) {
        mtc_err("SDL_CreateRenderer Error: %s", SDL_GetError());
		return 1;
	}

    set_glversion();
    gl_info();

    glLoadIdentity();
    glOrtho(-10.0, 10.0, -10.0, 10.0, -10.0, 10.0);
    glEnable(GL_DEPTH_TEST);
    glEnable( GL_TEXTURE_2D );
    glDepthFunc(GL_LEQUAL);
    //glCullFace(GL_BACK);
    //glFrontFace(GL_CCW);
    //glEnable(GL_CULL_FACE);

    GLuint etex = LoadTextureRAW("earth.raw");
    if (etex == 0) {
        mtc_err("Load texture failure");
        return 1;
    }

    mutil_create_earth(5, 0, 0, 0);

    SDL_Event e;
    bool quit = false;
    while (!quit) {
        while (SDL_PollEvent(&e)) {
            if (e.type == SDL_KEYDOWN) {
                switch (e.key.keysym.sym) {
                case SDLK_ESCAPE:
                    quit = true;
                    break;
                }
            }
        }

        rend_sun();
        mutil_rend_earth(etex);

        SDL_RenderPresent(m_render);
    }
    
	SDL_DestroyRenderer(m_render);
	SDL_DestroyWindow(win);
	SDL_Quit();

    return 0;
}
示例#12
0
文件: SDL2Stage.cpp 项目: Glidias/NME
void CreateMainFrame(FrameCreationCallback inOnFrame, int inWidth, int inHeight, unsigned int inFlags, const char *inTitle, Surface *inIcon)
{
	bool fullscreen = (inFlags & wfFullScreen) != 0;
	bool opengl = (inFlags & wfHardware) != 0;
	bool resizable = (inFlags & wfResizable) != 0;
	bool borderless = (inFlags & wfBorderless) != 0;
	bool vsync = (inFlags & wfVSync) != 0;
	
	sgShaderFlags = (inFlags & (wfAllowShaders|wfRequireShaders) );

	Rect r(100,100,inWidth,inHeight);
	
	int err = InitSDL();
	if (err == -1)
	{
		fprintf(stderr,"Could not initialize SDL : %s\n", SDL_GetError());
		inOnFrame(0);
	}
	
	//SDL_EnableUNICODE(1);
	//SDL_EnableKeyRepeat(500,30);
	//gSDLIsInit = true;

	#ifdef NME_MIXER
	#ifdef HX_WINDOWS
	int chunksize = 2048;
	#else
	int chunksize = 4096;
	#endif
	
	int frequency = 44100;
	//int frequency = MIX_DEFAULT_FREQUENCY //22050
	//The default frequency would have less latency, but is incompatible with the average MP3 file
	
	if (Mix_OpenAudio(frequency, MIX_DEFAULT_FORMAT, MIX_DEFAULT_CHANNELS, chunksize) != 0)
	{
		fprintf(stderr,"Could not open sound: %s\n", Mix_GetError());
		gSDLIsInit = false;
	}
	#endif
	
	//const SDL_VideoInfo *info  = SDL_GetVideoInfo();
	//sgDesktopWidth = info->current_w;
	//sgDesktopHeight = info->current_h;
	
	//#ifdef RASPBERRYPI
	//sdl_flags = SDL_SWSURFACE;
	//if (opengl)
		//fullscreen = true;
	//#else
	//sdl_flags = SDL_HWSURFACE;
	//#endif
	
	//int use_w = fullscreen ? 0 : inWidth;
	//int use_h = fullscreen ? 0 : inHeight;
	
	
	int windowFlags = 0;
	
	if (opengl) windowFlags |= SDL_WINDOW_OPENGL;
	if (resizable) windowFlags |= SDL_WINDOW_RESIZABLE;
	if (borderless) windowFlags |= SDL_WINDOW_BORDERLESS;
	if (fullscreen) windowFlags |= SDL_WINDOW_FULLSCREEN; //SDL_WINDOW_FULLSCREEN_DESKTOP;
	
	SDL_Window *window = SDL_CreateWindow (inTitle, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, fullscreen ? 0 : inWidth, fullscreen ? 0 : inHeight, windowFlags);
	
	if (!window) return;
	
	int renderFlags = 0;
	
	if (opengl) renderFlags |= SDL_RENDERER_ACCELERATED;
	if (vsync) renderFlags |= SDL_RENDERER_PRESENTVSYNC;
	
	SDL_Renderer *renderer = SDL_CreateRenderer (window, -1, renderFlags);
	
	if (!renderer && opengl) {
		
		opengl = false;
		renderFlags &= ~SDL_RENDERER_ACCELERATED;
		
		renderer = SDL_CreateRenderer (window, -1, renderFlags);
		
	}
	
	if (!renderer) return;
	
	if (opengl) {
		
		//SDL_GL_SetAttribute();
		// set attributes?
		
	}
	
	
/*#if defined(IPHONE) || defined(BLACKBERRY) || defined(EMSCRIPTEN)
	sdl_flags |= SDL_NOFRAME;
#else
	if (inIcon)
	{
		SDL_Surface *sdl = SurfaceToSDL(inIcon);
		SDL_WM_SetIcon( sdl, NULL );
	}
#endif


	#if defined (HX_WINDOWS) || defined (HX_LINUX)
	//SDL_WM_SetCaption( inTitle, 0 );
	#endif

	SDL_Surface* screen = 0;
	bool is_opengl = false;
	sgIsOGL2 = false;

	#ifdef RASPBERRYPI
	bool nmeEgl = true;
	#else
	bool nmeEgl = false;
	#endif

	if (opengl && !nmeEgl)
	{
		int  aa_tries = (inFlags & wfHW_AA) ? ( (inFlags & wfHW_AA_HIRES) ? 2 : 1 ) : 0;
	
		//int bpp = info->vfmt->BitsPerPixel;
		int startingPass = 0;

		// Try for 24:8  depth:stencil
		if (inFlags & wfStencilBuffer)
			startingPass = 1;
 
		#if defined (WEBOS) || defined (BLACKBERRY) || defined(EMSCRIPTEN)
		// Start at 16 bits...
		startingPass = 2;
		#endif

		// No need to loop over depth
		if (!(inFlags & wfDepthBuffer))
			startingPass = 2;

		int oglLevelPasses = 1;

		#if !defined(NME_FORCE_GLES1) && (defined(WEBOS) || defined(BLACKBERRY) || defined(EMSCRIPTEN))
		// Try 2 then 1 ?
		if ( (inFlags & wfAllowShaders) && !(inFlags & wfRequireShaders) )
			oglLevelPasses = 2;
		#endif

		// Find config...

		for(int oglPass = 0; oglPass< oglLevelPasses && !is_opengl; oglPass++)
		{
			#ifdef NME_FORCE_GLES1
			int level = 1;
			#else
			int level = (inFlags & wfRequireShaders) ? 2 : (inFlags & wfAllowShaders) ? 2-oglPass : 1;
			#endif
		  
	
			for(int depthPass=startingPass;depthPass<3 && !is_opengl;depthPass++)
			{
				// Initialize the display
				for(int aa_pass = aa_tries; aa_pass>=0 && !is_opengl; --aa_pass)
				{
					SDL_GL_SetAttribute(SDL_GL_RED_SIZE,  8 );
					SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE,8 );
					SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8 );
	
					#if defined(WEBOS) || defined(BLACKBERRY) || defined(EMSCRIPTEN)
					SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, level);
					#endif
					// try 32 24 or 16 bit depth...
					if (inFlags & wfDepthBuffer)
						SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE,  32 - depthPass*8 );
	
					if (inFlags & wfStencilBuffer)
						SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8 );
	
					SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
				
					if (aa_tries > 0)
					{
						SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, aa_pass>0);
						SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES,  1<<aa_pass );
					}
					
					#ifndef EMSCRIPTEN
					if ( inFlags & wfVSync )
					{
						SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, 1);
					}
					#endif
	
					sdl_flags |= SDL_OPENGL;
				
					//if (!(screen = SDL_SetVideoMode( use_w, use_h, 32, sdl_flags)))
					if (!(screen = SDL_CreateWindow(inTitle, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, use_w, use_h, sdl_flags)))
					{
						if (depthPass==2 && aa_pass==0 && oglPass==oglLevelPasses-1)
						{
							sdl_flags &= ~SDL_OPENGL;
							fprintf(stderr, "Couldn't set OpenGL mode32: %s\n", SDL_GetError());
						}
					}
					else
					{
						is_opengl = true;
						#if defined(WEBOS) || defined(BLACKBERRY) || defined(EMSCRIPTEN)
						sgIsOGL2 = level==2;
						#else
						// TODO: check extensions support
						sgIsOGL2 = (inFlags & (wfAllowShaders | wfRequireShaders) );
						#endif
						break;
					}
				}
			}
		}
	}
 
	if (!screen)
	{
		if (!opengl || !nmeEgl)
			sdl_flags |= SDL_DOUBLEBUF;

		//screen = SDL_SetVideoMode( use_w, use_h, 32, sdl_flags );
		screen = SDL_CreateWindow(inTitle, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, use_w, use_h, sdl_flags);
		if (!screen)
		{
			fprintf(stderr, "Couldn't set video mode: %s\n", SDL_GetError());
			inOnFrame(0);
			gSDLIsInit = false;
			return;
		}
	}

	#ifdef RASPBERRYPI
	if (opengl)
	{
		sgIsOGL2 = (inFlags & (wfAllowShaders | wfRequireShaders) );
			
		use_w = screen->w;
		use_h = screen->h;
		bool ok = nmeEGLCreate( 0, use_w, use_h,
								sgIsOGL2,
								(inFlags & wfDepthBuffer) ? 16 : 0,
								(inFlags & wfStencilBuffer) ? 8 : 0,
								0 );
		if (ok)
			is_opengl = true;
	}
	#endif
	
	HintColourOrder( is_opengl || screen->format->Rmask==0xff );
*/
	
	int numJoysticks = SDL_NumJoysticks();
	
	if (sgJoystickEnabled && numJoysticks > 0)
	{
		for (int i = 0; i < numJoysticks; i++)
		{
			sgJoystick = SDL_JoystickOpen(i);
		}
		SDL_JoystickEventState(SDL_TRUE);
	}
	
	sgSDLFrame = new SDLFrame(window, renderer, windowFlags, opengl, inWidth, inHeight);
	inOnFrame(sgSDLFrame);
	StartAnimation();
}
示例#13
0
int
main(int argc, char *argv[])
{

    int index;                  /* index of last key we pushed in the bitmap font */
    SDL_Window *window;
    SDL_Event event;            /* last event received */
    SDL_Keymod mod;             /* key modifiers of last key we pushed */
    SDL_Scancode scancode;      /* scancode of last key we pushed */

    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        printf("Error initializing SDL: %s", SDL_GetError());
    }
    /* create window */
    window = SDL_CreateWindow("iPhone keyboard test", 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, 0);
    /* create renderer */
    renderer = SDL_CreateRenderer(window, -1, 0);

    /* load up our font */
    loadFont();

    /* draw the background, we'll just paint over it */
    SDL_SetRenderDrawColor(renderer, bg_color.r, bg_color.g, bg_color.b,
                           bg_color.unused);
    SDL_RenderFillRect(renderer, NULL);
    SDL_RenderPresent(renderer);

    int done = 0;
    /* loop till we get SDL_Quit */
    while (SDL_WaitEvent(&event)) {
        switch (event.type) {
        case SDL_QUIT:
            done = 1;
            break;
        case SDL_KEYDOWN:
            index = keyToIndex(event.key.keysym);
            scancode = event.key.keysym.scancode;
            mod = event.key.keysym.mod;
            if (scancode == SDL_SCANCODE_DELETE) {
                /* if user hit delete, delete the last character */
                backspace();
                lastCharWasColon = 0;
            } else if (lastCharWasColon && scancode == SDL_SCANCODE_0
                       && (mod & KMOD_SHIFT)) {
                /* if our last key was a colon and this one is a close paren, the make a hoppy face */
                backspace();
                drawIndex(32);  /* index for happy face */
                numChars++;
                drawCursor();
                lastCharWasColon = 0;
            } else if (index != -1) {
                /* if we aren't doing a happy face, then just draw the normal character */
                drawIndex(index);
                numChars++;
                drawCursor();
                lastCharWasColon =
                    (event.key.keysym.scancode == SDL_SCANCODE_SEMICOLON
                     && (event.key.keysym.mod & KMOD_SHIFT));
            }
            /* check if the key was a colon */
            /* draw our updates to the screen */
            SDL_RenderPresent(renderer);
            break;
        case SDL_MOUSEBUTTONUP:
            /*      mouse up toggles onscreen keyboard visibility */
            if (SDL_IsTextInputActive()) {
                SDL_StopTextInput();
            } else {
                SDL_StartTextInput();
            }
            break;
        }
    }
    cleanup();
    return 0;
}
示例#14
0
int main(int argc, char* args[]) {
    // This will be the window we'll be rendering to
    SDL_Window *window = NULL;

    SDL_Renderer *renderer = NULL;

    TTF_Font *font;

    SDL_Texture *sheet = NULL;
    Text text;

    init_sprites();
    event_init();

    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        printf("SDL could not initialize! SDL_ERROR: %s\n", SDL_GetError());
    } else {
        //if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, 1)) {
        //    printf("Warning: Linear texture filtering not enabled");
        //}
        window = SDL_CreateWindow("Piggle",
                                  SDL_WINDOWPOS_UNDEFINED,
                                  SDL_WINDOWPOS_UNDEFINED,
                                  SCREEN_WIDTH,
                                  SCREEN_HEIGHT,
                                  SDL_WINDOW_SHOWN);
        if (window == NULL) {
            printf("Window could not be created! SDL_Error: %s\n",
                   SDL_GetError());
        } else {
            renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
            if (renderer == NULL) {
                printf("Renderer couldn't be created. Shit's f****d, becuase %s"
                       ", dude.\n", SDL_GetError());
            } else {
                SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);

                int imgFlags = IMG_INIT_PNG;
                if (!(IMG_Init(imgFlags) & imgFlags)) {
                    printf("SDL_image couldn't be initialized. Shit's f****d, "
                           "because %s, dude.\n", IMG_GetError());
                }

                if (TTF_Init() == -1) {
                    printf("SDL_ttf couldn't initialize. Shit's f****d, becuase"
                           " %s, dude.\n", TTF_GetError());
                }
            }
            font = TTF_OpenFont("DroidSansMono.ttf", 16);
            if (font == NULL) {
                printf("Failed to load lazy font. Shit's f****d, because %s, "
                       "dude.", TTF_GetError());
            }
                
            sheet = loadTexture("img/sprites.png", renderer);
            // When quit is set to true, we'll stop running
            bool quit = false;
            piggle_scene_over = false;
            // Event handler
            SDL_Event sdl_event;

            // Set the current scene to the start scene
            piggle_scene_update = start_scene_update;

            while (!quit) {
                timer_start();
                EventList events = EventList_new();
                while (SDL_PollEvent(&sdl_event) != 0) {
                    Event event;
                    // If the user presses that little "x"
                    if (sdl_event.type == SDL_QUIT) {
                        quit = true;
                        event.type = QUIT;
                    } else if (sdl_event.type == SDL_KEYDOWN) {
                        event.type = KEYDOWN;
                        int key = sdl_event.key.keysym.sym;
                        event.value = event_value_from_key(key);
                    } else if (sdl_event.type == SDL_KEYUP) {
                        event.type = KEYUP;
                        int key = sdl_event.key.keysym.sym;
                        event.value = event_value_from_key(key);
                    } else {
                        continue;
                    }
                    events.add_event(&events, event);
                }
                SDL_RenderClear(renderer);
                DrawActionList actions = DrawActionList_new();
                piggle_scene_update(&events, &actions);
                events.destroy(&events);
                int i;
                for (i = 0; i < actions.length; i++) {
                    DrawAction action = actions.actions[i];
                    if (action.type == SPRITE) {
                        SDL_Rect *sprite = &sprites[action.sprite];
                        SDL_Rect dest;
                        dest.x = action.x;
                        dest.y = action.y;
                        dest.w = sprite->w;
                        dest.h = sprite->h;
                        SDL_RenderCopy(renderer, sheet, sprite, &dest);
                    } else if (action.type == TEXT) {
                        SDL_Color color = {action.text.red,
                                           action.text.green,
                                           action.text.blue};
                        textureFromText(action.text.text, color, &text, font,
                                        renderer);
                        SDL_Rect textRect;
                        textRect.x = action.x;
                        textRect.y = action.y;
                        textRect.w = text.width;
                        textRect.h = text.height;
                        SDL_RenderCopy(renderer, text.texture, NULL, &textRect);
                        SDL_DestroyTexture(text.texture);
                    } else if (action.type == RECTANGLE) {
                        SDL_Rect rect = {.x = action.x,
                                         .y = action.y,
                                         .w = action.rect.width,
                                         .h = action.rect.height};
                        SDL_SetRenderDrawColor(renderer, action.rect.red,
                                               action.rect.green,
                                               action.rect.blue, 255);
                        SDL_RenderFillRect(renderer, &rect);
                    }
                }
                SDL_RenderPresent(renderer);
                actions.destroy(&actions);
                if (piggle_scene_over) {
                    piggle_scene_update = piggle_scene_next;
                    piggle_scene_over = false;
                }
                if (timer_get_ticks() < 1000 / 60) {
                    SDL_Delay((1000 / 60) - timer_get_ticks());
                }
            }
        }
    }

    SDL_DestroyTexture(sheet);
    SDL_DestroyTexture(text.texture);
    text.texture = NULL;
    sheet = NULL;
    TTF_CloseFont(font);
    font = NULL;
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    window = NULL;
    renderer = NULL;

    // Quit SDL subsystems
    TTF_Quit();
    IMG_Quit();
    SDL_Quit();

    event_uninit();

    return 0;
}
示例#15
0
int
wmain(void) {
    uint64 PerfCountFrequency = SDL_GetPerformanceFrequency();
    SDL_Event Event;
    SDL_Window *Window;
    SDL_Renderer *Renderer;

    if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMECONTROLLER | SDL_INIT_HAPTIC) != 0) {
        char *Error = "Could not initialize SDL: %s\n";
        printf(Error, SDL_GetError());

        return -1;
    }

    atexit(SDL_Quit);

    int WindowWidth = 1300;
    int WindowHeight = 870;
    int BytesPerPixel = 4;

    Window = SDL_CreateWindow("Echelon",
                              30, 30,
                              WindowWidth, WindowHeight,
                              SDL_WINDOW_RESIZABLE);
    
    if(Window) {
        Renderer = SDL_CreateRenderer(Window, -1, 0);

        if(Renderer) {
            GlobalRunning = true;
            window_dimensions Dimensions = SDLGetWindowDimensions(Window);
            SDLCreateNewTexture(&GlobalBuffer,
                                Renderer,
                                Dimensions.Width, Dimensions.Height,
                                BytesPerPixel);

            uint64 LastCounter = SDL_GetPerformanceCounter();
            uint64 LastCycleCount = __rdtsc();

            real64 DebugTimer = 0;
            real64 FPSTimer = 0;
            real64 UpdateTimer = 0;

            uint32 FPS = 0;
            uint32 UPS = 0;
            
            keyboard_input KeyboardInput = {};
            gamepad_input GamePadInput = {};

            game_code Game = LoadGameCode();

            game_memory GameMemory = {0};
            GameMemory.IsInitialized = false;
            GameMemory.PlayRumble = SDLPlayRumble;
            GameMemory.WindowDimensions = SDLGetWindowDimensions(Window);
            GameMemory.PermanentStorageSize = Gigabytes(4);
            GameMemory.PermanentStorage = VirtualAlloc(0,
                                                       GameMemory.PermanentStorageSize,
                                                       MEM_COMMIT, PAGE_READWRITE);

            //Assert((GameMemory.PermanentStorageSize));
            
            GameMemory.TransientStorageSize = Megabytes(4);
            GameMemory.TransientStorage = VirtualAlloc(0,
                                                       GameMemory.TransientStorageSize,
                                                       MEM_COMMIT, PAGE_READWRITE);
            //Assert((GameMemory.TransientStorageSize));

            Game.GameInit(&GameMemory);
            
            while(GlobalRunning) {
                // NOTE(Redab): This needs to while loop because we need
                // to handle events as long as they are available.
                while(SDL_PollEvent(&Event)) {
                    SDLHandleEvent(&Event, &Dimensions);
                    SDLHandleUserInput(&Event, &Game, &GameMemory, &KeyboardInput, &GamePadInput);
                }

                uint64 EndCycleCount = __rdtsc();
                uint64 EndCounter = SDL_GetPerformanceCounter();
                uint64 CounterElapsed = EndCounter - LastCounter;
                uint64 CyclesElapsed = EndCycleCount - LastCycleCount;

                // NOTE(Redab): CounterElapsed Contains the number of
                // clock cycles since last check. So we need to divide
                // this by the number of cycles per second which we
                // have in PerCountFrequency. Multiplied by 1000 to
                // get milliseconds.

                real64 SecondsPerFrame = ((real64)CounterElapsed / (real64)PerfCountFrequency);
                real64 MSPerFrame = SecondsPerFrame * 1000.0f;
                
                real64 KCPF = ((real64)CyclesElapsed / (1000.0f));

                FPSTimer += MSPerFrame;
                UpdateTimer += MSPerFrame;
                DebugTimer += MSPerFrame;

                if(UpdateTimer >= (1000.0f / 60.0f)) {
                    GameMemory.WindowDimensions = Dimensions;                        
                    Game.GameUpdate(&GameMemory, &KeyboardInput, &GamePadInput, UpdateTimer / 1000.0f);

                    UPS++;
                    UpdateTimer = 0;
                }

                if(FPSTimer >= (1000.0f / 60.0f)) {
                    SDLGameRender(&GlobalBuffer, &Game);
                    SDLBlitFrameToWindow(&GlobalBuffer, Renderer);
                    SDL_RenderPresent(Renderer); // Flip
                    
                    FPS++;
                    FPSTimer = 0;
                }
                
                if(DebugTimer >= 1000.0f) {
                    printf("%.05fms/f, FPS: %d, UPS: %d, %.02fKc/f, Timer: %.02f\n",
                           MSPerFrame, FPS, UPS, KCPF, DebugTimer);

                    FPS = 0;
                    UPS = 0;
                    DebugTimer = 0;
                }

                LastCycleCount = EndCycleCount;
                LastCounter = EndCounter;
            }
        } else {
            printf("Failed to create SDL_Renderer: %s\n", SDL_GetError());
        }
    } else {
        printf("Failed to create SDL_Window: %s\n", SDL_GetError());
    }

    SDL_CloseAudio();
    SDL_Quit();
    return 0;
}
示例#16
0
int iniciar( SDL_Window** janela, SDL_Renderer** render)
{
	bool sucesso = true;
	

	//Inicia o SDL
	if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0)
	{
		printf("En: SDL could not initialize! SDL_Error: %s\n", SDL_GetError() );
		printf("Pt: SDL nao pode ser iniciado! Err	o: %s\n", SDL_GetError() );
		sucesso = false;
	}     
	else
	{
		//Adquirindo as medidas da tela
		//Variavel que armazena as medidas da tela e a frequencia
		SDL_DisplayMode telaAtual;
		
		//Chamando a função para definir as propriedades da tela atual (retorna 0 se for sucesso)
		if(SDL_GetCurrentDisplayMode(0, &telaAtual) != 0)
		{
			//Em caso de erro
			printf("En: Could not get display mode for video display : %s",  SDL_GetError());
			printf("Pt: Nao foi possivel obter um monitor e suas propriedades  : %s", SDL_GetError());	
			sucesso = false;
		}
		else
		{
			int alturaTela =28*telaAtual.h/34;
			int larguraTela = 31*telaAtual.h/34;

			ofstream out;
			out.open("config.txt");
			out<<"altura = "<< alturaTela <<"\n"<<"largura = "<< larguraTela;
			
			//out<<"altura = "<<395<<"\n"<<"largura = "<< 487;
			out.close();

			*janela = SDL_CreateWindow( nome.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, larguraTela , alturaTela, SDL_WINDOW_SHOWN );
			//*janela = SDL_CreateWindow( nome.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 487, 395, SDL_WINDOW_SHOWN );

			if(*janela == NULL)
			{
				printf( "En: Window could not be created! SDL_Error: %s\n", SDL_GetError() );
				printf( "Pt: Não foi possivel criar a janela! Erro: %s\n", SDL_GetError() );
				sucesso = false;
			}
			else
			{
				*render = SDL_CreateRenderer( *janela, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC );
				//Verificando se render foi inicializada com sucesso
				if(*render == NULL)
				{
					printf( "En: Render could not be created! SDL Error: %s\n", SDL_GetError() );
					printf( "Pt: Não foi possivel criar a Renderer! Erro: %s\n", SDL_GetError() );
					sucesso = false	;
				}
				else
				{
						//Se a render tiver sido iniciada corretamente, definir a cor dela
						SDL_SetRenderDrawColor( *render, 0xFF, 0xFF, 0xFF, 0xFF );

						//Inicializando a biblioteca do SDL para carregar imagens .png
						int imgFlags = IMG_INIT_PNG;
						if( !( IMG_Init( imgFlags ) & imgFlags ) )
						{
							printf( "En: SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError() );
							printf( "Pt: Não foi possivel iniciar a biblioteca SDL_image! Erro: %s\n", IMG_GetError() );
							sucesso = false;
						}
						//Inicado as bibliotecas basicas do SDL vamos inicar duas outra bibliotecas, uma de controle de som e outra de fontes
						if(TTF_Init() == -1)
						{
							printf("En: SDL_ttf could not initialize! SDL_tff Error: %s\n", TTF_GetError() );
							printf("Pt: Não foi possivel iniciar a biblioteca SDL_ttf ! SDL_tff Erro: %s\n", TTF_GetError() );
							sucesso = false;
						}

						//Iniciando a biblioteca SDL_mixer
						if( Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 2048 ) < 0 )
						{
						    printf( "En: SDL_mixer could not initialize! SDL_mixer Error: %s\n", Mix_GetError() );
						    printf( "Pt: Não foi possivel iniciar a biblioteca SDL_mixer! Erro: %s\n", Mix_GetError() );
						    sucesso = false;
						}
				}

				

			}
		}
		

		
	}
	return sucesso;
}
int main(int argn, char **argv) 
{
    // Init SDL
    if(SDL_Init(SDL_INIT_VIDEO) != 0)
        fprintf(stderr, "Could not initialize SDL2: %s\n", SDL_GetError());

    printf("SDL Initialized\n");

    // Create screen texture
    SDL_Surface *screen, *message;
    int res_x = 800;
    int res_y = 600;
    int julia_mode = 0;

    if(argn == 1)
    {
        julia_mode = 0;
    } 
    else if ((argn == 2) && (strcmp(argv[1], "-julia") == 0))
    {
        julia_mode = 1;
        printf("Julia mode activated.\n");
    }

    int number_cores = get_cpus();
    int number_threads = number_cores * number_cores;

    printf("Number of CPUs/cores autodetected: %d\n", number_cores);

#ifdef CACHE
    // Init our cached points
    cached_points = malloc(res_y * 1000 * sizeof(int *));
    cached_x = malloc(res_y * 1000 * sizeof(float *));
    cached_y = malloc(res_y * 1000 * sizeof(float *));
    if (cached_points == NULL)
    {
        fprintf(stderr, "Bad luck, out of memory\n");
        return 2;
    }

    int count;
    for (count = 0; count < res_y * 1000; count++)
    {
        cached_points[count] = malloc(res_x * 1000 * sizeof(int));
        if(cached_points[count] == NULL)
        {
            fprintf(stderr, "Bad luck, out of memory\n");
            return 2;
        }
        cached_x[count] = malloc(res_x * 1000 * sizeof(float));
        cached_y[count] = malloc(res_x * 1000 * sizeof(float));
        /*for (count2 = 0; count2 < res_x * 100; count2++)
        {
            cached_points[count][count2] = -1;
        }*/
    }

    printf("Cache ready\n");
#endif

    // screen = SDL_SetVideoMode(res_x, res_y, 0, SDL_HWSURFACE|SDL_DOUBLEBUF);
    // screen = SDL_SetVideoMode(res_x, res_y, 0, SDL_DOUBLEBUF);
    SDL_Window *window = SDL_CreateWindow("MandelClassic",
                                           SDL_WINDOWPOS_UNDEFINED,
                                           SDL_WINDOWPOS_UNDEFINED,
                                           res_x, res_y, 0);

    SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, 0);

    if ((!window) || (!renderer))
	    fprintf(stderr,"Could not set video mode: %s\n",SDL_GetError());

    // Blank the window
    SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
    SDL_RenderClear(renderer);
    SDL_RenderPresent(renderer);

    SDL_Texture *texture_screen = SDL_CreateTexture(renderer,
                                                   SDL_PIXELFORMAT_ARGB8888,
                                                   SDL_TEXTUREACCESS_STREAMING,
                                                   res_x, res_y);

    screen = SDL_CreateRGBSurface(0, res_x, res_y , 32, 0, 0, 0, 0);

    //Initialize SDL_ttf
    if( TTF_Init() == -1 )
    { 
        printf("Error setting up TTF module.\n");
        return 1; 
    }

    // Load a font
    TTF_Font *font;
    font = TTF_OpenFont("font.ttf", 24);
    if (font == NULL)
    {
        printf("TTF_OpenFont() Failed: %s", TTF_GetError());
        SDL_Quit();
        return 1;
    }

    //The color of the font 
    SDL_Color textColor = { 255, 255, 255 };    

    // Prepare the resolution and sizes and colors, threads...
    iteration_pixels = malloc(res_x * res_y * sizeof(int));
    pthread_t threads[number_threads];
    piece_args arguments[number_threads];

    printf("Rendering...\n");

    float zoom = 1.0;
    float stop_point;

    if (julia_mode == 0)
        stop_point = 0.00001;
    else
        stop_point = -2.5;

    // We measure the time to do the zooming
    clock_t start = clock();

    while(zoom > stop_point)
    {
        int iteration, max_iteration, x, y, res;
        if((zoom < -0.02) && (zoom > -1.0))
        {
            max_iteration = 100;
        }
        else
        {
            max_iteration = 170;
        }

        int thread_count;

        for(thread_count = 0; thread_count < number_threads; thread_count++)
        {
            arguments[thread_count].res_x = res_x;
            arguments[thread_count].res_y = res_y;
            arguments[thread_count].zoom = zoom;
            arguments[thread_count].max_iteration = max_iteration;
            arguments[thread_count].total_threads = number_threads;
            arguments[thread_count].thread_number = thread_count;
            arguments[thread_count].julia_mode = julia_mode;
            pthread_create( &threads[thread_count], NULL, thread_launcher, (void*) &arguments[thread_count]);
        }

        for(thread_count = 0; thread_count < number_threads; thread_count++)
        {
            res = pthread_join(threads[thread_count], NULL);
            if (res != 0)
            {
                printf("Error in %d thread\n", thread_count);
            }
        }

        int rank;
        Uint32 *pixel;
        rank = screen->pitch/sizeof(Uint32);
        pixel = (Uint32*)screen->pixels;

        for(y = 0; y < res_y ; y++)
        {
            for(x = 0; x < res_x; x++)
            {
                iteration = iteration_pixels[x + y * res_x];
                if ((iteration < 128) && (iteration > 0)) {
                    pixel[x + y * rank] = SDL_MapRGBA(screen->format,
                                                       0,
                                                       20 + iteration,
                                                       0,
                                                       255);
                }
                else if ((iteration >= 128) && (iteration < max_iteration))
                {
                    pixel[x + y * rank] = SDL_MapRGBA(screen->format,
                                                       iteration,
                                                       148,
                                                       iteration,
                                                       255);
                }
                else
                {
                    pixel[x + y * rank] = SDL_MapRGBA(screen->format,
                                                       0,
                                                       0,
                                                       0,
                                                       255);
                } 
            }
        }

        if(julia_mode == 0)
            zoom = zoom * 0.99;
        else
            zoom -= 0.01; 

        // Draw message on a corner...
        char* msg = (char *)malloc(100 * sizeof(char));
        sprintf(msg, "Zoom level: %0.3f", zoom * 100.0);
        message = TTF_RenderText_Solid( font, msg, textColor );
        free(msg);
        if (message != NULL)
            SDL_BlitSurface(message, NULL, screen, NULL);

        free(message);

        SDL_UpdateTexture(texture_screen, NULL, (Uint32*)screen->pixels, 800 * sizeof (Uint32));
        SDL_RenderClear(renderer);
        SDL_RenderCopy(renderer, texture_screen, NULL, NULL);
        SDL_RenderPresent(renderer);

        // SDL_Flip(screen);
    }

    printf("Time elapsed %0.5f seconds\n", ((double)clock() - start) / CLOCKS_PER_SEC);

    SDL_Event ev;
    int active;

    active = 1;
    while(active)
    {
        /* Handle events */
        while(SDL_PollEvent(&ev))
        {
            if(ev.type == SDL_QUIT)
                active = 0; /* End */
        }
    }

    SDL_Quit();

    return 0;
}
static SDL_bool
WatchJoystick(SDL_Joystick * joystick)
{
    SDL_Window *window = NULL;
    SDL_Renderer *screen = NULL;
    SDL_Texture *background, *button, *axis, *marker;
    const char *name = NULL;
    SDL_bool retval = SDL_FALSE;
    SDL_bool done = SDL_FALSE, next=SDL_FALSE;
    SDL_Event event;
    SDL_Rect dst;
    int s, _s;
    Uint8 alpha=200, alpha_step = -1;
    Uint32 alpha_ticks;
    char mapping[4096], temp[4096];
    MappingStep *step;
    MappingStep steps[] = {
        {342, 132,  0.0,  MARKER_BUTTON, "x", -1, -1, -1, -1, ""},
        {387, 167,  0.0,  MARKER_BUTTON, "a", -1, -1, -1, -1, ""},
        {431, 132,  0.0,  MARKER_BUTTON, "b", -1, -1, -1, -1, ""},
        {389, 101,  0.0,  MARKER_BUTTON, "y", -1, -1, -1, -1, ""},
        {174, 132,  0.0,  MARKER_BUTTON, "back", -1, -1, -1, -1, ""},
        {233, 132,  0.0,  MARKER_BUTTON, "guide", -1, -1, -1, -1, ""},
        {289, 132,  0.0,  MARKER_BUTTON, "start", -1, -1, -1, -1, ""},        
        {116, 217,  0.0,  MARKER_BUTTON, "dpleft", -1, -1, -1, -1, ""},
        {154, 249,  0.0,  MARKER_BUTTON, "dpdown", -1, -1, -1, -1, ""},
        {186, 217,  0.0,  MARKER_BUTTON, "dpright", -1, -1, -1, -1, ""},
        {154, 188,  0.0,  MARKER_BUTTON, "dpup", -1, -1, -1, -1, ""},
        {77,  40,   0.0,  MARKER_BUTTON, "leftshoulder", -1, -1, -1, -1, ""},
        {91, 0,    0.0,  MARKER_BUTTON, "lefttrigger", -1, -1, -1, -1, ""},
        {396, 36,   0.0,  MARKER_BUTTON, "rightshoulder", -1, -1, -1, -1, ""},
        {375, 0,    0.0,  MARKER_BUTTON, "righttrigger", -1, -1, -1, -1, ""},
        {75,  154,  0.0,  MARKER_BUTTON, "leftstick", -1, -1, -1, -1, ""},
        {305, 230,  0.0,  MARKER_BUTTON, "rightstick", -1, -1, -1, -1, ""},
        {75,  154,  0.0,  MARKER_AXIS,   "leftx", -1, -1, -1, -1, ""},
        {75,  154,  90.0, MARKER_AXIS,   "lefty", -1, -1, -1, -1, ""},        
        {305, 230,  0.0,  MARKER_AXIS,   "rightx", -1, -1, -1, -1, ""},
        {305, 230,  90.0, MARKER_AXIS,   "righty", -1, -1, -1, -1, ""},
    };

    /* Create a window to display joystick axis position */
    window = SDL_CreateWindow("Game Controller Map", SDL_WINDOWPOS_CENTERED,
                              SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH,
                              SCREEN_HEIGHT, 0);
    if (window == NULL) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create window: %s\n", SDL_GetError());
        return SDL_FALSE;
    }

    screen = SDL_CreateRenderer(window, -1, 0);
    if (screen == NULL) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create renderer: %s\n", SDL_GetError());
        SDL_DestroyWindow(window);
        return SDL_FALSE;
    }
    
    background = LoadTexture(screen, "controllermap.bmp", SDL_FALSE);
    button = LoadTexture(screen, "button.bmp", SDL_TRUE);
    axis = LoadTexture(screen, "axis.bmp", SDL_TRUE);
    SDL_RaiseWindow(window);

    /* scale for platforms that don't give you the window size you asked for. */
    SDL_RenderSetLogicalSize(screen, SCREEN_WIDTH, SCREEN_HEIGHT);

    /* Print info about the joystick we are watching */
    name = SDL_JoystickName(joystick);
    SDL_Log("Watching joystick %d: (%s)\n", SDL_JoystickInstanceID(joystick),
           name ? name : "Unknown Joystick");
    SDL_Log("Joystick has %d axes, %d hats, %d balls, and %d buttons\n",
           SDL_JoystickNumAxes(joystick), SDL_JoystickNumHats(joystick),
           SDL_JoystickNumBalls(joystick), SDL_JoystickNumButtons(joystick));
    
    SDL_Log("\n\n\
    ====================================================================================\n\
    Press the buttons on your controller when indicated\n\
    (Your controller may look different than the picture)\n\
    If you want to correct a mistake, press backspace or the back button on your device\n\
    To skip a button, press SPACE or click/touch the screen\n\
    To exit, press ESC\n\
    ====================================================================================\n");
    
    /* Initialize mapping with GUID and name */
    SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joystick), temp, SDL_arraysize(temp));
    SDL_snprintf(mapping, SDL_arraysize(mapping), "%s,%s,platform:%s,",
        temp, name ? name : "Unknown Joystick", SDL_GetPlatform());

    /* Loop, getting joystick events! */
    for(s=0; s<SDL_arraysize(steps) && !done;) {
        /* blank screen, set up for drawing this frame. */
        step = &steps[s];
        SDL_strlcpy(step->mapping, mapping, SDL_arraysize(step->mapping));
        step->axis = -1;
        step->button = -1;
        step->hat = -1;
        step->hat_value = -1;
        SDL_SetClipboardText("TESTING TESTING 123");
        
        switch(step->marker) {
            case MARKER_AXIS:
                marker = axis;
                break;
            case MARKER_BUTTON:
                marker = button;
                break;
            default:
                break;
        }
        
        dst.x = step->x;
        dst.y = step->y;
        SDL_QueryTexture(marker, NULL, NULL, &dst.w, &dst.h);
        next=SDL_FALSE;

        SDL_SetRenderDrawColor(screen, 0xFF, 0xFF, 0xFF, SDL_ALPHA_OPAQUE);

        while (!done && !next) {
            if (SDL_GetTicks() - alpha_ticks > 5) {
                alpha_ticks = SDL_GetTicks();
                alpha += alpha_step;
                if (alpha == 255) {
                    alpha_step = -1;
                }
                if (alpha < 128) {
                    alpha_step = 1;
                }
            }
            
            SDL_RenderClear(screen);
            SDL_RenderCopy(screen, background, NULL, NULL);
            SDL_SetTextureAlphaMod(marker, alpha);
            SDL_SetTextureColorMod(marker, 10, 255, 21);
            SDL_RenderCopyEx(screen, marker, NULL, &dst, step->angle, NULL, 0);
            SDL_RenderPresent(screen);
            
            if (SDL_PollEvent(&event)) {
                switch (event.type) {
                case SDL_JOYAXISMOTION:
                    if (event.jaxis.value > 20000 || event.jaxis.value < -20000) {
                        for (_s = 0; _s < s; _s++) {
                            if (steps[_s].axis == event.jaxis.axis) {
                                break;
                            }
                        }
                        if (_s == s) {
                            step->axis = event.jaxis.axis;
                            SDL_strlcat(mapping, step->field, SDL_arraysize(mapping));
                            SDL_snprintf(temp, SDL_arraysize(temp), ":a%u,", event.jaxis.axis);
                            SDL_strlcat(mapping, temp, SDL_arraysize(mapping));
                            s++;
                            next=SDL_TRUE;
                        }
                    }
                    
                    break;
                case SDL_JOYHATMOTION:
                        for (_s = 0; _s < s; _s++) {
                            if (steps[_s].hat == event.jhat.hat && steps[_s].hat_value == event.jhat.value) {
                                break;
                            }
                        }
                        if (_s == s) {
                            step->hat = event.jhat.hat;
                            step->hat_value = event.jhat.value;
                            SDL_strlcat(mapping, step->field, SDL_arraysize(mapping));
                            SDL_snprintf(temp, SDL_arraysize(temp), ":h%u.%u,", event.jhat.hat, event.jhat.value );
                            SDL_strlcat(mapping, temp, SDL_arraysize(mapping));
                            s++;
                            next=SDL_TRUE;
                        }
                    break;
                case SDL_JOYBALLMOTION:
                    break;
                case SDL_JOYBUTTONUP:
                    for (_s = 0; _s < s; _s++) {
                        if (steps[_s].button == event.jbutton.button) {
                            break;
                        }
                    }
                    if (_s == s) {
                        step->button = event.jbutton.button;
                        SDL_strlcat(mapping, step->field, SDL_arraysize(mapping));
                        SDL_snprintf(temp, SDL_arraysize(temp), ":b%u,", event.jbutton.button);
                        SDL_strlcat(mapping, temp, SDL_arraysize(mapping));
                        s++;
                        next=SDL_TRUE;
                    }
                    break;
                case SDL_FINGERDOWN:
                case SDL_MOUSEBUTTONDOWN:
                    /* Skip this step */
                    s++;
                    next=SDL_TRUE;
                    break;
                case SDL_KEYDOWN:
                    if (event.key.keysym.sym == SDLK_BACKSPACE || event.key.keysym.sym == SDLK_AC_BACK) {
                        /* Undo! */
                        if (s > 0) {
                            SDL_strlcpy(mapping, step->mapping, SDL_arraysize(step->mapping));
                            s--;
                            next = SDL_TRUE;
                        }
                        break;
                    }
                    if (event.key.keysym.sym == SDLK_SPACE) {
                        /* Skip this step */
                        s++;
                        next=SDL_TRUE;
                        break;
                    }
                    
                    if ((event.key.keysym.sym != SDLK_ESCAPE)) {
                        break;
                    }
                    /* Fall through to signal quit */
                case SDL_QUIT:
                    done = SDL_TRUE;
                    break;
                default:
                    break;
                }
            }
        }

    }

    if (s == SDL_arraysize(steps) ) {
        SDL_Log("Mapping:\n\n%s\n\n", mapping);
        /* Print to stdout as well so the user can cat the output somewhere */
        printf("%s\n", mapping);
    }
    
    while(SDL_PollEvent(&event)) {};
    
    SDL_DestroyRenderer(screen);
    SDL_DestroyWindow(window);
    return retval;
}
示例#19
0
int main(int argc, char** argv){
	//Start up SDL and make sure it went ok
	if (SDL_Init(SDL_INIT_EVERYTHING) != 0){
		logSDLError(std::cout, "SDL_Init");
		return 1;
	}
	//Also need to init SDL_ttf
	if (TTF_Init() != 0){
		logSDLError(std::cout, "TTF_Init");
		SDL_Quit();
		return 1;
	}

	//Setup our window and renderer
	SDL_Window *window = SDL_CreateWindow("Lesson 6", SDL_WINDOWPOS_CENTERED,
			SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
	if (window == nullptr){
		logSDLError(std::cout, "CreateWindow");
		TTF_Quit();
		SDL_Quit();
		return 1;
	}
	SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
	if (renderer == nullptr){
		logSDLError(std::cout, "CreateRenderer");
		cleanup(window);
		TTF_Quit();
		SDL_Quit();
		return 1;
	}

	//We'll render the string "TTF fonts are cool!" in white
	//Color is in RGB format
	SDL_Color color = { 255, 255, 255, 255 };
	SDL_Texture *image = renderText("TTF fonts are cool!", ASSET("Lesson6/sample.ttf"), color, 64, renderer);
	if (image == nullptr){
		cleanup(image, renderer, window);
		TTF_Quit();
		SDL_Quit();
		return 1;
	}

	//Get the texture w/h so we can center it in the screen
	int iW, iH;
	SDL_QueryTexture(image, NULL, NULL, &iW, &iH);
	int x = SCREEN_WIDTH / 2 - iW / 2;
	int y = SCREEN_HEIGHT / 2 - iH / 2;

	SDL_Event e;
	bool quit = false;
	while (!quit){
		//Event Polling
		while (SDL_PollEvent(&e)){
			if (e.type == SDL_QUIT){
				quit = true;
			}
			if (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_ESCAPE){
				quit = true;
			}
		}
		SDL_RenderClear(renderer);
		//We can draw our message as we do any other texture, since it's been
		//rendered to a texture
		renderTexture(image, renderer, x, y);
		SDL_RenderPresent(renderer);
	}
	//Clean up
	cleanup(image, renderer, window);
	TTF_Quit();
	SDL_Quit();

	return 0;
}
示例#20
0
int Global::init(){
    Global::CONFIG_FILE = "game.conf";
    Config * config = new Config(Global::CONFIG_FILE);

    Global::SCREEN_WIDTH=960;
    Global::SCREEN_HEIGHT=540;
    Global::SCREEN_RES_WIDTH=atoi(config->getSetting("GAMESETTINGS","RES_X").c_str());
    Global::SCREEN_RES_HEIGHT=atoi(config->getSetting("GAMESETTINGS","RES_Y").c_str());;

    Global::GRAVITY=840;

    //Initialize SDL
	if( SDL_Init( SDL_INIT_VIDEO ) < 0 )
	{
		printf( "SDL could not initialize! SDL Error: %s\n", SDL_GetError() );
		return 1;
	}

    //Enable VSync
    if( !SDL_SetHint( SDL_HINT_RENDER_VSYNC, "1" ) )
    {
        printf( "Warning: VSync not enabled!" );
    }

    //Set texture filtering to linear
    if( !SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "1" ) )
    {
        printf( "Warning: Linear texture filtering not enabled!" );
    }

    //Create window
    Uint32 flags = SDL_WINDOW_SHOWN;
    if(config->getSetting("GAMESETTINGS","WINDOW_BORDER").compare("FALSE")==0){
        flags = flags|SDL_WINDOW_BORDERLESS;
    }
    Global::gameWindow = SDL_CreateWindow( "SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, Global::SCREEN_RES_WIDTH, Global::SCREEN_RES_HEIGHT, flags);
    if( Global::gameWindow == NULL )
    {
        printf( "Window could not be created! SDL Error: %s\n", SDL_GetError() );
        return 1;
    }

    //Create renderer for window
    Global::gameRenderer = SDL_CreateRenderer( Global::gameWindow, -1, SDL_RENDERER_ACCELERATED );
    if( Global::gameRenderer == NULL )
    {
        printf( "Renderer could not be created! SDL Error: %s\n", SDL_GetError() );
        return 1;
    }
    SDL_RenderSetScale(gameRenderer,(float)Global::SCREEN_RES_WIDTH/(float)Global::SCREEN_WIDTH,(float)Global::SCREEN_RES_HEIGHT/(float)Global::SCREEN_HEIGHT);

    //Initialize PNG loading
    int imgFlags = IMG_INIT_PNG;
    if( !( IMG_Init( imgFlags ) & imgFlags ) )
    {
        printf( "SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError() );
        return 1;
    }

    return 0;
}
SDL_bool
WatchGameController(SDL_GameController * gamecontroller)
{
    const char *name = SDL_GameControllerName(gamecontroller);
    const char *basetitle = "Game Controller Test: ";
    const size_t titlelen = SDL_strlen(basetitle) + SDL_strlen(name) + 1;
    char *title = (char *)SDL_malloc(titlelen);
    SDL_Window *window = NULL;

    retval = SDL_FALSE;
    done = SDL_FALSE;

    if (title) {
        SDL_snprintf(title, titlelen, "%s%s", basetitle, name);
    }

    /* Create a window to display controller state */
    window = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED,
                              SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH,
                              SCREEN_HEIGHT, 0);
    if (window == NULL) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create window: %s\n", SDL_GetError());
        return SDL_FALSE;
    }

    screen = SDL_CreateRenderer(window, -1, 0);
    if (screen == NULL) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create renderer: %s\n", SDL_GetError());
        SDL_DestroyWindow(window);
        return SDL_FALSE;
    }

    SDL_SetRenderDrawColor(screen, 0x00, 0x00, 0x00, SDL_ALPHA_OPAQUE);
    SDL_RenderClear(screen);
    SDL_RenderPresent(screen);
    SDL_RaiseWindow(window);

    /* scale for platforms that don't give you the window size you asked for. */
    SDL_RenderSetLogicalSize(screen, SCREEN_WIDTH, SCREEN_HEIGHT);

    background = LoadTexture(screen, "controllermap.bmp", SDL_FALSE);
    button = LoadTexture(screen, "button.bmp", SDL_TRUE);
    axis = LoadTexture(screen, "axis.bmp", SDL_TRUE);

    if (!background || !button || !axis) {
        SDL_DestroyRenderer(screen);
        SDL_DestroyWindow(window);
        return SDL_FALSE;
    }
    SDL_SetTextureColorMod(button, 10, 255, 21);
    SDL_SetTextureColorMod(axis, 10, 255, 21);

    /* !!! FIXME: */
    /*SDL_RenderSetLogicalSize(screen, background->w, background->h);*/

    /* Print info about the controller we are watching */
    SDL_Log("Watching controller %s\n",  name ? name : "Unknown Controller");

    /* Loop, getting controller events! */
#ifdef __EMSCRIPTEN__
    emscripten_set_main_loop_arg(loop, gamecontroller, 0, 1);
#else
    while (!done) {
        loop(gamecontroller);
    }
#endif

    SDL_DestroyRenderer(screen);
    screen = NULL;
    background = NULL;
    button = NULL;
    axis = NULL;
    SDL_DestroyWindow(window);
    return retval;
}
示例#22
0
int main(void)
{

SDL_Window *win;
SDL_Renderer *ren;
SDL_Surface *bmp;
SDL_Texture *tex;
int i;


if(SDL_Init(SDL_INIT_VIDEO)!=0)
  {
    fprintf(stderr,"Couldn't init video: %s\n",SDL_GetError());
    return(1);
  }

win= SDL_CreateWindow("Hello world!", 100, 100, 640, 480, SDL_WINDOW_SHOWN);
if(win==NULL){
	fprintf(stderr,"SDL_CreateWindow Error: %s\n",SDL_GetError());
	SDL_Quit();
	return 1;
}

ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (ren == NULL){
	SDL_DestroyWindow(win);
	fprintf(stderr,"SDL_CreateRenderer Error: %s\n",SDL_GetError());
	SDL_Quit();
	return 1;
}

bmp = SDL_LoadBMP("WOLF1.bmp");
if (bmp == NULL){
	SDL_DestroyRenderer(ren);
	SDL_DestroyWindow(win);
	fprintf(stderr,"SDL_LoadBMP Error: %s\n",SDL_GetError());
	SDL_Quit();
	return 1;
}

tex = SDL_CreateTextureFromSurface(ren, bmp);
SDL_FreeSurface(bmp);
if (tex == NULL){
	SDL_DestroyRenderer(ren);
	SDL_DestroyWindow(win);
	fprintf(stderr,"SDL_CreateTextureFromSurface Error: %s\n",SDL_GetError());
	SDL_Quit();
	return 1;
}

//A sleepy rendering loop, wait for 3 seconds and render and present the screen each time
for (i = 0; i < 3; ++i){
	//First clear the renderer
	SDL_RenderClear(ren);
	//Draw the texture
	SDL_RenderCopy(ren, tex, NULL, NULL);
	//Draw a Line with a color
        SDL_SetRenderDrawColor(ren, 0, 0, 0, 255);
        SDL_RenderDrawLine(ren,0,0,640,480);
	//Update the screen
	SDL_RenderPresent(ren);
	//Take a quick break after all that hard work
	SDL_Delay(1000);
}

SDL_DestroyTexture(tex);
SDL_DestroyRenderer(ren);
SDL_DestroyWindow(win);
SDL_Quit();
return 0;
}
示例#23
0
/*
 * Lesson 1: Hello World!
 */
int main(int argc, char** argv){
	//First we need to start up SDL, and make sure it went ok
	if (SDL_Init(SDL_INIT_EVERYTHING) != 0){
		std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl;
		return 1;
	}
	
	//Now create a window with title "Hello World" at 100, 100 on the screen with w:640 h:480 and show it
	SDL_Window *win = SDL_CreateWindow("Hello World!", 100, 100, 640, 480, SDL_WINDOW_SHOWN);
	//Make sure creating our window went ok
	if (win == nullptr){
		std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl;
		return 1;
	}

	//Create a renderer that will draw to the window, -1 specifies that we want to load whichever
	//video driver supports the flags we're passing
	//Flags: SDL_RENDERER_ACCELERATED: We want to use hardware accelerated rendering
	//SDL_RENDERER_PRESENTVSYNC: We want the renderer's present function (update screen) to be
	//synchornized with the monitor's refresh rate
	SDL_Renderer *ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
	if (ren == nullptr){
		SDL_DestroyWindow(win);
		std::cout << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl;
		SDL_Quit();
		return 1;
	}

	//SDL 2.0 now uses textures to draw things but SDL_LoadBMP returns a surface
	//this lets us choose when to upload or remove textures from the GPU
	std::string imagePath = getResourcePath("Lesson1") + "hello.bmp";
	SDL_Surface *bmp = SDL_LoadBMP(imagePath.c_str());
	if (bmp == nullptr){
		SDL_DestroyRenderer(ren);
		SDL_DestroyWindow(win);
		std::cout << "SDL_LoadBMP Error: " << SDL_GetError() << std::endl;
		SDL_Quit();
		return 1;
	}

	//To use a hardware accelerated texture for rendering we can create one from
	//the surface we loaded
	SDL_Texture *tex = SDL_CreateTextureFromSurface(ren, bmp);
	//We no longer need the surface
	SDL_FreeSurface(bmp);
	if (tex == nullptr){
		SDL_DestroyRenderer(ren);
		SDL_DestroyWindow(win);
		std::cout << "SDL_CreateTextureFromSurface Error: " << SDL_GetError() << std::endl;
		SDL_Quit();
		return 1;
	}
	
	//Now lets draw our image
	//First clear the renderer
	SDL_RenderClear(ren);
	//Draw the texture
	SDL_RenderCopy(ren, tex, NULL, NULL);
	//Update the screen
	SDL_RenderPresent(ren);

	//Have the program wait for 2000ms so we get a chance to see the screen
	SDL_Delay(2000);

	//Clean up our objects and quit
	SDL_DestroyTexture(tex);
	SDL_DestroyRenderer(ren);
	SDL_DestroyWindow(win);
	SDL_Quit();
	
	return 0;
}
示例#24
0
int main ( int argc, char** argv )
{
	/* initialize random seed: */
	  srand (time(NULL));

    // initialize SDL video
    if ( SDL_Init( SDL_INIT_VIDEO ) < 0 )
    {
        printf( "Unable to init SDL: %s\n", SDL_GetError() );
        return 1;
    }
    /*//Initialize SDL_ttf
	if( TTF_Init() == -1 )
	{
		printf( "SDL_ttf could not initialize! SDL_ttf Error: %s\n", TTF_GetError() );
		return 1;
	}

	 Sans = TTF_OpenFont("lazy.ttf", 28);
	if( Sans == NULL )
	{
		printf( "Unable to open Font! SDL Error: %s\n", SDL_GetError() );
	}*/

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

    //Set texture filtering to linear
    if( !SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "1" ) )
    {
        printf( "Warning: Linear texture filtering not enabled!" );
    }

    // create a new window
    SDL_Window *win = SDL_CreateWindow("Tetris", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
    if (win == nullptr){
        std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl;
        SDL_Quit();
        return 1;
    }

    gRenderer = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
    if (gRenderer == nullptr){
        SDL_DestroyWindow(win);
        std::cout << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl;
        SDL_Quit();
        return 1;
    }

    bool quit = false;	//Main loop flag
    SDL_Event e;	//Event handler

    CurPiece= new Piece(static_cast<TetrisPieces>(rand()%7),80,Block::Blocksize,gRenderer); //currently existing piece
    //blocks.push_back(Block(Block::Blocksize*5,Block::Blocksize*10,gRenderer,{100,80,70,0xFF}));

    //Set callback
    SDL_TimerID timerID = SDL_AddTimer( 1000, callback,NULL);

    while( !quit )	//While application is running
    {
        //Handle events on queue
        while( SDL_PollEvent( &e ))
        {
            //User requests quit
            if( e.type == SDL_QUIT )
            {
                quit = true;
            }//User presses a key
            else if( e.type == SDL_KEYDOWN )
            {
				if(e.key.keysym.sym == SDLK_LEFT)
				{
					CurPiece->Move(-Block::Blocksize,0);
					if(checkEdgeCollision()||CheckCollision())
						CurPiece->Move(Block::Blocksize,0);
				}
				if(e.key.keysym.sym == SDLK_RIGHT)
				{
					CurPiece->Move(Block::Blocksize,0);
					if(checkEdgeCollision()||CheckCollision())
						CurPiece->Move(-Block::Blocksize,0);
				}
				if(e.key.keysym.sym == SDLK_DOWN)
				{
					CurPiece->Move(0,Block::Blocksize);
					if(checkEdgeCollision()||CheckCollision())
						CurPiece->Move(0,-Block::Blocksize);
				}
				if(e.key.keysym.sym == SDLK_SPACE)
				{
					CurPiece->Rotate();
				}
            }
        }

        //Clear screen
        SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF );
        SDL_RenderClear( gRenderer );

        //DisplayText("score:",outlineRect.w+outlineRect.x+20,50,{0x00,0x00,0x00,0xFF});
		SDL_SetRenderDrawColor( gRenderer, 0x00, 0x00, 0x00, 0xFF );
		SDL_RenderDrawRect( gRenderer, &outlineRect );

		for_each (blocks.begin(), blocks.end(), std::mem_fun_ref(&Block::Draw));
		CurPiece->Draw();
        //Update screen
        SDL_RenderPresent( gRenderer );
        //SDL_Delay(100);
    }

    delete CurPiece;

    //Free global font
	TTF_CloseFont( Sans );

    //Destroy window
	SDL_DestroyRenderer( gRenderer );
	SDL_DestroyWindow( win );

	SDL_RemoveTimer( timerID );
	//Quit SDL subsystems
	SDL_Quit();
    // all is well ;)
    printf("Exited cleanly\n");
    return 0;
}
示例#25
0
int main(int argc, char** argv)
{
  if(argc != 2){
    printf("usage : %s vidfilename\n", argv[0]);
    return 0;
  }

  /* parse arg */
  filename = argv[1];
  

  /* the window will be resized */
  /* after reading video size */
  winWidth = 640;
  winHeight = 480;

  /************/
  /* init sdl */
  /************/
  if( SDL_Init( SDL_INIT_VIDEO|SDL_INIT_AUDIO|SDL_INIT_TIMER ) < 0 ) {
    fprintf( stderr, "Video initialization failed: %s\n", SDL_GetError( ) );
    SDL_Quit( );
    exit(0);
  }

  /* set windows attributes */
  SDL_GetDesktopDisplayMode(0, &desktopMode);
  SDL_SetWindowDisplayMode(screen, &desktopMode); //seems not working ?

  flags = SDL_WINDOW_SHOWN|SDL_WINDOW_RESIZABLE|SDL_WINDOW_OPENGL;

  /* create display */
  screen = SDL_CreateWindow("Waave player",\
			    SDL_WINDOWPOS_UNDEFINED,\
			    SDL_WINDOWPOS_UNDEFINED,\
			    winWidth,\
			    winHeight,\
			    flags);
  
  if( !screen ) {
    fprintf( stderr, "Video mode set failed: %s\n", SDL_GetError( ) );
    SDL_Quit( );
    exit(0);
  }
  
  /**************/
  /* init waave */
  /**************/

  /* start waave and load file */
  WV_waaveInit(WAAVE_INIT_AUDIO|WAAVE_INIT_VIDEO);
  stream = WV_getStream(filename);
  
  /* build a streaming object for the screen */
  int streamType = WV_getStreamType(stream);
  if(streamType == WV_STREAM_TYPE_VIDEO || streamType == WV_STREAM_TYPE_AUDIOVIDEO){
    screenRenderer = SDL_CreateRenderer(screen, -1, SDL_RENDERER_ACCELERATED);
    SDL_RenderClear(screenRenderer);
    streamObj = WV_getStreamRendererObj(screenRenderer, NULL);
    WV_setStreamingMethod(stream, streamObj);
  }

  /* load the stream */
  WV_loadStream(stream);
  
  /* reset window size for video */
  if(streamObj){
    winWidth = streamObj->srcWidth;
    winHeight = streamObj->srcHeight;
    SDL_SetWindowSize(screen, winWidth, winHeight);
    WV_resetStreamRendererOutput(streamObj, screenRenderer, NULL); //!! update the object !!
  }

  /* at start the stream is paused */
  /* so we launch playback */
  WV_playStream(stream);
  
  /*****************/
  /* display loop  */
  /*****************/
  while( 1 ) {
    processEvents( );
  }
  return(0);
}
示例#26
0
/*
 * initialize sdl video
 * args:
 *   width - video width
 *   height - video height
 *   flags - window flags:
 *              0- none
 *              1- fullscreen
 *              2- maximized
 *
 * asserts:
 *   none
 *
 * returns: error code
 */
static int video_init(int width, int height, int flags)
{
	int w = width;
	int h = height;
	int32_t my_flags = SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE;

	switch(flags)
	{
		case 2:
		  my_flags |= SDL_WINDOW_MAXIMIZED;
		  break;
		case 1:
		  my_flags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
		  break;
		case 0:
		default:
		  break;
	}

	if(verbosity > 0)
		printf("RENDER: Initializing SDL2 render\n");

    if (sdl_window == NULL) /*init SDL*/
    {
        if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER) < 0)
        {
            fprintf(stderr, "RENDER: Couldn't initialize SDL2: %s\n", SDL_GetError());
            return -1;
        }

        SDL_SetHint("SDL_HINT_RENDER_SCALE_QUALITY", "1");

		sdl_window = SDL_CreateWindow(
			"Guvcview Video",                  // window title
			SDL_WINDOWPOS_UNDEFINED,           // initial x position
			SDL_WINDOWPOS_UNDEFINED,           // initial y position
			w,                               // width, in pixels
			h,                               // height, in pixels
			my_flags
		);

		if(sdl_window == NULL)
		{
			fprintf(stderr, "RENDER: (SDL2) Couldn't open window: %s\n", SDL_GetError());
			render_sdl2_clean();
            return -2;
		}

		int display_index = SDL_GetWindowDisplayIndex(sdl_window);

		int err = SDL_GetDesktopDisplayMode(display_index, &display_mode);
		if(!err)
		{
			if(verbosity > 0)
				printf("RENDER: video display %i ->  %dx%dpx @ %dhz\n",
					display_index,
					display_mode.w,
					display_mode.h,
					display_mode.refresh_rate);
		}
		else
			fprintf(stderr, "RENDER: Couldn't determine display mode for video display %i\n", display_index);

		if(w > display_mode.w)
			w = display_mode.w;
		if(h > display_mode.h)
			h = display_mode.h;

		if(verbosity > 0)
			printf("RENDER: setting window size to %ix%i\n", w, h);

		SDL_SetWindowSize(sdl_window, w, h);
    }

    if(verbosity > 2)
    {
		/* Allocate a renderer info struct*/
        SDL_RendererInfo *rend_info = (SDL_RendererInfo *) malloc(sizeof(SDL_RendererInfo));
        if (!rend_info)
        {
                fprintf(stderr, "RENDER: Couldn't allocate memory for the renderer info data structure\n");
                render_sdl2_clean();
                return -5;
        }
        /* Print the list of the available renderers*/
        printf("\nRENDER: Available SDL2 rendering drivers:\n");
        int i = 0;
        for (i = 0; i < SDL_GetNumRenderDrivers(); i++)
        {
            if (SDL_GetRenderDriverInfo(i, rend_info) < 0)
            {
                fprintf(stderr, " Couldn't get SDL2 render driver information: %s\n", SDL_GetError());
            }
            else
            {
                printf(" %2d: %s\n", i, rend_info->name);
                printf("    SDL_RENDERER_TARGETTEXTURE [%c]\n", (rend_info->flags & SDL_RENDERER_TARGETTEXTURE) ? 'X' : ' ');
                printf("    SDL_RENDERER_SOFTWARE      [%c]\n", (rend_info->flags & SDL_RENDERER_SOFTWARE) ? 'X' : ' ');
                printf("    SDL_RENDERER_ACCELERATED   [%c]\n", (rend_info->flags & SDL_RENDERER_ACCELERATED) ? 'X' : ' ');
                printf("    SDL_RENDERER_PRESENTVSYNC  [%c]\n", (rend_info->flags & SDL_RENDERER_PRESENTVSYNC) ? 'X' : ' ');
            }
        }

        free(rend_info);
	}

    main_renderer = SDL_CreateRenderer(sdl_window, -1,
		SDL_RENDERER_TARGETTEXTURE |
		SDL_RENDERER_PRESENTVSYNC  |
		SDL_RENDERER_ACCELERATED);

	if(main_renderer == NULL)
	{
		fprintf(stderr, "RENDER: (SDL2) Couldn't get a accelerated renderer: %s\n", SDL_GetError());
		fprintf(stderr, "RENDER: (SDL2) trying with a software renderer\n");

		main_renderer = SDL_CreateRenderer(sdl_window, -1,
		SDL_RENDERER_TARGETTEXTURE |
		SDL_RENDERER_SOFTWARE);


		if(main_renderer == NULL)
		{
			fprintf(stderr, "RENDER: (SDL2) Couldn't get a software renderer: %s\n", SDL_GetError());
			fprintf(stderr, "RENDER: (SDL2) giving up...\n");
			render_sdl2_clean();
			return -3;
		}
	}

	if(verbosity > 2)
    {
		/* Allocate a renderer info struct*/
        SDL_RendererInfo *rend_info = (SDL_RendererInfo *) malloc(sizeof(SDL_RendererInfo));
        if (!rend_info)
        {
                fprintf(stderr, "RENDER: Couldn't allocate memory for the renderer info data structure\n");
                render_sdl2_clean();
                return -5;
        }

		/* Print the name of the current rendering driver */
		if (SDL_GetRendererInfo(main_renderer, rend_info) < 0)
		{
			fprintf(stderr, "Couldn't get SDL2 rendering driver information: %s\n", SDL_GetError());
		}
		printf("RENDER: rendering driver in use: %s\n", rend_info->name);
		printf("    SDL_RENDERER_TARGETTEXTURE [%c]\n", (rend_info->flags & SDL_RENDERER_TARGETTEXTURE) ? 'X' : ' ');
		printf("    SDL_RENDERER_SOFTWARE      [%c]\n", (rend_info->flags & SDL_RENDERER_SOFTWARE) ? 'X' : ' ');
		printf("    SDL_RENDERER_ACCELERATED   [%c]\n", (rend_info->flags & SDL_RENDERER_ACCELERATED) ? 'X' : ' ');
		printf("    SDL_RENDERER_PRESENTVSYNC  [%c]\n", (rend_info->flags & SDL_RENDERER_PRESENTVSYNC) ? 'X' : ' ');

		free(rend_info);
	}

	SDL_RenderSetLogicalSize(main_renderer, width, height);
	SDL_SetRenderDrawBlendMode(main_renderer, SDL_BLENDMODE_NONE);

    rending_texture = SDL_CreateTexture(main_renderer,
		SDL_PIXELFORMAT_IYUV,  /*yuv420p*/
		SDL_TEXTUREACCESS_STREAMING,
		width,
		height);

	if(rending_texture == NULL)
	{
		fprintf(stderr, "RENDER: (SDL2) Couldn't get a texture for rending: %s\n", SDL_GetError());
		render_sdl2_clean();
		return -4;
	}

    return 0;
}
示例#27
0
int init()
{
    SDL_DisplayMode mode;

    // Initialize SDL itself
    printf("SDL_Init()\n");
    if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) != 0)
    {
        printf("SDL_Init error: %s\n", SDL_GetError());

        return 0;
    }

    // Get the current display mode
    printf("SDL_GetCurrentDisplayMode()\n");
    if(SDL_GetCurrentDisplayMode( 0, &mode ) != 0)
    {
        printf("SDL_GetCurrentDisplayMode error: %s\n", SDL_GetError());

        SDL_Quit();

        return 0;
    }

    rect_screen.w = mode.w;
    rect_screen.h = mode.h;

    //Create a new full-screen window
    printf("SDL_CreateWindow()\n");
    window = SDL_CreateWindow("Multiplatform Base Application",
                              SDL_WINDOWPOS_UNDEFINED,
                              SDL_WINDOWPOS_UNDEFINED,
                              rect_screen.w,
                              rect_screen.h,
                              SDL_WINDOW_SHOWN);
    if(!window)
    {
        printf("SDL_CreateWindow error: %s\n", SDL_GetError());

        SDL_Quit();

        return 0;
    }

    // Create a renderer
    printf("SDL_CreateRenderer()\n");
    renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
    if(!renderer)
    {
        printf("SDL_CreateRenderer error: %s\n", SDL_GetError());

        SDL_DestroyWindow(window);
        SDL_Quit();

        return 0;
    }

    // Init audio
    printf("Mix_Init()\n");
    if(Mix_Init(MIX_INIT_OGG) != MIX_INIT_OGG)
    {
        printf("Mix_Init error: %s\n", Mix_GetError());

        SDL_DestroyRenderer(renderer);
        SDL_DestroyWindow(window);
        SDL_Quit();

        return 0;
    }

    // Open audio device
    printf("Mix_OpenAudio()\n");
    if(Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, MIX_DEFAULT_CHANNELS, 1024) != 0)
    {
        printf("Mix_OpenAudio error: %s\n", Mix_GetError());

        Mix_Quit();
        SDL_DestroyRenderer(renderer);
        SDL_DestroyWindow(window);
        SDL_Quit();

        return 0;
    }

    return 1;
}
示例#28
0
void init(void) {

  texturesList = createList();
  musicList = createList();
  fontList = createList();
  black.r = 0; black.g = 0; black.b = 0;
  white.r = 255; white.g = 255; white.b = 255;

 // Initialize SDL2
  if( SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) {
    fprintf(stderr, "Unable to initialize SDL: %s \n", SDL_GetError());
    quit(1);
  }

  // Display available audio device
  int count = SDL_GetNumAudioDevices(0), i;
  for (i = 0; i < count; ++i ) {
    fprintf(stderr, "Audio device %d: %s\n", i, SDL_GetAudioDeviceName(i, 0));
  }

  // init sound
  int audio_rate = 22050;
  Uint16 audio_format = AUDIO_S16SYS;
  int nb_audio_channels = 4;
  int audio_buffers = 4096;

  if(Mix_OpenAudio(audio_rate, audio_format, nb_audio_channels, audio_buffers) != 0) {
    fprintf(stderr, "Unable to initialize audio: %s\n", Mix_GetError());
    quit(1);
  }

  // Get desktop information
  if (SDL_GetDesktopDisplayMode(0, &displaymode) < 0) {
    fprintf(stderr, "Could not get display mode: %s\n", SDL_GetError());
    quit(1);
  }

  viewport.x = 0;
  viewport.y = 0;
  viewport.w = MIN(displaymode.w, 800);
  viewport.h = MIN(displaymode.h, 600);

  // Create an application window with the following settings:
  window = SDL_CreateWindow(
      "Game example",                    //    window title
      SDL_WINDOWPOS_UNDEFINED,           //    initial x destination
      SDL_WINDOWPOS_UNDEFINED,           //    initial y destination
      viewport.w,                        //    width, in pixels
      viewport.h,                        //    height, in pixels
      SDL_WINDOW_SHOWN                   //    flags
  );

  // Check that the window was successfully made
  if(window==NULL){   
      // In the event that the window could not be made...
      fprintf(stderr, "Could not create window: %s\n", SDL_GetError());
      quit(1);
  }
  
  renderer = SDL_CreateRenderer(window, -1, 0); // SDL_RENDERER_PRESENTVSYNC
  if (renderer < 0) {
      fprintf(stderr, "Could not create renderer: %s\n", SDL_GetError());
      quit(1);
  }

  SDL_RenderGetViewport(renderer, &viewport);

  if (TTF_Init() == -1) {
      fprintf(stderr, "Unable to initialize SDL_ttf: %s \n", TTF_GetError());
      quit(1);
  }

}
示例#29
0
文件: main.cpp 项目: baloi/c_me
int main(int argc, char **argv)
{

    if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {
        std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl;
        return 0;
    }

    SDL_Window *win = SDL_CreateWindow("Hello World", 100, 100, 640, 480, 
        SDL_WINDOW_SHOWN);
    if (win == nullptr) {
        std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl;
        SDL_Quit();
        return 1;
    }


    SDL_Renderer *ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED |
            SDL_RENDERER_PRESENTVSYNC);
    if (ren == nullptr) {
        SDL_DestroyWindow(win);
        std::cout << "SDL_CreateRenderer Error: " << SDL_GetError() 
                << std::endl;
        SDL_Quit();
        return 1;
    }

    std::string imagePath = getResourcePath("Lesson1") + "mad_tux.bmp";
    SDL_Surface *bmp = SDL_LoadBMP(imagePath.c_str());
    if (bmp == nullptr) {
        SDL_DestroyRenderer(ren);
        SDL_DestroyWindow(win);
        std::cout << "SDL_LoadBMP Error: " << SDL_GetError() << std::endl;
        SDL_Quit();
        return 1;
    }

    SDL_Texture *tex = SDL_CreateTextureFromSurface(ren, bmp);
    SDL_FreeSurface(bmp);
    if (tex == nullptr) {
        SDL_DestroyRenderer(ren);
        SDL_DestroyWindow(win);
        std::cout << "SDL_CreateTextureFromSurface Error: " << SDL_GetError()
                << std::endl;
        SDL_Quit();
        return 1;
    }

    SDL_RenderClear(ren);
    SDL_RenderCopy(ren, tex, NULL, NULL);
    SDL_RenderPresent(ren);

    SDL_Delay(8000);

    // Cleaning up
    SDL_DestroyTexture(tex);
    SDL_DestroyRenderer(ren);
    SDL_DestroyWindow(win);
    SDL_Quit();


    return 0;
}
int main(int argc, char* argv[])
{

    AVFormatContext	*pFormatCtx;
    int				i, videoindex;
    AVCodecContext	*pCodecCtx;
    AVCodec			*pCodec;
    AVFrame	*pFrame,*pFrameYUV;
    uint8_t *out_buffer;
    AVPacket *packet;
    int ret, got_picture;

    //------------SDL----------------
    int screen_w,screen_h;
    SDL_Window *screen;
    SDL_Renderer* sdlRenderer;
    SDL_Texture* sdlTexture;
    SDL_Rect sdlRect;
    SDL_Thread *video_tid;
    SDL_Event event;

    struct SwsContext *img_convert_ctx;

    char filepath[]="bigbuckbunny_480x272.h265";

    av_register_all();
    avformat_network_init();
    pFormatCtx = avformat_alloc_context();

    if(avformat_open_input(&pFormatCtx,filepath,NULL,NULL)!=0) {
        printf("Couldn't open input stream.\n");
        return -1;
    }
    if(avformat_find_stream_info(pFormatCtx,NULL)<0) {
        printf("Couldn't find stream information.\n");
        return -1;
    }
    videoindex=-1;
    for(i=0; i<pFormatCtx->nb_streams; i++)
        if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
            videoindex=i;
            break;
        }
    if(videoindex==-1) {
        printf("Didn't find a video stream.\n");
        return -1;
    }
    pCodecCtx=pFormatCtx->streams[videoindex]->codec;
    pCodec=avcodec_find_decoder(pCodecCtx->codec_id);
    if(pCodec==NULL) {
        printf("Codec not found.\n");
        return -1;
    }
    if(avcodec_open2(pCodecCtx, pCodec,NULL)<0) {
        printf("Could not open codec.\n");
        return -1;
    }
    pFrame=av_frame_alloc();
    pFrameYUV=av_frame_alloc();
    out_buffer=(uint8_t *)av_malloc(avpicture_get_size(PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height));
    avpicture_fill((AVPicture *)pFrameYUV, out_buffer, PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height);

    //Output Info-----------------------------
    printf("---------------- File Information ---------------\n");
    av_dump_format(pFormatCtx,0,filepath,0);
    printf("-------------------------------------------------\n");

    img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt,
                                     pCodecCtx->width, pCodecCtx->height, PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);


    if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) {
        printf( "Could not initialize SDL - %s\n", SDL_GetError());
        return -1;
    }
    //SDL 2.0 Support for multiple windows
    screen_w = pCodecCtx->width;
    screen_h = pCodecCtx->height;
    screen = SDL_CreateWindow("Simplest ffmpeg player's Window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
                              screen_w, screen_h,SDL_WINDOW_OPENGL);

    if(!screen) {
        printf("SDL: could not create window - exiting:%s\n",SDL_GetError());
        return -1;
    }
    sdlRenderer = SDL_CreateRenderer(screen, -1, 0);
    //IYUV: Y + U + V  (3 planes)
    //YV12: Y + V + U  (3 planes)
    sdlTexture = SDL_CreateTexture(sdlRenderer, SDL_PIXELFORMAT_IYUV, SDL_TEXTUREACCESS_STREAMING,pCodecCtx->width,pCodecCtx->height);

    sdlRect.x=0;
    sdlRect.y=0;
    sdlRect.w=screen_w;
    sdlRect.h=screen_h;

    packet=(AVPacket *)av_malloc(sizeof(AVPacket));

    video_tid = SDL_CreateThread(sfp_refresh_thread,NULL,NULL);
    //------------SDL End------------
    //Event Loop

    for (;;) {
        //Wait
        SDL_WaitEvent(&event);
        if(event.type==SFM_REFRESH_EVENT) {
            //------------------------------
            if(av_read_frame(pFormatCtx, packet)>=0) {
                if(packet->stream_index==videoindex) {
                    ret = avcodec_decode_video2(pCodecCtx, pFrame, &got_picture, packet);
                    if(ret < 0) {
                        printf("Decode Error.\n");
                        return -1;
                    }
                    if(got_picture) {
                        sws_scale(img_convert_ctx, (const uint8_t* const*)pFrame->data, pFrame->linesize, 0, pCodecCtx->height, pFrameYUV->data, pFrameYUV->linesize);
                        //SDL---------------------------
                        SDL_UpdateTexture( sdlTexture, NULL, pFrameYUV->data[0], pFrameYUV->linesize[0] );
                        SDL_RenderClear( sdlRenderer );
                        //SDL_RenderCopy( sdlRenderer, sdlTexture, &sdlRect, &sdlRect );
                        SDL_RenderCopy( sdlRenderer, sdlTexture, NULL, NULL);
                        SDL_RenderPresent( sdlRenderer );
                        //SDL End-----------------------
                    }
                }
                av_free_packet(packet);
            } else {
                //Exit Thread
                thread_exit=1;
            }
        } else if(event.type==SDL_KEYDOWN) {
            //Pause
            if(event.key.keysym.sym==SDLK_SPACE)
                thread_pause=!thread_pause;
        } else if(event.type==SDL_QUIT) {
            thread_exit=1;
        } else if(event.type==SFM_BREAK_EVENT) {
            break;
        }

    }

    sws_freeContext(img_convert_ctx);

    SDL_Quit();
    //--------------
    av_frame_free(&pFrameYUV);
    av_frame_free(&pFrame);
    avcodec_close(pCodecCtx);
    avformat_close_input(&pFormatCtx);

    return 0;
}