int main( int argc, char* args[] ) { //Start up SDL and create window if( !init() ) { printf( "Failed to initialize!\n" ); } else { //Load media if( !loadMedia() ) { printf( "Failed to load media!\n" ); } else { //Main loop flag bool quit = false; //Event handler SDL_Event e; //Modulation component Uint8 a = 255; //While application is running while( !quit ) { //Handle events on queue while( SDL_PollEvent( &e ) != 0 ) { //User requests quit if( e.type == SDL_QUIT ) { quit = true; } //Handle key presses else if( e.type == SDL_KEYDOWN ) { //Increase alpha on w if( e.key.keysym.sym == SDLK_w ) { //Cap if over 255 if( a + 32 > 255 ) { a = 255; } //Increment otherwise else { a += 32; } } //Decrease alpha on s else if( e.key.keysym.sym == SDLK_s ) { //Cap if below 0 if( a - 32 < 0 ) { a = 0; } //Decrement otherwise else { a -= 32; } } } } //Clear screen SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF ); SDL_RenderClear( gRenderer ); //Render background gBackgroundTexture.render( 0, 0 ); //Render front blended gModulatedTexture.setAlpha( a ); gModulatedTexture.render( 0, 0 ); //Update screen SDL_RenderPresent( gRenderer ); } } } //Free resources and close SDL close(); return 0; }
int main(int argc, char* argv[]) { //initialize and loading variables char *bgmm[11] = { "l1.mp3", "l2.mp3", "l3.mp3", "l4.mp3", "l5.mp3", "l6.mp3", "l7.mp3", "l8.mp3", "l9.mp3", "l10.mp3", "l11.mp3" }; char *bv[11] = { "can we live together.wav", "can't you just relax do you even remember.wav", "chage is good for you.wav", "grace and integrity are what define us.wav", "how do thrive and grow under pressure.wav", "i don't want you to keep going.wav", "i know sometimes it feels like you have no controle", "i want to help you but you need to let me.wav", "is there another way.wav", "once an action is done it cannot be undone.wav", "push any further and yu will break.wav" }; SDL_Color color; const point center = { 220.0, 350.0 }; int currenttick, score=0; short circleradius = 44,musicselect=0; boolean mainmenu = yes; double theta = 0.0,speed=0.09; //Uint8 alpha; SDL_Renderer *rendertarget = NULL; SDL_Rect rectangle1 = { 320, 0, 100, 20 }, rectangle2 = { 230, rectangle1.y-80, 100, 20 }; SDL_Rect littlerectangle1 = { 310, rectangle1.y - 165, 50, 20 }; SDL_Rect cube1 = { 300, rectangle1.y - 270, 40, 40 }, cube2 = { 310, cube1.y - 90, 40, 40 }, cube3 = { 305, cube2.y - 90, 40, 40 }; SDL_Rect redballposition = { center.x + circleradius*sin(theta), center.y + circleradius*cos(theta), 25, 25 }; SDL_Rect blueballposition = { center.x - circleradius*sin(theta), center.y - circleradius*cos(theta), 25, 25 }; const Uint8 *keystate; SDL_Window *window = NULL; SDL_Texture *redball = NULL, *blueball = NULL, *box = NULL; //gametexture // Initialize SDL2 SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO); Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, MIX_DEFAULT_CHANNELS, 2560); Mix_Music *bgm = Mix_LoadMUS("l1.mp3"); Mix_Chunk *voice = Mix_LoadWAV("trust your instincts.wav"), *hitsound = Mix_LoadWAV("Samples/3816133910831170.wav"); Mix_PlayChannel(2,voice,0); Mix_PlayMusic(bgm, -1); // Create an application window with the following settings: window = SDL_CreateWindow("An SDL2 window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 440, 480, SDL_WINDOW_SHOWN ); rendertarget = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); box = loadTexture("box.png", rendertarget); redball = loadTexture("redball.png", rendertarget); blueball = loadTexture("bleuball.png", rendertarget); //SDL_SetRenderDrawColor(rendertarget, 0x23, 0x23, 0x23, 0x23); SDL_SetRenderDrawColor(rendertarget, 0x99, 0x99, 0xF8, 0x23); color.r = 0x99; color.g = 0x99; color.b = 0xF8; color.a = 0x23; option select = exitgame; //gameloop boolean gamerunning = yes, programruns = yes; SDL_Event e; while (programruns == yes){ while (gamerunning == yes && select == startgame){ while (SDL_PollEvent(&e)) { if (e.type == SDL_QUIT) gamerunning = no; }; srand(time(0)); currenttick = SDL_GetTicks(); if (e.key.keysym.scancode == SDL_SCANCODE_ESCAPE){ SDL_RenderClear(rendertarget); SDL_RenderPresent(rendertarget); //SDL_RenderCopy(rendertarget, gameTitle, NULL, &Gametitleposition); //update(gameTitle, Gametitleposition); SDL_RenderPresent(rendertarget); mainmenu = yes; break; //code to stop game and get back to menu } keystate = SDL_GetKeyboardState(NULL); if (keystate[SDL_SCANCODE_LEFT]) { theta += speed; redballposition.x = center.x + circleradius*sin(theta); redballposition.y = center.y + circleradius*cos(theta); blueballposition.x = center.x - circleradius*sin(theta); blueballposition.y = center.y - circleradius*cos(theta); } else if (keystate[SDL_SCANCODE_RIGHT]){ theta -= speed; redballposition.x = center.x + circleradius*sin(theta); redballposition.y = center.y + circleradius*cos(theta); blueballposition.x = center.x - circleradius*sin(theta); blueballposition.y = center.y - circleradius*cos(theta); } else if (keystate[SDL_SCANCODE_UP]){ circleradius += 2; redballposition.x = center.x + circleradius*sin(theta); redballposition.y = center.y + circleradius*cos(theta); blueballposition.x = center.x - circleradius*sin(theta); blueballposition.y = center.y - circleradius*cos(theta); } else if (keystate[SDL_SCANCODE_DOWN]){ circleradius -= 2; redballposition.x = center.x + circleradius*sin(theta); redballposition.y = center.y + circleradius*cos(theta); blueballposition.x = center.x - circleradius*sin(theta); blueballposition.y = center.y - circleradius*cos(theta); } movebox(rectangle1); srand(currenttick); movebox(rectangle2); srand(currenttick); movebox(littlerectangle1); srand(currenttick); movebox(cube1); srand(currenttick); movebox(cube2); srand(currenttick); movebox(cube3); SDL_RenderClear(rendertarget); update(redball, redballposition); update(blueball, blueballposition); update(box, rectangle1); update(box, rectangle2); update(box, littlerectangle1); update(box, cube1); update(box, cube2); update(box, cube3); SDL_RenderPresent(rendertarget); if (aBallhit(rectangle1) || aBallhit(rectangle2) || aBallhit(littlerectangle1) || aBallhit(cube1) || aBallhit(cube2) || aBallhit(cube3)){ Mix_PlayChannel(1, hitsound, 0); //reinitialize Game //rectangle1 = { 220, 0, 100, 20 }; rectangle1.x= 220; rectangle1.y= 0; rectangle1.w= 100; rectangle1.h= 20; //rectangle2 = { 130, rectangle1.y - 80, 100, 20 }; rectangle2.x= 130; rectangle2.y= rectangle1.y - 80; rectangle2.w= 100; rectangle2.h= 20; //littlerectangle1 = { 210, rectangle1.y - 165, 50, 20 }; littlerectangle1.x= 210; littlerectangle1.y= rectangle1.y - 165; littlerectangle1.w= 50; littlerectangle1.h= 20; //cube1 = { 200, rectangle1.y - 270, 40, 40 }; cube1.x= 200; cube1.y= rectangle1.y - 270; cube1.w= 40; cube1.h= 40; //cube2 = { 210, cube1.y - 90, 40, 40 }; cube2.x= 210; cube2.y= cube1.y - 90; cube2.w= 40; cube2.h= 40; //cube3 = { 205, cube2.y - 90, 40, 40 }; cube3.x= 205; cube3.y= cube2.y - 90; cube3.w= 40; cube3.h= 40; //redballposition = { center.x + circleradius*sin(theta), center.y + circleradius*cos(theta), 25, 25 }; redballposition.x= center.x + circleradius*sin(theta); redballposition.y= center.y + circleradius*cos(theta); redballposition.w= 25; redballposition.h= 25; //blueballposition = { center.x - circleradius*sin(theta), center.y - circleradius*cos(theta), 25, 25 }; blueballposition.x= center.x - circleradius*sin(theta); blueballposition.y= center.y - circleradius*cos(theta); blueballposition.w= 25; blueballposition.h= 25; circleradius = 44; gamerunning = yes; mainmenu = yes; printf("\n your score is: %d", score); score = 0; Mix_HaltMusic(); Mix_FreeMusic(bgm); if (musicselect == 10) musicselect = 0; else musicselect += 1; bgm = Mix_LoadMUS(bgmm[musicselect]); voice = Mix_LoadWAV(bv[musicselect]); Mix_PlayMusic(bgm,-1); Mix_PlayChannel(2, voice, 0); srand(currenttick); color.b = rand(); srand(currenttick*100); color.a = rand(); srand(currenttick*1000); color.g = rand(); srand(currenttick*10000); color.r = rand(); SDL_SetRenderDrawColor(rendertarget, color.r, color.g, color.b, color.a); break; //insert code when collision happens } if (musicselect == 6 ){ color.b = rand(); srand(currenttick * 100); color.r = rand(); srand(currenttick * 1000); color.g = rand(); SDL_SetTextureColorMod(box, color.r, color.g, color.b); } else if (musicselect == 7){ //SDL_SetTextureColorMod(box, 0, 0, 0); } //if (rectangle1.y >= 200){ // alpha = 20; // SDL_SetTextureAlphaMod(box,alpha); //} //else // alpha=100; if( (notout(redballposition,blueballposition))&&(rectangle1.y == 400 || rectangle2.y == 400 || littlerectangle1.y == 400 || cube1.y == 400 || cube2.y == 400 || cube3.y == 400)){ score += 1; // printf("\n score = %d", score); } if (SDL_GetTicks() - currenttick<1000.0 / 60)/*60 FPS*/ { SDL_Delay(1000 / 60 - SDL_GetTicks() + currenttick); } } runmenu(&programruns,&mainmenu,rendertarget,&select); } // Close and destroy the window SDL_DestroyWindow(window); // Clean up SDL_Quit(); IMG_Quit(); Mix_Quit(); SDL_DestroyTexture(redball); SDL_DestroyTexture(blueball); SDL_DestroyTexture(box); SDL_DestroyRenderer(rendertarget); redball = NULL; blueball = NULL; box = NULL; rendertarget = NULL; return 0; }
void Graphics::clear() { SDL_RenderClear(this->_renderer); }
void VideoDecodcEncodc::decodec() { AVFormatContext *pFormatCtx; int i, videoindex; AVCodecContext *pCodecCtx; AVCodec *pCodec; AVFrame *pFrame, *pFrameYUV; uint8_t *out_buffer; AVPacket *packet; int ret, got_picture,y_size; //------------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; FILE *pFile =NULL; //char filepath[]="bigbuckbunny_480x272.h265"; char filepath[] = "Titanic.ts"; 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 ; } if (avformat_find_stream_info(pFormatCtx, NULL)<0){ printf("Couldn't find stream information.\n"); return ; } 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 ; } pCodecCtx = pFormatCtx->streams[videoindex]->codec; pCodec = avcodec_find_decoder(pCodecCtx->codec_id); if (pCodec == NULL){ printf("Codec not found.\n"); return ; } if (avcodec_open2(pCodecCtx, pCodec, NULL)<0){ printf("Could not open codec.\n"); return ; } #if OUTPUT_YUV420P pFile = fopen("output.yuv","wb+"); #endif 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 ; } //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 ; } 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){ while (1){ if (av_read_frame(pFormatCtx, packet)<0) thread_exit = 1; if (packet->stream_index == videoindex) break; } ret = avcodec_decode_video2(pCodecCtx, pFrame, &got_picture, packet); if (ret < 0){ printf("Decode Error.\n"); return ; } if (got_picture){ sws_scale(img_convert_ctx, (const uint8_t* const*)pFrame->data, pFrame->linesize, 0, pCodecCtx->height, pFrameYUV->data, pFrameYUV->linesize); #if OUTPUT_YUV420P y_size = pCodecCtx->width*pCodecCtx->height; fwrite(pFrameYUV->data[0], 1, y_size, pFile); //Y fwrite(pFrameYUV->data[1], 1, y_size / 4, pFile); //U fwrite(pFrameYUV->data[2], 1, y_size / 4, pFile); //V #endif //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 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); }
void CSDL_Setup::Begin() { SDL_PollEvent(mainEvent); SDL_RenderClear(renderer); }
int main(int argc, char **argv) { int done = 0; SDL_Window *window; SDL_Renderer *renderer; /* !!! FIXME: check for errors. */ SDL_Init(SDL_INIT_VIDEO); window = SDL_CreateWindow("Drag the red boxes", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_BORDERLESS | SDL_WINDOW_RESIZABLE); renderer = SDL_CreateRenderer(window, -1, 0); if (SDL_SetWindowHitTest(window, hitTest, NULL) == -1) { SDL_Log("Enabling hit-testing failed!\n"); SDL_Quit(); return 1; } while (!done) { SDL_Event e; int nothing_to_do = 1; SDL_SetRenderDrawColor(renderer, 0, 0, 127, 255); SDL_RenderClear(renderer); SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255); SDL_RenderFillRects(renderer, areas, SDL_arraysize(drag_areas)); SDL_RenderPresent(renderer); while (SDL_PollEvent(&e)) { nothing_to_do = 0; switch (e.type) { case SDL_MOUSEBUTTONDOWN: SDL_Log("button down!\n"); break; case SDL_MOUSEBUTTONUP: SDL_Log("button up!\n"); break; case SDL_WINDOWEVENT: if (e.window.event == SDL_WINDOWEVENT_MOVED) { SDL_Log("Window event moved to (%d, %d)!\n", (int) e.window.data1, (int) e.window.data2); } break; case SDL_KEYDOWN: if (e.key.keysym.sym == SDLK_ESCAPE) { done = 1; } else if (e.key.keysym.sym == SDLK_x) { if (!areas) { areas = drag_areas; numareas = SDL_arraysize(drag_areas); } else { areas = NULL; numareas = 0; } } break; case SDL_QUIT: done = 1; break; } } if (nothing_to_do) { SDL_Delay(50); } } SDL_Quit(); return 0; }
game_status state_in_game(SDL_Renderer *renderer, game* p_game) { bool done=false; game_status ret_code = QUIT; map *p_map = p_game->p_map; while (!done){ //update display //clear SDL_SetRenderDrawColor(renderer, 0x0, 0x0, 0x0, 0xFF); SDL_RenderClear(renderer); //draw the map map_draw(p_map, renderer); //draw the chipset image_draw(p_map->p_chipset, renderer, 0, 0); //input SDL_Event event; while (SDL_PollEvent(&event)){ if(event.type == SDL_QUIT){ done=true; break; } const int cam_speed = 8; switch ( event.type ) { case SDL_KEYDOWN: switch (event.key.keysym.sym) { case SDLK_q: done=true; break; case SDLK_s: map_save(p_map, p_game->map_save_path); break; case SDLK_LEFT: p_map->o_camera.x -= cam_speed; break; case SDLK_RIGHT: p_map->o_camera.x += cam_speed; break; case SDLK_UP: p_map->o_camera.y -= cam_speed; break; case SDLK_DOWN: p_map->o_camera.y += cam_speed; break; default: break; } break; case SDL_MOUSEBUTTONDOWN: map_tile_click(p_map, event.button.x, event.button.y, event.button.button); break; case SDL_MOUSEMOTION: map_mouse_move(p_map, renderer, event.button.x, event.button.y); break; case SDL_MOUSEWHEEL: if(event.button.x < 0) p_map->o_camera.y--; else if(event.button.x > 0) p_map->o_camera.y++; break; default: break; } } //render SDL_RenderPresent(renderer); } return ret_code; }
std::shared_ptr<Texture> Generic::Load(std::vector<std::vector<int>> map, std::shared_ptr<Entity> ent, std::string path, unsigned width, unsigned height, float starting_point_x, float starting_point_y, int frame_width, int frame_height) { if (!path.size()) { Output_Handler::Error << "ERR Generic::Load : No path supplied\n"; return nullptr; } if (!map.size() || !map[0].size()) { Output_Handler::Error << "ERR Generic::Change : Given map has width/height equal to 0\n"; return nullptr; } SDL_Texture* gt = nullptr; for (auto& ttr : Texture::__Textures) if (path == ttr->__Path && dynamic_cast<Generic*>(ttr.get())) { gt = dynamic_cast<Generic*>(ttr.get())->__Generic_Texture; break; } if (!gt) gt = IMG_LoadTexture(Screen::Renderer, path.c_str()); if (!gt) { Output_Handler::Error << "ERR Texture::Load : No valid texture file supplied\n"; return nullptr; } auto texture = SDL_CreateTexture ( Screen::Renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, frame_width * map[0].size(), frame_height * map.size() ); if (!texture) { Output_Handler::Error << "ERR Texture::Load : Couldn't create SDL_Texture (probably size is too big)\n"; SDL_DestroyTexture(gt); return nullptr; } Texture::__Textures.emplace_back(std::make_shared<Generic>()); Texture::__Load(ent, Texture::__Textures.back(), frame_width * map[0].size(), frame_height * map.size(), starting_point_x, starting_point_y); std::shared_ptr<Generic> ts = std::static_pointer_cast<Generic>(Texture::__Textures.back()); ts->__Generic_Texture = gt; ts->__Generic_Width = width; ts->__Generic_Height = height; ts->__Width = frame_width * map[0].size(); ts->__Height = frame_height * map.size(); ts->__SDL_Texture = texture; ts->__Tilemap = map; ts->__Path = path; if (frame_width == 0) ts->Frame_Width = width; else if (frame_width < 0) ts->Frame_Width = width / -frame_width; else ts->Frame_Width = frame_width; if (frame_height == 0) ts->Frame_Height = height; else if (frame_height < 0) ts->Frame_Height = height / -frame_height; else ts->Frame_Height = frame_height; if (ent) ent->texture = Texture::__Textures.back(); SDL_SetTextureBlendMode(ts->__SDL_Texture, SDL_BLENDMODE_BLEND); SDL_SetRenderTarget(Screen::Renderer, ts->__SDL_Texture); SDL_Rect src = { 0,0, (int)frame_width, (int)frame_height }; SDL_Rect dst = { 0,0, (int)frame_width, (int)frame_height }; auto get_frame_pos = [&ts](int frame)->std::pair<int, int> { if (frame < 0) return std::pair<int, int>( frame, frame ); std::pair<int, int> p; p.second = 0; p.first = frame * (int)ts->Frame_Width; while (p.first >= (int)ts->__Generic_Width) { p.first -= ts->__Generic_Width; p.second += ts->Frame_Height; } return p; }; SDL_RenderClear(Screen::Renderer); for (unsigned i = 0; i < map.size(); i++) { for (unsigned j = 0; j < map[i].size(); j++) { if (map[i][j] < (int)ts->Tiles_Count()) { auto frame_pos = get_frame_pos(map[i][j]); src.x = frame_pos.first; src.y = frame_pos.second; } else { Output_Handler::Output << "MSG Generic::Change : Tile " << map[i][j] << " doesn't exist (max " << ts->Tiles_Count() - 1 << "); no tile is drawn\n"; src.x = 0; src.y = 0; } if(src.x >= 0 && src.y >= 0) SDL_RenderCopy(Screen::Renderer, ts->__Generic_Texture, &src, &dst); dst.x += frame_width; } dst.y += frame_height; dst.x = 0; } //ent->__Type = ET_Generic; SDL_SetRenderTarget(Screen::Renderer, NULL); return Texture::__Textures.back(); }
void StateHandler::Game() { bool quit = false; bool quitToOs = false; double deltaTime = 0.0; GameTimer gameTimer; DebugInfo debugInfo(myRenderer); Enemy a(myRenderer, eEnemyType::Mollusk); Entity b(myRenderer); a.SetPosition(450, 450); b.SetPosition(500, 500); SDL_Event eventQueue; while (quit == false) { gameTimer.Update(); deltaTime = gameTimer.GetDeltaTime(); debugInfo.Update(gameTimer); while(SDL_PollEvent(&eventQueue) != 0) { if(eventQueue.type == SDL_QUIT) { quitToOs = true; quit = true; } else if (eventQueue.type == SDL_KEYDOWN) { switch(eventQueue.key.keysym.sym) { case SDLK_ESCAPE: quitToOs = true; quit = true; break; case SDLK_F10: debugInfo.ToggleShow(); break; } } } SDL_SetRenderDrawColor(myRenderer, 0x00, 0x00, 0x00, 0xFF); SDL_RenderClear(myRenderer); a.Update(deltaTime); //b.Update(deltaTime); b.Render(); a.Render(); debugInfo.Render(); SDL_RenderPresent(myRenderer); } if(quitToOs == true) { SetState(eGameStates::Quit); } else { SetState(eGameStates::MainMenu); } }
void _Cairo_graphics_surfaces <_Graphics_math_float_impl>::surfaces::_Render_to_native_surface < _Cairo::_Cairo_graphics_surfaces <_Graphics_math_float_impl>::surfaces::_Output_surface_data*, basic_output_surface <_Cairo::_Cairo_graphics_surfaces <_Graphics_math_float_impl>> > ( _Cairo::_Cairo_graphics_surfaces <_Graphics_math_float_impl>::surfaces::_Output_surface_data * & osdp, basic_output_surface <_Cairo::_Cairo_graphics_surfaces <_Graphics_math_float_impl>> & sfc ) { auto& osd = *osdp; const cairo_filter_t cairoFilter = CAIRO_FILTER_GOOD; auto& data = osd.data; double displayWidth = static_cast<double>(data.display_dimensions.x()); double displayHeight = static_cast<double>(data.display_dimensions.y()); double backBufferWidth = static_cast<double>(data.back_buffer.dimensions.x()); double backBufferHeight = static_cast<double>(data.back_buffer.dimensions.y()); auto backBufferSfc = data.back_buffer.surface.get(); auto displaySfc = data.display_surface.get(); auto displayContext = data.display_context.get(); cairo_surface_flush(backBufferSfc); cairo_set_operator(displayContext, CAIRO_OPERATOR_SOURCE); if (osd.user_scaling_callback != nullptr) { bool letterbox = false; auto userRect = osd.user_scaling_callback(sfc, letterbox); if (letterbox) { if (data._Letterbox_brush == nullopt) { cairo_set_source_rgb(displayContext, 0.0, 0.0, 0.0); cairo_paint(displayContext); } else { auto pttn = data._Letterbox_brush.value().data().brush.get(); if (data._Letterbox_brush_props == nullopt) { cairo_pattern_set_extend(pttn, CAIRO_EXTEND_NONE); cairo_pattern_set_filter(pttn, CAIRO_FILTER_GOOD); cairo_matrix_t cPttnMatrix; cairo_matrix_init_identity(&cPttnMatrix); cairo_pattern_set_matrix(pttn, &cPttnMatrix); cairo_set_source(displayContext, pttn); cairo_paint(displayContext); } else { const basic_brush_props<_Cairo_graphics_surfaces<std::experimental::io2d::v1::_Graphics_math_float_impl>>& props = data._Letterbox_brush_props.value(); cairo_pattern_set_extend(pttn, _Extend_to_cairo_extend_t(props.wrap_mode())); cairo_pattern_set_filter(pttn, _Filter_to_cairo_filter_t(props.filter())); cairo_matrix_t cPttnMatrix; const auto& m = props.brush_matrix(); cairo_matrix_init(&cPttnMatrix, m.m00(), m.m01(), m.m10(), m.m11(), m.m20(), m.m21()); cairo_pattern_set_matrix(pttn, &cPttnMatrix); cairo_set_source(displayContext, pttn); cairo_paint(displayContext); } } } cairo_matrix_t ctm; cairo_matrix_init_scale(&ctm, 1.0 / displayWidth / static_cast<double>(userRect.width()), 1.0 / displayHeight / static_cast<double>(userRect.height())); cairo_matrix_translate(&ctm, -static_cast<double>(userRect.x()), -static_cast<double>(userRect.y())); unique_ptr<cairo_pattern_t, decltype(&cairo_pattern_destroy)> pat(cairo_pattern_create_for_surface(backBufferSfc), &cairo_pattern_destroy); auto patPtr = pat.get(); cairo_pattern_set_matrix(patPtr, &ctm); cairo_pattern_set_extend(patPtr, CAIRO_EXTEND_NONE); cairo_pattern_set_filter(patPtr, cairoFilter); cairo_set_source(displayContext, patPtr); cairo_paint(displayContext); } else { // Calculate the destRect values. switch (data.scl) { case std::experimental::io2d::scaling::letterbox: { _Render_for_scaling_uniform_or_letterbox(osd); } break; case std::experimental::io2d::scaling::uniform: { _Render_for_scaling_uniform_or_letterbox(osd); } break; case std::experimental::io2d::scaling::fill_uniform: { // Maintain aspect ratio and center, but overflow if needed rather than letterboxing. if (backBufferWidth == displayWidth && backBufferHeight == displayHeight) { cairo_set_source_surface(displayContext, backBufferSfc, 0.0, 0.0); cairo_paint(displayContext); } else { auto widthRatio = displayWidth / backBufferWidth; auto heightRatio = displayHeight / backBufferHeight; if (widthRatio < heightRatio) { cairo_set_source_rgb(displayContext, 0.0, 0.0, 0.0); cairo_paint(displayContext); cairo_matrix_t ctm; cairo_matrix_init_scale(&ctm, 1.0 / heightRatio, 1.0 / heightRatio); cairo_matrix_translate(&ctm, trunc(abs((displayWidth - (backBufferWidth * heightRatio)) / 2.0)), 0.0); unique_ptr<cairo_pattern_t, decltype(&cairo_pattern_destroy)> pat(cairo_pattern_create_for_surface(backBufferSfc), &cairo_pattern_destroy); auto patPtr = pat.get(); cairo_pattern_set_matrix(patPtr, &ctm); cairo_pattern_set_extend(patPtr, CAIRO_EXTEND_NONE); cairo_pattern_set_filter(patPtr, cairoFilter); cairo_set_source(displayContext, patPtr); cairo_paint(displayContext); } else { cairo_set_source_rgb(displayContext, 0.0, 0.0, 0.0); cairo_paint(displayContext); cairo_matrix_t ctm; cairo_matrix_init_scale(&ctm, 1.0 / widthRatio, 1.0 / widthRatio); cairo_matrix_translate(&ctm, 0.0, trunc(abs((displayHeight - (backBufferHeight * widthRatio)) / 2.0))); unique_ptr<cairo_pattern_t, decltype(&cairo_pattern_destroy)> pat(cairo_pattern_create_for_surface(backBufferSfc), &cairo_pattern_destroy); auto patPtr = pat.get(); cairo_pattern_set_matrix(patPtr, &ctm); cairo_pattern_set_extend(patPtr, CAIRO_EXTEND_NONE); cairo_pattern_set_filter(patPtr, cairoFilter); cairo_set_source(displayContext, patPtr); cairo_paint(displayContext); } } } break; case std::experimental::io2d::scaling::fill_exact: { // Maintain aspect ratio and center, but overflow if needed rather than letterboxing. if (backBufferWidth == displayWidth && backBufferHeight == displayHeight) { cairo_set_source_surface(displayContext, backBufferSfc, 0.0, 0.0); cairo_paint(displayContext); } else { auto widthRatio = displayWidth / backBufferWidth; auto heightRatio = displayHeight / backBufferHeight; cairo_matrix_t ctm; cairo_matrix_init_scale(&ctm, 1.0 / widthRatio, 1.0 / heightRatio); unique_ptr<cairo_pattern_t, decltype(&cairo_pattern_destroy)> pat(cairo_pattern_create_for_surface(backBufferSfc), &cairo_pattern_destroy); auto patPtr = pat.get(); cairo_pattern_set_matrix(patPtr, &ctm); cairo_pattern_set_extend(patPtr, CAIRO_EXTEND_NONE); cairo_pattern_set_filter(patPtr, cairoFilter); cairo_set_source(displayContext, patPtr); cairo_paint(displayContext); } } break; case std::experimental::io2d::scaling::none: { cairo_set_source_surface(displayContext, backBufferSfc, 0.0, 0.0); cairo_paint(displayContext); } break; default: { assert("Unexpected _Scaling value." && false); } break; } } // cairo_restore(_Native_context.get()); // This call to cairo_surface_flush is needed for Win32 surfaces to update. cairo_surface_flush(displaySfc); cairo_set_source_rgb(displayContext, 0.0, 0.0, 0.0); SDL_SetRenderDrawColor(data.renderer, 0, 0, 0, 255); if (SDL_RenderClear(data.renderer) != 0) { throw ::std::system_error(::std::make_error_code(::std::errc::io_error), SDL_GetError()); } // Copy Cairo canvas to SDL2 texture unsigned char * src = cairo_image_surface_get_data(displaySfc); // TODO([email protected]): compute the pitch, given const int pitch = (int)backBufferWidth * 4; // '4' == 4 bytes per pixel if (SDL_UpdateTexture(data.texture, nullptr, src, pitch) != 0) { throw ::std::system_error(::std::make_error_code(::std::errc::io_error), SDL_GetError()); } if (SDL_RenderCopy(data.renderer, data.texture, nullptr, nullptr) != 0) { throw ::std::system_error(::std::make_error_code(::std::errc::io_error), SDL_GetError()); } // Present latest image SDL_RenderPresent(data.renderer); }
int _tmain(int argc, _TCHAR* argv[]) { AVFormatContext *pFormatCtx; int i, videoindex; AVCodecContext *pCodecCtx; AVCodec *pCodec; char filepath[]="src01_480x272_22.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(av_find_stream_info(pFormatCtx)<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; } AVFrame *pFrame,*pFrameYUV; pFrame=avcodec_alloc_frame(); pFrameYUV=avcodec_alloc_frame(); uint8_t *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); //------------SDL---------------- if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) { printf( "Could not initialize SDL - %s\n", SDL_GetError()); return -1; } int screen_w=0,screen_h=0; SDL_Window *screen; //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; } SDL_Renderer* sdlRenderer = SDL_CreateRenderer(screen, -1, 0); //IYUV: Y + U + V (3 planes) //YV12: Y + V + U (3 planes) SDL_Texture* sdlTexture = SDL_CreateTexture(sdlRenderer, SDL_PIXELFORMAT_IYUV, SDL_TEXTUREACCESS_STREAMING,pCodecCtx->width,pCodecCtx->height); SDL_Rect sdlRect; sdlRect.x = 0; sdlRect.y = 0; sdlRect.w = screen_w; sdlRect.h = screen_h; int ret, got_picture; AVPacket *packet=(AVPacket *)av_malloc(sizeof(AVPacket)); //Output Info----------------------------- printf("File Information(文件信息)---------------------\n"); av_dump_format(pFormatCtx,0,filepath,0); printf("-------------------------------------------------\n"); struct SwsContext *img_convert_ctx; img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height, PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL); //-------------- SDL_Thread *video_tid = SDL_CreateThread(sfp_refresh_thread,NULL,NULL); // //Event Loop SDL_Event event; 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, &sdlRect, pFrameYUV->data[0], pFrameYUV->linesize[0] ); SDL_RenderClear( sdlRenderer ); SDL_RenderCopy( sdlRenderer, sdlTexture, &sdlRect, &sdlRect ); SDL_RenderPresent( sdlRenderer ); //SDL End----------------------- } } av_free_packet(packet); }else{ //Exit Thread thread_exit=1; break; } } } sws_freeContext(img_convert_ctx); SDL_Quit(); //-------------- av_free(out_buffer); av_free(pFrameYUV); avcodec_close(pCodecCtx); avformat_close_input(&pFormatCtx); return 0; }
int main( int argc, char* args[] ) { //Start up SDL and create window if( !init() ) { printf( "Failed to initialize!\n" ); } else { //The level tiles Tile* tileSet[ TOTAL_TILES ]; //Load media if( !loadMedia( tileSet ) ) { printf( "Failed to load media!\n" ); } else { //Main loop flag bool quit = false; //Event handler SDL_Event e; //The dot that will be moving around on the screen Dot dot; //Level camera SDL_Rect camera = { 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT }; //While application is running while( !quit ) { //Handle events on queue while( SDL_PollEvent( &e ) != 0 ) { //User requests quit if( e.type == SDL_QUIT ) { quit = true; } //Handle input for the dot dot.handleEvent( e ); } //Move the dot dot.move( tileSet ); dot.setCamera( camera ); //Clear screen SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF ); SDL_RenderClear( gRenderer ); //Render level for( int i = 0; i < TOTAL_TILES; ++i ) { tileSet[ i ]->render( camera ); } //Render dot dot.render( camera ); //Update screen SDL_RenderPresent( gRenderer ); } } //Free resources and close SDL close( tileSet ); } return 0; }
int main(int, char**){ //Start up SDL and make sure it went ok if (SDL_Init(SDL_INIT_VIDEO) != 0){ logSDLError(std::cout, "SDL_Init"); return 1; } //Setup our window and renderer SDL_Window *window = SDL_CreateWindow("Lesson 5", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); 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"); cleanup(window); SDL_Quit(); return 1; } const std::string resPath = getResourcePath("Lesson5"); SDL_Texture *image = loadTexture(resPath + "image.png", renderer); if (image == nullptr){ cleanup(image, renderer, window); IMG_Quit(); SDL_Quit(); return 1; } //iW and iH are the clip width and height //We'll be drawing only clips so get a center position for the w/h of a clip int iW = 100, iH = 100; int x = SCREEN_WIDTH / 2 - iW / 2; int y = SCREEN_HEIGHT / 2 - iH / 2; //Setup the clips for our image SDL_Rect clips[4]; //Since our clips our uniform in size we can generate a list of their //positions using some math (the specifics of this are covered in the lesson) for (int i = 0; i < 4; ++i){ clips[i].x = i / 2 * iW; clips[i].y = i % 2 * iH; clips[i].w = iW; clips[i].h = iH; } //Specify a default clip to start with int useClip = 0; SDL_Event e; bool quit = false; while (!quit){ //Event Polling while (SDL_PollEvent(&e)){ if (e.type == SDL_QUIT){ quit = true; } //Use number input to select which clip should be drawn if (e.type == SDL_KEYDOWN){ switch (e.key.keysym.sym){ case SDLK_1: useClip = 0; break; case SDLK_2: useClip = 1; break; case SDLK_3: useClip = 2; break; case SDLK_4: useClip = 3; break; case SDLK_ESCAPE: quit = true; break; default: break; } } } //Rendering SDL_RenderClear(renderer); //Draw the image renderTexture(image, renderer, x, y, &clips[useClip]); //Update the screen SDL_RenderPresent(renderer); } //Clean up cleanup(image, renderer, window); IMG_Quit(); SDL_Quit(); return 0; }
/****************************************************************************** * Display BackBuffer Flipping ******************************************************************************/ void display::flip() { SDL_SetRenderDrawColor(pRenderer, 0, 0, 0, 255); SDL_RenderPresent(pRenderer); SDL_RenderClear(pRenderer); }
void Game::Draw() { SDL_RenderClear(m_pRenderer); switch (StateManager::stateMachine->getCurrentGameStates()) { case MENU: m_StartGameMenu.backGroundMenu.Draw(m_pRenderer); // buttonsMenu.Draw(m_pRenderer); for (int iter = 0; iter < 5; iter++) m_StartGameMenu.m_buttonSet[iter].Draw(m_pRenderer); // txt.Draw(m_pRenderer); // level.Draw(m_pRenderer); break; case STARTGAME: texture.Draw(m_pRenderer); // for (int iter = 0; iter < 14; iter++) // m_cardSet[iter].Draw(m_pRenderer); m_cardLogic.Draw(m_pRenderer); m_Play.Draw(m_pRenderer); m_Bet.Draw(m_pRenderer); m_WIN.Draw(m_pRenderer); m_Credits.Draw(m_pRenderer); m_Menu.Draw(m_pRenderer); //BUTTON MENU txt.Draw(m_pRenderer); break; case RULES_OF_GAMES: m_StartGameMenu.backGroundForTeam.DrawRules(m_pRenderer); break; case TEAM_PROJECT: m_StartGameMenu.backGroundForTeam.DrawTeam(m_pRenderer); break; case GAMEOVER: texture.Draw(m_pRenderer); m_Play.Draw(m_pRenderer); m_Bet.Draw(m_pRenderer); m_WIN.Draw(m_pRenderer); m_Credits.Draw(m_pRenderer); m_Menu.Draw(m_pRenderer); //BUTTON MENU break; case VIEW_CARDS: if (m_Play.isIsClicked()) { m_cardLogic.GetCardFromDeck(); m_cardLogic.m_TwoCard.clear(); m_Play.setIsClicked(false); } texture.Draw(m_pRenderer); m_Play.Draw(m_pRenderer); m_Bet.Draw(m_pRenderer); m_WIN.Draw(m_pRenderer); m_Credits.Draw(m_pRenderer); m_Menu.Draw(m_pRenderer); //BUTTON MENU m_cardLogic.Draw(m_pRenderer); txt.Draw(m_pRenderer); break; } SDL_RenderPresent(m_pRenderer); }/*end of Draw*/
int video_copy_screen(s_screen *src) { void *data; int pitch, linew, i, h; unsigned char *sp; unsigned char *dp; SDL_Rect rectdes, rectsrc; rectsrc.x = rectsrc.y = 0; rectsrc.w = textureWidth; rectsrc.h = textureHeight; int hide_touch; extern int hide_t; linew = src->width * bytes_per_pixel; if(bscreen) { if(src->width != bscreen->w || src->height != bscreen->h) { return 0; } if(SDL_MUSTLOCK(bscreen)) { SDL_LockSurface(bscreen); } sp = (unsigned char *)src->data; dp = bscreen->pixels; h = src->height; do { //u16pcpy((unsigned short*)dp, sp, glpalette, linew); i = linew - 1; do { ((unsigned *)dp)[i] = glpalette[sp[i]]; } while(i--); sp += linew; dp += bscreen->pitch; } while(--h); data = bscreen->pixels; pitch = bscreen->pitch; } else { data = src->data; pitch = linew; } SDL_UpdateTexture(texture, &rectsrc, data, pitch); if(bscreen && SDL_MUSTLOCK(bscreen)) { SDL_UnlockSurface(bscreen); } if(stretch) { //rectdes.w = textureWidth; //rectdes.h = textureHeight; //rectdes.x = (viewportWidth-rectdes.w)/2; //rectdes.y = (viewportHeight-rectdes.h)/2; rectdes.w = viewportWidth; rectdes.h = viewportHeight; rectdes.x = 0; rectdes.y = 0; } else if(savedata.glscale > 0) { rectdes.w = textureWidth * savedata.glscale; rectdes.h = textureHeight * savedata.glscale; rectdes.x = (viewportWidth - rectdes.w) / 2; rectdes.y = (viewportHeight - rectdes.h) / 2; if(rectdes.h < viewportHeight - 2) { if(screendocking & DOCKTOP) { rectdes.y = 1; } else if(screendocking & DOCKBOTTOM) { rectdes.y = viewportHeight - 1 - rectdes.h; } } if(rectdes.w < viewportWidth - 2) { if(screendocking & DOCKLEFT) { rectdes.x = 1; } else if(screendocking & DOCKRIGHT) { rectdes.x = viewportWidth - 1 - rectdes.w; } } } else if((float)viewportWidth / (float)viewportHeight > (float)textureWidth / (float)textureHeight) { rectdes.h = viewportHeight; rectdes.w = rectdes.h * textureWidth / textureHeight; rectdes.x = (viewportWidth - rectdes.w) / 2; rectdes.y = 0; } else { rectdes.w = viewportWidth; rectdes.h = rectdes.w * textureHeight / textureWidth; rectdes.y = (viewportHeight - rectdes.h) / 2; rectdes.x = 0; } //SDL_SetHintWithPriority(SDL_HINT_RENDER_SCALE_QUALITY, savedata.glfilter[savedata.fullscreen]?"linear":"nearest", SDL_HINT_DEFAULT); SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); SDL_RenderClear(renderer); SDL_RenderCopy(renderer, texture, &rectsrc, &rectdes); hide_touch = (timer_gettick() > hide_t); for(i = 0, h = 0; i < MAXTOUCHB; i++) { h += touchstates[i]; if(!hide_touch && (i != SDID_SCREENSHOT || touchstates[i])) { SDL_SetTextureAlphaMod(buttons, touchstates[i] ? 128 : 64); SDL_RenderCopy(renderer, buttons, &btnsrc[i], &btndes[i]); } } if(h) { hide_t = timer_gettick() + 5000; } SDL_RenderPresent(renderer); SDL_Delay(1); return 1; }
int main(int argc, char* args[]) { Screen screen = {}; screen.width = SQUARE_DIM*SCALE*COLUMNS; screen.height = SQUARE_DIM*SCALE*ROWS; //init everything (window, main surface, renderer, SDL_Image) //NOTE: This is probably a bad way to do this since I am changing data inside function instead of returning something if(!init(&screen)) { printf("Something could not be initialized! Error: %s\n", SDL_GetError()); } //set Texture class render pointer Texture::setRenderer(screen.renderer); //set Square's main texture Square::setTexture("tiles.png"); //create a blockbuilder BlockBuilder builder; //get a block pointer Block* block = null; //create an array for the Tetris board that will hold all inanimate squares Board board = {0}; //int numGrid = ROWS*COLUMNS; //Square board_squares[ROWS*COLUMNS]; //set up locations for board squares board.numSquares = COLUMNS*ROWS; for(int i = 0; i < board.numSquares; ++i) { int x = (i%COLUMNS)*SQUARE_DIM*SCALE; int y = (i/COLUMNS)*SQUARE_DIM*SCALE; board.squares[i].setX(x); board.squares[i].setY(y); board.squares[i].concrete = 0; } //create vector for blocks //std::vector<Block*> blocks; //blocks.push_back(builder.buildBlock(L_BLOCK, RED, 0, 0)); bool quit = false; SDL_Event event; //timer variables uint32 currentTime = SDL_GetTicks(); uint32 previousTime = 0; //init RNG srand(time(0)); Color colors[4]; colors[0] = RED; colors[1] = BLUE; colors[2] = GREEN; colors[3] = YELLOW; BlockType blockTypes[5]; blockTypes[0] = T_BLOCK; blockTypes[1] = I_BLOCK; blockTypes[2] = O_BLOCK; blockTypes[3] = S_BLOCK; blockTypes[4] = L_BLOCK; while(!quit) { //check to see if there is no active block if(!block) { int color = rand()%4; int blockType = rand()%5; block = builder.buildBlock(blockTypes[blockType], colors[color], 210, 30); block->setLowestPoint(board.blocksInColumn); //block->setLowestBlockY(); } while(SDL_PollEvent(&event)) { if(event.type == SDL_QUIT) { quit = true; printf("QUITTING! Another successful run! :)\n"); } else if(event.type == SDL_KEYDOWN) { switch(event.key.keysym.sym) { case SDLK_UP: { //rotate block counter - clockwise block->rotateBlock(board.squares, board.blocksInColumn, -1); } break; case SDLK_DOWN: { } break; case SDLK_RIGHT: { block->moveBlock(VELOCITY, board.squares, board.blocksInColumn); } break; case SDLK_LEFT: { block->moveBlock(-VELOCITY, board.squares, board.blocksInColumn); } break; case SDLK_SPACE: { //first set block's squares to resting place height block->setToRest(); } break; default: { } } } } //clear screen set to light gray SDL_SetRenderDrawColor(screen.renderer, 0, 0, 0, 0); SDL_RenderClear(screen.renderer); //render the grid renderGrid(screen.renderer); //the block block->render(); //printf("Final Y: %d, LowY: %d\n", block->finalY, block->blockLowY); //render board for(int i = 0; i < board.numSquares; ++i) { if(!board.squares[i].concrete) //check if null { continue; } board.squares[i].renderBoardSquare(); } //printf("x: %d y: %d\n", block->getX(), block->getY()); SDL_RenderPresent(screen.renderer); //bool makeStatic = false; // has block reached its final resting place? //check to see if 1/2 of a second has passed. //if so, update locationsj currentTime = SDL_GetTicks(); if((currentTime - previousTime) > 500) { //printf("currentTime - previousTime = %d\n", currentTime - previousTime); //updateBlocks(&blocks, board_squares); if(updateBlocks(block, &board)) { block = null; //check to see if any rows are full FilledRowRegion check = checkBoard(&board); if(check.firstFilledRow > -1) //then there is a row that is filled! { clearBoard(check.firstFilledRow, check.lastFilledRow, &board); } } previousTime = currentTime; } } SDL_DestroyRenderer(screen.renderer); SDL_DestroyWindow(screen.window); screen.window = null; SDL_Quit(); IMG_Quit(); return 0; }
void video_clearscreen() { SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); SDL_RenderClear(renderer); //SDL_RenderPresent(renderer); }
void Window::fill(int r, int g, int b) { SDL_SetRenderDrawColor(renderer, r, 75, b, 255); SDL_RenderClear(renderer); }
void AppRenderer::clear() { SDL_RenderClear(this->get()); }
void CApp::OnRender() { SDL_RenderClear(renderer); levels[currentLevel]->display(renderer, player); // draw loot... levels[currentLevel]->drawLoot(renderer, player); levels[currentLevel]->drawMonsters(renderer, player); // draw player... if (moving_left) { player->direction = 0; player->setActiveAnimation(player->runLeft); if (levels[currentLevel]->getColAt(player->pos_x - 20 - (player->getWidth() / 2)/ 2, player->pos_y) != 1 && player->pos_x > 0) { player->pos_x -= 20 * delay; } player->idle = false; } else if (moving_right) { player->direction = 1; player->setActiveAnimation(player->runRight); if (levels[currentLevel]->getColAt(player->pos_x + 20 + (player->getWidth() / 2)/ 2, player->pos_y) != 1 && player->pos_x < levels[currentLevel]->getWidth() * 64) { player->pos_x += 20 * delay; } player->idle = false; } if (jumping >= 0) { if (player->direction == 0) { player->setActiveAnimation(player->jumpLeft); } else { player->setActiveAnimation(player->jumpRight); } player->idle = false; } if (player->idle) { if (player->direction == 0) { player->setActiveAnimation(player->idleLeft); } else { player->setActiveAnimation(player->idleRight); } } SDL_Texture *playertex = player->getActiveAnimation()->getFrame(); SDL_Rect dest; int x = player->pos_x - (player->getWidth() / 2); int y = player->pos_y - (player->getHeight() / 2); if (x > (levels[currentLevel]->getWidth() * 64) - 640) { x = 1280 - ((levels[currentLevel]->getWidth() * 64) - x); } else if (x > 640) { x = 640; } if (y > (levels[currentLevel]->getHeight() * 64) - 360) { y = 720 - ((levels[currentLevel]->getHeight() * 64) - y); } else if (y > 360) { y = 360; } dest.x = x; dest.y = y; dest.w = player->getWidth(); dest.h = player->getHeight(); SDL_RenderCopy(renderer, playertex, NULL, &dest); levels[currentLevel]->displayfg(renderer, player); levels[currentLevel]->drawFloaties(renderer, player, delay); // draw the gui std::stringstream ss; ss << "Level: " << (currentLevel + 1); SDL_Texture *lvlTex = RenderString(ss.str()); SDL_QueryTexture(lvlTex, NULL, NULL, &dest.w, &dest.h); dest.x = 640 - (dest.w / 2); dest.y = 10; SDL_RenderCopy(renderer, lvlTex, NULL, &dest); ss.str(""); ss << "Score: " << player->score; SDL_Texture *score = RenderString(ss.str()); SDL_QueryTexture(score, NULL, NULL, &dest.w, &dest.h); dest.x = 10; dest.y = 10; SDL_RenderCopy(renderer, score, NULL, &dest); SDL_RenderPresent(renderer); }
void SDLHardwareRenderDevice::blankScreen() { SDL_SetRenderTarget(renderer, texture); SDL_SetRenderDrawColor(renderer, background_color.r, background_color.g, background_color.b, background_color.a); SDL_RenderClear(renderer); return; }
void Page::background_clear_render(int r, int g, int b, int a) { SDL_SetRenderDrawColor(gRenderer, r, g, b, a); SDL_RenderClear(gRenderer); }
void clear(){ SDL_RenderClear(this->ren); }
int main(int argc, char *argv[]) { int i, done; SDL_Event event; /* Enable standard application logging */ SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO); /* Initialize test framework */ state = SDLTest_CommonCreateState(argv, SDL_INIT_VIDEO); if (!state) { return 1; } for (i = 1; i < argc;) { int consumed; consumed = SDLTest_CommonArg(state, i); /* needed voodoo to allow app to launch via OS X Finder */ if (SDL_strncmp(argv[i], "-psn", 4)==0) { consumed = 1; } if (consumed == 0) { consumed = -1; } if (consumed < 0) { SDL_Log("Usage: %s %s\n", argv[0], SDLTest_CommonUsage(state)); quit(1); } i += consumed; } if (!SDLTest_CommonInit(state)) { quit(2); } for (i = 0; i < state->num_windows; ++i) { SDL_Renderer *renderer = state->renderers[i]; SDL_SetRenderDrawColor(renderer, 0xA0, 0xA0, 0xA0, 0xFF); SDL_RenderClear(renderer); SDL_RenderPresent(renderer); } SDL_EventState(SDL_DROPFILE, SDL_ENABLE); /* Main render loop */ done = 0; while (!done) { /* Check for events */ while (SDL_PollEvent(&event)) { SDLTest_CommonEvent(state, &event, &done); if (event.type == SDL_DROPBEGIN) { SDL_Log("Drop beginning on window %u", (unsigned int) event.drop.windowID); } else if (event.type == SDL_DROPCOMPLETE) { SDL_Log("Drop complete on window %u", (unsigned int) event.drop.windowID); } else if ((event.type == SDL_DROPFILE) || (event.type == SDL_DROPTEXT)) { const char *typestr = (event.type == SDL_DROPFILE) ? "File" : "Text"; char *dropped_filedir = event.drop.file; SDL_Log("%s dropped on window %u: %s", typestr, (unsigned int) event.drop.windowID, dropped_filedir); SDL_free(dropped_filedir); } } } quit(0); /* keep the compiler happy ... */ return(0); }
int video_display_process(uint8_t* frame, int width, int height, int size) { //if we get a NULL frame, stop displaying. if(frame == NULL) { video_display_destroy(); return 0; } //first time called ? Initialize things. if(!initialized) { if(video_display_init_size(width, height) < 0) { fprintf(stderr, "[~][Display] Failed initialization.\n"); return -1; } if(video_display_set_size(width, height) < 0) return -1; initialized = 1; } //check whether the size of the video has changed if (width != current_width || height != current_height) if (video_display_set_size(width, height) < 0) return -1; //check whether there's new stuff in the input com buffer double new_update = jakopter_com_get_timestamp(com_in); if (new_update > prev_update) { update_infos(); if (want_screenshot) { take_screenshot(frame, size); want_screenshot = 0; jakopter_com_write_int(com_in, 24, 0); } prev_update = new_update; } pthread_mutex_lock(&mutex_process); if (current_process != NULL) { current_process(frame, width, height, size); } pthread_mutex_unlock(&mutex_process); unload_element(); if (load_element() < 0) fprintf(stderr, "Couldn't load graphic element\n"); // update the texture with our new frame if (SDL_UpdateTexture(frameTex, NULL, frame, width) < 0) { fprintf(stderr, "[~][Display] Failed to update frame texture : %s\n", SDL_GetError()); return -1; } //clear the renderer, then update it so that we get the new frame displayed. SDL_RenderClear(renderer); SDL_RenderCopy(renderer, frameTex, NULL, NULL); //SDL_RenderFillRect(renderer, &rectangle); //draw all overlay elements, when they exist int i = 0; for (i = 0 ; i < VIDEO_NB_NAV_INFOS ; i++) if (graphs[i].tex != NULL) SDL_RenderCopy(renderer, graphs[i].tex, NULL, &graphs[i].pos); pthread_mutex_lock(&mutex_graphics_list); struct graphics_list *current = icon_registry; while (current != NULL) { if (current->graphic != NULL && current->graphic->tex != NULL){ int ret = SDL_RenderCopy(renderer, current->graphic->tex, NULL, ¤t->graphic->pos); if (ret < 0) fprintf(stderr, "[~][display] RenderCopy() failed: %s\n", SDL_GetError()); } current = current->next; } pthread_mutex_unlock(&mutex_graphics_list); draw_attitude_indic(); draw_compass(); SDL_RenderPresent(renderer); return 0; }
int main( int argc, char* args[] ) { //Start up SDL and create window if( !init() ) { printf( "Failed to initialize!\n" ); } else { //Load media if( !loadMedia() ) { printf( "Failed to load media!\n" ); } else { //Main loop flag bool quit = false; //Event handler SDL_Event e; //Text rendering color SDL_Color textColor = { 0, 0, 0, 0xFF }; SDL_Color highlightColor = { 0xFF, 0, 0, 0xFF }; //Current input point int currentData = 0; //While application is running while( !quit ) { //Handle events on queue while( SDL_PollEvent( &e ) != 0 ) { //User requests quit if( e.type == SDL_QUIT ) { quit = true; } else if( e.type == SDL_KEYDOWN ) { switch( e.key.keysym.sym ) { //Previous data entry case SDLK_UP: //Rerender previous entry input point gDataTextures[ currentData ].loadFromRenderedText( std::to_string( (_Longlong)gData[ currentData ] ), textColor ); --currentData; if( currentData < 0 ) { currentData = TOTAL_DATA - 1; } //Rerender current entry input point gDataTextures[ currentData ].loadFromRenderedText( std::to_string( (_Longlong)gData[ currentData ] ), highlightColor ); break; //Next data entry case SDLK_DOWN: //Rerender previous entry input point gDataTextures[ currentData ].loadFromRenderedText( std::to_string( (_Longlong)gData[ currentData ] ), textColor ); ++currentData; if( currentData == TOTAL_DATA ) { currentData = 0; } //Rerender current entry input point gDataTextures[ currentData ].loadFromRenderedText( std::to_string( (_Longlong)gData[ currentData ] ), highlightColor ); break; //Decrement input point case SDLK_LEFT: --gData[ currentData ]; gDataTextures[ currentData ].loadFromRenderedText( std::to_string( (_Longlong)gData[ currentData ] ), highlightColor ); break; //Increment input point case SDLK_RIGHT: ++gData[ currentData ]; gDataTextures[ currentData ].loadFromRenderedText( std::to_string( (_Longlong)gData[ currentData ] ), highlightColor ); break; } } } //Clear screen SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF ); SDL_RenderClear( gRenderer ); //Render text textures gPromptTextTexture.render( ( SCREEN_WIDTH - gPromptTextTexture.getWidth() ) / 2, 0 ); for( int i = 0; i < TOTAL_DATA; ++i ) { gDataTextures[ i ].render( ( SCREEN_WIDTH - gDataTextures[ i ].getWidth() ) / 2, gPromptTextTexture.getHeight() + gDataTextures[ 0 ].getHeight() * i ); } //Update screen SDL_RenderPresent( gRenderer ); } } } //Free resources and close SDL close(); return 0; }
void ClearScreen() { SDL_RenderClear(renderer); }
void hello_world_run (HelloWorld* self) { gboolean quit = FALSE; SDL_Event e = {0}; gint frame = 0; g_return_if_fail (self != NULL); quit = FALSE; frame = 0; while (TRUE) { gboolean _tmp0_ = FALSE; SDL_Renderer* _tmp5_ = NULL; SDL_Renderer* _tmp6_ = NULL; SDL_Rect currentClip = {0}; gint _tmp7_ = 0; SDL_Rect _tmp8_ = {0}; MyTexture* _tmp9_ = NULL; SDL_Renderer* _tmp10_ = NULL; SDL_Rect _tmp11_ = {0}; gint _tmp12_ = 0; SDL_Rect _tmp13_ = {0}; gint _tmp14_ = 0; SDL_Rect _tmp15_ = {0}; SDL_Renderer* _tmp16_ = NULL; gint _tmp17_ = 0; gint _tmp18_ = 0; _tmp0_ = quit; if (!(!_tmp0_)) { break; } while (TRUE) { SDL_Event _tmp1_ = {0}; gint _tmp2_ = 0; SDL_Event _tmp3_ = {0}; SDL_EventType _tmp4_ = 0; _tmp2_ = SDL_PollEvent (&_tmp1_); (e); e = _tmp1_; if (!(_tmp2_ != 0)) { break; } _tmp3_ = e; _tmp4_ = _tmp3_.type; if (_tmp4_ == SDL_QUIT) { quit = TRUE; } } _tmp5_ = self->priv->renderer; SDL_SetRenderDrawColor (_tmp5_, (guint8) 0xFF, (guint8) 0xFF, (guint8) 0xFF, (guint8) SDL_ALPHA_OPAQUE); _tmp6_ = self->priv->renderer; SDL_RenderClear (_tmp6_); _tmp7_ = frame; _tmp8_ = self->priv->spriteClips[_tmp7_ / 4]; currentClip = _tmp8_; _tmp9_ = self->priv->spriteSheetTexture; _tmp10_ = self->priv->renderer; _tmp11_ = currentClip; _tmp12_ = _tmp11_.w; _tmp13_ = currentClip; _tmp14_ = _tmp13_.h; _tmp15_ = currentClip; my_texture_render (_tmp9_, _tmp10_, (HELLO_WORLD_SCREEN_WIDTH - _tmp12_) / 2, (HELLO_WORLD_SCREEN_HEIGHT - _tmp14_) / 2, &_tmp15_); _tmp16_ = self->priv->renderer; SDL_RenderPresent (_tmp16_); _tmp17_ = frame; frame = _tmp17_ + 1; _tmp18_ = frame; if ((_tmp18_ / 4) >= HELLO_WORLD_WALKING_ANIMATION_FRAMES) { frame = 0; } } (e); }
void World::Render(GUIstate* state) { SDL_RenderClear(m_render); Background_layer_one->Draw(0,0,0,true,m_render); for(unsigned int i = 0;i<m_meteorite.size();i++) { m_meteorite[i]->DrawMeteorite(true, m_render); m_meteorite[i]->Update(); } Background_layer_two->Draw(0,0,0,true,m_render); for(unsigned int i = 0;i<m_meteorite_two.size();i++) { m_meteorite_two[i]->DrawMeteorite(true, m_render); m_meteorite_two[i]->Update(); } if(state->m_gravity_active==1) { m_gravity->Draw((m_WWidth/2)-( m_gravity->m_img_width/2),(m_WHeight/2)-( m_gravity->m_img_height/2),1,true,m_render); } else { m_gravity->Draw((m_WWidth/2)-( m_gravity->m_img_width/2),(m_WHeight/2)-( m_gravity->m_img_height/2),0,true,m_render); } Background_layer_three->Draw(0,0,0,true,m_render); for(unsigned int i = 0;i<m_meteorite_three.size();i++) { m_meteorite_three[i]->DrawMeteorite(true, m_render); m_meteorite_three[i]->Update(); } for(unsigned int i = 0;i<m_Players.size();i++) { if(m_Players[i]->m_HP>0) { m_Players[i]->Draw(m_render); } else { if(!m_Players[i]->m_once_dead) m_Players[i]->CalculateDeath(); m_Players[i]->m_alive = m_Players[i]->Draw_Destroy_Ship(m_render); } } if(state->m_planet_active == 1) { m_planet_glow->Draw((m_WWidth/2)-( m_planet_glow->m_img_width/2),(m_WHeight/2)-( m_planet_glow->m_img_height/2),0,true,m_render); Planet->Draw((m_WWidth/2)-(Planet->m_passive_img_width/2),(m_WHeight/2)-(Planet->m_passive_img_height/2), 0, true,m_render); } int percent = (m_Players[0]->m_HP*100)/m_Players[0]->m_FullHP; hp_bar1->Draw_HpBar(0, 10,percent, m_render); int percent2 = (m_Players[1]->m_HP*100)/m_Players[1]->m_FullHP; hp_bar2->Draw_HpBar2(m_WWidth-(hp_bar2->m_passive_img_width), m_WHeight-(hp_bar2->m_passive_img_height),percent2, m_render); m_score_bar->Draw((m_WWidth/2)-(m_score_bar->m_img_width/2),0, 0, true,m_render); m_magenta_numbers->DrawButton (m_Players[0]->m_lives, m_render); m_cyan_numbers->DrawButton (m_Players[1]->m_lives, m_render); if(m_Players[0]->m_lives == 0||m_Players[1]->m_lives == 0) { m_OpacityFill->Draw(0,0,0,true,m_render); if(m_Players[0]->m_lives == 0 && !m_Players[0]->m_alive) { Player2Win->Draw((m_WWidth/2)-(Player1Win->m_img_width/2),(m_WHeight/2)-(Player1Win->m_img_height/2), 0, true,m_render); } else if(!m_Players[1]->m_alive) { Player1Win->Draw((m_WWidth/2)-(Player2Win->m_img_width/2),(m_WHeight/2)-(Player2Win->m_img_height/2), 0, true,m_render); } } SDL_RenderPresent(m_render); }