void SDLStub::destroy() { cleanupGfxMode(); SDL_Quit(); }
int main(int argc, char *argv[]) { GLuint vao; GLuint vbo; GLfloat vertices[] = { 0.5f, -0.5f, 0.0f, -0.5f, -0.5f, 0.0f, 0.0f, 0.5f, 0.0f, }; GLfloat colorUniform[3]; GLint colorUniformLocation; GLint status; GLuint vertexShader; GLuint fragmentShader; GLuint program; GLchar *pbuffer; GLchar buffer[4096]; GLsizei bufferLen; GLchar logBuffer[256]; GLsizei logBufferLen; GLboolean running = GL_FALSE; SDL_Window* window = NULL; SDL_GLContext glContext = NULL; if( 0 > SDL_Init(SDL_INIT_VIDEO) ){ printf("SDL_Init(Video) failed: %s\n", SDL_GetError()); goto error_sdl_init; } SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); window = SDL_CreateWindow(argv[0], 100, 100, 800, 600, SDL_WINDOW_OPENGL); if( !window ){ printf("SDL_CreateWindow failed: %s\n", SDL_GetError()); goto error_sdl_create_window; } glContext = SDL_GL_CreateContext(window); if( !glContext ){ printf("SDL_GL_CreateContext failed: %s\n", SDL_GetError()); goto error_sdl_gl_create_context; } if( 0 == gladLoadGLLoader(SDL_GL_GetProcAddress) ){ printf("gladLoadGLLoader failed\n"); goto error_glad_load_error; } /* load vertex data */ glGenVertexArrays(1, &vao); if( 0 == vao ){ printf("glGenVertexArrays failed: %d\n", glGetError()); goto error_gl_gen_vertex_arrays; } glBindVertexArray(vao); glGenBuffers(1, &vbo); if( 0 == vbo ){ printf("glGenBuffers failed: %d\n", glGetError()); goto error_gl_gen_buffers; } glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), NULL); glEnableVertexAttribArray(0); glBindVertexArray(0); program = glCreateProgram(); if( 0 == program ){ printf("glCreateProgram failed: %d\n", glGetError()); goto error_gl_create_program; } /* load vertex shader */ bufferLen = sizeof(buffer); if( 0 == loadFile("../03_02_UseUniformVariable/shader.vert", buffer, &bufferLen) ){ goto error_load_vertex_source; } vertexShader = glCreateShader(GL_VERTEX_SHADER); if( 0 == vertexShader ){ goto error_gl_create_vertex_shader; } pbuffer = buffer; glShaderSource(vertexShader, 1, &pbuffer, &bufferLen); glCompileShader(vertexShader); glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &status); if( 0 == status ){ glGetShaderInfoLog(vertexShader, sizeof(logBuffer), &logBufferLen, logBuffer); printf("compile shader failed:\n%s\nerror: %s\n", buffer, logBuffer); goto error_gl_compile_shader; } glAttachShader(program, vertexShader); glDeleteShader(vertexShader); vertexShader = 0; /* load fragment shader */ bufferLen = sizeof(buffer); if( 0 == loadFile("../03_02_UseUniformVariable/shader.frag", buffer, &bufferLen) ){ goto error_load_fragment_source; } fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); if( 0 == fragmentShader ){ goto error_gl_create_fragment_shader; } pbuffer = buffer; glShaderSource(fragmentShader, 1, &pbuffer, &bufferLen); glCompileShader(fragmentShader); glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &status); if( 0 == status ){ glGetShaderInfoLog(fragmentShader, sizeof(logBuffer), &logBufferLen, logBuffer); printf("compile shader failed:\n%s\nerror: %s\n", buffer, logBuffer); goto error_gl_compile_fragment_shader; } glAttachShader(program, fragmentShader); /* link program */ glLinkProgram(program); glGetProgramiv(program, GL_LINK_STATUS, &status); if( 0 == status ){ glGetProgramInfoLog(program, sizeof(logBuffer), &logBufferLen, logBuffer); printf("link program failed: %s\n", logBuffer); goto error_link_program; } colorUniformLocation = glGetUniformLocation(program, "vertColor"); if( -1 == colorUniformLocation ){ printf("get uniformm location failed: %d\n", glGetError()); goto error_get_uniform_vertColor_location; } glGetUniformfv(program, colorUniformLocation, colorUniform); running = GL_TRUE; while( running ){ SDL_Event event; while( SDL_PollEvent(&event)){ if( event.type == SDL_KEYDOWN ){ switch(event.key.keysym.sym){ case SDLK_1: if( colorUniform[0] > 0.0f ) colorUniform[0] -= 0.05f; break; case SDLK_2: if( colorUniform[0] < 1.0f ) colorUniform[0] += 0.05f; break; case SDLK_3: if( colorUniform[1] > 0.0f ) colorUniform[1] -= 0.05f; break; case SDLK_4: if( colorUniform[1] < 1.0f ) colorUniform[1] += 0.05f; break; case SDLK_5: if( colorUniform[2] > 0.0f ) colorUniform[2] -= 0.05f; break; case SDLK_6: if( colorUniform[2] < 1.0f ) colorUniform[2] += 0.05f; break; default: printf("quit\n"); running = GL_FALSE; break; } } } glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glBindVertexArray(vao); glUseProgram(program); glUniform3fv(colorUniformLocation, 1, colorUniform); //glUniform3f(colorUniformLocation, colorUniform[0], colorUniform[1], colorUniform[2]); glDrawArrays(GL_TRIANGLES, 0, 3); glUseProgram(0); glBindVertexArray(0); SDL_GL_SwapWindow(window); } glDeleteProgram(program); glDeleteBuffers(1, &vbo); glDeleteVertexArrays(1, &vao); SDL_GL_DeleteContext(glContext); SDL_DestroyWindow(window); SDL_Quit(); return 0; error_get_uniform_vertColor_location: error_link_program: error_gl_compile_fragment_shader: if( fragmentShader ) glDeleteShader(fragmentShader); error_gl_create_fragment_shader: error_load_fragment_source: error_gl_compile_shader: if( vertexShader ) glDeleteShader(vertexShader); error_gl_create_vertex_shader: error_load_vertex_source: glDeleteProgram(program); error_gl_create_program: glDeleteBuffers(1, &vbo); error_gl_gen_buffers: glDeleteVertexArrays(1, &vao); error_gl_gen_vertex_arrays: error_glad_load_error: SDL_GL_DeleteContext(glContext); error_sdl_gl_create_context: SDL_DestroyWindow(window); error_sdl_create_window: SDL_Quit(); error_sdl_init: return -1; }
/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */ static void quit(int rc) { SDL_Quit(); exit(rc); }
CPlayerSession::~CPlayerSession () { int hadthread = 0; #ifndef NEED_SDL_VIDEO_IN_MAIN_THREAD if (m_sync_thread) { send_sync_thread_a_message(MSG_STOP_THREAD); SDL_WaitThread(m_sync_thread, NULL); m_sync_thread = NULL; hadthread = 1; } #else send_sync_thread_a_message(MSG_STOP_THREAD); hadthread = 1; #endif if (m_streaming_media_set_up != 0 && session_control_is_aggregate()) { rtsp_command_t cmd; rtsp_decode_t *decode; memset(&cmd, 0, sizeof(rtsp_command_t)); rtsp_send_aggregate_teardown(m_rtsp_client, m_session_control_url, &cmd, &decode); free_decode_response(decode); } if (m_rtsp_client) { free_rtsp_client(m_rtsp_client); m_rtsp_client = NULL; } while (m_my_media != NULL) { CPlayerMedia *p; p = m_my_media; m_my_media = p->get_next(); delete p; } if (m_sdp_info) { sdp_free_session_desc(m_sdp_info); m_sdp_info = NULL; } if (m_sync_sem) { SDL_DestroySemaphore(m_sync_sem); m_sync_sem = NULL; } int quit_sdl = 1; if (m_video_sync != NULL) { // we need to know if we should quit SDL or not. If the control // code has grabbed the persistence, we don't want to quit if (m_video_sync->grabbed_video_persistence() != 0) { quit_sdl = 0; } delete m_video_sync; m_video_sync = NULL; } if (m_audio_sync != NULL) { delete m_audio_sync; m_audio_sync = NULL; } if (m_session_name) { free((void *)m_session_name); m_session_name = NULL; } if (m_content_base) { free((void *) m_content_base); m_content_base = NULL; } for (int ix = 0; ix < SESSION_DESC_COUNT; ix++) { if (m_session_desc[ix] != NULL) free((void *)m_session_desc[ix]); m_session_desc[ix] = NULL; } if (m_media_close_callback != NULL) { m_media_close_callback(m_media_close_callback_data); } while (m_unused_ports != NULL) { CIpPort *first; first = m_unused_ports; m_unused_ports = first->get_next(); delete first; } if (hadthread != 0 && quit_sdl != 0) { SDL_Quit(); } }
void SDLBase::finalize_SDL() { SDL_DestroyRenderer(screen_renderer); SDL_DestroyWindow(window); SDL_Quit(); }
/* ================================================================================ Game::Initialize Performs the bulk of game initialization. Creates a window, renderer, and resource managers. Loads resources, spawns entities, and creates the initial scene layout. ================================================================================ */ bool Game::Initialize() { // Instructions: std::cout << "***" << std::endl; std::cout << "*** Press A and D to move left and right" << std::endl; std::cout << "*** Press SPACE to jump" << std::endl; std::cout << "*** Press K to remove all the crawlers from a scene!" << std::endl; std::cout << "*** Press P to pause/unpause the game" << std::endl; std::cout << "*** Press V to show/hide the collision rectangles" << std::endl; std::cout << "*** Press 9 to stop/play background music" << std::endl; std::cout << "*** Press X to add a strong crawler on the ground tiles" << std::endl; std::cout << "*** Press C to add a weak crawler on the ground tiles" << std::endl; std::cout << "*** Press R to resurrect from death" << std::endl; std::cout << "*** Each coin is worth 5 points" << std::endl; std::cout << "*** Each weak crawler is worth 25 points" << std::endl; std::cout << "*** Each strong crawler is worth 50 points (2 x 25)" << std::endl; std::cout << "*** You have a total of 5 lives to begin with" << std::endl; std::cout << "***" << std::endl; // initialize SDL if (SDL_Init(SDL_INIT_VIDEO) < 0) { std::cerr << "*** Failed to initialize SDL: " << SDL_GetError() << std::endl; return false; } // initialize SDL_image add-on if (!IMG_Init(IMG_INIT_JPG | IMG_INIT_PNG)) { std::cerr << "*** Failed to initialize SDL_image: " << IMG_GetError() << std::endl; return false; } mScrWidth = 640; mScrHeight = 480; // create a window mWindow = SDL_CreateWindow("C++ Final Project", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, mScrWidth, mScrHeight, SDL_WINDOW_SHOWN /*| SDL_WINDOW_RESIZABLE*/); if (!mWindow) { std::cerr << "*** Failed to create window: " << SDL_GetError() << std::endl; return false; } // create a renderer that takes care of drawing stuff to the window mRenderer = SDL_CreateRenderer(mWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (!mRenderer) { std::cerr << "*** Failed to create renderer: " << SDL_GetError() << std::endl; return false; } // get a pointer to keyboard state managed by SDL mKeyState = SDL_GetKeyboardState(NULL); // Initialize SDL_ttf library if (TTF_Init() != 0) { std::cerr << "TTF_Init() Failed: " << TTF_GetError() << std::endl; SDL_Quit(); exit(1); } // create a texture manager mTexMgr = new GG::TextureManager; if (!mTexMgr->Initialize(mRenderer, "media/")) { std::cerr << "*** Failed to initialize texture manager" << std::endl; return false; } //Initialize SDL Audio if (SDL_INIT_AUDIO < 0) { std::cerr << "SDL audio not initialize! SDL Error: " << SDL_GetError() << std::endl; return false; } //Initialize SDL_mixer if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0) { std::cerr << "SDL_mixer could not initialize! SDL_mixer Error: " << Mix_GetError() << std::endl; return false; } //Load musicIn mMusic = Mix_LoadMUS("media/music.mp3"); mGoodGameOverMusic = Mix_LoadMUS("media/gameover_music.wav"); mBadGameOverMusic = Mix_LoadMUS("media/gameover_music.mp3"); if (mMusic == NULL || mGoodGameOverMusic == NULL || mBadGameOverMusic == NULL) { std::cerr << " Failed to load beat music! SDL_mixer Error:" << Mix_GetError() << std::endl; return false; } //loading the Coin Sound LoadSounds(); if (mCoinSound == NULL || mJumpSound == NULL || mStompSound == NULL || mDieSound == NULL || mStompSoundNoKill == NULL || mBlockSound == NULL) { std::cerr << "*** Failed to initialize mCoinSound" << Mix_GetError()<<std::endl; return false; } // load textures LoadTextures(); LoadGrayscaleTextures(); // initialize grid from a text file (including crawlers and coins!) LoadScene(mScene, true); // initialize the robot mRobot = new Robot(35.0f, mScrHeight-160.0f); // initialize the foreground mForeground = new Layer(0.0f, 0.0f, 800.0f, 480.0f, "Foreground", "Foreground2"); return true; }
void App::run() { is_running = true; //inicjalizacja SDL i utworzenie okan if(SDL_Init(SDL_INIT_VIDEO) == 0) { m_window = SDL_CreateWindow("TANKS", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, AppConfig::windows_rect.w, AppConfig::windows_rect.h, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE); if(m_window == nullptr) return; if(!(IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG)) return; if(TTF_Init() == -1) return; srand(time(NULL)); //inicjowanie generatora pseudolosowego Engine& engine = Engine::getEngine(); engine.initModules(); engine.getRenderer()->loadTexture(m_window); engine.getRenderer()->loadFont(); m_app_state = new Menu; double FPS; Uint32 time1, time2, dt, fps_time = 0, fps_count = 0, delay = 15; time1 = SDL_GetTicks(); while(is_running) { time2 = SDL_GetTicks(); dt = time2 - time1; time1 = time2; if(m_app_state->finished()) { AppState* new_state = m_app_state->nextState(); delete m_app_state; m_app_state = new_state; } if(m_app_state == nullptr) break; eventProces(); m_app_state->update(dt); m_app_state->draw(); SDL_Delay(delay); //FPS fps_time += dt; fps_count++; if(fps_time > 200) { FPS = (double)fps_count / fps_time * 1000; if(FPS > 60) delay++; else if(delay > 0) delay--; fps_time = 0; fps_count = 0; } } engine.destroyModules(); } SDL_DestroyWindow(m_window); m_window = nullptr; TTF_Quit(); IMG_Quit(); SDL_Quit(); }
bool Engine::Create(std::string title, short int width, short int height, char bits, Uint32 sdlFlags, Uint32 videoFlags, double fps, bool fullscreen, std::string maindir) { Assert ( width > 0 ); Assert ( height > 0 ); Assert ( bits > 8 ); Assert ( title != "" ); //I think it should work videoFlags_ = videoFlags; sdlFlags_ = sdlFlags; width_ = width; height_ = height; name_ = title; bits_ = bits; fullscreen_ = fullscreen; mainDir_ = maindir; if (SDL_Init(sdlFlags_) < 0) { std::cout << "Couldn't initialize SDL - " << SDL_GetError() << std::endl; return false; } SetupGLAttributes(); if(SDL_SetVideoMode(width_, height_, bits_, videoFlags_) == NULL) { std::cout << "Couldn't set GL mode >> " << SDL_GetError() << std::endl; SDL_Quit(); return false; } SDL_WM_SetCaption ( name_.c_str( ) , NULL ); Assert(SetupGL() && "OpenGL initialization"); std::cout<<"OpenGL initialized"<<std::endl; if(!Initialize()) { return false; } SDL_EnableUNICODE(1); SDL_EnableKeyRepeat(200,200); Resize(width_, height_); screen_ = SDL_GetVideoSurface(); if(fullscreen_) ToggleFullscreen(); tahomaFont_ = FontManager::Instance()->GetByName("tahoma16"); timer_ = new PrecisionTimer(fps); timer_->SmoothUpdatesOn(); timer_->Start(); return true; }
int main(void) { SDL_Surface *scr = wInitSDL(); DrawFillRect(scr, NULL, SDL_MapRGB(scr->format, 0, 0, 0)); wInitTheme(NULL); nSDL_Font *font = nSDL_LoadFont(NSDL_FONT_VGA, 255, 255, 255); nSDL_DrawStringCF(scr, font, 5, 5, "Couco\45 u !"); SDL_Flip(scr); wait_key_pressed(); nSDL_FreeFont(font); /* // Déclaration des widgets Widget *mainWidget = wWindow("Aide"); Widget *tabs = wTab(); // 1er onglet Widget *body1 = wBasicLayout(0); Widget *subody1 = wHorizontalLayout(0); Widget *im_tbtton = wPixmapNTI(image_buttonScratchpad); Widget *navigation = wText("Use the T-Button to navigate between tabs.\n\nIf you maintain this button while using RIGHT or LEFT buttons, you will be able to select your tab.\n\nMaintaining the T-Button plus pushing DEL will delete the selected tab from your work space.\n\nTo navigate faster in your texts, use CTRL+Directional Arrow.", 15); //2e onglet Widget *keys = wText("DOC - Quicksave the current file\nSHIFT + DOC - Quickave all files\n\nSHIFT + Directional Arrow - Select text\nCTRL + VAR - Copy selection\nVAR - Paste selection\n\nUse CTRL + (Character Button) or SHIFT + (Character Button) to get another character.\n\nHere are some useful examples :\nCTRL + ' , ' --> ;\nCTRL + ' 0 ' --> :\nCTRL + '.' --> !\nCTRL + '(-)' --> ?\nqu'est-ce qui bug au fond ??? Est-ce quand j'ai un wText avec progressbar mais non éditable ???\nCTRL+'2' = '\"'\nCTRL+'/' '\%'\nCTRL+'(' = '['\nSHIFT+'(' = '{'\nSHIFT+1 = '<'\nSHIT+'2' = '_'\nSHIFT+'3' = '>'\netc...\n\nUse CTRL+'?!>' to get some special characters. ", 17); // // 3e onglet Widget *body3 = wGridLayout(1, 3,0); Widget *text1 = wText("Rename a file with '.py' or '.py.tns' extension to get Python's syntax highlights.", 3); Widget *text2 = wText("You can then click ENTER at any time to execute and test your program.", 3); Widget *text3 = wText("If you placed the Micropython executable into a specific location, indicate his path via the 'Options' dialog box.", 3); wText_SetUnEditable(navigation); wText_SetUnEditable(keys); wText_SetUnEditable(text1); wText_SetUnEditable(text2); wText_SetUnEditable(text3); wTab_AddTab(tabs, "Navigation", body1); wTab_AddTab(tabs, "Keys", keys); wTab_AddTab(tabs, "Python", body3); wAddWidget(mainWidget, tabs); wAddWidget(body1, subody1); wAddWidget(subody1, im_tbtton); wAddWidget(subody1, wExLabel("<--- This is the awesome T-BUTTON.", ALIGN_LEFT, nSDL_LoadFont(NSDL_FONT_VGA, 204,15,225))); wAddWidget(body1, navigation); wAddWidget(body3, text1); wAddWidget(body3, text2); wAddWidget(body3, text3); wSetHeight(subody1, 24); wSetWidth(mainWidget, 300); wSetHeight(mainWidget, 220); wExecConstruct(mainWidget);//*/ wCloseTheme(); SDL_Quit(); return 1; }
void * thread_routine(void *arg) { struct mypara *recv_para = (struct mypara *)arg;; //recv para data AVFormatContext *pFormatCtx; int i, videoindex; AVCodecContext *pCodecCtx; AVCodec *pCodec; AVFrame *pFrame, *pFrameYUV; unsigned char *out_buffer; AVPacket *packet; int y_size; int ret, got_picture; struct SwsContext *img_convert_ctx; //char filepath[]="bigbuckbunny_480x272.h265"; char filepath[] = "rtsp://192.168.131.4/0"; //SDL--------------------------- int screen_w = 0, screen_h = 0; SDL_Window *screen; SDL_Renderer* sdlRenderer; SDL_Texture* sdlTexture; SDL_Rect sdlRect, sdlRect_tmp; FILE *fp_yuv; //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; } //pthread_mutex_lock(&mutex); if (avcodec_open2(pCodecCtx, pCodec, NULL) < 0){ printf("Could not open codec.\n"); return -1; } //pthread_mutex_unlock(&mutex); pFrame = av_frame_alloc(); pFrameYUV = av_frame_alloc(); out_buffer = (unsigned char *)av_malloc(av_image_get_buffer_size(AV_PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height, 1)); av_image_fill_arrays(pFrameYUV->data, pFrameYUV->linesize, out_buffer, AV_PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height, 1); packet = (AVPacket *)av_malloc(sizeof(AVPacket)); //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, AV_PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL); #if OUTPUT_YUV420P fp_yuv = fopen("output.yuv", "wb+"); #endif //if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) { // printf( "Could not initialize SDL - %s\n", SDL_GetError()); // return -1; //} screen_w = pCodecCtx->width; screen_h = pCodecCtx->height; //SDL 2.0 Support for multiple windows //screen = SDL_CreateWindow("Simplest ffmpeg player's Window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, // screen_w*2, screen_h, // SDL_WINDOW_OPENGL); screen = (*recv_para).screen; //get the screen if (!screen) { printf("SDL: could not create window - exiting:%s\n", SDL_GetError()); return -1; } //sdlRenderer = SDL_CreateRenderer(screen, -1, 0); sdlRenderer = (*recv_para).sdlRenderer;//get the sdlRenderer //IYUV: Y + U + V (3 planes) //YV12: Y + V + U (3 planes) pthread_mutex_lock(&mutex); sdlTexture = SDL_CreateTexture(sdlRenderer, SDL_PIXELFORMAT_IYUV, SDL_TEXTUREACCESS_STREAMING, pCodecCtx->width, pCodecCtx->height); pthread_mutex_unlock(&mutex); //temp sdlRect for render copy sdlRect_tmp.x = 0; sdlRect_tmp.y = 0; sdlRect_tmp.w = screen_w; sdlRect_tmp.h = screen_h; //four rect in one line // total 4*4 = 16 rect sdlRect.x = 0 + screen_w / 2 * ((*recv_para).id % 4); sdlRect.y = 0 + screen_h / 2 * ((*recv_para).id / 4); sdlRect.w = screen_w / 2; sdlRect.h = screen_h / 2; //SDL End---------------------- while (thread_exit && 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){ //printf("id:%d\n",(*recv_para).id); //打印线程id //printf("x_pos:%d y_pos:%d\n",sdlRect.x,sdlRect.y); //print rect position sws_scale(img_convert_ctx, (const unsigned char* 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, fp_yuv); //Y fwrite(pFrameYUV->data[1], 1, y_size / 4, fp_yuv); //U fwrite(pFrameYUV->data[2], 1, y_size / 4, fp_yuv); //V #endif //SDL--------------------------- #if 0 SDL_UpdateTexture(sdlTexture, NULL, pFrameYUV->data[0], pFrameYUV->linesize[0]); #else pthread_mutex_lock(&mutex); //mutex or SEGFAULT SDL_UpdateYUVTexture(sdlTexture, &sdlRect_tmp,//sdl tmp pFrameYUV->data[0], pFrameYUV->linesize[0], pFrameYUV->data[1], pFrameYUV->linesize[1], pFrameYUV->data[2], pFrameYUV->linesize[2]); #endif //SDL_RenderClear( sdlRenderer ); SDL_RenderCopy(sdlRenderer, sdlTexture, NULL, &sdlRect); //SDL_RenderCopy( sdlRenderer, sdlTexture, NULL, &sdlRect1); SDL_RenderPresent(sdlRenderer); pthread_mutex_unlock(&mutex); //SDL End----------------------- //Delay 40ms //SDL_Delay(40); } } av_free_packet(packet); } //flush decoder //FIX: Flush Frames remained in Codec while (1) { ret = avcodec_decode_video2(pCodecCtx, pFrame, &got_picture, packet); if (ret < 0) break; if (!got_picture) break; sws_scale(img_convert_ctx, (const unsigned char* const*)pFrame->data, pFrame->linesize, 0, pCodecCtx->height, pFrameYUV->data, pFrameYUV->linesize); #if OUTPUT_YUV420P int y_size = pCodecCtx->width*pCodecCtx->height; fwrite(pFrameYUV->data[0], 1, y_size, fp_yuv); //Y fwrite(pFrameYUV->data[1], 1, y_size / 4, fp_yuv); //U fwrite(pFrameYUV->data[2], 1, y_size / 4, fp_yuv); //V #endif //SDL--------------------------- SDL_UpdateTexture(sdlTexture, &sdlRect, pFrameYUV->data[0], pFrameYUV->linesize[0]); SDL_RenderClear(sdlRenderer); SDL_RenderCopy(sdlRenderer, sdlTexture, NULL, &sdlRect); SDL_RenderPresent(sdlRenderer); //SDL End----------------------- //Delay 40ms //SDL_Delay(40); } sws_freeContext(img_convert_ctx); #if OUTPUT_YUV420P fclose(fp_yuv); #endif SDL_RenderClear(sdlRenderer); SDL_Quit(); av_frame_free(&pFrameYUV); av_frame_free(&pFrame); avcodec_close(pCodecCtx); avformat_close_input(&pFormatCtx); }
// cleans up anything the program was using void cleanUp(ShaderProgram *program) { glDisableVertexAttribArray(program->positionAttribute); glDisableVertexAttribArray(program->texCoordAttribute); SDL_Quit(); }
int main(int argc, char **argv) { mtc_init("study", 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 World!", 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); m_render2 = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (!m_render || !m_render2) { mtc_err("SDL_CreateRenderer Error: %s", SDL_GetError()); return 1; } SDL_Texture *texbg = create_texture("bg.png"); SDL_Texture *texsp = create_texture("sprite.png"); int iw = 100, ih = 100; SDL_Rect clips[4]; 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; } SDL_Event e; bool quit = false; int curclip = 0, count = 0; while (!quit) { while (SDL_PollEvent(&e)) { if (e.type == SDL_QUIT) quit = true; if (e.type == SDL_KEYDOWN) { switch (e.key.keysym.sym) { case SDLK_ESCAPE: quit = true; break; case SDLK_UP: curclip = 0; break; case SDLK_DOWN: curclip = 1; break; case SDLK_LEFT: curclip = 2; break; case SDLK_RIGHT: curclip = 3; break; } } } SDL_Color color = {200, 200, 200}; char msg[1024]; snprintf(msg, sizeof(msg), "hello, bigml, ESC to quit %d", count++); SDL_Texture *texfont = create_texture_str(msg, color, 48); SDL_RenderClear(m_render); SDL_RenderClear(m_render2); rend_texture(0, 0, texbg); rend2_texture(20, 20, texfont); rend_texture_clip(WIN_WIDTH/3, WIN_HEIGHT/3, texsp, &clips[curclip]); SDL_RenderPresent(m_render); SDL_RenderPresent(m_render2); SDL_DestroyTexture(texfont); } //Clean up our objects and quit SDL_DestroyTexture(texbg); SDL_DestroyTexture(texsp); SDL_DestroyRenderer(m_render); SDL_DestroyRenderer(m_render2); SDL_DestroyWindow(win); SDL_Quit(); return 0; }
int AXWindow::run(){ if(setup){ setup(); } if(activeScene){ activeScene->start(); } SDL_Event event; bool inFocus = true; while(go == 1){ AXWindow::frameCount++; AXWindow::deltaTime = SDL_GetPerformanceCounter() - AXWindow::previousDeltaTime; AXWindow::previousDeltaTime = SDL_GetPerformanceCounter(); while(SDL_PollEvent(&event) != 0 ){ //User requests quit if(event.type == SDL_QUIT){ go = 0; break; }else if( event.type == SDL_KEYDOWN){ const std::string& temp = AXInput::setKeyDown(event.key.keysym.scancode); if(activeScene){ activeScene->inputChange(temp, 1); } }else if(event.type == SDL_KEYUP){ const std::string& temp = AXInput::setKeyUp(event.key.keysym.scancode); if(activeScene){ activeScene->inputChange(temp, 0); } }else if(event.type == SDL_MOUSEMOTION){ AXInput::mouseX = event.motion.x; AXInput::mouseY = event.motion.y; }else if(event.type == SDL_MOUSEBUTTONDOWN){ const std::string& temp = AXInput::mousePressed(event.button.button); if(activeScene){ activeScene->inputChange(temp, 1); } }else if(event.type == SDL_MOUSEBUTTONUP){ const std::string& temp = AXInput::mouseReleased(event.button.button); if(activeScene){ activeScene->inputChange(temp, 0); } }else if(event.type == SDL_CONTROLLERBUTTONDOWN){ const std::string& temp = AXInput::setKeyDown((SDL_GameControllerButton)event.cbutton.button+(AX_INPUT_CONTROLLER_OFFSET*(event.cdevice.which+1))); if(activeScene){ activeScene->inputChange(temp, 1); } }else if(event.type == SDL_CONTROLLERBUTTONUP){ const std::string& temp = AXInput::setKeyUp((SDL_GameControllerButton)event.cbutton.button+(AX_INPUT_CONTROLLER_OFFSET*(event.cdevice.which+1))); if(activeScene){ activeScene->inputChange(temp, 0); } }else if(event.type == SDL_CONTROLLERDEVICEADDED){ AXInput::controllers[event.cdevice.which] = SDL_GameControllerOpen(event.cdevice.which); }else if(event.type == SDL_CONTROLLERDEVICEREMOVED){ SDL_GameControllerClose(AXInput::controllers[event.cdevice.which]); AXInput::controllers[event.cdevice.which] = 0; }else if(event.type == SDL_CONTROLLERAXISMOTION){ AXInput::setAxisValue(AX_INPUT_CONTROLLER_AXIS_OFFSET+event.caxis.axis+AX_INPUT_CONTROLLER_OFFSET*(event.caxis.which+1), event.caxis.value); }else if(event.type == SDL_WINDOWEVENT){ if(event.window.event == SDL_WINDOWEVENT_FOCUS_GAINED){ inFocus = true; }else if(event.window.event == SDL_WINDOWEVENT_FOCUS_LOST){ inFocus = false; } } } if(inFocus){ if(update){ update(); } if(activeScene) { activeScene->update(); } } //Fill the surface wshite SDL_SetRenderDrawColor(AXWindow::renderer, backgroundColour.getR(), backgroundColour.getG(), backgroundColour.getB(), backgroundColour.getA()); SDL_RenderClear(AXWindow::renderer); if(inFocus){ SDL_SetRenderDrawColor(AXWindow::renderer, renderColour.getR(), renderColour.getG(), renderColour.getB(), renderColour.getA()); if(draw){ draw(); } if(activeScene) { activeScene->draw(); } } SDL_RenderPresent(AXWindow::renderer); } SDL_DestroyWindow(window); SDL_DestroyRenderer(renderer); //quit the SDLMix if(audioStatus){ while(Mix_Init(0)){ Mix_Quit(); } Mix_CloseAudio(); } //Quit SDL subsystems SDL_Quit(); return 0; }
int main(int argc, char ** argv) { SDL_Init(SDL_INIT_EVERYTHING); SDL_Quit(); return 0; };
void close() { SDL_Quit(); }
int main(int argc, char** argv) { Input in; Context C; navire nav_j[NB_BOATS]; navire nav_c[NB_BOATS]; int limit[4] = {43, 340, 43, 348}; int i, j; int** grille_c= NULL; int** grille_j = NULL; int done = 0; int gagne = 0; grille_c= malloc(T_GRILLE*sizeof(int*)); grille_j = malloc(T_GRILLE*sizeof(int*)); if(grille_c== NULL || grille_j == NULL) exit(EXIT_FAILURE); for(i = 0; i < T_GRILLE; i++) { grille_c[i] = calloc(T_GRILLE, sizeof(int)); grille_j[i] = calloc(T_GRILLE, sizeof(int)); if(grille_c[i] == NULL || grille_j == NULL) exit(EXIT_FAILURE); } (void) argc; (void) argv; /*Initialisation SDL, SDL_ttf*/ if(initSDL(&C) == -1) return EXIT_FAILURE; srand(time(NULL)); do { /*Initialisation contexte*/ if(initC(&C) == -1) return EXIT_FAILURE; for(i = 0; i < T_GRILLE; i++) { for(j = 0; j < T_GRILLE; j++) { grille_c[j][i] = 0; grille_j[j][i] = 0; } } for(i = 0; i < NB_BOATS; i++) { nav_j[i].c = 0; nav_c[i].c = 0; } done = 0; gagne = 0; memset(&in, 0, sizeof(in)); memset(nav_j, 0, sizeof(nav_j)); memset(nav_c, 0, sizeof(nav_c)); /*Placement des nav_j...*/ chtxt(&C, PLACE_NAV_J); placing_boats(&in, &C, nav_j); while(in.key[SDLK_RETURN]) { UpdateEvents(&in); SDL_Delay(20); } computer_placing_boats(nav_c); chtxt(&C, PLACE_NAV_C); /*On place maintenant le viseur*/ C.cViseur.x = 43; C.cViseur.y = 43; /*Boucle de jeu*/ while (!gagne && !in.key[SDLK_q] && !in.key[SDLK_r]) { done = 0; while(!done) { UpdateEvents(&in); if(in.quit || in.key[SDLK_q] || in.key[SDLK_r]) break; if(Evolution(&in, &C.cViseur.x, &C.cViseur.y, limit, NULL, 0)) { if(case_test(C.cViseur.x, C.cViseur.y, grille_c)) { grille_c[((C.cViseur.y-43)/CELL_W)][((C.cViseur.x-43)/CELL_W)] = 1; if(!joueurAttaque(&C, nav_c)) { done = 1; chtxt(&C, "..."); } else chtxt(&C, TOUCHE_NAV_J); coule(&C, nav_j, nav_c); if(victoire(nav_j, nav_c) == 2) { gagne = 1; chtxt(&C, VICTOIRE_J); UpdateScreen(&C, nav_j); while(1) { UpdateEvents(&in); if(in.key[SDLK_r] || in.key[SDLK_q]) break; SDL_Delay(30); } } } } UpdateScreen(&C, nav_j); if(!in.key[SDLK_LEFT] && !in.key[SDLK_RIGHT] && !in.key[SDLK_DOWN] && !in.key[SDLK_UP] && !in.key[SDLK_RETURN]) SDL_Delay(20); else SDL_Delay(200); } UpdateEvents(&in); if(in.quit || in.key[SDLK_q] || in.key[SDLK_r]) break; UpdateScreen(&C, nav_j); SDL_Delay(200); while(ordiAttaque(&C, nav_j, grille_j)) { chtxt(&C, TOUCHE_NAV_C); coule(&C, nav_j, nav_c); UpdateScreen(&C, nav_j); SDL_Delay(400); } if(victoire(nav_j, nav_c) == 1) { gagne = 1; chtxt(&C, VICTOIRE_C); UpdateScreen(&C, nav_j); while(1) { UpdateEvents(&in); if(in.key[SDLK_r] || in.key[SDLK_q]) break; SDL_Delay(30); } } } if(in.quit || in.key[SDLK_q]) break; } while(1); /*On libère tout*/ C.nbimg = sizeof(C.images_v)/sizeof(SDL_Surface); for(i = 0; i < C.nbimg; i++) SDL_FreeSurface(C.images_v[i]); C.nbimg = sizeof(C.images_h)/sizeof(SDL_Surface); for(i = 0; i < C.nbimg; i++) SDL_FreeSurface(C.images_h[i]); SDL_FreeSurface(C.viseur); SDL_FreeSurface(C.touche); SDL_FreeSurface(C.c_rate); SDL_FreeSurface(C.coule); SDL_FreeSurface(C.infobar); SDL_FreeSurface(C.texte); C.nbimg = sizeof(C.misc)/sizeof(SDL_Surface); for(i = 0; i < C.nbimg; i++) SDL_FreeSurface(C.misc[i]); free(C.cNavires); for(i = 0; i < T_GRILLE; i++) { free(grille_j[i]); free(grille_c[i]); } free(grille_c); free(grille_j); TTF_CloseFont(C.police); TTF_Quit(); SDL_Quit(); return EXIT_SUCCESS; }
void Gource::logic(float t, float dt) { if(draw_loading) return; if(message_timer>0.0f) message_timer -= dt; if(splash>0.0f) splash -= dt; //init log file if(commitlog == 0) { try { commitlog = determineFormat(logfile); } catch(SeekLogException& exception) { throw SDLAppException("unable to read log file"); } if(commitlog == 0) { //if not in a git dir and no log file, show help if(logfile.size() == 0 || logfile == ".") { SDL_Quit(); throw SDLAppException("", true); } else if(SDLAppDirExists(logfile)) { throw SDLAppException("directory not supported"); } else { throw SDLAppException("unsupported log format (you may need to regenerate your log file)"); } } if(gGourceSettings.start_position>0.0) { seekTo(gGourceSettings.start_position); } } slider.logic(dt); //apply rotation if(rotate_angle != 0.0f) { float s = sinf(rotate_angle); float c = cosf(rotate_angle); root->rotate(s, c); for(std::map<std::string,RUser*>::iterator it = users.begin(); it!=users.end(); it++) { RUser* user = it->second; vec2f userpos = user->getPos(); user->setPos(userpos.rotate(s, c)); } rotate_angle = 0.0f; } //still want to update camera while paused if(paused) { updateBounds(); updateQuadTree(); updateCamera(dt); return; } // get more entries if(commitqueue.size() == 0) { readLog(); } //loop in attempt to find commits if(commitqueue.size()==0 && commitlog->isSeekable() && gGourceSettings.loop) { first_read=true; seekTo(0.0); readLog(); } if(currtime==0 && commitqueue.size()) { currtime = lasttime = commitqueue[0].timestamp; subseconds = 0.0; } //set current time float time_inc = (dt * 86400.0 * gGourceSettings.days_per_second); int seconds = (int) time_inc; subseconds += time_inc - ((float) seconds); if(subseconds >= 1.0) { currtime += (int) subseconds; subseconds -= (int) subseconds; } currtime += seconds; // delete files for(std::vector<RFile*>::iterator it = gGourceRemovedFiles.begin(); it != gGourceRemovedFiles.end(); it++) { deleteFile(*it); } gGourceRemovedFiles.clear(); //add commits up until the current time while(commitqueue.size() > 0) { RCommit commit = commitqueue[0]; if(gGourceSettings.auto_skip_seconds>=0.0 && idle_time >= gGourceSettings.auto_skip_seconds) { currtime = lasttime = commit.timestamp; idle_time = 0.0; } if(commit.timestamp > currtime) break; processCommit(commit, t); currtime = lasttime = commit.timestamp; subseconds = 0.0; commitqueue.pop_front(); } //reset loop counters gGourceUserInnerLoops = 0; gGourceDirNodeInnerLoops = 0; gGourceFileInnerLoops = 0; interactUsers(); updateUsers(t, dt); updateQuadTree(); updateBounds(); updateDirs(dt); updateCamera(dt); updateTime(commitqueue.size() > 0 ? currtime : lasttime); }
~SDL() noexcept { SDL_Quit(); }
/* ================================================================================ Game::Shutdown Performs cleanup after the game ends. Deletes any active entities, releases resources, kills the window, and shuts down the supporting libs. ================================================================================ */ void Game::Shutdown() { //Frees the sound chunks and sets it to NULL Mix_FreeChunk(mCoinSound); mCoinSound = NULL; Mix_FreeChunk(mJumpSound); mJumpSound = NULL; Mix_FreeChunk(mStompSound); mStompSound = NULL; Mix_FreeChunk(mDieSound); mDieSound = NULL; Mix_FreeChunk(mStompSoundNoKill); mStompSoundNoKill = NULL; Mix_FreeChunk(mBlockSound); mBlockSound = NULL; //Free the music Mix_FreeMusic(mMusic); mMusic = NULL; Mix_FreeMusic(mGoodGameOverMusic); mGoodGameOverMusic = NULL; Mix_FreeMusic(mBadGameOverMusic); mBadGameOverMusic = NULL; //We also need to quit the mixer Mix_Quit(); delete mRobot; mRobot = NULL; // delete grid delete mGrid; mGrid = NULL; // delete all explosions std::list<Explosion*>::iterator it = mExplosions.begin(); for ( ; it != mExplosions.end(); ++it) { delete *it; } mExplosions.clear(); // delete all meteors std::list<Meteor*>::iterator metIt = mMeteors.begin(); for ( ; metIt != mMeteors.end(); ++metIt) { delete *metIt; } mMeteors.clear(); // delete all crawlers and clear the list std::list<Crawler*>::iterator crawlerIter = mCrawlers.begin(); for ( ; crawlerIter != mCrawlers.end(); ++crawlerIter) { Crawler* crawler = *crawlerIter; delete crawler; } mCrawlers.clear(); // delete all coins and clear the list std::list<Coin*>::iterator coinIter = mCoins.begin(); for ( ; coinIter != mCoins.end(); ++coinIter) { Coin* coin = *coinIter; delete coin; } mCoins.clear(); // delete all mushrooms std::list<Layer*>::iterator mushIter = mMushrooms.begin(); for ( ; mushIter != mMushrooms.end(); ++mushIter) { delete *mushIter; } mMeteors.clear(); // delete the texture manager (and all the textures it loaded for us) delete mTexMgr; mTexMgr = NULL; delete mBackground; mBackground = NULL; delete mForeground; mForeground = NULL; // Shutdown the TTF library TTF_Quit(); // unload the image libraries IMG_Quit(); // shut down SDL (deletes the window and renderer) SDL_Quit(); mWindow = NULL; mRenderer = NULL; mKeyState = NULL; }
void Game::cleanUp() { if(SDL_WasInit(SDL_INIT_VIDEO)) SDL_Quit(); }
/* Shut down the SDL with all stubs */ static void sdl_internal_quit (void) { /* Shut down SDL */ SDL_Quit(); }
int main(int argc, char *argv[]) { #if PPSSPP_PLATFORM(RPI) bcm_host_init(); #endif putenv((char*)"SDL_VIDEO_CENTERED=1"); SDL_SetHint(SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS, "0"); std::string app_name; std::string app_name_nice; std::string version; bool landscape; NativeGetAppInfo(&app_name, &app_name_nice, &landscape, &version); bool joystick_enabled = true; if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER | SDL_INIT_AUDIO) < 0) { joystick_enabled = false; if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) { fprintf(stderr, "Unable to initialize SDL: %s\n", SDL_GetError()); return 1; } } #ifdef __APPLE__ // Make sure to request a somewhat modern GL context at least - the // latest supported by MacOSX (really, really sad...) // Requires SDL 2.0 // We really should upgrade to SDL 2.0 soon. //SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); //SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); //SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); #endif #ifdef USING_EGL if (EGL_Open()) return 1; #endif // Get the video info before doing anything else, so we don't get skewed resolution results. // TODO: support multiple displays correctly SDL_DisplayMode displayMode; int should_be_zero = SDL_GetCurrentDisplayMode(0, &displayMode); if (should_be_zero != 0) { fprintf(stderr, "Could not get display mode: %s\n", SDL_GetError()); return 1; } g_DesktopWidth = displayMode.w; g_DesktopHeight = displayMode.h; SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetSwapInterval(1); Uint32 mode; #ifdef USING_GLES2 mode = SDL_WINDOW_OPENGL | SDL_WINDOW_FULLSCREEN; #else mode = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE; #endif int set_xres = -1; int set_yres = -1; bool portrait = false; bool set_ipad = false; float set_dpi = 1.0f; float set_scale = 1.0f; // Produce a new set of arguments with the ones we skip. int remain_argc = 1; const char *remain_argv[256] = { argv[0] }; for (int i = 1; i < argc; i++) { if (!strcmp(argv[i],"--fullscreen")) mode |= SDL_WINDOW_FULLSCREEN_DESKTOP; else if (set_xres == -2) set_xres = parseInt(argv[i]); else if (set_yres == -2) set_yres = parseInt(argv[i]); else if (set_dpi == -2) set_dpi = parseFloat(argv[i]); else if (set_scale == -2) set_scale = parseFloat(argv[i]); else if (!strcmp(argv[i],"--xres")) set_xres = -2; else if (!strcmp(argv[i],"--yres")) set_yres = -2; else if (!strcmp(argv[i],"--dpi")) set_dpi = -2; else if (!strcmp(argv[i],"--scale")) set_scale = -2; else if (!strcmp(argv[i],"--ipad")) set_ipad = true; else if (!strcmp(argv[i],"--portrait")) portrait = true; else { remain_argv[remain_argc++] = argv[i]; } } // Is resolution is too low to run windowed if (g_DesktopWidth < 480 * 2 && g_DesktopHeight < 272 * 2) { mode |= SDL_WINDOW_FULLSCREEN_DESKTOP; } if (mode & SDL_WINDOW_FULLSCREEN_DESKTOP) { pixel_xres = g_DesktopWidth; pixel_yres = g_DesktopHeight; g_Config.bFullScreen = true; } else { // set a sensible default resolution (2x) pixel_xres = 480 * 2 * set_scale; pixel_yres = 272 * 2 * set_scale; if (portrait) { std::swap(pixel_xres, pixel_yres); } g_Config.bFullScreen = false; } set_dpi = 1.0f / set_dpi; if (set_ipad) { pixel_xres = 1024; pixel_yres = 768; } if (!landscape) { std::swap(pixel_xres, pixel_yres); } if (set_xres > 0) { pixel_xres = set_xres; } if (set_yres > 0) { pixel_yres = set_yres; } float dpi_scale = 1.0f; if (set_dpi > 0) { dpi_scale = set_dpi; } dp_xres = (float)pixel_xres * dpi_scale; dp_yres = (float)pixel_yres * dpi_scale; #ifdef _MSC_VER // VFSRegister("temp/", new DirectoryAssetReader("E:\\Temp\\")); TCHAR path[MAX_PATH]; SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, path); PathAppend(path, (app_name + "\\").c_str()); #else // Mac / Linux char path[2048]; const char *the_path = getenv("HOME"); if (!the_path) { struct passwd* pwd = getpwuid(getuid()); if (pwd) the_path = pwd->pw_dir; } strcpy(path, the_path); if (path[strlen(path)-1] != '/') strcat(path, "/"); #endif #ifdef _WIN32 NativeInit(remain_argc, (const char **)remain_argv, path, "D:\\", nullptr); #else NativeInit(remain_argc, (const char **)remain_argv, path, "/tmp", nullptr); #endif // Use the setting from the config when initing the window. if (g_Config.bFullScreen) mode |= SDL_WINDOW_FULLSCREEN_DESKTOP; g_Screen = SDL_CreateWindow(app_name_nice.c_str(), SDL_WINDOWPOS_UNDEFINED_DISPLAY(getDisplayNumber()),\ SDL_WINDOWPOS_UNDEFINED, pixel_xres, pixel_yres, mode); if (g_Screen == NULL) { NativeShutdown(); fprintf(stderr, "SDL_CreateWindow failed: %s\n", SDL_GetError()); SDL_Quit(); return 2; } SDL_GLContext glContext = SDL_GL_CreateContext(g_Screen); if (glContext == NULL) { NativeShutdown(); fprintf(stderr, "SDL_GL_CreateContext failed: %s\n", SDL_GetError()); SDL_Quit(); return 2; } #ifdef USING_EGL EGL_Init(); #endif SDL_SetWindowTitle(g_Screen, (app_name_nice + " " + PPSSPP_GIT_VERSION).c_str()); #ifdef MOBILE_DEVICE SDL_ShowCursor(SDL_DISABLE); #endif #ifndef USING_GLES2 // Some core profile drivers elide certain extensions from GL_EXTENSIONS/etc. // glewExperimental allows us to force GLEW to search for the pointers anyway. if (gl_extensions.IsCoreContext) glewExperimental = true; if (GLEW_OK != glewInit()) { printf("Failed to initialize glew!\n"); return 1; } // Unfortunately, glew will generate an invalid enum error, ignore. if (gl_extensions.IsCoreContext) glGetError(); if (GLEW_VERSION_2_0) { printf("OpenGL 2.0 or higher.\n"); } else { printf("Sorry, this program requires OpenGL 2.0.\n"); return 1; } #endif pixel_in_dps_x = (float)pixel_xres / dp_xres; pixel_in_dps_y = (float)pixel_yres / dp_yres; g_dpi_scale_x = dp_xres / (float)pixel_xres; g_dpi_scale_y = dp_yres / (float)pixel_yres; g_dpi_scale_real_x = g_dpi_scale_x; g_dpi_scale_real_y = g_dpi_scale_y; printf("Pixels: %i x %i\n", pixel_xres, pixel_yres); printf("Virtual pixels: %i x %i\n", dp_xres, dp_yres); GraphicsContext *graphicsContext = new GLDummyGraphicsContext(); NativeInitGraphics(graphicsContext); NativeResized(); SDL_AudioSpec fmt, ret_fmt; memset(&fmt, 0, sizeof(fmt)); fmt.freq = 44100; fmt.format = AUDIO_S16; fmt.channels = 2; fmt.samples = 2048; fmt.callback = &mixaudio; fmt.userdata = (void *)0; if (SDL_OpenAudio(&fmt, &ret_fmt) < 0) { ELOG("Failed to open audio: %s", SDL_GetError()); } else { if (ret_fmt.samples != fmt.samples) // Notify, but still use it ELOG("Output audio samples: %d (requested: %d)", ret_fmt.samples, fmt.samples); if (ret_fmt.freq != fmt.freq || ret_fmt.format != fmt.format || ret_fmt.channels != fmt.channels) { ELOG("Sound buffer format does not match requested format."); ELOG("Output audio freq: %d (requested: %d)", ret_fmt.freq, fmt.freq); ELOG("Output audio format: %d (requested: %d)", ret_fmt.format, fmt.format); ELOG("Output audio channels: %d (requested: %d)", ret_fmt.channels, fmt.channels); ELOG("Provided output format does not match requirement, turning audio off"); SDL_CloseAudio(); } } // Audio must be unpaused _after_ NativeInit() SDL_PauseAudio(0); #ifndef _WIN32 if (joystick_enabled) { joystick = new SDLJoystick(); } else { joystick = nullptr; } #endif EnableFZ(); int framecount = 0; float t = 0; float lastT = 0; bool mouseDown = false; while (true) { SDL_Event event; while (SDL_PollEvent(&event)) { float mx = event.motion.x * g_dpi_scale_x; float my = event.motion.y * g_dpi_scale_y; switch (event.type) { case SDL_QUIT: g_QuitRequested = 1; break; #if !defined(MOBILE_DEVICE) case SDL_WINDOWEVENT: switch (event.window.event) { case SDL_WINDOWEVENT_RESIZED: { Uint32 window_flags = SDL_GetWindowFlags(g_Screen); bool fullscreen = (window_flags & SDL_WINDOW_FULLSCREEN); pixel_xres = event.window.data1; pixel_yres = event.window.data2; dp_xres = (float)pixel_xres * dpi_scale; dp_yres = (float)pixel_yres * dpi_scale; NativeResized(); // Set variable here in case fullscreen was toggled by hotkey g_Config.bFullScreen = fullscreen; // Hide/Show cursor correctly toggling fullscreen if (lastUIState == UISTATE_INGAME && fullscreen && !g_Config.bShowTouchControls) { SDL_ShowCursor(SDL_DISABLE); } else if (lastUIState != UISTATE_INGAME || !fullscreen) { SDL_ShowCursor(SDL_ENABLE); } break; } default: break; } break; #endif case SDL_KEYDOWN: { if (event.key.repeat > 0) { break;} int k = event.key.keysym.sym; KeyInput key; key.flags = KEY_DOWN; auto mapped = KeyMapRawSDLtoNative.find(k); if (mapped == KeyMapRawSDLtoNative.end() || mapped->second == NKCODE_UNKNOWN) { break; } key.keyCode = mapped->second; key.deviceId = DEVICE_ID_KEYBOARD; NativeKey(key); break; } case SDL_KEYUP: { if (event.key.repeat > 0) { break;} int k = event.key.keysym.sym; KeyInput key; key.flags = KEY_UP; auto mapped = KeyMapRawSDLtoNative.find(k); if (mapped == KeyMapRawSDLtoNative.end() || mapped->second == NKCODE_UNKNOWN) { break; } key.keyCode = mapped->second; key.deviceId = DEVICE_ID_KEYBOARD; NativeKey(key); break; } case SDL_TEXTINPUT: { int pos = 0; int c = u8_nextchar(event.text.text, &pos); KeyInput key; key.flags = KEY_CHAR; key.keyCode = c; key.deviceId = DEVICE_ID_KEYBOARD; NativeKey(key); break; } case SDL_MOUSEBUTTONDOWN: switch (event.button.button) { case SDL_BUTTON_LEFT: { mouseDown = true; TouchInput input; input.x = mx; input.y = my; input.flags = TOUCH_DOWN | TOUCH_MOUSE; input.id = 0; NativeTouch(input); KeyInput key(DEVICE_ID_MOUSE, NKCODE_EXT_MOUSEBUTTON_1, KEY_DOWN); NativeKey(key); } break; case SDL_BUTTON_RIGHT: { KeyInput key(DEVICE_ID_MOUSE, NKCODE_EXT_MOUSEBUTTON_2, KEY_DOWN); NativeKey(key); } break; } break; case SDL_MOUSEWHEEL: { KeyInput key; key.deviceId = DEVICE_ID_MOUSE; if (event.wheel.y > 0) { key.keyCode = NKCODE_EXT_MOUSEWHEEL_UP; } else { key.keyCode = NKCODE_EXT_MOUSEWHEEL_DOWN; } key.flags = KEY_DOWN; NativeKey(key); // SDL2 doesn't consider the mousewheel a button anymore // so let's send the KEY_UP right away. // Maybe KEY_UP alone will suffice? key.flags = KEY_UP; NativeKey(key); } case SDL_MOUSEMOTION: if (mouseDown) { TouchInput input; input.x = mx; input.y = my; input.flags = TOUCH_MOVE | TOUCH_MOUSE; input.id = 0; NativeTouch(input); } break; case SDL_MOUSEBUTTONUP: switch (event.button.button) { case SDL_BUTTON_LEFT: { mouseDown = false; TouchInput input; input.x = mx; input.y = my; input.flags = TOUCH_UP | TOUCH_MOUSE; input.id = 0; NativeTouch(input); KeyInput key(DEVICE_ID_MOUSE, NKCODE_EXT_MOUSEBUTTON_1, KEY_UP); NativeKey(key); } break; case SDL_BUTTON_RIGHT: { KeyInput key(DEVICE_ID_MOUSE, NKCODE_EXT_MOUSEBUTTON_2, KEY_UP); NativeKey(key); } break; } break; default: #ifndef _WIN32 if (joystick) { joystick->ProcessInput(event); } #endif break; } } if (g_QuitRequested) break; const uint8_t *keys = SDL_GetKeyboardState(NULL); UpdateRunLoop(); if (g_QuitRequested) break; #if !defined(MOBILE_DEVICE) if (lastUIState != GetUIState()) { lastUIState = GetUIState(); if (lastUIState == UISTATE_INGAME && g_Config.bFullScreen && !g_Config.bShowTouchControls) SDL_ShowCursor(SDL_DISABLE); if (lastUIState != UISTATE_INGAME && g_Config.bFullScreen) SDL_ShowCursor(SDL_ENABLE); } #endif if (framecount % 60 == 0) { // glsl_refresh(); // auto-reloads modified GLSL shaders once per second. } #ifdef USING_EGL eglSwapBuffers(g_eglDisplay, g_eglSurface); #else if (!keys[SDLK_TAB] || t - lastT >= 1.0/60.0) { SDL_GL_SwapWindow(g_Screen); lastT = t; } #endif ToggleFullScreenIfFlagSet(); time_update(); t = time_now(); framecount++; } #ifndef _WIN32 delete joystick; #endif NativeShutdownGraphics(); graphicsContext->Shutdown(); NativeShutdown(); delete graphicsContext; // Faster exit, thanks to the OS. Remove this if you want to debug shutdown // The speed difference is only really noticable on Linux. On Windows you do notice it though #ifndef MOBILE_DEVICE exit(0); #endif SDL_PauseAudio(1); SDL_CloseAudio(); #ifdef USING_EGL EGL_Close(); #endif SDL_GL_DeleteContext(glContext); SDL_Quit(); #if PPSSPP_PLATFORM(RPI) bcm_host_deinit(); #endif exit(0); return 0; }
/* * call before quitting */ void SdlApp::tear_down() { running = false; SDL_Quit(); }
int main(int argc, char *argv[]) { SDL_Event event; VideoState *is; is = av_mallocz(sizeof(VideoState)); if(argc < 2) { fprintf(stderr, "Usage: test <file>\n"); exit(1); } // Register all formats and codecs av_register_all(); if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) { fprintf(stderr, "Could not initialize SDL - %s\n", SDL_GetError()); exit(1); } // Make a screen to put our video #ifndef __DARWIN__ screen = SDL_SetVideoMode(640, 480, 0, 0); #else screen = SDL_SetVideoMode(640, 480, 24, 0); #endif if(!screen) { fprintf(stderr, "SDL: could not set video mode - exiting\n"); exit(1); } av_strlcpy(is->filename, argv[1], 1024); is->pictq_mutex = SDL_CreateMutex(); is->pictq_cond = SDL_CreateCond(); schedule_refresh(is, 40); is->parse_tid = SDL_CreateThread(decode_thread, is); if(!is->parse_tid) { av_free(is); return -1; } for(;;) { SDL_WaitEvent(&event); switch(event.type) { case FF_QUIT_EVENT: case SDL_QUIT: is->quit = 1; /* * If the video has finished playing, then both the picture and * audio queues are waiting for more data. Make them stop * waiting and terminate normally. */ SDL_CondSignal(is->audioq.cond); SDL_CondSignal(is->videoq.cond); SDL_Quit(); return 0; break; case FF_ALLOC_EVENT: alloc_picture(event.user.data1); break; case FF_REFRESH_EVENT: video_refresh_timer(event.user.data1); break; default: break; } } return 0; }
int main(int argc, char *argv[]) { SDL_Init(SDL_INIT_VIDEO); displayWindow = SDL_CreateWindow("My Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 360, SDL_WINDOW_OPENGL); SDL_GLContext context = SDL_GL_CreateContext(displayWindow); SDL_GL_MakeCurrent(displayWindow, context); #ifdef _WINDOWS glewInit(); #endif glViewport(0, 0, 640, 360); ShaderProgram program(RESOURCE_FOLDER"vertex_textured.glsl", RESOURCE_FOLDER"fragment_textured.glsl"); Matrix projectionMatrix; Matrix modelMatrix; Matrix viewMatrix; projectionMatrix.setOrthoProjection(-3.55f, 3.55f, -2.0f, 2.0f, -1.0f, 1.0f); program.setModelMatrix(modelMatrix); program.setProjectionMatrix(projectionMatrix); program.setViewMatrix(viewMatrix); glUseProgram(program.programID); float stevenPos = 0.0; float stevenJump = 0.1; glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); SDL_Event event; bool done = false; while (!done) { while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT || event.type == SDL_WINDOWEVENT_CLOSE) { done = true; } } glClearColor(0.5f, 0.3f, 0.4f, 0.1f); glClear(GL_COLOR_BUFFER_BIT); //Finn the Human GLuint img1 = LoadTexture("finn.png"); float vertices[] = { -0.5f, -1.0f, 0.5f, 1.0f, -0.5f, 1.0f, 0.5f, 1.0f, -0.5f, -1.0f, 0.5f, -1.0f }; glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, vertices); glEnableVertexAttribArray(program.positionAttribute); float texCoords[] = { 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f }; glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoords); glEnableVertexAttribArray(program.texCoordAttribute); modelMatrix.identity(); program.setModelMatrix(modelMatrix); glBindTexture(GL_TEXTURE_2D, img1); glDrawArrays(GL_TRIANGLES, 0, 6); glDisableVertexAttribArray(program.positionAttribute); glDisableVertexAttribArray(program.texCoordAttribute); //Rick and Morty GLuint img2 = LoadTexture("RickandMorty.png"); float vertices2[] = { -3.5f, -2.0f, -0.5f, 0.5f, -3.5f, 0.5f, -0.5f, 0.5f, -3.5, -2.0f, -0.5f, -2.0f }; glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, vertices2); glEnableVertexAttribArray(program.positionAttribute); float texCoords2[] = { 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f }; glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoords2); glEnableVertexAttribArray(program.texCoordAttribute); modelMatrix.identity(); program.setModelMatrix(modelMatrix); glBindTexture(GL_TEXTURE_2D, img2); glDrawArrays(GL_TRIANGLES, 0, 6); glDisableVertexAttribArray(program.positionAttribute); glDisableVertexAttribArray(program.texCoordAttribute); //Steven GLuint img3 = LoadTexture("steven.png"); float vertices3[] = { 1.0f, -1.0f, 3.0f, 1.0f, 1.0f, 1.0f, 3.0f, 1.0f, 1.0f, -1.0f, 3.0, -1.0f }; glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, vertices3); glEnableVertexAttribArray(program.positionAttribute); float texCoords3[] = { 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f }; glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoords3); glEnableVertexAttribArray(program.texCoordAttribute); if (stevenPos >= 1.0) stevenJump = -0.1; else if (stevenPos <= -1.0) stevenJump = 0.1; stevenPos += stevenJump; modelMatrix.identity(); modelMatrix.Translate(0.0, stevenPos, 0.0); program.setModelMatrix(modelMatrix); glBindTexture(GL_TEXTURE_2D, img3); glDrawArrays(GL_TRIANGLES, 0, 6); glDisableVertexAttribArray(program.positionAttribute); glDisableVertexAttribArray(program.texCoordAttribute); SDL_GL_SwapWindow(displayWindow); } SDL_Quit(); return 0; }
bool Visualization::initialize() { m_initialized = true; m_mousePosition[0] = m_mousePosition[1] = 1; m_crowdAvailableDt = 0.f; m_stopRequested = false; m_rotating = false; if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { printf("Could not initialize SDL.\n"); m_initialized = false; } else { // Center window char env[] = "SDL_VIDEO_CENTERED=1"; #ifdef _MSC_VER _putenv(env); #else putenv(env); #endif // Init OpenGL SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8); //#ifndef WIN32 SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4); //#endif const SDL_VideoInfo* vi = SDL_GetVideoInfo(); SDL_Surface* screen = 0; if (m_fullscreen) { m_winWidth = vi->current_w; m_winHeight = vi->current_h; screen = SDL_SetVideoMode(m_winWidth, m_winHeight, 0, SDL_OPENGL|SDL_FULLSCREEN); } else { m_winWidth = vi->current_w - 20; m_winHeight = vi->current_h - 80; screen = SDL_SetVideoMode(m_winWidth, m_winHeight, 0, SDL_OPENGL); } if (!screen) { printf("Could not initialise SDL opengl.\n"); m_initialized = false; } else { glEnable(GL_MULTISAMPLE); SDL_WM_SetCaption("Detour Crowd Demo", 0); if (!imguiRenderGLInit("DroidSans.ttf")) { printf("Could not init GUI renderer.\n"); m_initialized = false; } else if (!initializeCamera()) { printf("Unable to initialize the camera.\n"); m_initialized = false; } else if (m_debugInfo == 0 || !m_debugInfo->initialize()) { printf("Unable to initialize the crowd debug info.\n"); m_initialized = false; } else { m_initialized = true; glEnable(GL_CULL_FACE); float fogCol[4] = { 0.32f, 0.31f, 0.30f, 1.0f }; glEnable(GL_FOG); glFogi(GL_FOG_MODE, GL_LINEAR); glFogf(GL_FOG_START, m_zFar*0.1f); glFogf(GL_FOG_END, m_zFar*1.25f); glFogfv(GL_FOG_COLOR, fogCol); glDepthFunc(GL_LEQUAL); m_lastTickCount = SDL_GetTicks(); // Extract OpenGL view properties glGetDoublev(GL_PROJECTION_MATRIX, m_projection); glGetDoublev(GL_MODELVIEW_MATRIX, m_modelView); glGetIntegerv(GL_VIEWPORT, m_viewport); } } } if (!m_initialized) { SDL_Quit(); } return m_initialized; }
int main(int, char**) { // Setup SDL if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER) != 0) { printf("Error: %s\n", SDL_GetError()); return -1; } // Setup window SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); SDL_DisplayMode current; SDL_GetCurrentDisplayMode(0, ¤t); SDL_Window* window = SDL_CreateWindow("ImGui SDL2+OpenGL example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, SDL_WINDOW_OPENGL|SDL_WINDOW_RESIZABLE); SDL_GLContext gl_context = SDL_GL_CreateContext(window); SDL_GL_SetSwapInterval(1); // Enable vsync // Setup Dear ImGui binding IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls ImGui_ImplSdlGL2_Init(window); // Setup style ImGui::StyleColorsDark(); //ImGui::StyleColorsClassic(); // Load Fonts // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. // - Read 'misc/fonts/README.txt' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //io.Fonts->AddFontDefault(); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f); //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); //IM_ASSERT(font != NULL); bool show_demo_window = true; bool show_another_window = false; ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); // Main loop bool done = false; while (!done) { // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. SDL_Event event; while (SDL_PollEvent(&event)) { ImGui_ImplSdlGL2_ProcessEvent(&event); if (event.type == SDL_QUIT) done = true; } ImGui_ImplSdlGL2_NewFrame(window); // 1. Show a simple window. // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets automatically appears in a window called "Debug". { static float f = 0.0f; static int counter = 0; ImGui::Text("Hello, world!"); // Display some text (you can use a format string too) ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our windows open/close state ImGui::Checkbox("Another Window", &show_another_window); if (ImGui::Button("Button")) // Buttons return true when clicked (NB: most widgets return true when edited/activated) counter++; ImGui::SameLine(); ImGui::Text("counter = %d", counter); ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); } // 2. Show another simple window. In most cases you will use an explicit Begin/End pair to name your windows. if (show_another_window) { ImGui::Begin("Another Window", &show_another_window); ImGui::Text("Hello from another window!"); if (ImGui::Button("Close Me")) show_another_window = false; ImGui::End(); } // 3. Show the ImGui demo window. Most of the sample code is in ImGui::ShowDemoWindow(). Read its code to learn more about Dear ImGui! if (show_demo_window) { ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiCond_FirstUseEver); // Normally user code doesn't need/want to call this because positions are saved in .ini file anyway. Here we just want to make the demo initial state a bit more friendly! ImGui::ShowDemoWindow(&show_demo_window); } // Rendering glViewport(0, 0, (int)ImGui::GetIO().DisplaySize.x, (int)ImGui::GetIO().DisplaySize.y); glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w); glClear(GL_COLOR_BUFFER_BIT); //glUseProgram(0); // You may want this if using this code in an OpenGL 3+ context where shaders may be bound ImGui::Render(); ImGui_ImplSdlGL2_RenderDrawData(ImGui::GetDrawData()); SDL_GL_SwapWindow(window); } // Cleanup ImGui_ImplSdlGL2_Shutdown(); ImGui::DestroyContext(); SDL_GL_DeleteContext(gl_context); SDL_DestroyWindow(window); SDL_Quit(); return 0; }
// Quit static mrb_value mrb_sdl_quit (mrb_state *mrb, mrb_value self) { SDL_Quit(); return mrb_nil_value(); }
int main(int argc, char **argv) { Uint8 *RawMooseData; SDL_RWops *handle; SDL_Surface *screen; SDL_Surface *MooseFrame[MOOSEFRAMES_COUNT]; SDL_Overlay *overlay; SDL_Rect overlayrect; SDL_Event event; Uint32 lastftick; int paused = 0; int resized = 0; int i; int fps = 12; int fpsdelay; int overlay_format = SDL_YUY2_OVERLAY; int scale = 5; if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE) < 0) { fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError()); return 3; } while (argc > 1) { if (strcmp(argv[1], "-fps") == 0) { if (argv[2]) { fps = atoi(argv[2]); if (fps == 0) { fprintf(stderr, "The -fps option requires an argument [from 1 to 1000], default is 12.\n"); quit(10); } if ((fps < 0) || (fps > 1000)) { fprintf(stderr, "The -fps option must be in range from 1 to 1000, default is 12.\n"); quit(10); } argv += 2; argc -= 2; } else { fprintf(stderr, "The -fps option requires an argument [from 1 to 1000], default is 12.\n"); quit(10); } } else if (strcmp(argv[1], "-format") == 0) { if (argv[2]) { if (!strcmp(argv[2], "YV12")) overlay_format = SDL_YV12_OVERLAY; else if (!strcmp(argv[2], "IYUV")) overlay_format = SDL_IYUV_OVERLAY; else if (!strcmp(argv[2], "YUY2")) overlay_format = SDL_YUY2_OVERLAY; else if (!strcmp(argv[2], "UYVY")) overlay_format = SDL_UYVY_OVERLAY; else if (!strcmp(argv[2], "YVYU")) overlay_format = SDL_YVYU_OVERLAY; else { fprintf(stderr, "The -format option %s is not recognized, see help for info.\n", argv[2]); quit(10); } argv += 2; argc -= 2; } else { fprintf(stderr, "The -format option requires an argument, default is YUY2.\n"); quit(10); } } else if (strcmp(argv[1], "-scale") == 0) { if (argv[2]) { scale = atoi(argv[2]); if (scale == 0) { fprintf(stderr, "The -scale option requires an argument [from 1 to 50], default is 5.\n"); quit(10); } if ((scale < 0) || (scale > 50)) { fprintf(stderr, "The -scale option must be in range from 1 to 50, default is 5.\n"); quit(10); } argv += 2; argc -= 2; } else { fprintf(stderr, "The -fps option requires an argument [from 1 to 1000], default is 12.\n"); quit(10); } } else if ((strcmp(argv[1], "-help") == 0) || (strcmp(argv[1], "-h") == 0)) { PrintUsage(argv[0]); quit(0); } else { fprintf(stderr, "Unrecognized option: %s.\n", argv[1]); quit(10); } break; } RawMooseData = (Uint8 *) malloc(MOOSEFRAME_SIZE * MOOSEFRAMES_COUNT); if (RawMooseData == NULL) { fprintf(stderr, "Can't allocate memory for movie !\n"); free(RawMooseData); quit(1); } /* load the trojan moose images */ handle = SDL_RWFromFile("moose.dat", "rb"); if (handle == NULL) { fprintf(stderr, "Can't find the file moose.dat !\n"); free(RawMooseData); quit(2); } SDL_RWread(handle, RawMooseData, MOOSEFRAME_SIZE, MOOSEFRAMES_COUNT); SDL_RWclose(handle); /* Set video mode */ if ((screen = SDL_SetVideoMode(MOOSEPIC_W * scale, MOOSEPIC_H * scale, 0, SDL_RESIZABLE | SDL_SWSURFACE)) == NULL) { fprintf(stderr, "Couldn't set video mode: %s\n", SDL_GetError()); free(RawMooseData); quit(4); } /* Set the window manager title bar */ SDL_WM_SetCaption("SDL test overlay: running moose", "testoverlay2"); for (i = 0; i < MOOSEFRAMES_COUNT; i++) { MooseFrame[i] = SDL_CreateRGBSurfaceFrom(RawMooseData + i * MOOSEFRAME_SIZE, MOOSEPIC_W, MOOSEPIC_H, 8, MOOSEPIC_W, 0, 0, 0, 0); if (MooseFrame[i] == NULL) { fprintf(stderr, "Couldn't create SDL_Surfaces:%s\n", SDL_GetError()); free(RawMooseData); quit(5); } SDL_SetColors(MooseFrame[i], MooseColors, 0, 84); { SDL_Surface *newsurf; SDL_PixelFormat format; format.palette = NULL; format.BitsPerPixel = 32; format.BytesPerPixel = 4; #if SDL_BYTEORDER == SDL_LIL_ENDIAN format.Rshift = 0; format.Gshift = 8; format.Bshift = 16; #else format.Rshift = 24; format.Gshift = 16; format.Bshift = 8; #endif format.Ashift = 0; format.Rmask = 0xff << format.Rshift; format.Gmask = 0xff << format.Gshift; format.Bmask = 0xff << format.Bshift; format.Amask = 0; format.Rloss = 0; format.Gloss = 0; format.Bloss = 0; format.Aloss = 8; newsurf = SDL_ConvertSurface(MooseFrame[i], &format, SDL_SWSURFACE); if (!newsurf) { fprintf(stderr, "Couldn't convert picture to 32bits RGB: %s\n", SDL_GetError()); quit(6); } SDL_FreeSurface(MooseFrame[i]); MooseFrame[i] = newsurf; } } free(RawMooseData); overlay = SDL_CreateYUVOverlay(MOOSEPIC_W, MOOSEPIC_H, overlay_format, screen); if (!overlay) { fprintf(stderr, "Couldn't create overlay: %s\n", SDL_GetError()); quit(7); } printf("Created %dx%dx%d %s %s overlay\n", overlay->w, overlay->h, overlay->planes, overlay->hw_overlay ? "hardware" : "software", overlay->format == SDL_YV12_OVERLAY ? "YV12" : overlay->format == SDL_IYUV_OVERLAY ? "IYUV" : overlay->format == SDL_YUY2_OVERLAY ? "YUY2" : overlay->format == SDL_UYVY_OVERLAY ? "UYVY" : overlay->format == SDL_YVYU_OVERLAY ? "YVYU" : "Unknown"); for (i = 0; i < overlay->planes; i++) { printf(" plane %d: pitch=%d\n", i, overlay->pitches[i]); } overlayrect.x = 0; overlayrect.y = 0; overlayrect.w = MOOSEPIC_W * scale; overlayrect.h = MOOSEPIC_H * scale; /* set the start frame */ i = 0; fpsdelay = 1000 / fps; /* Ignore key up events, they don't even get filtered */ SDL_EventState(SDL_KEYUP, SDL_IGNORE); lastftick = SDL_GetTicks(); /* Loop, waiting for QUIT or RESIZE */ while (1) { if (SDL_PollEvent(&event)) { switch (event.type) { case SDL_VIDEORESIZE: screen = SDL_SetVideoMode(event.resize.w, event.resize.h, 0, SDL_RESIZABLE | SDL_SWSURFACE); overlayrect.w = event.resize.w; overlayrect.h = event.resize.h; if (paused) { resized = 1; } break; case SDL_MOUSEBUTTONDOWN: overlayrect.x = event.button.x - overlayrect.w / 2; overlayrect.y = event.button.y - overlayrect.h / 2; break; case SDL_KEYDOWN: if (event.key.keysym.sym == SDLK_SPACE) { paused = !paused; break; } if (event.key.keysym.sym != SDLK_ESCAPE) { break; } case SDL_QUIT: SDL_FreeYUVOverlay(overlay); for (i = 0; i < MOOSEFRAMES_COUNT; i++) { SDL_FreeSurface(MooseFrame[i]); } quit(0); } } if ((!paused) || (resized)) { if (((SDL_GetTicks() - lastftick) > fpsdelay) || (resized)) { lastftick = SDL_GetTicks(); switch (overlay_format) { case SDL_YUY2_OVERLAY: ConvertRGBtoYUY2(MooseFrame[i], overlay, 0, 100); break; case SDL_YV12_OVERLAY: ConvertRGBtoYV12(MooseFrame[i], overlay, 0, 100); break; case SDL_UYVY_OVERLAY: ConvertRGBtoUYVY(MooseFrame[i], overlay, 0, 100); break; case SDL_YVYU_OVERLAY: ConvertRGBtoYVYU(MooseFrame[i], overlay, 0, 100); break; case SDL_IYUV_OVERLAY: ConvertRGBtoIYUV(MooseFrame[i], overlay, 0, 100); break; } SDL_DisplayYUVOverlay(overlay, &overlayrect); if (!resized) { i++; if (i == 10) { i = 0; } } else { resized = 0; } } } /* kind of timeslice to OS */ SDL_Delay(1); } SDL_Quit(); return 0; }
void clean_up(){ SDL_FreeSurface(image); SDL_Quit(); }