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); }
int CALLBACK WinMain( _In_ HINSTANCE hInstance, _In_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nCmdShow) { int flags = 0; dfDeltaTime = 43.f; ScreenResolution.x = 800.f; ScreenResolution.y = 600.f; GameResolution.x = 640.f; GameResolution.y = 480.f; if( SDL_Init( SDL_INIT_VIDEO ) < 0 ) { printf( "Video initialization failed: %s\n", SDL_GetError( ) ); GameExit( 1 ); } if( SDL_Init( SDL_INIT_JOYSTICK ) < 0 ) { printf( "Input initialization failed: %s\n", SDL_GetError( ) ); GameExit( 1 ); } if( SDL_Init( SDL_INIT_GAMECONTROLLER ) < 0 ) { printf( "Input initialization failed: %s\n", SDL_GetError( ) ); GameExit( 1 ); } if( SDL_Init( SDL_INIT_AUDIO ) < 0 ) { printf( "Audio initialization failed: %s\n", SDL_GetError( ) ); GameExit( 1 ); } //Initialize SDL_mixer if( Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 2048 ) < 0 ) { printf( "SDL_mixer could not initialize! SDL_mixer Error: %s\n", Mix_GetError() ); GameExit( 1 ); } SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 5 ); SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 5 ); SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 5 ); SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 ); SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); //flags = SDL_WINDOW_FULLSCREEN | SDL_WINDOW_OPENGL; flags = SDL_WINDOW_OPENGL; RenderSystem::window = SDL_CreateWindow("Dufresne", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, ScreenResolution.x, ScreenResolution.y, flags); flags = IMG_INIT_JPG | IMG_INIT_PNG; int initted = IMG_Init(flags); if(initted & flags != flags) { printf("Failed to Init SDL Image\n"); printf("IMG_Init: %s\n", IMG_GetError()); GameExit( 1 ); // handle error } // init gl SDL_GLContext glcontext; glcontext = SDL_GL_CreateContext(RenderSystem::window); GLint GlewInitResult = glewInit(); if (GlewInitResult != GLEW_OK) { printf("ERROR: %s\n",glewGetErrorString(GlewInitResult)); GameExit( 1 ); } glEnable(GL_TEXTURE_2D); tinyjson_init(); InitEngine(); assMan = AssetManager(); std::wstring path = L"fart\\"; assMan.CalculateLoosePackageSize(path); assMan.LoadLoosePackage(path); assMan.DebugTestWritePoolToFile(); sfxMan = SoundSystem(); sfxMan.Init(); sceneMan.Init(); input = Input(); input.Init(); dfScene* scene1 = sceneMan.CreateScene("scene-left"); dfScene* scene2 = sceneMan.CreateScene("scene-right"); scene1->setupFunc = &SetupScene1; scene2->setupFunc = &SetupScene2; sceneMan.LoadScene(scene1); Uint32 previousMiliseconds = 0; while(true) { Uint32 currentMiliseconds = SDL_GetTicks(); dfRandomFloat = dfRand(); dfTotalTime = currentMiliseconds / 1000.f; dfDeltaTime = (currentMiliseconds / 1000.f) - (previousMiliseconds / 1000.f); if(testDude->tf.rectangle.left > GameResolution.x) { sceneMan.LoadScene(scene2); } if(testDude->tf.rectangle.right < 0) { sceneMan.LoadScene(scene1); } if(input.keyboard.n1.tapped) { sceneMan.renderer.UpdateResolution(640, 480); } if(input.keyboard.n2.tapped) { sceneMan.renderer.UpdateResolution(300, 300); } if(input.keyboard.n3.tapped) { sceneMan.renderer.UpdateResolution(450, 300); } input.Update(); sceneMan.Update(); SDL_GL_SwapWindow(RenderSystem::window); } return 0; }
static gboolean process (GeglOperation *operation, GeglBuffer *input, const GeglRectangle *result, gint level) { GeglChantO *o = GEGL_CHANT_PROPERTIES (operation); GeglBuffer *source; SDL_Surface **sdl_outwin = NULL; /*op_sym (op, "sdl_outwin");*/ init_sdl (); if (!handle) handle = g_timeout_add (500, idle, NULL); if (!o->screen || o->width != result->width || o->height != result->height) { if (sdl_outwin) { if (o->screen) { SDL_FreeSurface (o->screen); o->screen = NULL; } o->screen = SDL_CreateRGBSurface (SDL_SWSURFACE, result->width, result->height, 32, 0xff0000, 0x00ff00, 0x0000ff, 0x000000); *sdl_outwin = o->screen; if (!o->screen) { fprintf (stderr, "CreateRGBSurface failed: %s\n", SDL_GetError ()); return -1; } } else { o->screen = SDL_SetVideoMode (result->width, result->height, 32, SDL_SWSURFACE); if (!o->screen) { fprintf (stderr, "Unable to set SDL mode: %s\n", SDL_GetError ()); return -1; } } o->width = result->width ; o->height = result->height; } /* * There seems to be a valid faster path to the SDL desired display format * in B'G'R'A, perhaps babl should have been able to figure this out ito? * */ source = gegl_buffer_create_sub_buffer (input, result); gegl_buffer_get (source, NULL, 1.0, babl_format_new (babl_model ("RGBA"), babl_type ("u8"), babl_component ("B"), babl_component ("G"), babl_component ("R"), babl_component ("A"), NULL), ((SDL_Surface*)o->screen)->pixels, GEGL_AUTO_ROWSTRIDE, GEGL_ABYSS_NONE); g_object_unref (source); if (!sdl_outwin) { SDL_UpdateRect (o->screen, 0, 0, 0, 0); SDL_WM_SetCaption (o->window_title, o->icon_title); } o->width = result->width ; o->height = result->height; return TRUE; }
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 main( int argc, char* argv[] ) { /* Information about the current video settings. */ const SDL_VideoInfo* info = NULL; /* Dimensions of our window. */ int width = 0; int height = 0; /* Color depth in bits of our window. */ int bpp = 0; /* Flags we will pass into SDL_SetVideoMode. */ int flags = 0; /* First, initialize SDL’s video subsystem. */ if( SDL_Init( SDL_INIT_VIDEO ) < 0 ) { /* Failed, exit. */ fprintf( stderr, "Video initialization failed: %s\n", SDL_GetError( ) ); quit_tutorial( 1 ); } /* Let’s get some video information. */ info = SDL_GetVideoInfo( ); if( !info ) { /* This should probably never happen. */ fprintf( stderr, "Video query failed: %s\n", SDL_GetError( ) ); quit_tutorial( 1 ); } /* * Set our width/height to 640/480 (you would * of course let the user decide this in a normal * app). We get the bpp we will request from * the display. On X11, VidMode can’t change * resolution, so this is probably being overly * safe. Under Win32, ChangeDisplaySettings * can change the bpp. */ width = 640; height = 480; bpp = info->vfmt->BitsPerPixel; /* * Now, we want to setup our requested * window attributes for our OpenGL window. * We want *at least* 5 bits of red, green * and blue. We also want at least a 16-bit * depth buffer. * * The last thing we do is request a double * buffered window. ’1’ turns on double * buffering, ’0’ turns it off. * * Note that we do not use SDL_DOUBLEBUF in * the flags to SDL_SetVideoMode. That does * not affect the GL attribute state, only * the standard 2D blitting setup. */ SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 5 ); SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 5 ); SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 5 ); SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 ); SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); /* * We want to request that SDL provide us * with an OpenGL window, in a fullscreen * video mode. * * EXERCISE: * Make starting windowed an option, and * handle the resize events properly with * glViewport. */ flags = SDL_OPENGL | SDL_FULLSCREEN; /* * Set the video mode */ if( SDL_SetVideoMode( width, height, bpp, flags ) == 0 ) { /* * This could happen for a variety of reasons, * including DISPLAY not being set, the specified * resolution not being available, etc. */ fprintf( stderr, "Video mode set failed: %s\n", SDL_GetError( ) ); quit_tutorial( 1 ); } /* * At this point, we should have a properly setup * double-buffered window for use with OpenGL. */ setup_opengl( width, height ); /* * Now we want to begin our normal app process-- * an event loop with a lot of redrawing. */ while( 1 ) { /* Process incoming events. */ process_events( ); /* Draw the screen. */ draw_screen( ); } /* * EXERCISE: * Record timings using SDL_GetTicks() and * and print out frames per second at program * end. */ /* Never reached. */ return 0; }
bool SdlJoystick::init() { #if SDL_VERSION_ATLEAST(1,3,0) SDL_Init(SDL_INIT_JOYSTICK | SDL_INIT_HAPTIC); #else SDL_Init(SDL_INIT_JOYSTICK); #endif if (mDeviceNumber >= SDL_NumJoysticks()) { vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_CRITICAL_LVL) << clrOutBOLD(clrRED, "ERROR") << ": Added for joystick number " << mDeviceNumber << " but there are only " << SDL_NumJoysticks() << " joysticks.\n" << vprDEBUG_FLUSH; return false; } mJoystick = SDL_JoystickOpen(mDeviceNumber); if (!mJoystick) { vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_CRITICAL_LVL) << "ERROR: Failed to open joystick " << mDeviceNumber << ": " << SDL_GetError(); return false; } mButtons.resize(SDL_JoystickNumButtons(mJoystick), gadget::DigitalState::OFF); mAxes.resize(SDL_JoystickNumAxes(mJoystick), 0.0f); mHats.resize(SDL_JoystickNumHats(mJoystick), gadget::HatState::CENTERED); gadget::Digital::addDigitalSample(mButtons); gadget::Analog::addAnalogSample(mAxes); gadget::Hat::addHatSample(mHats); #if SDL_VERSION_ATLEAST(2,0,0) mHardwareName = SDL_JoystickName(mJoystick); #else mHardwareName = SDL_JoystickName(mDeviceNumber); #endif cout << "Found Joystick " << mDeviceNumber << ": " << mHardwareName << endl << " Axis: " << mAxes.size() << endl << " Buttons: " << mButtons.size() << endl << " Hats: " << mHats.size() << endl << " Balls: " << SDL_JoystickNumBalls(mJoystick) << " (Unused)" << endl #if SDL_VERSION_ATLEAST(1,3,0) << " Haptics: " << (SDL_JoystickIsHaptic(mJoystick) ? "YES" : "NO") #else << " Haptics: Not supported by SDL 1.2" #endif << endl; #if SDL_VERSION_ATLEAST(1,3,0) if (SDL_JoystickIsHaptic(mJoystick)) { mHaptic = SDL_HapticOpenFromJoystick(mJoystick); if (!mHaptic) { vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_CRITICAL_LVL) << "ERROR: Failed to initialize haptics on " << mDeviceNumber << ": " << SDL_GetError(); return true; } unsigned int cap = getCapabilities(); cout << " Loaded Effects: " << getMaxStoredEffects() << endl << " Played Effects: " << getMaxPlayingEffects() << endl << " Axes Count: " << getNumAxes() << endl << " Support for:"; if (cap & RumbleEffect::CONSTANT) cout << " constant"; if (cap & RumbleEffect::SINE) cout << " sine"; if (cap & RumbleEffect::SQUARE) cout << " square"; if (cap & RumbleEffect::TRIANGLE) cout << " triangle"; if (cap & RumbleEffect::SAWTOOTHUP) cout << " saw-tooth-up"; if (cap & RumbleEffect::SAWTOOTHDOWN) cout << " saw-tooth-down"; if (cap & RumbleEffect::RAMP) cout << " ramp"; if (cap & RumbleEffect::SPRING) cout << " spring"; if (cap & RumbleEffect::DAMPER) cout << " damper"; if (cap & RumbleEffect::INERTIA) cout << " inertia"; if (cap & RumbleEffect::FRICTION) cout << " friction"; if (cap & RumbleEffect::CUSTOM) cout << " custom"; if (cap & RumbleEffect::GAIN) cout << " gain"; if (cap & RumbleEffect::AUTOCENTER) cout << " auto-center"; if (cap & RumbleEffect::STATUS) cout << " status"; if (cap & RumbleEffect::PAUSE) cout << " pause"; cout << endl; } #endif mInitialized = true; return true; }
void RPG_Graphics_Cursor_Manager::updateBG(SDL_Rect& dirtyRegion_out, const SDL_Rect* clipRect_in, const bool& lockedAccess_in, const bool& debug_in) { RPG_TRACE(ACE_TEXT("RPG_Graphics_Cursor_Manager::updateBG")); // sanity check(s) ACE_ASSERT(myBG); ACE_ASSERT(myHighlightWindow); SDL_Surface* target_surface = myHighlightWindow->getScreen(); ACE_ASSERT(target_surface); // init return value(s) ACE_OS::memset(&dirtyRegion_out, 0, sizeof(dirtyRegion_out)); // *NOTE*: this function handles two distinct use-cases: // 1. the map window has changed (clipRect_in == NULL) --> update that // bit (if any) of the cached bg // 2. a part of the screen has changed (clipRect_in != NULL) // --> update that bit (if any) of the cached bg // step1: set clip area SDL_Rect clip_area = {0, 0, 0, 0}; if (clipRect_in == NULL) myHighlightWindow->getArea(clip_area, false); else clip_area = *clipRect_in; // step2: intersect with cached bg SDL_Rect cached_area; cached_area.x = static_cast<int16_t>(myBGPosition.first); cached_area.y = static_cast<int16_t>(myBGPosition.second); cached_area.w = myBG->w; cached_area.h = myBG->h; SDL_Rect intersection = {0, 0, 0, 0}; intersection = RPG_Graphics_SDL_Tools::intersect(cached_area, clip_area); // sanity check(s) if ((intersection.w == 0) || // cached bg fully outside of "dirty" area ? (intersection.h == 0)) return; // --> nothing to do... if ((intersection.w == cached_area.w) && (intersection.h == cached_area.h)) { // cached cursor bg fully inside of map // --> just get a fresh copy RPG_Graphics_Surface::get(myBGPosition, true, // use (fast) blitting method *target_surface, *myBG); // debug info if (debug_in) { // show bg surface in left upper corner ACE_ASSERT(target_surface->w >= myBG->w); ACE_ASSERT(target_surface->h >= myBG->h); // compute bounding box SDL_Rect dirty_region; dirty_region.x = 0; dirty_region.y = 0; dirty_region.w = myBG->w; dirty_region.h = myBG->h; // RPG_Graphics_Surface::unclip(); if (myScreenLock && lockedAccess_in) myScreenLock->lock(); RPG_Graphics_Surface::put(std::make_pair(dirty_region.x, dirty_region.y), *myBG, target_surface, dirty_region); if (myScreenLock && lockedAccess_in) myScreenLock->unlock(); // RPG_Graphics_Surface::clip(); } // end IF return; // --> done... } // end IF // step3: adjust intersection coordinates (relative to cached bg surface) intersection.x -= cached_area.x; intersection.y -= cached_area.y; // step4: get a fresh copy from that part of the map SDL_Surface* new_bg = RPG_Graphics_Surface::create(static_cast<unsigned int>(myBG->w), static_cast<unsigned int>(myBG->h)); ACE_ASSERT(new_bg); RPG_Graphics_Surface::get(myBGPosition, true, // use (fast) blitting method *target_surface, *new_bg); // step5: mask the "dirty" bit of the cached bg if (SDL_FillRect(myBG, &intersection, RPG_Graphics_SDL_Tools::getColor(COLOR_BLACK_A0, // transparent *myBG))) { ACE_DEBUG((LM_ERROR, ACE_TEXT("failed to SDL_FillRect(): \"%s\", aborting\n"), ACE_TEXT(SDL_GetError()))); // clean up SDL_FreeSurface(new_bg); return; } // end IF // step6: blit the cached bg onto the fresh copy if (SDL_BlitSurface(myBG, // source NULL, // aspect (--> everything) new_bg, // target NULL)) // aspect (--> everything) { ACE_DEBUG((LM_ERROR, ACE_TEXT("failed to SDL_BlitSurface(): %s, aborting\n"), ACE_TEXT(SDL_GetError()))); // clean up SDL_FreeSurface(new_bg); return; } // end IF // clean up SDL_FreeSurface(myBG); myBG = new_bg; // debug info if (debug_in) { // show bg surface in left upper corner ACE_ASSERT(target_surface->w >= myBG->w); ACE_ASSERT(target_surface->h >= myBG->h); // compute bounding box SDL_Rect dirty_region; dirty_region.x = 0; dirty_region.y = 0; dirty_region.w = myBG->w; dirty_region.h = myBG->h; // RPG_Graphics_Surface::unclip(); if (myScreenLock && lockedAccess_in) myScreenLock->lock(); RPG_Graphics_Surface::put(std::make_pair(dirty_region.x, dirty_region.y), *myBG, target_surface, dirty_region); if (myScreenLock && lockedAccess_in) myScreenLock->unlock(); // RPG_Graphics_Surface::clip(); } // end IF }
/** * \brief Convert audio using various conversion structures * * \sa https://wiki.libsdl.org/SDL_BuildAudioCVT * \sa https://wiki.libsdl.org/SDL_ConvertAudio */ int audio_convertAudio() { int result; SDL_AudioCVT cvt; SDL_AudioSpec spec1; SDL_AudioSpec spec2; int c; char message[128]; int i, ii, j, jj, k, kk, l, ll; /* Iterate over bitmask that determines which parameters are modified in the conversion */ for (c = 1; c < 8; c++) { SDL_strlcpy(message, "Changing:", 128); if (c & 1) { SDL_strlcat(message, " Format", 128); } if (c & 2) { SDL_strlcat(message, " Channels", 128); } if (c & 4) { SDL_strlcat(message, " Frequencies", 128); } SDLTest_Log("%s", message); /* All source conversions with random conversion targets */ for (i = 0; i < _numAudioFormats; i++) { for (j = 0; j < _numAudioChannels; j++) { for (k = 0; k < _numAudioFrequencies; k++) { spec1.format = _audioFormats[i]; spec1.channels = _audioChannels[j]; spec1.freq = _audioFrequencies[k]; /* Ensure we have a different target format */ do { if (c & 1) { ii = SDLTest_RandomIntegerInRange(0, _numAudioFormats - 1); } else { ii = 1; } if (c & 2) { jj = SDLTest_RandomIntegerInRange(0, _numAudioChannels - 1); } else { jj= j; } if (c & 4) { kk = SDLTest_RandomIntegerInRange(0, _numAudioFrequencies - 1); } else { kk = k; } } while ((i == ii) && (j == jj) && (k == kk)); spec2.format = _audioFormats[ii]; spec2.channels = _audioChannels[jj]; spec2.freq = _audioFrequencies[kk]; result = SDL_BuildAudioCVT(&cvt, spec1.format, spec1.channels, spec1.freq, spec2.format, spec2.channels, spec2.freq); SDLTest_AssertPass("Call to SDL_BuildAudioCVT(format[%i]=%s(%i),channels[%i]=%i,freq[%i]=%i ==> format[%i]=%s(%i),channels[%i]=%i,freq[%i]=%i)", i, _audioFormatsVerbose[i], spec1.format, j, spec1.channels, k, spec1.freq, ii, _audioFormatsVerbose[ii], spec2.format, jj, spec2.channels, kk, spec2.freq); SDLTest_AssertCheck(result == 1, "Verify result value; expected: 1, got: %i", result); if (result != 1) { SDLTest_LogError("%s", SDL_GetError()); } else { SDLTest_AssertCheck(cvt.len_mult > 0, "Verify that cvt.len_mult value; expected: >0, got: %i", cvt.len_mult); if (cvt.len_mult < 1) return TEST_ABORTED; /* Create some random data to convert */ l = 64; ll = l * cvt.len_mult; SDLTest_Log("Creating dummy sample buffer of %i length (%i bytes)", l, ll); cvt.len = l; cvt.buf = (Uint8 *)SDL_malloc(ll); SDLTest_AssertCheck(cvt.buf != NULL, "Check data buffer to convert is not NULL"); if (cvt.buf == NULL) return TEST_ABORTED; /* Convert the data */ result = SDL_ConvertAudio(&cvt); SDLTest_AssertPass("Call to SDL_ConvertAudio()"); SDLTest_AssertCheck(result == 0, "Verify result value; expected: 0; got: %i", result); SDLTest_AssertCheck(cvt.buf != NULL, "Verify conversion buffer is not NULL"); SDLTest_AssertCheck(cvt.len_ratio > 0.0, "Verify conversion length ratio; expected: >0; got: %f", cvt.len_ratio); /* Free converted buffer */ SDL_free(cvt.buf); cvt.buf = NULL; } } } } } return TEST_COMPLETED; }
void RPG_Graphics_Cursor_Manager::restoreHighlightBG(const RPG_Graphics_Position_t& viewPort_in, SDL_Rect& dirtyRegion_out, const SDL_Rect* clipRectangle_in, const bool& lockedAccess_in, const bool& debug_in) { RPG_TRACE(ACE_TEXT("RPG_Graphics_Cursor_Manager::restoreHighlightBG")); // step0: init return value(s) ACE_OS::memset(&dirtyRegion_out, 0, sizeof(dirtyRegion_out)); // sanity check(s) ACE_ASSERT(myHighlightWindow); SDL_Surface* target_surface = myHighlightWindow->getScreen(); ACE_ASSERT(target_surface); ACE_ASSERT(!myHighlightBGCache.empty()); if ((myHighlightBGCache.size() == 1) && (myHighlightBGCache.front().first == std::make_pair(std::numeric_limits<unsigned int>::max(), std::numeric_limits<unsigned int>::max()))) return; // nothing to do SDL_Rect window_area, clip_area, clip_rectangle, source_clip_rectangle; myHighlightWindow->getArea(window_area, true); myHighlightWindow->getArea(clip_area, false); if (clipRectangle_in) clip_area = *clipRectangle_in; RPG_Graphics_Position_t screen_position; SDL_Rect cursor_clip_rectangle = {static_cast<Sint16>(myBGPosition.first), static_cast<Sint16>(myBGPosition.second), static_cast<Uint16>(myBG->w), static_cast<Uint16>(myBG->h)}, temp_rectangle; std::vector<SDL_Rect> cursor_relevant_clip_rectangles; myHighlightWindow->clip(); if (lockedAccess_in && myScreenLock) myScreenLock->lock(); for (RPG_Graphics_TileCacheConstIterator_t iterator = myHighlightBGCache.begin(); iterator != myHighlightBGCache.end(); iterator++) { screen_position = RPG_Graphics_Common_Tools::map2Screen((*iterator).first, std::make_pair(window_area.w, window_area.h), viewPort_in); source_clip_rectangle.x = screen_position.first; source_clip_rectangle.y = screen_position.second; source_clip_rectangle.w = (*iterator).second->w; source_clip_rectangle.h = (*iterator).second->h; clip_rectangle = RPG_Graphics_SDL_Tools::intersect(source_clip_rectangle, clip_area); dirtyRegion_out = RPG_Graphics_SDL_Tools::boundingBox(dirtyRegion_out, clip_rectangle); source_clip_rectangle.x = clip_rectangle.x - screen_position.first; source_clip_rectangle.y = clip_rectangle.y - screen_position.second; if (!clip_rectangle.w || !clip_rectangle.h) continue; // nothing to do... temp_rectangle = clip_rectangle; // restore / clear background if (SDL_BlitSurface((*iterator).second, // source &source_clip_rectangle, // aspect target_surface, // target &clip_rectangle)) // aspect ACE_DEBUG((LM_ERROR, ACE_TEXT("failed to SDL_BlitSurface(): \"%s\", continuing\n"), ACE_TEXT(SDL_GetError()))); temp_rectangle = RPG_Graphics_SDL_Tools::intersect(cursor_clip_rectangle, temp_rectangle); if (temp_rectangle.w || temp_rectangle.h) cursor_relevant_clip_rectangles.push_back(temp_rectangle); } // end FOR if (lockedAccess_in && myScreenLock) myScreenLock->unlock(); myHighlightWindow->unclip(); // *NOTE*: iff the highlight bg(s) intersected the cursor bg, an update is // needed of (that/those bit(s) of) the cursor bg... for (std::vector<SDL_Rect>::const_iterator iterator = cursor_relevant_clip_rectangles.begin(); iterator != cursor_relevant_clip_rectangles.end(); iterator++) { updateBG(temp_rectangle, &(*iterator), lockedAccess_in, debug_in); if (debug_in) dirtyRegion_out = RPG_Graphics_SDL_Tools::boundingBox(temp_rectangle, dirtyRegion_out); } // end FOR }
void RPG_Graphics_Cursor_Manager::updateHighlightBG(const RPG_Graphics_Position_t& viewPort_in, SDL_Rect& dirtyRegion_out, const SDL_Rect* clipRectangle_in, const bool& lockedAccess_in, const bool& debug_in) { RPG_TRACE(ACE_TEXT("RPG_Graphics_Cursor_Manager::updateHighlightBG")); // sanity check(s) ACE_ASSERT(myHighlightWindow); SDL_Surface* target_surface = myHighlightWindow->getScreen(); ACE_ASSERT(target_surface); // init return value(s) ACE_OS::memset(&dirtyRegion_out, 0, sizeof(dirtyRegion_out)); SDL_Rect window_area, clip_area, clip_rectangle, source_clip_rectangle; myHighlightWindow->getArea(window_area, true); myHighlightWindow->getArea(clip_area, false); if (clipRectangle_in) clip_area = *clipRectangle_in; RPG_Graphics_Position_t screen_position; SDL_Surface* new_background = NULL; if (myScreenLock && lockedAccess_in && debug_in) myScreenLock->lock(); for (RPG_Graphics_TileCacheIterator_t iterator = myHighlightBGCache.begin(); iterator != myHighlightBGCache.end(); iterator++) { screen_position = RPG_Graphics_Common_Tools::map2Screen((*iterator).first, std::make_pair(window_area.w, window_area.h), viewPort_in); source_clip_rectangle.x = screen_position.first; source_clip_rectangle.y = screen_position.second; source_clip_rectangle.w = (*iterator).second->w; source_clip_rectangle.h = (*iterator).second->h; clip_rectangle = RPG_Graphics_SDL_Tools::intersect(clip_area, source_clip_rectangle); if (!clip_rectangle.w || !clip_rectangle.h) continue; // nothing to do... if ((clip_rectangle.w == (*iterator).second->w) && (clip_rectangle.h == (*iterator).second->h)) { // cached highlight bg completely "dirty" // --> just get a fresh copy RPG_Graphics_Surface::get(screen_position, true, // use (fast) blitting method *target_surface, *(*iterator).second); // debug info if (debug_in) { // show bg surface in left upper corner ACE_ASSERT(target_surface->w >= (*iterator).second->w); ACE_ASSERT(target_surface->h >= (*iterator).second->h); // compute bounding box SDL_Rect dirty_region; dirty_region.x = target_surface->w - (*iterator).second->w; dirty_region.y = target_surface->h - (*iterator).second->h; dirty_region.w = (*iterator).second->w; dirty_region.h = (*iterator).second->h; RPG_Graphics_Surface::put(std::make_pair(dirty_region.x, dirty_region.y), *(*iterator).second, target_surface, dirty_region); dirtyRegion_out = RPG_Graphics_SDL_Tools::boundingBox(dirty_region, dirtyRegion_out); } // end IF continue; } // end IF // get a fresh copy from that part of the map new_background = RPG_Graphics_Surface::create(static_cast<unsigned int>((*iterator).second->w), static_cast<unsigned int>((*iterator).second->h)); if (!new_background) { ACE_DEBUG((LM_ERROR, ACE_TEXT("failed to RPG_Graphics_Surface::create(%u,%u), continuing\n"), (*iterator).second->w, (*iterator).second->h)); continue; } // end IF RPG_Graphics_Surface::get(screen_position, true, // use (fast) blitting method *target_surface, *new_background); // mask the "dirty" bit of the cached bg // --> adjust intersection coordinates (relative to cached bg surface) clip_rectangle.x -= screen_position.first; clip_rectangle.y -= screen_position.second; if (SDL_FillRect((*iterator).second, &clip_rectangle, RPG_Graphics_SDL_Tools::getColor(COLOR_BLACK_A0, // transparent *(*iterator).second))) { ACE_DEBUG((LM_ERROR, ACE_TEXT("failed to SDL_FillRect(): \"%s\", continuing\n"), ACE_TEXT(SDL_GetError()))); // clean up SDL_FreeSurface(new_background); continue; } // end IF // blit the cached/masked bg onto the fresh copy if (SDL_BlitSurface((*iterator).second, // source NULL, // aspect (--> everything) new_background, // target NULL)) // aspect (--> everything) { ACE_DEBUG((LM_ERROR, ACE_TEXT("failed to SDL_BlitSurface(): %s, continuing\n"), ACE_TEXT(SDL_GetError()))); // clean up SDL_FreeSurface(new_background); continue; } // end IF // clean up SDL_FreeSurface((*iterator).second); (*iterator).second = new_background; // debug info if (debug_in) { // show bg surface in left upper corner ACE_ASSERT(target_surface->w >= (*iterator).second->w); ACE_ASSERT(target_surface->h >= (*iterator).second->h); // compute bounding box SDL_Rect dirty_region; dirty_region.x = 0; dirty_region.y = 0; dirty_region.w = (*iterator).second->w; dirty_region.h = (*iterator).second->h; RPG_Graphics_Surface::put(std::make_pair(dirty_region.x, dirty_region.y), *(*iterator).second, target_surface, dirty_region); dirtyRegion_out = RPG_Graphics_SDL_Tools::boundingBox(dirty_region, dirtyRegion_out); } // end IF } // end FOR if (myScreenLock && lockedAccess_in && debug_in) myScreenLock->unlock(); }
/* =============== SNDDMA_Init =============== */ qboolean SNDDMA_Init(void) { char drivername[128]; SDL_AudioSpec desired; SDL_AudioSpec obtained; int tmp; if (snd_inited) return qtrue; if (!s_sdlBits) { s_sdlBits = Cvar_Get("s_sdlBits", "16", CVAR_ARCHIVE); s_sdlSpeed = Cvar_Get("s_sdlSpeed", "0", CVAR_ARCHIVE); s_sdlChannels = Cvar_Get("s_sdlChannels", "2", CVAR_ARCHIVE); s_sdlDevSamps = Cvar_Get("s_sdlDevSamps", "0", CVAR_ARCHIVE); s_sdlMixSamps = Cvar_Get("s_sdlMixSamps", "0", CVAR_ARCHIVE); } Com_DPrintf( "SDL_Init( SDL_INIT_AUDIO )... " ); if (!SDL_WasInit(SDL_INIT_AUDIO)) { if (SDL_Init(SDL_INIT_AUDIO) == -1) { Com_DPrintf( "FAILED (%s)\n", SDL_GetError( ) ); return qfalse; } } Com_DPrintf( "OK\n" ); if (SDL_AudioDriverName(drivername, sizeof (drivername)) == NULL) strcpy(drivername, "(UNKNOWN)"); Com_DPrintf("SDL audio driver is \"%s\".\n", drivername); memset(&desired, '\0', sizeof (desired)); memset(&obtained, '\0', sizeof (obtained)); tmp = ((int) s_sdlBits->value); if ((tmp != 16) && (tmp != 8)) tmp = 16; desired.freq = (int) s_sdlSpeed->value; if(!desired.freq) desired.freq = 22050; desired.format = ((tmp == 16) ? AUDIO_S16SYS : AUDIO_U8); // I dunno if this is the best idea, but I'll give it a try... // should probably check a cvar for this... if (s_sdlDevSamps->value) desired.samples = s_sdlDevSamps->value; else { // just pick a sane default. if (desired.freq <= 11025) desired.samples = 256; else if (desired.freq <= 22050) desired.samples = 512; else if (desired.freq <= 44100) desired.samples = 1024; else desired.samples = 2048; // (*shrug*) } desired.channels = (int) s_sdlChannels->value; desired.callback = SNDDMA_AudioCallback; if (SDL_OpenAudio(&desired, &obtained) == -1) { Com_Printf("SDL_OpenAudio() failed: %s\n", SDL_GetError()); SDL_QuitSubSystem(SDL_INIT_AUDIO); return qfalse; } SNDDMA_PrintAudiospec("SDL_AudioSpec", &obtained); // dma.samples needs to be big, or id's mixer will just refuse to // work at all; we need to keep it significantly bigger than the // amount of SDL callback samples, and just copy a little each time // the callback runs. // 32768 is what the OSS driver filled in here on my system. I don't // know if it's a good value overall, but at least we know it's // reasonable...this is why I let the user override. tmp = s_sdlMixSamps->value; if (!tmp) tmp = (obtained.samples * obtained.channels) * 10; if (tmp & (tmp - 1)) // not a power of two? Seems to confuse something. { int val = 1; while (val < tmp) val <<= 1; tmp = val; } dmapos = 0; dma.samplebits = obtained.format & 0xFF; // first byte of format is bits. dma.channels = obtained.channels; dma.samples = tmp; dma.submission_chunk = 1; dma.speed = obtained.freq; dmasize = (dma.samples * (dma.samplebits/8)); dma.buffer = calloc(1, dmasize); Com_DPrintf("Starting SDL audio callback...\n"); SDL_PauseAudio(0); // start callback. Com_DPrintf("SDL audio initialized.\n"); snd_inited = qtrue; return qtrue; }
/** * Toggle between fullscreen and window mode * @return either NR_OK or NR_UNKNOWN_ERROR **/ nrResult nrCRenderContextSDL::setFullscreen(bool bFull){ if (!_inFullscreen && bFull){ if(SDL_WM_ToggleFullScreen(_mainWindow) == 0){ nrLog.Log(NR_LOG_ENGINE, "nrCRenderContextSDL: Failed to go into fullscreen mode : %s" ,SDL_GetError()); return NR_UNKNOWN_ERROR; } }else if (_inFullscreen && !bFull){ if(SDL_WM_ToggleFullScreen(_mainWindow) == 0){ nrLog.Log(NR_LOG_ENGINE, "nrCRenderContextSDL: Failed to go into windowed mode : %s" ,SDL_GetError()); return NR_UNKNOWN_ERROR; } } return NR_OK; }
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 glcontext = SDL_GL_CreateContext(window); // Setup ImGui binding ImGui_ImplSdlGL2_Init(window); // Setup style ImGui::StyleColorsClassic(); //ImGui::StyleColorsDark(); // 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 'extra_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 \\ ! //ImGuiIO& io = ImGui::GetIO(); //io.Fonts->AddFontDefault(); //io.Fonts->AddFontFromFileTTF("../../extra_fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../extra_fonts/Cousine-Regular.ttf", 15.0f); //io.Fonts->AddFontFromFileTTF("../../extra_fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../extra_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; ImGui::Text("Hello, world!"); // Some text (you can use a format string too) ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float as a slider from 0.0f to 1.0f ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats as a color if (ImGui::Button("Demo Window")) // Use buttons to toggle our bools. We could use Checkbox() as well. show_demo_window ^= 1; if (ImGui::Button("Another Window")) show_another_window ^= 1; 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 the window. if (show_another_window) { ImGui::Begin("Another Window", &show_another_window); ImGui::Text("Hello from another window!"); ImGui::End(); } // 3. Show the ImGui demo window. Most of the sample code is in ImGui::ShowDemoWindow(). 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(); SDL_GL_SwapWindow(window); } // Cleanup ImGui_ImplSdlGL2_Shutdown(); SDL_GL_DeleteContext(glcontext); SDL_DestroyWindow(window); SDL_Quit(); return 0; }
int AXWindow::init(float wWidth, float wHeight, const char* title, unsigned int flags, AXFunction setup, AXFunction update, AXFunction draw){ if(initiated){ return -1; } startTime = std::time(0); AXWindow::setup = setup; AXWindow::update = update; AXWindow::draw = draw; //The window we'll be rendering to runPath = SDL_GetBasePath(); //Initialize SDL if(SDL_Init(SDL_INIT_EVERYTHING) < 0) { AXLog::log("SDL could not initialize!", SDL_GetError(), AX_LOG_ERROR); return -1; } if(TTF_Init() < 0){ AXLog::log("SDL_TTF could not initialise!", TTF_GetError(), AX_LOG_ERROR); return -1; } //get the display size SDL_DisplayMode mode; if(SDL_GetCurrentDisplayMode(0, &mode) == 0){ displayWidth = mode.w; displayHeight = mode.h; }else{ AXLog::log("Display data failed to load", "displayWidth and displayHeight will be inaccurate", AX_LOG_WARNING); std::cout << SDL_GetError() << std::endl; } //if it's <0 default to the display size if(wWidth < 0){ wWidth = displayWidth; } if(wHeight < 0){ wHeight = displayHeight; } //Create a window AXWindow::window = SDL_CreateWindow(title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, wWidth, wHeight, SDL_WINDOW_SHOWN); if(window == NULL ){ AXLog::log("Window could not be created!", SDL_GetError(), AX_LOG_ERROR); return -1; } //check the window flags if(flags & AX_WINDOWED){ SDL_SetWindowFullscreen(window, 0); }else if(flags & AX_FULLSCREEN){ SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN); }else{ SDL_SetWindowFullscreen(window, 0); } //save the window width and height AXWindow::windowWidth = wWidth; AXWindow::windowHeight = wHeight; //make a renderer AXWindow::renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); gladLoadGLLoader(SDL_GL_GetProcAddress); glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); backgroundColour.set(255, 255, 255, 255); renderColour.set(0, 0, 0, 255); //set blend mode SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND); //check the flags for noaudio audioStatus = !(flags & AX_NOAUDIO); if(audioStatus){ //open the aduio channel if(Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 1024) != 0){ AXLog::log("Audio failed to initialise.", Mix_GetError(), AX_LOG_ERROR); audioStatus = false; } int flags=MIX_INIT_OGG; int initted=Mix_Init(flags); if((initted&flags) != flags) { AXLog::log("Mix_Init", "Failed to init required ogg!", AX_LOG_ERROR); AXLog::log("Mix_Init", Mix_GetError(), AX_LOG_ERROR); } } AXInput::init(); AXNetwork::init(); if(!(flags&AX_NOANALYTICS)){ std::vector<AXNetworkPair> pairs; pairs.push_back(AXNetworkPair("v", std::to_string(AX_VERSION))); pairs.push_back(AXNetworkPair("t", std::to_string(startTime))); AXNetwork::MTPOSTRequestSimple("http://axilya.com/analytics.php", pairs, false); } initiated = true; return 1; }
int os_inner_init(const char* title) { const char* display; struct utsname uts; struct sigaction term_action; struct sigaction quit_action; struct sigaction hup_action; struct sigaction pipe_action; #ifdef USE_SDL SDL_version compiled; #endif unsigned char endian[4] = { 0x1, 0x2, 0x3, 0x4 }; uint32 endian_little = 0x04030201; uint32 endian_big = 0x01020304; log_std(("os: os_inner_init\n")); if (uname(&uts) != 0) { log_std(("ERROR:os: uname failed\n")); } else { log_std(("os: sys %s\n", uts.sysname)); log_std(("os: release %s\n", uts.release)); log_std(("os: version %s\n", uts.version)); log_std(("os: machine %s\n", uts.machine)); } #if HAVE_SYSCONF #ifdef _SC_CLK_TCK log_std(("os: sysconf(_SC_CLK_TCK) %ld\n", sysconf(_SC_CLK_TCK))); #endif #ifdef _SC_NPROCESSORS_CONF log_std(("os: sysconf(_SC_NPROCESSORS_CONF) %ld\n", sysconf(_SC_NPROCESSORS_CONF))); #endif #ifdef _SC_NPROCESSORS_ONLN log_std(("os: sysconf(_SC_NPROCESSORS_ONLN) %ld\n", sysconf(_SC_NPROCESSORS_ONLN))); #endif #ifdef _SC_PHYS_PAGES log_std(("os: sysconf(_SC_PHYS_PAGES) %ld\n", sysconf(_SC_PHYS_PAGES))); #endif #ifdef _SC_AVPHYS_PAGES log_std(("os: sysconf(_SC_AVPHYS_PAGES) %ld\n", sysconf(_SC_AVPHYS_PAGES))); #endif #ifdef _SC_CHAR_BIT log_std(("os: sysconf(_SC_CHAR_BIT) %ld\n", sysconf(_SC_CHAR_BIT))); #endif #ifdef _SC_LONG_BIT log_std(("os: sysconf(_SC_LONG_BIT) %ld\n", sysconf(_SC_LONG_BIT))); #endif #ifdef _SC_WORD_BIT log_std(("os: sysconf(_SC_WORD_BIT) %ld\n", sysconf(_SC_WORD_BIT))); #endif #endif #ifdef _POSIX_PRIORITY_SCHEDULING /* OSDEF Check for POSIX scheduling */ log_std(("os: scheduling available\n")); #else log_std(("os: scheduling NOT available\n")); #endif /* print the compiler version */ #if defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__GNUC_PATCHLEVEL__) /* OSDEF Detect compiler version */ #define COMPILER_RESOLVE(a) #a #define COMPILER(a, b, c) COMPILER_RESOLVE(a) "." COMPILER_RESOLVE(b) "." COMPILER_RESOLVE(c) log_std(("os: compiler GNU %s\n", COMPILER(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__))); #else log_std(("os: compiler unknown\n")); #endif /* check for int size */ if (sizeof(uint8) != 1) { target_err("The program is compiled with invalid uint8 type.\n"); return -1; } if (sizeof(uint16) != 2) { target_err("The program is compiled with invalid uint16 type.\n"); return -1; } if (sizeof(uint32) != 4) { target_err("The program is compiled with invalid uint32 type.\n"); return -1; } if (sizeof(uint64) != 8) { target_err("The program is compiled with invalid uint64 type.\n"); return -1; } /* check for the endianess */ #ifdef USE_MSB log_std(("os: compiled big endian system\n")); if (memcmp(endian, &endian_big, 4) != 0) { target_err("The program is compiled as bigendian but system doesn't appear to be bigendian.\n"); return -1; } #endif #ifdef USE_LSB log_std(("os: compiled little endian system\n")); if (memcmp(endian, &endian_little, 4) != 0) { target_err("The program is compiled as littleendian but system doesn't appear to be littleendian.\n"); return -1; } #endif #ifdef USE_SMP /* check the thread support */ if (os_thread() != 0) { target_err("Error on the threading support.\n"); return -1; } #endif /* get DISPLAY environment variable */ display = getenv("DISPLAY"); if (display) log_std(("os: DISPLAY=%s\n", display)); else log_std(("os: DISPLAY undef\n")); /* probe the delay system */ os_delay(); if (!os_internal_wm_active()) { log_std(("os: save term\n")); if (tcgetattr(fileno(stdin), &OS.term) != 0) { log_std(("ERROR:os: error getting the tty state.\n")); OS.term_active = 0; } else { OS.term_active = 1; } } #if defined(USE_X) OS.x_active = 0; { int event_base, error_base; int major_version, minor_version; log_std(("os: XOpenDisplay()\n")); OS.dga_display = XOpenDisplay(0); if (OS.dga_display) { OS.x_active = 1; } else { log_std(("WARNING:os: XOpenDisplay() failed. All the X drivers will be disabled.\n")); } } #endif #if defined(USE_SVGALIB) OS.svgalib_active = 0; if (!os_internal_wm_active()) { int h; log_std(("os: open /dev/svga\n")); /* try opening the device, otherwise vga_init() will abort the program. */ h = open("/dev/svga", O_RDWR); if (h >= 0) { int res; close(h); vga_disabledriverreport(); /* check the version of the SVGALIB */ res = vga_setmode(-1); if (res < 0 || res < 0x1911) { /* 1.9.11 */ log_std(("WARNING:os: invalid SVGALIB version %x. All the SVGALIB drivers will be disabled.\n", (int)res)); /* don't print the message. It may be a normal condition. */ /* target_nfo("Invalid SVGALIB version, you need SVGALIB version 1.9.x or 2.0.x.\nPlease upgrade or recompile without SVGALIB support.\n"); */ } else { log_std(("os: vga_init()\n")); if (vga_init() != 0) { log_std(("os: vga_init() failed\n")); target_err("Error initializing the SVGALIB video support.\n"); return -1; } OS.svgalib_active = 1; } } else { log_std(("WARNING:os: open /dev/svga failed. All the SVGALIB drivers will be disabled.\n")); /* don't print the message. It may be a normal condition. */ /* target_nfo("Error opening the SVGALIB device /dev/svga.\n"); */ } } else { log_std(("WARNING:os: vga_init() skipped because X is active. All the SVGALIB drivers will be disabled.\n")); /* don't print the message. It may be a normal condition. */ /* target_nfo("SVGALIB not initialized because it's unusable in X.\n"); */ } #endif #if defined(USE_SDL) log_std(("os: SDL_Init(SDL_INIT_NOPARACHUTE)\n")); if (SDL_Init(SDL_INIT_NOPARACHUTE) != 0) { log_std(("os: SDL_Init() failed, %s\n", SDL_GetError())); target_err("Error initializing the SDL video support.\n"); return -1; } OS.sdl_active = 1; SDL_VERSION(&compiled); log_std(("os: compiled with sdl %d.%d.%d\n", compiled.major, compiled.minor, compiled.patch)); log_std(("os: linked with sdl %d.%d.%d\n", SDL_Linked_Version()->major, SDL_Linked_Version()->minor, SDL_Linked_Version()->patch)); #ifdef USE_MSB if (SDL_BYTEORDER != SDL_BIG_ENDIAN) { target_err("Invalid SDL endianess.\n"); return -1; } #endif #ifdef USE_LSB if (SDL_BYTEORDER != SDL_LIL_ENDIAN) { target_err("Invalid SDL endianess.\n"); return -1; } #endif #endif #if defined(USE_SLANG) OS.slang_active = 0; if (!os_internal_wm_active()) { log_std(("os: SLtt_get_terminfo()\n")); SLtt_get_terminfo(); log_std(("os: SLsmg_init_smg()\n")); SLsmg_init_smg(); OS.slang_active = 1; } else { log_std(("WARNING:os: SLang_init_tty() skipped because X is active. All the SLang drivers will be disabled.\n")); } #endif #if defined(USE_CURSES) OS.curses_active = 0; if (!os_internal_wm_active()) { log_std(("os: initscr()\n")); initscr(); start_color(); cbreak(); noecho(); nonl(); OS.curses_active = 1; } else { log_std(("WARNING:os: curses initscr() skipped because X is active. All the curses drivers will be disabled.\n")); } #endif /* set the titlebar */ sncpy(OS.title_buffer, sizeof(OS.title_buffer), title); /* set some signal handlers */ /* STANDARD signals */ term_action.sa_handler = (void (*)(int))os_signal; /* block external generated signals in the signal handler */ sigemptyset(&term_action.sa_mask); sigaddset(&term_action.sa_mask, SIGALRM); sigaddset(&term_action.sa_mask, SIGINT); sigaddset(&term_action.sa_mask, SIGTERM); sigaddset(&term_action.sa_mask, SIGHUP); sigaddset(&term_action.sa_mask, SIGQUIT); term_action.sa_flags = SA_RESTART | SA_SIGINFO; /* external generated */ sigaction(SIGALRM, &term_action, 0); sigaction(SIGINT, &term_action, 0); sigaction(SIGTERM, &term_action, 0); /* internal generated */ sigaction(SIGABRT, &term_action, 0); sigaction(SIGFPE, &term_action, 0); sigaction(SIGILL, &term_action, 0); sigaction(SIGSEGV, &term_action, 0); sigaction(SIGBUS, &term_action, 0); /* HUP signal */ hup_action.sa_handler = os_hup_signal; sigemptyset(&hup_action.sa_mask); hup_action.sa_flags = SA_RESTART; sigaction(SIGHUP, &hup_action, 0); /* QUIT signal */ quit_action.sa_handler = os_quit_signal; sigemptyset(&quit_action.sa_mask); quit_action.sa_flags = SA_RESTART; sigaction(SIGQUIT, &quit_action, 0); /* PIPE signal, ignoring it force some functions to */ /* return with error. It happen for example on the LCD sockets. */ pipe_action.sa_handler = SIG_IGN; sigemptyset(&pipe_action.sa_mask); pipe_action.sa_flags = SA_RESTART; sigaction(SIGPIPE, &pipe_action, 0); return 0; }
/** * \brief Checkes calls with invalid input to SDL_BuildAudioCVT * * \sa https://wiki.libsdl.org/SDL_BuildAudioCVT */ int audio_buildAudioCVTNegative() { const char *expectedError = "Parameter 'cvt' is invalid"; const char *error; int result; SDL_AudioCVT cvt; SDL_AudioSpec spec1; SDL_AudioSpec spec2; int i; char message[256]; /* Valid format */ spec1.format = AUDIO_S8; spec1.channels = 1; spec1.freq = 22050; spec2.format = AUDIO_S16LSB; spec2.channels = 2; spec2.freq = 44100; SDL_ClearError(); SDLTest_AssertPass("Call to SDL_ClearError()"); /* NULL input for CVT buffer */ result = SDL_BuildAudioCVT((SDL_AudioCVT *)NULL, spec1.format, spec1.channels, spec1.freq, spec2.format, spec2.channels, spec2.freq); SDLTest_AssertPass("Call to SDL_BuildAudioCVT(NULL,...)"); SDLTest_AssertCheck(result == -1, "Verify result value; expected: -1, got: %i", result); error = SDL_GetError(); SDLTest_AssertPass("Call to SDL_GetError()"); SDLTest_AssertCheck(error != NULL, "Validate that error message was not NULL"); if (error != NULL) { SDLTest_AssertCheck(SDL_strcmp(error, expectedError) == 0, "Validate error message, expected: '%s', got: '%s'", expectedError, error); } /* Invalid conversions */ for (i = 1; i < 64; i++) { /* Valid format to start with */ spec1.format = AUDIO_S8; spec1.channels = 1; spec1.freq = 22050; spec2.format = AUDIO_S16LSB; spec2.channels = 2; spec2.freq = 44100; SDL_ClearError(); SDLTest_AssertPass("Call to SDL_ClearError()"); /* Set various invalid format inputs */ SDL_strlcpy(message, "Invalid: ", 256); if (i & 1) { SDL_strlcat(message, " spec1.format", 256); spec1.format = 0; } if (i & 2) { SDL_strlcat(message, " spec1.channels", 256); spec1.channels = 0; } if (i & 4) { SDL_strlcat(message, " spec1.freq", 256); spec1.freq = 0; } if (i & 8) { SDL_strlcat(message, " spec2.format", 256); spec2.format = 0; } if (i & 16) { SDL_strlcat(message, " spec2.channels", 256); spec2.channels = 0; } if (i & 32) { SDL_strlcat(message, " spec2.freq", 256); spec2.freq = 0; } SDLTest_Log("%s", message); result = SDL_BuildAudioCVT(&cvt, spec1.format, spec1.channels, spec1.freq, spec2.format, spec2.channels, spec2.freq); SDLTest_AssertPass("Call to SDL_BuildAudioCVT(spec1 ==> spec2)"); SDLTest_AssertCheck(result == -1, "Verify result value; expected: -1, got: %i", result); error = SDL_GetError(); SDLTest_AssertPass("Call to SDL_GetError()"); SDLTest_AssertCheck(error != NULL && error[0] != '\0', "Validate that error message was not NULL or empty"); } SDL_ClearError(); SDLTest_AssertPass("Call to SDL_ClearError()"); return TEST_COMPLETED; }
int SDL_SetError(const char *fmt, ...) { va_list ap; SDL_error *error; /* Ignore call if invalid format pointer was passed */ if (fmt == NULL) return -1; /* Copy in the key, mark error as valid */ error = SDL_GetErrBuf(); error->error = 1; SDL_strlcpy((char *) error->key, fmt, sizeof(error->key)); va_start(ap, fmt); error->argc = 0; while (*fmt) { if (*fmt++ == '%') { while (*fmt == '.' || (*fmt >= '0' && *fmt <= '9')) { ++fmt; } switch (*fmt++) { case 0: /* Malformed format string.. */ --fmt; break; case 'c': case 'i': case 'd': case 'u': case 'o': case 'x': case 'X': error->args[error->argc++].value_i = va_arg(ap, int); break; case 'f': error->args[error->argc++].value_f = va_arg(ap, double); break; case 'p': error->args[error->argc++].value_ptr = va_arg(ap, void *); break; case 's': { int i = error->argc; const char *str = va_arg(ap, const char *); if (str == NULL) str = "(null)"; SDL_strlcpy((char *) error->args[i].buf, str, ERR_MAX_STRLEN); error->argc++; } break; default: break; } if (error->argc >= ERR_MAX_ARGS) { break; } } } va_end(ap); /* If we are in debug mode, print out an error message */ SDL_LogError(SDL_LOG_CATEGORY_ERROR, "%s", SDL_GetError()); return -1; }
bool CA2_Inicia() { // Testa se já inicializou ou não if(CA2_inicializado) return true; // Limpa as variáveis CA2_Reset(); // Testa se já foi inicializado o vídeo (se não foi, cai fora!) if(SDL_WasInit(SDL_INIT_AUDIO)) return false; // Inicia a parte de áudio da SDL if (SDL_InitSubSystem(SDL_INIT_AUDIO) < 0) { printf("Não conseguiu iniciar a Chien Audio 2 (subseistema SDL). Erro do sistema: %s\n", SDL_GetError()); return false; } // Abre o sistema de mixagem if(Mix_OpenAudio(44100, AUDIO_S16SYS, 2, CA2_BUFFER_MIXER) < 0) { // Fecha o áudio da SDL SDL_QuitSubSystem(SDL_INIT_AUDIO); printf("Não conseguiu iniciar a Chien Audio 2 (formato de áudio). Erro do sistema: %s\n", SDL_GetError()); return false; } // Indica que está inicializado e retorna CA2_inicializado = true; // Ajusta o volume no máximo (default) CA2_AjustaVolume(100, 100); lTela = screen->w; return true; }
bool Drawable::loadFromRenderedText( std::string textureText, SDL_Color textColor ) { //Get rid of preexisting texture free(); TTF_Font * gFont = TTF_OpenFont(GlobalDefs::getResource(RESOURCE_FONT, "zorque.ttf").c_str(),40); //Render text surface SDL_Surface* textSurface = TTF_RenderText_Solid( gFont, textureText.c_str(), textColor ); TTF_CloseFont(gFont); if( textSurface == NULL ) { printf( "Unable to render text surface! SDL_ttf Error: %s\n", TTF_GetError() ); } else { //Create texture from surface pixels mTexture = SDL_CreateTextureFromSurface( renderer, textSurface ); if( mTexture == NULL ) { printf( "Unable to create texture from rendered text! SDL Error: %s\n", SDL_GetError() ); } else { //Get image dimensions image_size = {textSurface->w, textSurface->h}; render_size = image_size; } //Get rid of old surface SDL_FreeSurface( textSurface ); } //Return success return mTexture != NULL; }
std::string SDLAPI::getError() { return "Error: " + std::string(SDL_GetError()); }
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; }
/* =============== IN_InitJoystick =============== */ static void IN_InitJoystick( void ) { int i = 0; int total = 0; char buf[16384] = ""; if (stick != NULL) SDL_JoystickClose(stick); stick = NULL; memset(&stick_state, '\0', sizeof (stick_state)); if (!SDL_WasInit(SDL_INIT_JOYSTICK)) { Com_DPrintf("Calling SDL_Init(SDL_INIT_JOYSTICK)...\n"); if (SDL_Init(SDL_INIT_JOYSTICK) == -1) { Com_DPrintf("SDL_Init(SDL_INIT_JOYSTICK) failed: %s\n", SDL_GetError()); return; } Com_DPrintf("SDL_Init(SDL_INIT_JOYSTICK) passed.\n"); } total = SDL_NumJoysticks(); Com_DPrintf("%d possible joysticks\n", total); // Print list and build cvar to allow ui to select joystick. for (i = 0; i < total; i++) { Q_strcat(buf, sizeof(buf), SDL_JoystickName(i)); Q_strcat(buf, sizeof(buf), "\n"); } Cvar_Get( "in_availableJoysticks", buf, CVAR_ROM ); if( !in_joystick->integer ) { Com_DPrintf( "Joystick is not active.\n" ); SDL_QuitSubSystem(SDL_INIT_JOYSTICK); return; } in_joystickNo = Cvar_Get( "in_joystickNo", "0", CVAR_ARCHIVE ); if( in_joystickNo->integer < 0 || in_joystickNo->integer >= total ) Cvar_Set( "in_joystickNo", "0" ); in_joystickUseAnalog = Cvar_Get( "in_joystickUseAnalog", "0", CVAR_ARCHIVE ); stick = SDL_JoystickOpen( in_joystickNo->integer ); if (stick == NULL) { Com_DPrintf( "No joystick opened.\n" ); return; } Com_DPrintf( "Joystick %d opened\n", in_joystickNo->integer ); Com_DPrintf( "Name: %s\n", SDL_JoystickName(in_joystickNo->integer) ); Com_DPrintf( "Axes: %d\n", SDL_JoystickNumAxes(stick) ); Com_DPrintf( "Hats: %d\n", SDL_JoystickNumHats(stick) ); Com_DPrintf( "Buttons: %d\n", SDL_JoystickNumButtons(stick) ); Com_DPrintf( "Balls: %d\n", SDL_JoystickNumBalls(stick) ); Com_DPrintf( "Use Analog: %s\n", in_joystickUseAnalog->integer ? "Yes" : "No" ); SDL_JoystickEventState(SDL_QUERY); }
int main(int argc, char *argv[]) { int retval = 0; struct sigaction l_SSa; SDL_Event l_SEvent; /* Open file. Because this is just a example we asume What you are doing and give file first argument */ if (! (m_SInfile = sf_open(argv[1], SFM_READ, &m_SSinfo))) { fprintf (stderr, "main: Not able to open input file %s.\n", argv[1]) ; sf_perror (NULL) ; return 1 ; } printf("Opened file: (%s)\n", argv[1]); l_SSa.sa_flags = SA_SIGINFO; sigemptyset(&l_SSa.sa_mask); l_SSa.sa_sigaction = handler; if (sigaction(SIGINT, &l_SSa, NULL) == -1) { fprintf(stderr, "main: Can't set SIGINT handler!\n"); sf_close(m_SInfile); return -1; } if (sigaction(SIGHUP, &l_SSa, NULL) == -1) { fprintf(stderr, "main: Can't set SIGHUP handler!\n"); sf_close(m_SInfile); goto exit; } /* SDL initialize */ if(SDL_Init(SDL_INIT_AUDIO | SDL_INIT_TIMER)) { fprintf(stderr, "main: Could not initialize SDL - %s\n", SDL_GetError()); goto exit; } printf("We have samplerate: %5d and channels %2d\n", m_SSinfo.samplerate, m_SSinfo.channels); if( m_SSinfo.format & SF_FORMAT_PCM_S8 ) { printf("Subformat: 8-bit!\n"); } else if( m_SSinfo.format & SF_FORMAT_PCM_16 ) { printf("Subformat: 16-bit!\n"); } else if( m_SSinfo.format & SF_FORMAT_PCM_24 ) { printf("Subformat: 24-bit!\n"); } else if( m_SSinfo.format & SF_FORMAT_PCM_32 ) { printf("Subformat: 32-bit!\n"); } else if( m_SSinfo.format & SF_FORMAT_FLOAT ) { printf("Subformat: FLOAT!\n"); } else if( m_SSinfo.format & SF_FORMAT_DOUBLE ) { printf("Subformat: DOUBLE!\n"); } SDL_zero(m_SWantedSpec); SDL_zero(m_SSDLspec); m_SWantedSpec.freq = m_SSinfo.samplerate; #if SDL_MAJOR_VERSION == 2 m_SWantedSpec.format = AUDIO_F32LSB; #else m_SWantedSpec.format = AUDIO_S16LSB; #endif m_SWantedSpec.channels = m_SSinfo.channels; m_SWantedSpec.silence = 0; m_SWantedSpec.samples = 1024; m_SWantedSpec.callback = sdlLibsndfileCb; m_SWantedSpec.userdata = m_SInfile; if(SDL_OpenAudio(&m_SWantedSpec, &m_SSDLspec) < 0) { fprintf(stderr, "main: SDL_OpenAudio: %s\n", SDL_GetError()); goto exit; } SDL_PauseAudio(0); atexit(SDL_Quit); /* Loop until we exit */ while(!l_iLoop) { SDL_PollEvent(&l_SEvent); } exit: /* clean up and disconnect */ printf("\nExit and clean\n"); sf_close(m_SInfile); m_SInfile = NULL; return retval; }
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; }
// Loads a texture bool Object3D::loadTexture(GLuint& index,const char* path,GLuint type,GLuint clamp,bool mipmap) { SDL_Surface *img; img = SDL_LoadBMP(path); if (img == NULL) { std::cout << "Unable to load bitmap :" << SDL_GetError() << std::endl; return false; } // converts from BGR to RGB if ((type == GL_RGB)||(type == GL_RGBA)) { const int offset = (type == GL_RGB ? 3 : 4); unsigned char* iterator = static_cast<unsigned char*>(img->pixels); unsigned char *tmp0,*tmp1; for (int i = 0; i < img->w * img->h; ++i) { tmp0 = iterator; tmp1 = iterator + 2; std::swap(*tmp0,*tmp1); iterator += offset; } } glGenTextures(1,&index); glBindTexture(GL_TEXTURE_2D,index); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,clamp); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,clamp); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); if (mipmap) { glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_LINEAR); gluBuild2DMipmaps(GL_TEXTURE_2D, type, img->w, img->h, type, GL_UNSIGNED_BYTE, img->pixels); } else { glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, type, img->w, img->h, 0, type, GL_UNSIGNED_BYTE, img->pixels); } SDL_FreeSurface(img); return true; }
static PyObject* get_error (PyObject* self) { return Text_FromUTF8 (SDL_GetError ()); }
int main (int argc, char* argv[]) { /* Current video settings. */ const SDL_VideoInfo* info = NULL; int width = 0; int height = 0; int bpp = 0; int flags = 0; if (SDL_Init(SDL_INIT_VIDEO) < 0) { fprintf(stderr, "Video initialization failed: %s\n", SDL_GetError()); quit(1); } info = SDL_GetVideoInfo(); if (!info) { fprintf(stderr, "Video query failed: %s\n", SDL_GetError()); quit(1); } width = 640;//1366; height = 480;//768; bpp = info->vfmt->BitsPerPixel; /* We want *at least* 5 bits of red, green * and blue. We also want at least a 16-bit * depth buffer. * * The last thing we do is request a double * buffered window. '1' turns on double * buffering, '0' turns it off. */ SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); /* EXERCISE: * Handle the resize events properly with * glViewport. */ flags = SDL_OPENGL | SDL_SWSURFACE; //flags = SDL_OPENGL | SDL_FULLSCREEN; if (SDL_SetVideoMode(width, height, bpp, flags) == 0) { /* * This could happen for a variety of reasons, * including DISPLAY not being set, the specified * resolution not being available, etc. */ fprintf (stderr, "Video mode set failed: %s\n", SDL_GetError()); quit(1); } setup_opengl(width, height); /* Event loop. */ int time; while(1) { time = SDL_GetTicks(); process_events(); draw_screen(); printf("\r%.2f FPS ", 1000.0 / (SDL_GetTicks() - time)); if (time % 8 == 1) { fflush(stdout); } } /* * EXERCISE: * Record timings using SDL_GetTicks() and * and print out frames per second at program * end. */ return 0; }
int main(int argc, char* argv[]) { //Check for arguments if(argc < 4) { printf("Usage: %s <userName> <passWord> <CDKey>\n", argv[0]); exit(0); } //Initialize pointers to arguments with reasonable names char* uName = argv[1]; char* pWord = argv[2]; char* key = argv[3]; //Get the current time, to be used later unsigned int currTime = time(NULL); //unsigned int currTime = 1369345567; //Get the length of the two arguments, plus two for underscores int len = strlen(uName) + strlen(pWord) + 2; //Add 10 for the length of the time, 1 for the null-term int maxLen = len + 11; //Get some space for our (xor'd) string char* tokenStr = (char*) malloc(maxLen * sizeof(char)); //Set up a count var for later int count; //And a socket file descriptor int sock; //Memory for connecting to the server struct sockaddr_in; struct in_addr; struct addrinfo hints; struct addrinfo* results; char readBuff[4096]; //Our game server is at genericgameserver.com on port 12345 char* hostName = "genericgameserver.com"; char* port = "12345"; //This will hold our version of the hash: char oData[SHA256_DIGEST_LENGTH]; //get the length of the expected message: int msgLen = 1 + strlen(key) + 11; //This will hold our plaintext: char* oMsgBuff; //Build the plaintext string: snprintf(tokenStr, maxLen, "%s_%s_%d", uName, pWord, currTime); //'encrypt' the string with our CD key, keeping the null term for(count = 0; count < maxLen - 1; count ++) { tokenStr[count] = tokenStr[count] ^ key[count]; } //Null out the hints structure, as we don't know anything yet: memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_DGRAM; hints.ai_protocol = 0; getaddrinfo(hostName, port, &hints, &results); sock = socket(results->ai_family, results->ai_socktype, results->ai_protocol); if(sock < 0) { perror("Couldn't create socket"); exit(2); } //Connect to the server, or die trying if(connect(sock, results->ai_addr, results->ai_addrlen) < 0) { perror("Couldn't connect"); exit(1); } //We're connected, write our message write(sock, tokenStr, maxLen - 1); //Now, read from the socket: read(sock, readBuff, 4096); //Allocate our plaintext memory, then build it in: oMsgBuff = (char*) malloc(sizeof(unsigned char) * msgLen); snprintf(oMsgBuff, msgLen, "%d_%s", currTime, key); //Hashing related things: SHA256((unsigned const char*) oMsgBuff, strlen(oMsgBuff), (unsigned char*) oData); for(count = 0; count < SHA256_DIGEST_LENGTH; count ++) { if(oData[count] != readBuff[count]) { break; } } if(count == SHA256_DIGEST_LENGTH) { //Play "Game" //Initialize SDL: if(SDL_Init(SDL_INIT_VIDEO) < 0) { fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError()); exit(1); } SDL_Surface *screen; screen = SDL_SetVideoMode(300, 300, 16, SDL_SWSURFACE); if(screen == NULL) { fprintf(stderr, "Unable to set screen: %s\n", SDL_GetError()); exit(2); } //This will be be a rectangle describing the screen, a 300x300 px box SDL_Rect screenRect; screenRect.x = screenRect.y = 0; screenRect.w = screenRect.h = 300; Uint32 black = SDL_MapRGB(screen->format, 0,0,0); Uint32 white = SDL_MapRGB(screen->format, 0xFF,0xFF,0xFF); SDL_FillRect(screen, &screenRect, black); int h; int bl = 165; int tl = 135; int tmpx, tmpy; //Character spacing int chrSpc = 10; h = bl - tl; SDL_Rect lr; lr.h = lr.w = 3; lr.x = 10; //Draw the letters: //m for(lr.y = tl; lr.y < bl; lr.y ++) { SDL_FillRect(screen, &lr, white); } for(lr.y = tl; lr.y < h / 2 + tl; lr.y ++) { lr.x ++; SDL_FillRect(screen, &lr, white); } for(; lr.y > tl; lr.y --) { lr.x ++; SDL_FillRect(screen, &lr, white); } for(lr.y = tl; lr.y < bl; lr.y ++) { SDL_FillRect(screen, &lr, white); } lr.x += chrSpc; //C tmpx = lr.x; for(lr.y = tl + h/2; lr.y < bl; lr.y ++) { lr.x ++; SDL_FillRect(screen, &lr, white); } lr.x = tmpx; for(lr.y = tl + h/2; lr.y > tl; lr.y --) { lr.x ++; SDL_FillRect(screen, &lr, white); } lr.x += chrSpc; //A for(lr.y = bl; lr.y > tl; lr.y -= 2) { lr.x ++; SDL_FillRect(screen, &lr, white); if(lr.y <= tl + h/2) { tmpy = lr.y; lr.y = tl + h/2; SDL_FillRect(screen, &lr, white); lr.y = tmpy; } } for(lr.y = tl; lr.y < bl; lr.y += 2) { lr.x ++; SDL_FillRect(screen, &lr, white); if(lr.y <= bl - h/2) { tmpy = lr.y; lr.y = tl + h/2; SDL_FillRect(screen, &lr, white); lr.y = tmpy; } } lr.x += chrSpc; //- tmpx = lr.x; for(lr.y = tl + h/2; lr.x < tmpx + chrSpc; lr.x ++) { SDL_FillRect(screen, &lr, white); } lr.x += chrSpc; //1 for(lr.y = tl; lr.y < bl; lr.y ++) { SDL_FillRect(screen, &lr, white); } lr.x += chrSpc; //2 //A 2 is a backwards C plus a straight line on the bottom: tmpx = lr.x; for(lr.y = bl; lr.y > tl + h/2; lr.y --) { lr.x ++; SDL_FillRect(screen, &lr, white); tmpy = lr.y; lr.y = bl; SDL_FillRect(screen, &lr, white); lr.y = tmpy; } lr.x = tmpx; for(lr.y = tl; lr.y < tl + h/2; lr.y ++) { lr.x ++; SDL_FillRect(screen, &lr, white); } lr.x += chrSpc; //1 for(lr.y = tl; lr.y < bl; lr.y ++) { SDL_FillRect(screen, &lr, white); } lr.x += chrSpc; //C tmpx = lr.x; for(lr.y = tl + h/2; lr.y < bl; lr.y ++) { lr.x ++; SDL_FillRect(screen, &lr, white); } lr.x = tmpx; for(lr.y = tl + h/2; lr.y > tl; lr.y --) { lr.x ++; SDL_FillRect(screen, &lr, white); } lr.x += chrSpc; //4 for(lr.y = tl; lr.y < tl + h/2; lr.y ++) SDL_FillRect(screen, &lr, white); tmpx = lr.x; for(; lr.x < tmpx + chrSpc; lr.x ++) SDL_FillRect(screen, &lr, white); for(lr.y = tl; lr.y < bl; lr.y ++) { SDL_FillRect(screen, &lr, white); } lr.x += chrSpc; //1 for(lr.y = tl; lr.y < bl; lr.y ++) { SDL_FillRect(screen, &lr, white); } lr.x += chrSpc; //2 tmpx = lr.x; for(lr.y = bl; lr.y > tl + h/2; lr.y --) { lr.x ++; SDL_FillRect(screen, &lr, white); tmpy = lr.y; lr.y = bl; SDL_FillRect(screen, &lr, white); lr.y = tmpy; } lr.x = tmpx; for(lr.y = tl; lr.y < tl + h/2; lr.y ++) { lr.x ++; SDL_FillRect(screen, &lr, white); } lr.x += chrSpc; //D //A D is a backwards C with a line on the left for(lr.y = tl; lr.y < bl; lr.y ++) { SDL_FillRect(screen, &lr, white); } tmpx = lr.x; for(lr.y = bl; lr.y > tl + h/2; lr.y --) { lr.x ++; SDL_FillRect(screen, &lr, white); } lr.x = tmpx; for(lr.y = tl; lr.y < tl + h/2; lr.y ++) { lr.x ++; SDL_FillRect(screen, &lr, white); } lr.x += chrSpc; lr.y = 0; lr.w = 1; lr.h = 300; for(lr.x = 0; lr.x < 300; lr.x ++) { SDL_UpdateRect(screen, lr.x, lr.y, lr.w, lr.h); usleep(1000); } sleep(3); } else { printf("Error: Incorrect authentication. Please run this program with"); printf(" the correct auth info.\n"); } freeaddrinfo(results); free(tokenStr); free(oMsgBuff); return 0; }
SDLWindow::SDLWindow (Application* application, int width, int height, int flags, const char* title) { currentApplication = application; this->flags = flags; int sdlFlags = 0; if (flags & WINDOW_FLAG_FULLSCREEN) sdlFlags |= SDL_WINDOW_FULLSCREEN_DESKTOP; if (flags & WINDOW_FLAG_RESIZABLE) sdlFlags |= SDL_WINDOW_RESIZABLE; if (flags & WINDOW_FLAG_BORDERLESS) sdlFlags |= SDL_WINDOW_BORDERLESS; if (flags & WINDOW_FLAG_HARDWARE) { sdlFlags |= SDL_WINDOW_OPENGL; //sdlFlags |= SDL_WINDOW_ALLOW_HIGHDPI; #if defined (HX_WINDOWS) && defined (NATIVE_TOOLKIT_SDL_ANGLE) SDL_GL_SetAttribute (SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); SDL_GL_SetAttribute (SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute (SDL_GL_CONTEXT_MINOR_VERSION, 0); SDL_SetHint (SDL_HINT_VIDEO_WIN_D3DCOMPILER, "d3dcompiler_47.dll"); #endif if (flags & WINDOW_FLAG_DEPTH_BUFFER) { SDL_GL_SetAttribute (SDL_GL_DEPTH_SIZE, 32 - (flags & WINDOW_FLAG_STENCIL_BUFFER) ? 8 : 0); } if (flags & WINDOW_FLAG_STENCIL_BUFFER) { SDL_GL_SetAttribute (SDL_GL_STENCIL_SIZE, 8); } if (flags & WINDOW_FLAG_HW_AA_HIRES) { SDL_GL_SetAttribute (SDL_GL_MULTISAMPLEBUFFERS, true); SDL_GL_SetAttribute (SDL_GL_MULTISAMPLESAMPLES, 4); } else if (flags & WINDOW_FLAG_HW_AA) { SDL_GL_SetAttribute (SDL_GL_MULTISAMPLEBUFFERS, true); SDL_GL_SetAttribute (SDL_GL_MULTISAMPLESAMPLES, 2); } } sdlWindow = SDL_CreateWindow (title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, sdlFlags); if (!sdlWindow) { printf ("Could not create SDL window: %s.\n", SDL_GetError ()); } ((SDLApplication*)currentApplication)->RegisterWindow (this); #ifdef HX_WINDOWS HINSTANCE handle = ::GetModuleHandle (nullptr); HICON icon = ::LoadIcon (handle, MAKEINTRESOURCE (1)); if (icon != nullptr) { SDL_SysWMinfo wminfo; SDL_VERSION (&wminfo.version); if (SDL_GetWindowWMInfo (sdlWindow, &wminfo) == 1) { HWND hwnd = wminfo.info.win.window; ::SetClassLong (hwnd, GCL_HICON, reinterpret_cast<LONG>(icon)); } } #endif }
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); } pstrcpy(is->filename, sizeof(is->filename), argv[1]); 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; 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; }