/* =============== GLimp_SetMode =============== */ static int GLimp_SetMode(int mode, qboolean fullscreen, qboolean noborder) { const char *glstring; int perChannelColorBits; int colorBits, depthBits, stencilBits; int samples; int i = 0; SDL_Surface *icon = NULL; Uint32 flags = SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL; SDL_DisplayMode desktopMode; int display = 0; int x = 0, y = 0; Com_Printf( "Initializing OpenGL display\n"); if ( r_allowResize->integer ) flags |= SDL_WINDOW_RESIZABLE; /*icon = SDL_CreateRGBSurfaceFrom( (void *)CLIENT_WINDOW_ICON.pixel_data, CLIENT_WINDOW_ICON.width, CLIENT_WINDOW_ICON.height, CLIENT_WINDOW_ICON.bytes_per_pixel * 8, CLIENT_WINDOW_ICON.bytes_per_pixel * CLIENT_WINDOW_ICON.width, #ifdef Q3_LITTLE_ENDIAN 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000 #else 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF #endif );*/ // If a window exists, note its display index if( screen != NULL ) display = SDL_GetWindowDisplayIndex( screen ); if( SDL_GetDesktopDisplayMode( display, &desktopMode ) == 0 ) { displayAspect = (float)desktopMode.w / (float)desktopMode.h; Com_Printf( "Display aspect: %.3f\n", displayAspect ); } else { memset( &desktopMode, 0, sizeof( SDL_DisplayMode ) ); Com_Printf( "Cannot determine display aspect, assuming 1.333\n" ); } Com_Printf( "...setting mode %d:", mode ); if (mode == -2) { // use desktop video resolution if( desktopMode.h > 0 ) { glConfig.vidWidth = desktopMode.w; glConfig.vidHeight = desktopMode.h; } else { glConfig.vidWidth = 640; glConfig.vidHeight = 480; Com_Printf( "Cannot determine display resolution, assuming 640x480\n" ); } //glConfig.windowAspect = (float)glConfig.vidWidth / (float)glConfig.vidHeight; } else if ( !R_GetModeInfo( &glConfig.vidWidth, &glConfig.vidHeight, /*&glConfig.windowAspect,*/ mode ) ) { Com_Printf( " invalid mode\n" ); return RSERR_INVALID_MODE; } Com_Printf( " %d %d\n", glConfig.vidWidth, glConfig.vidHeight); // Center window if( r_centerWindow->integer && !fullscreen ) { x = ( desktopMode.w / 2 ) - ( glConfig.vidWidth / 2 ); y = ( desktopMode.h / 2 ) - ( glConfig.vidHeight / 2 ); } // Destroy existing state if it exists if( opengl_context != NULL ) { SDL_GL_DeleteContext( opengl_context ); opengl_context = NULL; } if( screen != NULL ) { SDL_GetWindowPosition( screen, &x, &y ); Com_DPrintf( "Existing window at %dx%d before being destroyed\n", x, y ); SDL_DestroyWindow( screen ); screen = NULL; } if( fullscreen ) { flags |= SDL_WINDOW_FULLSCREEN; glConfig.isFullscreen = qtrue; } else { if( noborder ) flags |= SDL_WINDOW_BORDERLESS; glConfig.isFullscreen = qfalse; } colorBits = r_colorbits->value; if ((!colorBits) || (colorBits >= 32)) colorBits = 24; if (!r_depthbits->value) depthBits = 24; else depthBits = r_depthbits->value; stencilBits = r_stencilbits->value; //samples = r_ext_multisample->value; for (i = 0; i < 16; i++) { int testColorBits, testDepthBits, testStencilBits; // 0 - default // 1 - minus colorBits // 2 - minus depthBits // 3 - minus stencil if ((i % 4) == 0 && i) { // one pass, reduce switch (i / 4) { case 2 : if (colorBits == 24) colorBits = 16; break; case 1 : if (depthBits == 24) depthBits = 16; else if (depthBits == 16) depthBits = 8; case 3 : if (stencilBits == 24) stencilBits = 16; else if (stencilBits == 16) stencilBits = 8; } } testColorBits = colorBits; testDepthBits = depthBits; testStencilBits = stencilBits; if ((i % 4) == 3) { // reduce colorBits if (testColorBits == 24) testColorBits = 16; } if ((i % 4) == 2) { // reduce depthBits if (testDepthBits == 24) testDepthBits = 16; else if (testDepthBits == 16) testDepthBits = 8; } if ((i % 4) == 1) { // reduce stencilBits if (testStencilBits == 24) testStencilBits = 16; else if (testStencilBits == 16) testStencilBits = 8; else testStencilBits = 0; } if (testColorBits == 24) perChannelColorBits = 8; else perChannelColorBits = 4; #ifdef __sgi /* Fix for SGIs grabbing too many bits of color */ if (perChannelColorBits == 4) perChannelColorBits = 0; /* Use minimum size for 16-bit color */ /* Need alpha or else SGIs choose 36+ bit RGB mode */ SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, 1); #endif SDL_GL_SetAttribute( SDL_GL_RED_SIZE, perChannelColorBits ); SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, perChannelColorBits ); SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, perChannelColorBits ); SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, testDepthBits ); SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, testStencilBits ); /*SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS, samples ? 1 : 0 ); SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES, samples );*/ if(r_stereo->integer) { glConfig.stereoEnabled = qtrue; SDL_GL_SetAttribute(SDL_GL_STEREO, 1); } else { glConfig.stereoEnabled = qfalse; SDL_GL_SetAttribute(SDL_GL_STEREO, 0); } SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); // If not allowing software GL, demand accelerated if( !r_allowSoftwareGL->integer ) SDL_GL_SetAttribute( SDL_GL_ACCELERATED_VISUAL, 1 ); if( ( screen = SDL_CreateWindow( CLIENT_WINDOW_TITLE, x, y, glConfig.vidWidth, glConfig.vidHeight, flags ) ) == 0 ) { Com_DPrintf( "SDL_CreateWindow failed: %s\n", SDL_GetError( ) ); continue; } if( fullscreen ) { SDL_DisplayMode mode; switch( testColorBits ) { case 16: mode.format = SDL_PIXELFORMAT_RGB565; break; case 24: mode.format = SDL_PIXELFORMAT_RGB24; break; default: Com_DPrintf( "testColorBits is %d, can't fullscreen\n", testColorBits ); continue; } mode.w = glConfig.vidWidth; mode.h = glConfig.vidHeight; mode.refresh_rate = glConfig.displayFrequency = Cvar_VariableIntegerValue( "r_displayRefresh" ); mode.driverdata = NULL; if( SDL_SetWindowDisplayMode( screen, &mode ) < 0 ) { Com_DPrintf( "SDL_SetWindowDisplayMode failed: %s\n", SDL_GetError( ) ); continue; } } SDL_SetWindowTitle( screen, CLIENT_WINDOW_TITLE ); SDL_SetWindowIcon( screen, icon ); if( ( opengl_context = SDL_GL_CreateContext( screen ) ) == NULL ) { Com_Printf( "SDL_GL_CreateContext failed: %s\n", SDL_GetError( ) ); continue; } if( SDL_GL_MakeCurrent( screen, opengl_context ) < 0 ) { Com_Printf( "SDL_GL_MakeCurrent failed: %s\n", SDL_GetError( ) ); continue; } SDL_GL_SetSwapInterval( r_swapInterval->integer ); glConfig.colorBits = testColorBits; glConfig.depthBits = testDepthBits; glConfig.stencilBits = testStencilBits; Com_Printf( "Using %d color bits, %d depth, %d stencil display.\n", glConfig.colorBits, glConfig.depthBits, glConfig.stencilBits ); break; } /*SDL_FreeSurface( icon );*/ GLimp_DetectAvailableModes(); glstring = (char *) qglGetString (GL_RENDERER); Com_Printf( "GL_RENDERER: %s\n", glstring ); return RSERR_OK; #if 0 const char* glstring; int sdlcolorbits; int colorbits, depthbits, stencilbits; int tcolorbits, tdepthbits, tstencilbits; int samples; int i = 0; Uint32 flags = SDL_WINDOW_OPENGL; Com_Printf( "Initializing OpenGL display\n"); if ( r_allowResize->integer ) flags |= SDL_WINDOW_RESIZABLE; if( videoInfo == NULL ) { static SDL_DisplayMode sVideoInfo; static SDL_PixelFormat sPixelFormat; if (SDL_GetCurrentDisplayMode( 0, &sVideoInfo ) < 0) Com_Error(ERR_FATAL, "SDL_GetCurrentDisplayMode failed : %s\n", SDL_GetError()); // Take a copy of the videoInfo sPixelFormat.format = sVideoInfo.format; sPixelFormat.palette = NULL; // Should already be the case //Com_Memcpy( &sVideoInfo, videoInfo, sizeof( SDL_DisplayMode ) ); sVideoInfo.format = sPixelFormat.format; videoInfo = &sVideoInfo; if( videoInfo->h > 0 ) { glConfig.displayWidth = videoInfo->w; glConfig.displayHeight = videoInfo->h; // Guess the display aspect ratio through the desktop resolution // by assuming (relatively safely) that it is set at or close to // the display's native aspect ratio glConfig.displayAspect = (float)videoInfo->w / (float)videoInfo->h; Com_Printf( "Estimated display aspect: %.3f\n", glConfig.displayAspect ); } else { glConfig.displayWidth = 480; glConfig.displayHeight = 640; glConfig.displayAspect = 1.333f; Com_Printf( "Cannot estimate display resolution/aspect, assuming 640x480/1.333\n" ); } } Com_Printf( "...setting mode %d:", mode ); if (mode == -2) { // use desktop video resolution if( videoInfo->h > 0 ) { glConfig.vidWidth = videoInfo->w; glConfig.vidHeight = videoInfo->h; } else { glConfig.vidWidth = 640; glConfig.vidHeight = 480; Com_Printf( "Cannot determine display resolution, assuming 640x480\n" ); } glConfig.displayAspect = (float)glConfig.vidWidth / (float)glConfig.vidHeight; } else if ( !R_GetModeInfo( &glConfig.vidWidth, &glConfig.vidHeight, /*&glConfig.displayAspect,*/ mode ) ) { Com_Printf( " invalid mode\n" ); return RSERR_INVALID_MODE; } Com_Printf( " %d %d\n", glConfig.vidWidth, glConfig.vidHeight); if (fullscreen) { flags |= SDL_WINDOW_FULLSCREEN; glConfig.isFullscreen = qtrue; } else { if (noborder) flags |= SDL_WINDOW_BORDERLESS; glConfig.isFullscreen = qfalse; } colorbits = r_colorbits->value; if ((!colorbits) || (colorbits >= 32)) colorbits = 24; if (!r_depthbits->value) depthbits = 24; else depthbits = r_depthbits->value; stencilbits = r_stencilbits->value; //samples = r_ext_multisample->value; for (i = 0; i < 16; i++) { // 0 - default // 1 - minus colorbits // 2 - minus depthbits // 3 - minus stencil if ((i % 4) == 0 && i) { // one pass, reduce switch (i / 4) { case 2 : if (colorbits == 24) colorbits = 16; break; case 1 : if (depthbits == 24) depthbits = 16; else if (depthbits == 16) depthbits = 8; case 3 : if (stencilbits == 24) stencilbits = 16; else if (stencilbits == 16) stencilbits = 8; } } tcolorbits = colorbits; tdepthbits = depthbits; tstencilbits = stencilbits; if ((i % 4) == 3) { // reduce colorbits if (tcolorbits == 24) tcolorbits = 16; } if ((i % 4) == 2) { // reduce depthbits if (tdepthbits == 24) tdepthbits = 16; else if (tdepthbits == 16) tdepthbits = 8; } if ((i % 4) == 1) { // reduce stencilbits if (tstencilbits == 24) tstencilbits = 16; else if (tstencilbits == 16) tstencilbits = 8; else tstencilbits = 0; } sdlcolorbits = 4; if (tcolorbits == 24) sdlcolorbits = 8; #ifdef __sgi /* Fix for SGIs grabbing too many bits of color */ if (sdlcolorbits == 4) sdlcolorbits = 0; /* Use minimum size for 16-bit color */ /* Need alpha or else SGIs choose 36+ bit RGB mode */ SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, 1); #endif SDL_GL_SetAttribute( SDL_GL_RED_SIZE, sdlcolorbits ); SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, sdlcolorbits ); SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, sdlcolorbits ); SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, tdepthbits ); SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, tstencilbits ); SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS, samples ? 1 : 0 ); SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES, samples ); /*if(r_stereoEnabled->integer) { glConfig.stereoEnabled = qtrue; SDL_GL_SetAttribute(SDL_GL_STEREO, 1); } else {*/ glConfig.stereoEnabled = qfalse; SDL_GL_SetAttribute(SDL_GL_STEREO, 0); //} SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); #if 0 // See http://bugzilla.icculus.org/show_bug.cgi?id=3526 // If not allowing software GL, demand accelerated if( !r_allowSoftwareGL->integer ) { if( SDL_GL_SetAttribute( SDL_GL_ACCELERATED_VISUAL, 1 ) < 0 ) { Com_Printf( "Unable to guarantee accelerated " "visual with libSDL < 1.2.10\n" ); } } #endif if( SDL_GL_SetSwapInterval(r_swapInterval->integer ) < 0 ) Com_Printf( "SDL_GL_SetSwapInterval not supported\n" ); #ifdef USE_ICON { SDL_Surface *icon = SDL_CreateRGBSurfaceFrom( (void *)CLIENT_WINDOW_ICON.pixel_data, CLIENT_WINDOW_ICON.width, CLIENT_WINDOW_ICON.height, CLIENT_WINDOW_ICON.bytes_per_pixel * 8, CLIENT_WINDOW_ICON.bytes_per_pixel * CLIENT_WINDOW_ICON.width, #ifdef Q3_LITTLE_ENDIAN 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000 #else 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF #endif ); SDL_WM_SetIcon( icon, NULL ); SDL_FreeSurface( icon ); } #endif // FIXME: Product name cvar_t *com_productName = Cvar_Get("com_productName", "OpenJK" /* PRODUCT_NAME */, CVAR_ROM); //SDL_SetWindowTitle(com_productName->string, com_productName->string); SDL_ShowCursor(0); if (!(window = SDL_CreateWindow(com_productName->string, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, glConfig.vidWidth, glConfig.vidHeight, flags))) { Com_Printf( "SDL_CreateWindow failed: %s\n", SDL_GetError( ) ); continue; } opengl_context = SDL_GL_CreateContext(window); Com_Printf( "Using %d/%d/%d Color bits, %d depth, %d stencil display.\n", sdlcolorbits, sdlcolorbits, sdlcolorbits, tdepthbits, tstencilbits); glConfig.colorBits = tcolorbits; glConfig.depthBits = tdepthbits; glConfig.stencilBits = tstencilbits; break; } GLimp_DetectAvailableModes(); if (!window) { Com_Printf( "Couldn't get a visual\n" ); return RSERR_INVALID_MODE; } screen = window; // FIXME: Defines needed here glstring = (char *) qglGetString (GL_RENDERER); Com_Printf( "GL_RENDERER: %s\n", glstring ); return RSERR_OK; #endif }
SDL_Surface * SDL_SetVideoMode(int width, int height, int bpp, Uint32 flags) { SDL_DisplayMode desktop_mode; int display = GetVideoDisplay(); int window_x = SDL_WINDOWPOS_UNDEFINED_DISPLAY(display); int window_y = SDL_WINDOWPOS_UNDEFINED_DISPLAY(display); int window_w; int window_h; Uint32 window_flags; Uint32 surface_flags; if (!SDL_GetVideoDevice()) { if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE) < 0) { return NULL; } } SDL_GetDesktopDisplayMode(display, &desktop_mode); if (width == 0) { width = desktop_mode.w; } if (height == 0) { height = desktop_mode.h; } if (bpp == 0) { bpp = SDL_BITSPERPIXEL(desktop_mode.format); } /* See if we can simply resize the existing window and surface */ if (SDL_ResizeVideoMode(width, height, bpp, flags) == 0) { return SDL_PublicSurface; } /* Destroy existing window */ SDL_PublicSurface = NULL; if (SDL_ShadowSurface) { SDL_ShadowSurface->flags &= ~SDL_DONTFREE; SDL_FreeSurface(SDL_ShadowSurface); SDL_ShadowSurface = NULL; } if (SDL_VideoSurface) { SDL_VideoSurface->flags &= ~SDL_DONTFREE; SDL_FreeSurface(SDL_VideoSurface); SDL_VideoSurface = NULL; } if (SDL_VideoContext) { /* SDL_GL_MakeCurrent(0, NULL); *//* Doesn't do anything */ SDL_GL_DeleteContext(SDL_VideoContext); SDL_VideoContext = NULL; } if (SDL_VideoWindow) { SDL_GetWindowPosition(SDL_VideoWindow, &window_x, &window_y); SDL_DestroyWindow(SDL_VideoWindow); } /* Set up the event filter */ if (!SDL_GetEventFilter(NULL, NULL)) { SDL_SetEventFilter(SDL_CompatEventFilter, NULL); } /* Create a new window */ window_flags = SDL_WINDOW_SHOWN; if (flags & SDL_FULLSCREEN) { window_flags |= SDL_WINDOW_FULLSCREEN; } if (flags & SDL_OPENGL) { window_flags |= SDL_WINDOW_OPENGL; } if (flags & SDL_RESIZABLE) { window_flags |= SDL_WINDOW_RESIZABLE; } if (flags & SDL_NOFRAME) { window_flags |= SDL_WINDOW_BORDERLESS; } GetEnvironmentWindowPosition(width, height, &window_x, &window_y); SDL_VideoWindow = SDL_CreateWindow(wm_title, window_x, window_y, width, height, window_flags); if (!SDL_VideoWindow) { return NULL; } SDL_SetWindowIcon(SDL_VideoWindow, SDL_VideoIcon); SetupScreenSaver(flags); window_flags = SDL_GetWindowFlags(SDL_VideoWindow); surface_flags = 0; if (window_flags & SDL_WINDOW_FULLSCREEN) { surface_flags |= SDL_FULLSCREEN; } if ((window_flags & SDL_WINDOW_OPENGL) && (flags & SDL_OPENGL)) { surface_flags |= SDL_OPENGL; } if (window_flags & SDL_WINDOW_RESIZABLE) { surface_flags |= SDL_RESIZABLE; } if (window_flags & SDL_WINDOW_BORDERLESS) { surface_flags |= SDL_NOFRAME; } SDL_VideoFlags = flags; /* If we're in OpenGL mode, just create a stub surface and we're done! */ if (flags & SDL_OPENGL) { SDL_VideoContext = SDL_GL_CreateContext(SDL_VideoWindow); if (!SDL_VideoContext) { return NULL; } if (SDL_GL_MakeCurrent(SDL_VideoWindow, SDL_VideoContext) < 0) { return NULL; } SDL_VideoSurface = SDL_CreateRGBSurfaceFrom(NULL, width, height, bpp, 0, 0, 0, 0, 0); if (!SDL_VideoSurface) { return NULL; } SDL_VideoSurface->flags |= surface_flags; SDL_PublicSurface = SDL_VideoSurface; return SDL_PublicSurface; } /* Create the screen surface */ SDL_WindowSurface = SDL_GetWindowSurface(SDL_VideoWindow); if (!SDL_WindowSurface) { return NULL; } /* Center the public surface in the window surface */ SDL_GetWindowSize(SDL_VideoWindow, &window_w, &window_h); SDL_VideoViewport.x = (window_w - width)/2; SDL_VideoViewport.y = (window_h - height)/2; SDL_VideoViewport.w = width; SDL_VideoViewport.h = height; SDL_VideoSurface = SDL_CreateRGBSurfaceFrom(NULL, 0, 0, 32, 0, 0, 0, 0, 0); SDL_VideoSurface->flags |= surface_flags; SDL_VideoSurface->flags |= SDL_DONTFREE; SDL_FreeFormat(SDL_VideoSurface->format); SDL_VideoSurface->format = SDL_WindowSurface->format; SDL_VideoSurface->format->refcount++; SDL_VideoSurface->w = width; SDL_VideoSurface->h = height; SDL_VideoSurface->pitch = SDL_WindowSurface->pitch; SDL_VideoSurface->pixels = (void *)((Uint8 *)SDL_WindowSurface->pixels + SDL_VideoViewport.y * SDL_VideoSurface->pitch + SDL_VideoViewport.x * SDL_VideoSurface->format->BytesPerPixel); SDL_SetClipRect(SDL_VideoSurface, NULL); /* Create a shadow surface if necessary */ if ((bpp != SDL_VideoSurface->format->BitsPerPixel) && !(flags & SDL_ANYFORMAT)) { SDL_ShadowSurface = SDL_CreateRGBSurface(0, width, height, bpp, 0, 0, 0, 0); if (!SDL_ShadowSurface) { return NULL; } SDL_ShadowSurface->flags |= surface_flags; SDL_ShadowSurface->flags |= SDL_DONTFREE; /* 8-bit SDL_ShadowSurface surfaces report that they have exclusive palette */ if (SDL_ShadowSurface->format->palette) { SDL_ShadowSurface->flags |= SDL_HWPALETTE; SDL_DitherColors(SDL_ShadowSurface->format->palette->colors, SDL_ShadowSurface->format->BitsPerPixel); } SDL_FillRect(SDL_ShadowSurface, NULL, SDL_MapRGB(SDL_ShadowSurface->format, 0, 0, 0)); } SDL_PublicSurface = (SDL_ShadowSurface ? SDL_ShadowSurface : SDL_VideoSurface); ClearVideoSurface(); /* We're finally done! */ return SDL_PublicSurface; }
int main() { FILE *fp = fopen("a.yuv","rb"); char * iter; int i,j; int width, height; if(!fp) perror("No File"); width = 640; height = 480; printf(" Width %d Height %d \n",width,height); unsigned char *y = new unsigned char[width * height *1.5]; int usize = width * height /4 ; unsigned char *u = new unsigned char[usize]; unsigned char* v = new unsigned char[usize]; unsigned char *u_iter = u; unsigned char *v_iter = v; int k=fread(y,1,width*height *1.5,fp); printf(" %x %x %d\n",y[0],y[1],k); // for chroma for (int i=0; i < width *height /4; i+=2) { fread(u_iter++,1,1,fp); fread(v_iter++,1,1,fp); //printf(" %x %x\n",*u_iter,*v_iter); } // init SDL SDL_Surface *screen; // even with SDL2, we can still bring ancient code back SDL_Window *window; SDL_Surface *image; SDL_Renderer *renderer; SDL_Texture *texture; if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) { fprintf(stderr, "Could not initialize SDL - %s\n", SDL_GetError()); exit(1); } // create the window like normal window = SDL_CreateWindow("YUV Display", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, 0); // but instead of creating a renderer, we can draw directly to the screen //screen = SDL_GetWindowSurface(window); renderer = SDL_CreateRenderer(window, -1, 0); if (!renderer) { fprintf(stderr, "SDL: could not create renderer - exiting\n"); exit(1); } // Allocate a place to put our YUV image on that screen texture = SDL_CreateTexture( renderer, SDL_PIXELFORMAT_IYUV, SDL_TEXTUREACCESS_STREAMING, width, height ); if (!texture) { fprintf(stderr, "SDL: could not create texture - exiting\n"); exit(1); } // Cretae window and surface SDL_UpdateYUVTexture( texture, NULL, (unsigned char *)y, width, u, width/2, v, width/2 ); SDL_RenderClear(renderer); SDL_RenderCopy(renderer, texture, NULL, NULL); SDL_RenderPresent(renderer); SDL_Delay(8000); SDL_DestroyWindow(window); SDL_Quit(); // return 0; }
void window_init(void) { // SDL base stuff if (SDL_Init(SDL_INIT_EVERYTHING) < 0) { error(1, SDL_GetError()); } if ((windowMain = SDL_CreateWindow("Engine", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, windowWidth, windowHeight, FLAGS)) == NULL) { error(1, SDL_GetError()); } SDL_SetWindowMinimumSize(windowMain, 100, 100); // Renderer stuff windowMainGLContext = SDL_GL_CreateContext(windowMain); // yes, it's openGL stuff int oglId = -1; int rdnum = SDL_GetNumRenderDrivers(); for (int i=0;i<rdnum;i++) { SDL_RendererInfo info; if (SDL_GetRenderDriverInfo(i, &info)) { continue; } if (!strcmp(info.name, "opengl")) { oglId = i; } } if (oglId == -1) { error(-1, "Cannot find the OpenGL renderer driver."); } if ((windowMainRenderer = SDL_CreateRenderer(windowMain, oglId, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC)) < 0) { error(1, SDL_GetError()); } // OpenGL stuff SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, true); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); if (SDL_GL_SetSwapInterval(17) < 0) { log_write(loggingLevel_warn, "Unable to setup VSync ! %s", SDL_GetError()); } glShadeModel(GL_SMOOTH); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); //glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClearColor(1.0f, 1.0f, 1.0f, 0.0f); glClearDepth(1.0f); glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(fov, (float)windowWidth/(float)windowHeight, 1.0f, 100.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glViewport(0, 0, windowWidth, windowHeight); if (glGetError() != GL_NO_ERROR) { error(glGetError(), "OpenGL error."); } log_write(loggingLevel_debug, "GL version: %s", glGetString(GL_VERSION)); log_write(loggingLevel_debug, "GL vendor: %s", glGetString(GL_VENDOR)); log_write(loggingLevel_debug, "GL renderer: %s", glGetString(GL_RENDERER)); log_write(loggingLevel_debug, "Video driver: %s", SDL_GetCurrentVideoDriver()); // nothing else to do }
/* -------------------------------------------------------------------------------- INIT -------------------------------------------------------------------------------- * Master init function. Being a game made in SDL2, SDL2 and its subsystems * are obviously critical to the functionality of the program. Also, their * initialization is kept here because it's tidier. */ bool init( void ) { /* Init SDL */ if( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_AUDIO ) < 0 ) { printf("ERROR: Could not init SDL. SDL Error: %s\n", SDL_GetError() ); return( false ); } /* Init SDL_image */ if( ( IMG_Init( IMG_INIT_PNG ) & IMG_INIT_PNG ) == false ) { printf("ERROR: Could not init SDL_image. IMG Error: %s\n", IMG_GetError() ); return( false ); } /* Init SDL_mixer */ if( Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 2048 ) < 0 ) { printf("ERROR: Could not init SDL_mixer. Mix Error: %s\n", Mix_GetError() ); return( false ); } /* Init SDL_ttf */ if( TTF_Init() == -1 ) { printf("ERROR: Could not init SDL_ttf. TTF Error: %s\n", TTF_GetError() ); return( false ); } /* Create our window */ gWindow = SDL_CreateWindow( "BELTED (working title)", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WWIDTH, WHEIGHT, SDL_WINDOW_SHOWN ); if( gWindow == NULL ) { printf("ERROR: Could not create window. SDL Error: %s\n", SDL_GetError() ); return( false ); } /* * Create the renderer * * We check for the limiting of FPS as a futureproofing thing. Also, * theoretically a bug-solving or performance thing. */ /* If they want to limit FPS, don't vsync */ if( limitFPS ) gRenderer = SDL_CreateRenderer( gWindow, -1, SDL_RENDERER_ACCELERATED ); /* Otherwise, use vsync */ else { gRenderer = SDL_CreateRenderer( gWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC ); } if( gRenderer == NULL ) { printf("ERROR: Could not create renderer. SDL Error: %s\n", SDL_GetError() ); return( false ); } /* Just for shits and giggles, we'll seed random here */ srand( (unsigned int)time(NULL) ); /* Init boundary dimensions */ BWIDTH = WWIDTH; BHEIGHT = WHEIGHT - 100; /* Init colors */ init_colors(); /* Init blend mode */ SDL_SetRenderDrawBlendMode( gRenderer, SDL_BLENDMODE_BLEND ); /* Init transitions */ init_transition(); /* If we made it this far, we're golden */ return( true ); }
static int sdl_init(void **ctx, platform_params *params, void (*onFrame)(void *), void *user, int audio_only) { *ctx = 0; #ifdef __MINGW32__ putenv("SDL_AUDIODRIVER=winmm"); #endif int flags = audio_only ? SDL_INIT_AUDIO : SDL_INIT_EVERYTHING & ~(SDL_INIT_TIMER | SDL_INIT_HAPTIC); if (SDL_Init(flags) < 0) { printf("error: sdl2 init failed: %s\n", SDL_GetError()); return 0; } #if PLATFORM_SDL platform_ctx *platform = (platform_ctx *)calloc(1, sizeof(platform_ctx)); platform->onFrame = onFrame; platform->user = user; platform->params = params; /*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_ALPHA_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);*/ SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); //SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32); //SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); #ifndef EMSCRIPTEN SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); #endif SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 8); platform->window = SDL_CreateWindow("LVG Player", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 1024, 800, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_SHOWN | SDL_WINDOW_ALLOW_HIGHDPI); if (!platform->window) { SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0); platform->window = SDL_CreateWindow("LVG Player", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 1024, 800, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_SHOWN | SDL_WINDOW_ALLOW_HIGHDPI); if (!platform->window) { printf("error: sdl2 init failed: %s\n", SDL_GetError()); fflush(stdout); sdl_release(platform); return 0; } } platform->context = SDL_GL_CreateContext(platform->window); SDL_GL_MakeCurrent(platform->window, platform->context); #ifndef EMSCRIPTEN if (!gladLoadGLLoader((GLADloadproc)SDL_GL_GetProcAddress)) { printf("error: glad init failed\n"); sdl_release(platform); return 0; } #endif *ctx = platform; #endif return 1; }
void sdl_init(int width, int height, bool fullscreen) { sdlCurrentFrame = sdlNextFrame = 0; int drv_index = -1, it = 0; char rendername[256] = { 0 }; if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS)) { fprintf(stderr, "Could not initialize SDL - %s\n", SDL_GetError()); exit(1); } 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_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1); fullscreen_flags = fullscreen?SDL_WINDOW_FULLSCREEN_DESKTOP:0; window = SDL_CreateWindow("Moonlight", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, SDL_WINDOW_OPENGL | fullscreen_flags); if(!window) { fprintf(stderr, "SDL: could not create window - exiting\n"); exit(1); } SDL_GLContext ctx = SDL_GL_CreateContext(window); SDL_GL_MakeCurrent(window, ctx); glGetStringAPI = (glGetString_Func)SDL_GL_GetProcAddress("glGetString"); for(it = 0; it < SDL_GetNumRenderDrivers(); it++) { SDL_RendererInfo info; SDL_GetRenderDriverInfo(it,&info); strcat(rendername, info.name); strcat(rendername, " "); if(strcmp("opengles2", info.name) == 0) drv_index = it; } fprintf(stdout, "Available Renderers: %s\n", rendername); fprintf(stdout, "Vendor : %s\n", glGetStringAPI(GL_VENDOR)); fprintf(stdout, "Renderer : %s\n", glGetStringAPI(GL_RENDERER)); fprintf(stdout, "Version : %s\n", glGetStringAPI(GL_VERSION)); fprintf(stdout, "Extensions : %s\n", glGetStringAPI(GL_EXTENSIONS)); SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear"); SDL_SetRelativeMouseMode(SDL_TRUE); renderer = SDL_CreateRenderer(window, drv_index, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (!renderer) { printf("SDL_CreateRenderer failed: %s\n", SDL_GetError()); exit(1); } SDL_ShowCursor(SDL_DISABLE); bmp = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_YV12, SDL_TEXTUREACCESS_STREAMING, width, height); if (!bmp) { fprintf(stderr, "SDL: could not create texture - exiting\n"); exit(1); } mutex = SDL_CreateMutex(); if (!mutex) { fprintf(stderr, "Couldn't create mutex\n"); exit(1); } }
int main(int argc, char *argv[]) { int w = 5, h = 5; SDL_Window *window; SDL_Renderer *renderer; SDL_Surface *background; SDL_Rect bg_rect = { 0, 0, 12, 12 }; SDL_Surface *surface; SDL_Rect tgt_rect = { 0, 0, 5, 5 }; Uint32 pf; SDL_Surface *new_surface; SDL_Rect tgt_rect2 = { 6, 0, 5, 5 }; SDL_Texture *bg_tex; Uint32 first_pixel; Uint8 r,g,b,a; Uint32 colour_key; int waiting; SDL_Init(SDL_INIT_VIDEO); window = SDL_CreateWindow("Color key conversion test", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 100, 100, 0); renderer = SDL_CreateRenderer(window, -1, 0); SDL_RenderSetScale(renderer, 8, 8); // create green background surface background = SDL_CreateRGBSurface(0, 12, 12, 32, 0,0,0,0); SDL_FillRect(background, &bg_rect, SDL_MapRGB(background->format, 100,200,100)); // create 16-bit surface surface = SDL_CreateRGBSurfaceFrom(pixel_data, w, h, 16, w*2, 0x0000f800,0x000007e0,0x0000001f,0); SDL_SetColorKey(surface, SDL_TRUE, 0xB54A); // blit original surface to left hand side of background SDL_BlitSurface(surface, NULL, background, &tgt_rect); // convert surface to 32-bit (suitable for window) pf = SDL_GetWindowPixelFormat(window); new_surface = SDL_ConvertSurfaceFormat(surface, pf, 0); // blit converted surface to right hand side SDL_BlitSurface(new_surface, NULL, background, &tgt_rect2); // show everything bg_tex = SDL_CreateTextureFromSurface(renderer, background); SDL_RenderCopy(renderer, bg_tex, NULL, &bg_rect); SDL_RenderPresent(renderer); // print value of first pixel first_pixel = ((Uint32 *) new_surface->pixels)[0]; SDL_GetRGBA(first_pixel, new_surface->format, &r,&g,&b,&a); printf("First pixel = %08x (%d,%d,%d alpha %d)\n", first_pixel, r,g,b,a); // print value of colour key SDL_GetColorKey(new_surface, &colour_key); SDL_GetRGB(colour_key, new_surface->format, &r,&g,&b); printf("colour key = %08x (%d,%d,%d)\n", colour_key, r,g,b); waiting = 1; while (waiting) { SDL_Event evt; SDL_WaitEvent(&evt); if (evt.type == SDL_QUIT) waiting = 0; } SDL_FreeSurface(new_surface); SDL_FreeSurface(surface); SDL_DestroyTexture(bg_tex); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); return 0; }
bool openvox::Window::init(GameDisplayMode* displayMode /*= nullptr*/) { if (isInitialized()) return false; if (displayMode) m_displayMode = *displayMode; SDL_WindowFlags flags = (SDL_WindowFlags)DEFAULT_WINDOW_FLAGS; if (m_displayMode.isResizable) flags = (SDL_WindowFlags)(flags | SDL_WINDOW_RESIZABLE); if (m_displayMode.isBorderless) flags = (SDL_WindowFlags)(flags | SDL_WINDOW_BORDERLESS); if (m_displayMode.isFullscreen) flags = (SDL_WindowFlags)(flags | SDL_WINDOW_FULLSCREEN); m_window = SDL_CreateWindow(DEFAULT_TITLE, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, m_displayMode.screenWidth, m_displayMode.screenHeight, flags); // Create The Window if (m_window == nullptr) { printf("Window Creation Failed\r\n"); return false; } SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, (int)m_displayMode.major); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, (int)m_displayMode.minor); if (m_displayMode.core) { SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); } else { SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY); } m_glc = SDL_GL_CreateContext((SDL_Window*)m_window); SDL_GL_MakeCurrent((SDL_Window*)m_window, (SDL_GLContext)m_glc); // Check for a valid context if (m_glc == nullptr) { printf("Could Not Create OpenGL Context"); return false; } // Initialize GLEW if (glewInit() != GLEW_OK) { printf("Glew failed to initialize. Your graphics card is probably WAY too old. Or you forgot to extract the .zip. It might be time for an upgrade :)"); return false; } // Create default clear values glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClearDepth(1.0f); // Initialize Frame Buffer glViewport(0, 0, getWidth(), getHeight()); { // Get supported window resolutions SDL_DisplayMode mode; // TODO(Ben): Handle other displays indices. int displayIndex = 0; int numDisplayModes = SDL_GetNumDisplayModes(displayIndex); for (int i = 0; i < numDisplayModes; i++) { SDL_GetDisplayMode(displayIndex, i, &mode); u32v2 res(mode.w, mode.h); if (i == 0 || m_supportedResolutions.back() != res) { m_supportedResolutions.push_back(res); } } } // Set More Display Settings setSwapInterval(m_displayMode.swapInterval, true); // Push input from this window and receive quit signals // TODO(Ben): Input // openvox::InputDispatcher::init(this); // openvox::InputDispatcher::window.onClose += makeDelegate(*this, &Window::onQuitSignal); // openvox::InputDispatcher::onQuit += makeDelegate(*this, &Window::onQuitSignal); // openvox::InputDispatcher::window.onResize += makeDelegate(*this, &Window::onResize); m_quitSignal = false; return true; }
std::string SceneRenderer::renderImage2(FBEntity const& file, std::vector<ModelFaceBase*> *) { int width = Settings::Instance()->SDL_Window_Width; int height = Settings::Instance()->SDL_Window_Height; if (SDL_Init(SDL_INIT_EVERYTHING) < 0) Settings::Instance()->funcDoLog(Settings::Instance()->string_format("[SceneRenderer] Render Error: SDL could not initialize! SDL Error: %s\n", SDL_GetError())); else { 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_ACCELERATED_VISUAL, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 16); SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_SetHint(SDL_HINT_VIDEO_HIGHDPI_DISABLED, "1"); SDL_DisplayMode current; SDL_GetCurrentDisplayMode(0, ¤t); SDL_Window *gWindow = SDL_CreateWindow("Kuplung", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, Settings::Instance()->SDL_Window_Flags); SDL_GLContext glContext; if (gWindow == NULL) Settings::Instance()->funcDoLog(Settings::Instance()->string_format("[SceneRenderer] Render Error: Window could not be created! SDL Error: %s\n", SDL_GetError())); else { glContext = SDL_GL_CreateContext(gWindow); if (!glContext) Settings::Instance()->funcDoLog(Settings::Instance()->string_format("[SceneRenderer] Render Error: Unable to create OpenGL context! SDL Error: %s\n", SDL_GetError())); else { if (SDL_GL_MakeCurrent(gWindow, glContext) < 0) Settings::Instance()->funcDoLog(Settings::Instance()->string_format("[SceneRenderer] Render Warning: Unable to set current context! SDL Error: %s\n", SDL_GetError())); else { glViewport(0, 0, width, height); glClearColor(Settings::Instance()->guiClearColor.r, Settings::Instance()->guiClearColor.g, Settings::Instance()->guiClearColor.b, Settings::Instance()->guiClearColor.w); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); this->managerObjects.render(); //managerObjects->renderSkybox(); // // render models // for (int i=0; i<(int)(*meshModelFaces).size(); i++) { // ModelFaceBase* mmf = (*meshModelFaces)[i]; // glm::mat4 mtxModel = glm::mat4(1.0); // // reposition like the grid perspective // if (managerObjects->Setting_FixedGridWorld) // mtxModel *= managerObjects->grid->matrixModel; // // scale // mtxModel = glm::scale(mtxModel, glm::vec3(mmf->scaleX->point, mmf->scaleY->point, mmf->scaleZ->point)); // // rotate // mtxModel = glm::translate(mtxModel, glm::vec3(0, 0, 0)); // mtxModel = glm::rotate(mtxModel, glm::radians(mmf->rotateX->point), glm::vec3(1, 0, 0)); // mtxModel = glm::rotate(mtxModel, glm::radians(mmf->rotateY->point), glm::vec3(0, 1, 0)); // mtxModel = glm::rotate(mtxModel, glm::radians(mmf->rotateZ->point), glm::vec3(0, 0, 1)); // mtxModel = glm::translate(mtxModel, glm::vec3(0, 0, 0)); // // translate // mtxModel = glm::translate(mtxModel, glm::vec3(mmf->positionX->point, mmf->positionY->point, mmf->positionZ->point)); // // general // mmf->setOptionsFOV(managerObjects->Setting_FOV); // // outlining // mmf->setOptionsSelected(0); // mmf->setOptionsOutlineColor(managerObjects->Setting_OutlineColor); // mmf->setOptionsOutlineThickness(managerObjects->Setting_OutlineThickness); // // lights // mmf->lightSources = managerObjects->lightSources; // mmf->matrixProjection = managerObjects->matrixProjection; // mmf->matrixCamera = managerObjects->camera->matrixCamera; // mmf->vecCameraPosition = managerObjects->camera->cameraPosition; // mmf->matrixModel = mtxModel; // mmf->renderModel(); // } SDL_GL_SwapWindow(gWindow); SDL_Surface *image = SDL_CreateRGBSurface(SDL_SWSURFACE, width, height, 24, 0x000000FF, 0x0000FF00, 0x00FF0000, 0); glReadBuffer(GL_FRONT); glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, image->pixels); // flip vertically int index; void* temp_row; int height_div_2; temp_row = (void *)malloc(image->pitch); if(NULL == temp_row) Settings::Instance()->funcDoLog("Not enough memory for image inversion"); height_div_2 = int(image->h * .5); for (index = 0; index < height_div_2; index++) { memcpy((Uint8 *)temp_row,(Uint8 *)(image->pixels) + image->pitch * index, image->pitch); memcpy((Uint8 *)(image->pixels) + image->pitch * index, (Uint8 *)(image->pixels) + image->pitch * (image->h - index - 1), image->pitch); memcpy((Uint8 *)(image->pixels) + image->pitch * (image->h - index - 1), temp_row, image->pitch); } free(temp_row); std::string f = file.path + "/" + file.title + ".bmp"; SDL_SaveBMP(image, f.c_str()); SDL_FreeSurface(image); SDL_GL_DeleteContext(glContext); } } SDL_DestroyWindow(gWindow); } } return ""; }
int main(int argc, char *argv[]) { SDL_Init(SDL_INIT_VIDEO); SDL_Window *window = SDL_CreateWindow("CopyCraft", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 1024, 768, SDL_WINDOW_OPENGL|SDL_WINDOW_RESIZABLE); SDL_GLContext glcontext = SDL_GL_CreateContext(window); init_opengl(); glewInit(); init(); float x = 0.0, y = 30.0; SDL_Event event; bool done = 0; printf("total faces drawn: %d\n", get_total_faces()); int i,j,k; float rot_amount; //Initialise VBO - do only once, at start of program //Create a variable to hold the VBO identifier GLuint triangleVBO[2]; float *verticies; float *colors; float *texcoords; verticies = new float[get_total_faces()*4*3]; colors = new float[get_total_faces()*4*3]; texcoords = new float[get_total_faces()*4*2]; int num_faces_populated; num_faces_populated = populate_verticies(verticies, colors, texcoords); printf("Number of faces populated: %d\n", num_faces_populated); //Create a new VBO and use the variable id to store the VBO id glGenBuffers(3, &triangleVBO[0]); //Make the new VBO active glBindBuffer(GL_ARRAY_BUFFER, triangleVBO[0]); //Upload vertex data to the video device glBufferData(GL_ARRAY_BUFFER, sizeof(float)*num_faces_populated*4*3, verticies, GL_STATIC_DRAW); //Make the new VBO active glBindBuffer(GL_ARRAY_BUFFER, triangleVBO[1]); //Upload vertex data to the video device glBufferData(GL_ARRAY_BUFFER, sizeof(float)*num_faces_populated*4*3, colors, GL_STATIC_DRAW); //Make the new VBO active glBindBuffer(GL_ARRAY_BUFFER, triangleVBO[2]); //Upload vertex data to the video device glBufferData(GL_ARRAY_BUFFER, sizeof(float)*num_faces_populated*4*2, texcoords, GL_STATIC_DRAW); //Make the new VBO active. Repeat here incase changed since initialisation glBindBuffer(GL_ARRAY_BUFFER, triangleVBO[0]); glVertexPointer(3, GL_FLOAT, 0, NULL); glBindBuffer(GL_ARRAY_BUFFER, triangleVBO[1]); glColorPointer(3, GL_FLOAT, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, triangleVBO[2]); glTexCoordPointer(2, GL_FLOAT, 0, 0); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); while(!done) { while(SDL_PollEvent(&event)) { if(event.type == SDL_QUIT || event.type == SDL_QUIT) done = 1; } glLoadIdentity(); glClearColor(0,0,0,1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); gluLookAt(16.0f,40.0f, 20.0f,0.0f,0.0f,0.0f,0.0f,1.0f,0.0f); rot_amount = SDL_GetTicks()/10; glPushMatrix(); glRotatef(rot_amount,0,1,0); //Actually draw the triangle, giving the number of vertices provided glDrawArrays(GL_QUADS, 0, num_faces_populated*4); glPopMatrix(); SDL_GL_SwapWindow(window); } SDL_GL_DeleteContext(glcontext); SDL_DestroyWindow(window); SDL_Quit(); return 0; }
void Renderer::init() { // TODO: android/ios // _width = deviceWidth; // _height = deviceHeight; // Game::getInstance()->engineSettings()->setFullscreen(true); // Game::getInstance()->engineSettings()->setScale(1); //or 2, if fullhd device std::string message = "SDL_CreateWindow " + std::to_string(_size.width()) + "x" + std::to_string(_size.height()) + "x" +std::to_string(32)+ " - "; uint32_t flags = SDL_WINDOW_SHOWN; if (Game::getInstance()->settings()->fullscreen()) { flags |= SDL_WINDOW_FULLSCREEN; } _sdlWindow = SDL_CreateWindow("", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, _size.width(), _size.height(), flags); if (!_sdlWindow) { throw Exception(message + "[FAIL]"); } Logger::info("RENDERER") << message + "[OK]" << std::endl; message = "SDL_CreateRenderer - "; _sdlRenderer = SDL_CreateRenderer(_sdlWindow, -1, SDL_RENDERER_ACCELERATED); if (!_sdlRenderer) { throw Exception(message + "[FAIL]"); } Logger::info("RENDERER") << message + "[OK]" << std::endl; SDL_SetRenderDrawBlendMode(_sdlRenderer, SDL_BLENDMODE_BLEND); if (Game::getInstance()->settings()->scale() != 0) { switch (Game::getInstance()->settings()->scale()) { default: case 1: _size.setWidth((int)(_size.width() / (_size.height() / 480.0))); _size.setHeight(480); break; case 2: _size.setWidth((int)(_size.width() / (_size.height() / 960.0))); _size.setHeight(960); break; } SDL_RenderSetLogicalSize(_sdlRenderer, _size.width(), _size.height()); SDL_RenderGetScale(_sdlRenderer, &_scaleX, &_scaleY); } SDL_RendererInfo rendererInfo; SDL_GetRendererInfo(_sdlRenderer, &rendererInfo); Logger::info("RENDERER") << "name: " << rendererInfo.name << std::endl; if (rendererInfo.flags & SDL_RENDERER_SOFTWARE) { Logger::info("RENDERER") << "flags: SDL_RENDERER_SOFTWARE" << std::endl; } if (rendererInfo.flags & SDL_RENDERER_ACCELERATED) { Logger::info("RENDERER") << "flags: SDL_RENDERER_ACCELERATED" << std::endl; } Logger::info("RENDERER") << "num_texture_formats: " << rendererInfo.num_texture_formats << std::endl; for (unsigned int i = 0; i != 16; i++) { auto& info = Logger::info("RENDERER"); info << "texture_formats[" << i << "]: "; auto format = rendererInfo.texture_formats[i]; switch (format) { case SDL_PIXELFORMAT_INDEX1LSB: info << "SDL_PIXELFORMAT_INDEX1LSB"; break; case SDL_PIXELFORMAT_INDEX1MSB: info << "SDL_PIXELFORMAT_INDEX1MSB"; break; case SDL_PIXELFORMAT_INDEX4LSB: info << "SDL_PIXELFORMAT_INDEX4LSB"; break; case SDL_PIXELFORMAT_INDEX4MSB: info << "SDL_PIXELFORMAT_INDEX4MSB"; break; case SDL_PIXELFORMAT_INDEX8: info << "SDL_PIXELFORMAT_INDEX8"; break; case SDL_PIXELFORMAT_RGBA8888: info << "SDL_PIXELFORMAT_RGBA8888"; break; case SDL_PIXELFORMAT_ARGB8888: info << "SDL_PIXELFORMAT_ARGB8888"; break; case SDL_PIXELFORMAT_RGB888: info << "SDL_PIXELFORMAT_RGB888"; break; default: info << format; break; } info << std::endl; } Logger::info("RENDERER") << "max_texture_width: " << rendererInfo.max_texture_width << std::endl; Logger::info("RENDERER") << "max_texture_height: " << rendererInfo.max_texture_height << std::endl; }
int main(int argc, char *argv[]) { int index; /* index of last key we pushed in the bitmap font */ SDL_Window *window; SDL_Event event; /* last event received */ SDLMod mod; /* key modifiers of last key we pushed */ SDL_ScanCode scancode; /* scancode of last key we pushed */ if (SDL_Init(SDL_INIT_VIDEO) < 0) { printf("Error initializing SDL: %s", SDL_GetError()); } /* create window */ window = SDL_CreateWindow("iPhone keyboard test", 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, 0); /* create renderer */ renderer = SDL_CreateRenderer(window, -1, 0); /* load up our font */ loadFont(); /* draw the background, we'll just paint over it */ SDL_SetRenderDrawColor(renderer, bg_color.r, bg_color.g, bg_color.b, bg_color.unused); SDL_RenderFillRect(renderer, NULL); SDL_RenderPresent(renderer); int done = 0; /* loop till we get SDL_Quit */ while (SDL_WaitEvent(&event)) { switch (event.type) { case SDL_QUIT: done = 1; break; case SDL_KEYDOWN: index = keyToIndex(event.key.keysym); scancode = event.key.keysym.scancode; mod = event.key.keysym.mod; if (scancode == SDL_SCANCODE_DELETE) { /* if user hit delete, delete the last character */ backspace(); lastCharWasColon = 0; } else if (lastCharWasColon && scancode == SDL_SCANCODE_0 && (mod & KMOD_SHIFT)) { /* if our last key was a colon and this one is a close paren, the make a hoppy face */ backspace(); drawIndex(32); /* index for happy face */ numChars++; drawCursor(); lastCharWasColon = 0; } else if (index != -1) { /* if we aren't doing a happy face, then just draw the normal character */ drawIndex(index); numChars++; drawCursor(); lastCharWasColon = (event.key.keysym.scancode == SDL_SCANCODE_SEMICOLON && (event.key.keysym.mod & KMOD_SHIFT)); } /* check if the key was a colon */ /* draw our updates to the screen */ SDL_RenderPresent(renderer); break; #ifdef __IPHONEOS__ case SDL_MOUSEBUTTONUP: /* mouse up toggles onscreen keyboard visibility this function is available ONLY on iPhone OS */ SDL_iPhoneKeyboardToggle(window); break; #endif } } cleanup(); return 0; }
int main(int argc, char **argv) { bool fullscreen = false; if (SDL_Init(0) != 0){ ERR("SDL_Init\n"); return 1; } SDL_Window* Window = SDL_CreateWindow("SDL Nine", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE ); if (!Window) { ERR("SDL_CreateWindow\n"); return 1; } d3d = SDL_Direct3DCreate9Ex(Window); if (!d3d) { ERR("X11_Direct3DCreate9\n"); return 1; } { HWND FakeWnd= (HWND)Window; D3DDISPLAYMODEEX mode; D3DPRESENT_PARAMETERS d3dpp; fillin_present_parameters(Window, SCREEN_WIDTH, SCREEN_HEIGHT, fullscreen, d3dpp, mode); // create a device class using this information and the info from the d3dpp stuct HRESULT hr = d3d->CreateDeviceEx(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, FakeWnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &d3dpp, &mode, &d3ddev); if (FAILED(hr)) { ERR("X11_Direct3DCreate9\n"); return 1; } } init_graphics(); // call the function to initialize the triangle Uint32 MainWindowID = SDL_GetWindowID(Window); bool quit = false; SDL_Event e; //While application is running while (!quit) { //Handle events on queue while (SDL_PollEvent(&e) != 0) { //User requests quit if (e.type == SDL_QUIT) { quit = true; } else if (e.type == SDL_WINDOWEVENT && e.window.windowID == MainWindowID) { switch (e.window.event) { case SDL_WINDOWEVENT_SIZE_CHANGED: { int width = e.window.data1; int height = e.window.data2; bool ok = set_window_size(Window, width, height, fullscreen); if (ok) load_triangle(width, height, v_buffer); } break; } } else if (e.type == SDL_KEYDOWN && e.window.windowID == MainWindowID && e.key.keysym.sym == SDLK_F11 && e.key.state == SDL_PRESSED) { fullscreen = !fullscreen; bool ok = set_window_size(Window, SCREEN_WIDTH, SCREEN_HEIGHT, fullscreen); if (ok) load_triangle(SCREEN_WIDTH, SCREEN_HEIGHT, v_buffer); } } //Render quad render_frame(); } // clean up DirectX { v_buffer->Release(); // close and release the vertex buffer d3ddev->Release(); // close and release the 3D device d3d->Release(); // close and release Direct3D } SDL_Quit(); return 0; }
static int draw13_window_create(sdl_window_info *window, int width, int height) { // allocate memory for our structures sdl_info *sdl = (sdl_info *) osd_malloc(sizeof(*sdl)); mame_printf_verbose("Enter draw13_window_create\n"); memset(sdl, 0, sizeof(*sdl)); window->dxdata = sdl; sdl->extra_flags = (window->fullscreen ? SDL_WINDOW_BORDERLESS | SDL_WINDOW_INPUT_FOCUS | SDL_WINDOW_FULLSCREEN : SDL_WINDOW_RESIZABLE); // create the SDL window window->sdl_window = SDL_CreateWindow(window->title, SDL_WINDOWPOS_UNDEFINED_DISPLAY(window->monitor->handle), SDL_WINDOWPOS_UNDEFINED, width, height, sdl->extra_flags); if (window->fullscreen && video_config.switchres) { SDL_DisplayMode mode; SDL_GetCurrentDisplayMode(window->monitor->handle, &mode); mode.w = width; mode.h = height; if (window->refresh) mode.refresh_rate = window->refresh; if (window->depth) { switch (window->depth) { case 15: mode.format = SDL_PIXELFORMAT_RGB555; break; case 16: mode.format = SDL_PIXELFORMAT_RGB565; break; case 24: mode.format = SDL_PIXELFORMAT_RGB24; break; case 32: mode.format = SDL_PIXELFORMAT_RGB888; break; default: mame_printf_warning("Ignoring depth %d\n", window->depth); } } SDL_SetWindowDisplayMode(window->sdl_window, &mode); // Try to set mode } else SDL_SetWindowDisplayMode(window->sdl_window, NULL); // Use desktop // create renderer if (video_config.waitvsync) sdl->sdl_renderer = SDL_CreateRenderer(window->sdl_window, -1, SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_ACCELERATED); else sdl->sdl_renderer = SDL_CreateRenderer(window->sdl_window, -1, SDL_RENDERER_ACCELERATED); if (!sdl->sdl_renderer) { fatalerror("Error on creating renderer: %s \n", SDL_GetError()); } //SDL_SelectRenderer(window->sdl_window); SDL_ShowWindow(window->sdl_window); //SDL_SetWindowFullscreen(window->window_id, window->fullscreen); SDL_RaiseWindow(window->sdl_window); SDL_GetWindowSize(window->sdl_window, &window->width, &window->height); sdl->blittimer = 3; // in case any textures try to come up before these are validated, // OpenGL guarantees all implementations can handle something this size. sdl->texture_max_width = 64; sdl->texture_max_height = 64; SDL_RenderPresent(sdl->sdl_renderer); mame_printf_verbose("Leave draw13_window_create\n"); return 0; }
// 初期化 // 成功したときは0を、失敗したときは-1を返す。 int Game::Initialize(void) { // 初期化 if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER) < 0) { fprintf(stderr, "SDLの初期化に失敗しました:%s\n", SDL_GetError()); return -1; } if (TTF_Init() < 0) { fprintf(stderr, "TTFの初期化に失敗しました:%s\n", TTF_GetError()); return -1; } window = SDL_CreateWindow("パズルゲーム", SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,WINDOW_WIDE,WINDOW_HIGH,0); screen = SDL_GetWindowSurface(window); if (screen == NULL) { fprintf(stderr, "画面の初期化に失敗しました:%s\n", SDL_GetError()); Finalize(); return -1; } /* 画像を読み込む */ section_image = IMG_Load("section_image.png"); if (section_image == NULL) { fprintf(stderr, "画像の読み込みに失敗しました:%s\n", SDL_GetError()); Finalize(); return -1; } section_image_02 = IMG_Load("section_image_02.png"); if (section_image_02 == NULL) { fprintf(stderr, "画像の読み込みに失敗しました:%s\n", SDL_GetError()); Finalize(); return -1; } block_image = IMG_Load("block_image.png"); if (block_image == NULL) { fprintf(stderr, "画像の読み込みに失敗しました:%s\n", SDL_GetError()); Finalize(); return -1; } particle_image = IMG_Load("particle_image.png"); if (particle_image == NULL) { fprintf(stderr, "画像の読み込みに失敗しました:%s\n", SDL_GetError()); Finalize(); return -1; } // フォント読み込む font = TTF_OpenFont("AquaKana.ttc", 24); if (font == NULL) { fprintf(stderr, "fontの取得に失敗しました:%s\n", SDL_GetError()); Finalize(); return -1; } big_font = TTF_OpenFont("AquaKana.ttc", 36); if (big_font == NULL) { fprintf(stderr, "big_fontの取得に失敗しました:%s\n", SDL_GetError()); Finalize(); return -1; } // SDL_Mixerオープン Mix_OpenAudio(22050,AUDIO_S16,2,4096); // BGM読み込み music_main = Mix_LoadMUS("music_main.mp3"); if (music_main == NULL) { fprintf(stderr, "music_mainの取得に失敗しました:%s\n", SDL_GetError()); Finalize(); return -1; } // ブロック破壊音読み込み music_break = Mix_LoadWAV("music_break.mp3"); if (music_break == NULL) { fprintf(stderr, "music_breakの取得に失敗しました:%s\n", SDL_GetError()); Finalize(); return -1; } // 音量調節 Mix_VolumeMusic(10); Mix_Volume(-1,5); return 0; }
int ysdl2Init(void) { if (type != -1) return type; /* Initialisation simple */ if (SDL_Init(SDL_INIT_EVERYTHING) != 0 ) { DPRINT_ERR("Échec de l'initialisation de la SDL (%s)\n",SDL_GetError()); return -1; } if(TTF_Init()==-1) { DPRINT_ERR("TTF_Init: %s\n", TTF_GetError()); goto ttf_fail; } // initializing Flags for PNG Images int imgFlags = IMG_INIT_PNG | IMG_INIT_JPG | IMG_INIT_TIF; // Simple check of the Flags if(!(IMG_Init(imgFlags)&imgFlags)) { DPRINT_ERR("SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError()); goto img_fail; } /* Création de la fenêtre */ sg.pWindow = SDL_CreateWindow("YIRL isn't a rogue like", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIN_W_SIZE, WIN_H_SIZE, SDL_WINDOW_SHOWN); if(!sg.pWindow) { DPRINT_ERR("Error to creeate window:: %s\n",SDL_GetError()); goto win_fail; } // Render for the main windows sg.renderer = SDL_CreateRenderer(sg.pWindow, -1, SDL_RENDERER_TARGETTEXTURE); if (!sg.renderer) { DPRINT_ERR("Get render from window: %s\n", TTF_GetError()); goto fail; } if (SDL_SetRenderDrawBlendMode(sg.renderer, SDL_BLENDMODE_BLEND) < 0) { goto fail; } if (sgSetDefaultFont("./sample.ttf") < 0) DPRINT_WARN("can not load \"./sample.ttf\"\n"); // fill the window with a black rectangle // SDL_Rect rect = sg.getRect(); SDL_RenderClear(sg.renderer); SDL_RenderPresent(sg.renderer); type = ywidRegistreRender(sdlResize, SDLPollEvent, SDLWaitEvent); return type; fail: SDL_DestroyWindow(sg.pWindow); win_fail: TTF_Quit(); img_fail: IMG_Quit(); ttf_fail: SDL_Quit(); return -1; }
int main(int argc, char **argv) { SDL_Init(SDL_INIT_VIDEO); SDL_Window *ventana = SDL_CreateWindow("Hi", 200, 200, 864, 510, SDL_WINDOW_SHOWN); SDL_Renderer *render = SDL_CreateRenderer(ventana, -1, SDL_RENDERER_ACCELERATED); //se carga la imagen que contiene todos los graficos SDL_Surface * bmp = SDL_LoadBMP("atlas.bmp"); //se define el blanco como color transparente SDL_SetColorKey(bmp, 1, SDL_MapRGB(bmp->format, 255, 255, 255)); SDL_Texture *textura = SDL_CreateTextureFromSurface(render, bmp); SDL_FreeSurface(bmp); SDL_Event event; if (textura == NULL) { std::cout << "FAILED TO FIND THE IMAGE" << std::endl; } SDL_RenderClear(render); renderFondo(render, textura); //Rectangulo con las coordenadas donde se encuentra el pagaro en la textura SDL_Rect rectangulo_origen; rectangulo_origen.x = 174;//174 azul 6 amarillo rectangulo_origen.y = 982; rectangulo_origen.w = 34; rectangulo_origen.h = 24; //Rectangulo con las coordenadas donde se pintara el pagaro en el render SDL_Rect rectangulo_destino; rectangulo_destino.x = 100; rectangulo_destino.y = 300; rectangulo_destino.w = 34; rectangulo_destino.h = 24; SDL_RenderCopy(render, textura, &rectangulo_origen, &rectangulo_destino); SDL_Rect rectangulo_origen_tubo; rectangulo_origen_tubo.x = 112; rectangulo_origen_tubo.y = 646; rectangulo_origen_tubo.w = 52; rectangulo_origen_tubo.h = 320; SDL_Rect rectangulo_destino_tubo; rectangulo_destino_tubo.x = 800; rectangulo_destino_tubo.y = -150; rectangulo_destino_tubo.w = 52; rectangulo_destino_tubo.h = 320; SDL_RenderCopy(render, textura, &rectangulo_origen_tubo, &rectangulo_destino_tubo); SDL_Rect rectangulo_origen_tubo1; rectangulo_origen_tubo1.x = 168; rectangulo_origen_tubo1.y = 646; rectangulo_origen_tubo1.w = 52; rectangulo_origen_tubo1.h = 320; SDL_Rect rectangulo_destino_tubo1; rectangulo_destino_tubo1.x = 800; rectangulo_destino_tubo1.y = 320; rectangulo_destino_tubo1.w = 52; rectangulo_destino_tubo1.h = 320; SDL_RenderCopy(render, textura, &rectangulo_origen_tubo1, &rectangulo_destino_tubo1); SDL_RenderPresent(render); int done = 1; double angulo = 330; const int FPS = 24; //Cuantos frames por segundo queremos, 60 es el que utilizan los televisores const int DELAY_TIME = 1000.0f / FPS; //1000 ms entre los fps da el numero de milisegundos entre cada frame Uint32 frameStart, frameTime; while (done) { frameStart = SDL_GetTicks(); //validacion del piso if (rectangulo_destino.y < 400) { rectangulo_destino.y += 10; } //validacion del angulo maximo if (angulo < 450) { angulo += 15; } if(rectangulo_destino_tubo.x > 0){ rectangulo_destino_tubo.x -= 2; rectangulo_destino_tubo1.x -= 2; }else{ rectangulo_destino_tubo.x = 864; rectangulo_destino_tubo1.x = 864; } //mientras exista un evento en el pila de eventos while (SDL_PollEvent(&event)) { //salto if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_SPACE) { rectangulo_destino.y -= 100; angulo = 300; } else if (event.type == SDL_QUIT) { done = 0; } } //se pinta actualiza el render SDL_RenderClear(render); renderFondo(render, textura); //funciona como copy pero rota la imagen con el angulo SDL_RenderCopy(render, textura, &rectangulo_origen_tubo, &rectangulo_destino_tubo); SDL_RenderCopy(render, textura, &rectangulo_origen_tubo1, &rectangulo_destino_tubo1); SDL_RenderCopyEx(render, textura, &rectangulo_origen, &rectangulo_destino, angulo, NULL, SDL_FLIP_NONE); SDL_RenderPresent(render); if(colision(&rectangulo_destino,&rectangulo_destino_tubo) ||colision(&rectangulo_destino,&rectangulo_destino_tubo1)) { done = 0; } frameTime = SDL_GetTicks() - frameStart; //Tiempo que ha tardado en presentarse el frame if (frameTime < DELAY_TIME)//Si es menor al tiempo que deber à a ser { SDL_Delay((int)(DELAY_TIME - frameTime));//Espera un tiempo } } angulo = 450; while(rectangulo_destino.y < 400) { frameStart = SDL_GetTicks(); rectangulo_destino.y += 10; //se pinta actualiza el render SDL_RenderClear(render); renderFondo(render, textura); //funciona como copy pero rota la imagen con el angulo SDL_RenderCopy(render, textura, &rectangulo_origen_tubo, &rectangulo_destino_tubo); SDL_RenderCopy(render, textura, &rectangulo_origen_tubo1, &rectangulo_destino_tubo1); SDL_RenderCopyEx(render, textura, &rectangulo_origen, &rectangulo_destino, angulo, NULL, SDL_FLIP_NONE); SDL_RenderPresent(render); frameTime = SDL_GetTicks() - frameStart; //Tiempo que ha tardado en presentarse el frame if (frameTime < DELAY_TIME)//Si es menor al tiempo que deber à a ser { SDL_Delay((int)(DELAY_TIME - frameTime));//Espera un tiempo } } SDL_Delay(5000); /* Free all objects */ SDL_DestroyTexture(textura); SDL_DestroyRenderer(render); SDL_DestroyWindow(ventana); /* Quit program */ SDL_Quit(); return 0; }
s32 proc() { #if _WIN32 SetProcessDPIAware(); #endif #if defined(__APPLE__) SDL_SetHint(SDL_HINT_MOUSE_RELATIVE_MODE_WARP, "1"); #endif // Initialize SDL if (SDL_Init( SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_GAMECONTROLLER | SDL_INIT_HAPTIC | SDL_INIT_TIMER | SDL_INIT_JOYSTICK ) < 0) { fprintf(stderr, "Failed to initialize SDL: %s\n", SDL_GetError()); return -1; } Loader::data_directory = SDL_GetPrefPath("HelveticaScenario", "Yearning"); SDL_GameControllerAddMappingsFromFile("gamecontrollerdb.txt"); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0); { SDL_DisplayMode display; SDL_GetDesktopDisplayMode(0, &display); Loader::settings_load(display.w, display.h); } if (SDL_SetRelativeMouseMode(SDL_TRUE) != 0) { fprintf(stderr, "Failed to set relative mouse mode: %s\n", SDL_GetError()); return -1; } window = SDL_CreateWindow ( "The Yearning", 0, 0, Settings::width, Settings::height, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_INPUT_GRABBED | SDL_WINDOW_INPUT_FOCUS | SDL_WINDOW_MOUSE_FOCUS | SDL_WINDOW_MOUSE_CAPTURE | SDL_WINDOW_ALLOW_HIGHDPI | (Settings::fullscreen ? SDL_WINDOW_FULLSCREEN : SDL_WINDOW_BORDERLESS) ); #if defined(__APPLE__) SDL_SetWindowGrab(window, SDL_TRUE); #endif // Open a window and create its OpenGL context if (!window) { fprintf(stderr, "Failed to open SDL window. Most likely your GPU is out of date! %s\n", SDL_GetError()); SDL_Quit(); return -1; } SDL_GLContext context = SDL_GL_CreateContext(window); if (!context) { fprintf(stderr, "Failed to create GL context: %s\n", SDL_GetError()); return -1; } if (SDL_GL_SetSwapInterval(Settings::vsync ? 1 : 0) != 0) { fprintf(stderr, "Failed to set OpenGL swap interval: %s\n", SDL_GetError()); return -1; } { glewExperimental = true; // Needed for core profile GLenum glew_result = glewInit(); if (glew_result != GLEW_OK) { fprintf(stderr, "Failed to initialize GLEW: %s\n", glewGetErrorString(glew_result)); return -1; } } glGetError(); // Clear initial error caused by GLEW render_init(); // Launch threads Sync<LoopSync> render_sync; LoopSwapper swapper_render_update = render_sync.swapper(0); LoopSwapper swapper_render = render_sync.swapper(1); Sync<PhysicsSync, 1> physics_sync; PhysicsSwapper swapper_physics = physics_sync.swapper(); PhysicsSwapper swapper_physics_update = physics_sync.swapper(); std::thread thread_physics(Physics::loop, &swapper_physics); std::thread thread_update(Loop::loop, &swapper_render_update, &swapper_physics_update); std::thread thread_ai(AI::loop); LoopSync* sync = swapper_render.get(); r64 last_time = SDL_GetTicks() / 1000.0; b8 has_focus = true; SDL_PumpEvents(); const u8* sdl_keys = SDL_GetKeyboardState(0); refresh_controllers(); while (true) { render(sync); // Swap buffers SDL_GL_SwapWindow(window); SDL_PumpEvents(); memcpy(sync->input.keys, sdl_keys, sizeof(sync->input.keys)); sync->input.keys[(s32)KeyCode::MouseWheelDown] = false; sync->input.keys[(s32)KeyCode::MouseWheelUp] = false; SDL_Event sdl_event; while (SDL_PollEvent(&sdl_event)) { if (sdl_event.type == SDL_QUIT) sync->quit = true; else if (sdl_event.type == SDL_MOUSEWHEEL) { b8 up = sdl_event.wheel.y > 0; if (sdl_event.wheel.direction == SDL_MOUSEWHEEL_FLIPPED) up = !up; if (up) sync->input.keys[(s32)KeyCode::MouseWheelUp] = true; else sync->input.keys[(s32)KeyCode::MouseWheelDown] = true; } else if (sdl_event.type == SDL_JOYDEVICEADDED || sdl_event.type == SDL_JOYDEVICEREMOVED) refresh_controllers(); else if (sdl_event.type == SDL_WINDOWEVENT) { if (sdl_event.window.event == SDL_WINDOWEVENT_FOCUS_GAINED) has_focus = true; else if (sdl_event.window.event == SDL_WINDOWEVENT_FOCUS_LOST) has_focus = false; } } sync->input.focus = has_focus; s32 mouse_buttons = SDL_GetRelativeMouseState(&sync->input.cursor_x, &sync->input.cursor_y); sync->input.keys[(s32)KeyCode::MouseLeft] = mouse_buttons & (1 << 0); sync->input.keys[(s32)KeyCode::MouseMiddle] = mouse_buttons & (1 << 1); sync->input.keys[(s32)KeyCode::MouseRight] = mouse_buttons & (1 << 2); s32 active_gamepads = 0; for (s32 i = 0; i < MAX_GAMEPADS; i++) { SDL_GameController* controller = controllers[i]; Gamepad* gamepad = &sync->input.gamepads[i]; gamepad->active = controller != 0; gamepad->btns = 0; if (gamepad->active) { gamepad->left_x = (r32)SDL_GameControllerGetAxis(controller, SDL_CONTROLLER_AXIS_LEFTX) / 32767.0f; gamepad->left_y = (r32)SDL_GameControllerGetAxis(controller, SDL_CONTROLLER_AXIS_LEFTY) / 32767.0f; gamepad->right_x = (r32)SDL_GameControllerGetAxis(controller, SDL_CONTROLLER_AXIS_RIGHTX) / 32767.0f; gamepad->right_y = (r32)SDL_GameControllerGetAxis(controller, SDL_CONTROLLER_AXIS_RIGHTY) / 32767.0f; gamepad->left_trigger = (r32)SDL_GameControllerGetAxis(controller, SDL_CONTROLLER_AXIS_TRIGGERLEFT) / 32767.0f; gamepad->right_trigger = (r32)SDL_GameControllerGetAxis(controller, SDL_CONTROLLER_AXIS_TRIGGERRIGHT) / 32767.0f; if (gamepad->left_trigger > 0.5f) gamepad->btns |= Gamepad::Btn::LeftTrigger; if (gamepad->right_trigger > 0.5f) gamepad->btns |= Gamepad::Btn::RightTrigger; if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_LEFTSHOULDER)) gamepad->btns |= Gamepad::Btn::LeftShoulder; if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER)) gamepad->btns |= Gamepad::Btn::RightShoulder; if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_LEFTSTICK)) gamepad->btns |= Gamepad::Btn::LeftClick; if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_RIGHTSTICK)) gamepad->btns |= Gamepad::Btn::RightClick; if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_A)) gamepad->btns |= Gamepad::Btn::A; if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_B)) gamepad->btns |= Gamepad::Btn::B; if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_X)) gamepad->btns |= Gamepad::Btn::X; if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_Y)) gamepad->btns |= Gamepad::Btn::Y; if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_BACK)) gamepad->btns |= Gamepad::Btn::Back; if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_START)) gamepad->btns |= Gamepad::Btn::Start; if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_DPAD_UP)) gamepad->btns |= Gamepad::Btn::DUp; if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_DPAD_DOWN)) gamepad->btns |= Gamepad::Btn::DDown; if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_DPAD_LEFT)) gamepad->btns |= Gamepad::Btn::DLeft; if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_DPAD_RIGHT)) gamepad->btns |= Gamepad::Btn::DRight; if (gamepad->rumble > 0.0f) SDL_HapticRumblePlay(haptics[i], gamepad->rumble, 33); gamepad->rumble = 0.0f; active_gamepads++; } else { gamepad->left_x = 0.0f; gamepad->left_y = 0.0f; gamepad->right_x = 0.0f; gamepad->right_y = 0.0f; gamepad->left_trigger = 0.0f; gamepad->right_trigger = 0.0f; gamepad->rumble = 0.0f; } } SDL_GetWindowSize(window, &sync->input.width, &sync->input.height); r64 time = (SDL_GetTicks() / 1000.0); sync->time.total = (r32)time; sync->time.delta = vi_min((r32)(time - last_time), 0.25f); last_time = time; b8 quit = sync->quit; sync = swapper_render.swap<SwapType_Read>(); if (quit || sync->quit) break; } AI::quit(); thread_update.join(); thread_physics.join(); thread_ai.join(); SDL_GL_DeleteContext(context); SDL_DestroyWindow(window); // SDL sucks for (s32 i = 0; i < MAX_GAMEPADS; i++) { if (haptics[i]) SDL_HapticClose(haptics[i]); } SDL_Quit(); return 0; }
int main(int, char**) { //initialise SDL system and the video subsystem if (SDL_Init(SDL_INIT_VIDEO) != 0) { QuitWithError("SDL_Init Error: "); } //Create a Window SDL_Window *win = SDL_CreateWindow("Hello World!", 100, 100, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); if (win == nullptr) { QuitWithError("SDL_CreateWindow Error: "); } //SDL_SetWindowFullscreen(win, SDL_WINDOW_FULLSCREEN); Mix_Music *music = NULL; Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 4096) == -1; std::string basepath(SDL_GetBasePath()); music = Mix_LoadMUS((basepath + "background.wav").c_str()); Mix_PlayMusic(music, -1); Render* renderer = new Render(win); //Main loop flag bool quit = false; b2Vec2 Gravity(0.f, 0.0098f); b2World World(Gravity); string bgPath = basepath + "background22.bmp"; SDL_Surface* back = SDL_LoadBMP(bgPath.c_str()); SDL_Rect* backGroundRect = renderer->AddSurfaceToRenderer(back, 0, -600, 1.0f); Button button = Button(-200, -50, World, renderer); Door door = Door(600, -100, renderer); Level level = Level(World, renderer); Player player = Player(100, 500, World, renderer); vector<Cannon*> cannons; cannons.push_back(new Cannon(170, 350, World, renderer, 1)); cannons.push_back(new Cannon(1010, 50, World, renderer, 2)); cannons.push_back(new Cannon(170, 450, World, renderer, 1)); cannons.push_back(new Cannon(1010, 150, World, renderer, 2)); cannons.push_back(new Cannon(170, 550, World, renderer, 1)); cannons.push_back(new Cannon(1010, 250, World, renderer, 2)); MenuScene* menu = new MenuScene(1200, 100, renderer); SDL_Event e; //thread t1(&Process::run, Process((*(game)))); //Passing references //t1.detach(); //detaches from SDL mainline float prevTicks = SDL_GetTicks(); float currentTicks = SDL_GetTicks(); float FPS = 0; int fpsTimer = 0; SDL_Init(0); //game loop while (!quit) { World.Step(1 / 60.f, 6, 2); while (SDL_PollEvent(&e) != 0) { if (inputHandler.CheckInput(SDLK_ESCAPE, e)) { quit = true; } } if (menu->playBool == false && menu->quitBool == false) { renderer->DrawMenuScene(); menu->Update(renderer); } if (menu->playBool == true) { //PLAY GAME STATE int dir = player.Move(inputHandler, e); for (int i = 0; i < cannons.size(); i++) { cannons.at(i)->Update(); } SDL_Rect rec(player.spriteRect); rec.y = player.GetY(); for (int j = 0; j < cannons.size(); j++) { for (int i = 0; i < cannons.at(j)->fireballs.size(); i++) { if (cannons.at(j)->fireballs.at(i)->CheckCollision(&rec) == true) { std::cout << "Collision Detected!" << std::endl; player.Respawn(); button.setOnce(false); button.buttonBody->SetTransform(b2Vec2(880 / SCALE, 39 / SCALE), 0); door.spriteRect->x = -1000; door.spriteRect->y = -1000; player.prevPosX.clear(); player.prevPosY.clear(); player.count = 0; } } } button.Update(); if (button.CheckCollision(&rec) == true) { std::cout << "Collision Detected!" << std::endl; button.collision = true; button.spriteRect->x = -2000; button.spriteRect->y = -2000; button.buttonBody->SetTransform(b2Vec2(-2000, -2000), 0); //door.Draw(renderer); } if (door.CheckCollision(&rec) == true) { button.buttonBody->SetTransform(b2Vec2(880 / SCALE, 39/ SCALE), 0); std::cout << "Collision Detected!" << std::endl; player.Respawn(); button.setOnce(false); door.spriteRect->x = -1000; door.spriteRect->y = -1000; player.prevPosX.clear(); player.prevPosY.clear(); player.count = 0; player.Respawn(); menu->playBool = false; menu->quitBool = false; menu->backGroundRect->x = 0; menu->current = 0; button.collision = false; } if (button.collision == false) { door.DrawCage(renderer); } if (button.collision == true) { door.DrawNoCage(renderer); } int ticks = SDL_GetTicks(); int seconds = ticks / 50; int sprite = seconds % 8; renderer->Update(player.srcRect, player.dstRect, *player.LeftTexture, *player.RightTexture, *player.StandTexture, sprite, dir, player.moving, player.GetY()); player.dstRect.w = player.spriteRect.w; player.dstRect.h = player.spriteRect.h; player.dstRect.x = player.spriteRect.x; player.dstRect.y = player.spriteRect.y + 5; } if (menu->quitBool == true) { quit = true; } fpsthink(); if (fpsTimer == 60) { printf("%f\n", framespersecond); fpsTimer = 0; } fpsTimer++; } SDL_DestroyRenderer(renderer->ren); SDL_DestroyWindow(win); SDL_DestroyMutex(mutex); SDL_Quit(); return 0; }
void sprite_play(sd_bk_file *bk, int scale, int anim, int sprite) { if(!check_anim_sprite(bk, anim, sprite)) return; SDL_Surface *surface; SDL_Texture *texture; SDL_Texture *background; SDL_Texture *rendertarget; SDL_Rect rect; SDL_Rect dstrect; sd_sprite *s = bk->anims[anim]->animation->sprites[sprite]; SDL_Window *window = SDL_CreateWindow( "OMF2097 Remake", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 320 * scale, 200 * scale, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL ); if (!window) { printf("Could not create window: %s\n", SDL_GetError()); return; } printf("Sprite Info: pos=(%d,%d) size=(%d,%d) len=%d\n", s->pos_x, s->pos_y, s->img->w, s->img->h, s->img->len); SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); uint32_t rmask, gmask, bmask, amask; rmask = 0x000000ff; gmask = 0x0000ff00; bmask = 0x00ff0000; amask = 0xff000000; sd_rgba_image *img = sd_vga_image_decode(bk->background, bk->palettes[0], -1); if(!(surface = SDL_CreateRGBSurfaceFrom((void*)img->data, img->w, img->h, 32, img->w*4, rmask, gmask, bmask, amask))) { printf("Could not create surface: %s\n", SDL_GetError()); return; } if ((background = SDL_CreateTextureFromSurface(renderer, surface)) == 0) { printf("Could not create texture: %s\n", SDL_GetError()); return; } if((rendertarget = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, 320, 200)) == 0) { printf("Could not create texture: %s\n", SDL_GetError()); return; } SDL_FreeSurface(surface); sd_rgba_image_delete(img); img = sd_sprite_image_decode(s->img, bk->palettes[0], -1); if(!(surface = SDL_CreateRGBSurfaceFrom((void*)img->data, img->w, img->h, 32, img->w*4, rmask, gmask, bmask, amask))) { printf("Could not create surface: %s\n", SDL_GetError()); return; } if ((texture = SDL_CreateTextureFromSurface(renderer, surface)) == 0) { printf("Could not create texture: %s\n", SDL_GetError()); return; } SDL_FreeSurface(surface); sd_rgba_image_delete(img); rect.x = s->pos_x; rect.y = s->pos_y; rect.w = s->img->w; rect.h = s->img->h; dstrect.x = 0; dstrect.y = 0; dstrect.w = 320 * scale; dstrect.h = 200 * scale; while(1) { SDL_Event e; if (SDL_PollEvent(&e)) { if (e.type == SDL_QUIT) { break; } else if (e.type == SDL_KEYUP) { int i = anim; int changed = 0; switch (e.key.keysym.sym) { case SDLK_RIGHT: sprite = (sprite+1) % bk->anims[anim]->animation->frame_count; printf("sprite is now %u\n", sprite); changed = 1; break; case SDLK_LEFT: sprite--; if (sprite < 0) { sprite = bk->anims[anim]->animation->frame_count - 1; } changed = 1; break; case SDLK_UP: i++; while (!check_anim(bk, i) && i < 50) { i++; } if (i == 50) { printf("no more animations\n"); } else { anim = i; printf("UP: animation is now %u\n", anim); sd_bk_anim *bka = bk->anims[anim]; sd_animation *ani = bka->animation; bkanim_info(bka, ani, anim); sprite = 0; } changed = 1; break; case SDLK_DOWN: i--; while (!check_anim(bk, i) && i >= 0) { i--; } if (i < 0) { printf("no previous animations\n"); } else { anim = i; printf("DOWN: animation is now %u\n", anim); sd_bk_anim *bka = bk->anims[anim]; sd_animation *ani = bka->animation; bkanim_info(bka, ani, anim); sprite = 0; } changed = 1; break; default: changed = 0; } if (changed) { s = bk->anims[anim]->animation->sprites[sprite]; img = sd_sprite_image_decode(s->img, bk->palettes[0], -1); int x = s->pos_x + bk->anims[anim]->animation->start_x; int y = s->pos_y + bk->anims[anim]->animation->start_y; printf("Sprite Info: pos=(%d,%d) size=(%d,%d) len=%d\n", x, y, s->img->w, s->img->h, s->img->len); if(!(surface = SDL_CreateRGBSurfaceFrom((void*)img->data, img->w, img->h, 32, img->w*4, rmask, gmask, bmask, amask))) { printf("Could not create surface: %s\n", SDL_GetError()); return; } if ((texture = SDL_CreateTextureFromSurface(renderer, surface)) == 0) { printf("Could not create texture: %s\n", SDL_GetError()); return; } SDL_FreeSurface(surface); rect.x = x; rect.y = y; rect.w = s->img->w; rect.h = s->img->h; } } } SDL_RenderClear(renderer); SDL_SetRenderTarget(renderer, rendertarget); SDL_RenderCopy(renderer, background, NULL, NULL); SDL_RenderCopy(renderer, texture, NULL, &rect); // render the collision data SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255); for(int i = 0; i < bk->anims[anim]->animation->col_coord_count; i++) { int x = bk->anims[anim]->animation->col_coord_table[i].x; int y = bk->anims[anim]->animation->col_coord_table[i].y; int y_ext = bk->anims[anim]->animation->col_coord_table[i].y_ext; if (y_ext == sprite) { SDL_RenderDrawPoint(renderer, x, y); } } SDL_SetRenderTarget(renderer, NULL); SDL_RenderCopy(renderer, rendertarget, NULL, &dstrect); SDL_RenderPresent(renderer); SDL_Delay(10); // don't chew too much CPU } // Close and destroy the window SDL_DestroyWindow(window); // Clean up SDL_Quit(); }
int main(int argc, char *argv[]) { //Set the window title std::string title = "Sky Zone Omega"; //Set the window and target resolutions C_Vec2 targetRes = C_Vec2(1080, 608); C_Vec2 windowRes = C_Vec2(1080, 608); //Initialise SDL if (SDL_Init(SDL_INIT_VIDEO) < 0) { //Failed initialisation C_Utilities::logE("SDL failed to initialise: " + std::string(SDL_GetError())); return -1; } //Initialise SDL_ttf if (TTF_Init() < 0) { //Failed initialisation C_Utilities::logE("SDL_ttf failed to initialise: " + std::string(TTF_GetError())); return -1; } //Initialise SDL_mixer if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0) { C_Utilities::logE("SDL_mixer failed to initialise: " + std::string(Mix_GetError())); return -1; } //Time Check unsigned int lastTime = SDL_GetTicks(); #if !defined(_DEBUG) //Create Window C_Vec2 windowPos = C_Vec2(100, 100); SDL_Window *window = SDL_CreateWindow(title.c_str(), (int)windowPos.x, (int)windowPos.y, (int)windowRes.x, (int)windowRes.y, SDL_WINDOW_SHOWN | SDL_WINDOW_FULLSCREEN_DESKTOP); #else //Create Window C_Vec2 windowPos = C_Vec2(100, 100); SDL_Window *window = SDL_CreateWindow(title.c_str(), (int)windowPos.x, (int)windowPos.y, (int)windowRes.x, (int)windowRes.y, SDL_WINDOW_SHOWN); #endif //Create Renderer from the window SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, 0); //Set the renderer to work out the render at this resolution and then scale it up the //closest resolution it can to the windows resolution (adds bars of the render colour) SDL_RenderSetLogicalSize(renderer, (int)targetRes.x, (int)targetRes.y); //The background music C_Music* backgroundMusic = new C_Music("Assets/Audio/gameplayLoop.ogg"); //Setup state manager and initial state S_StateManager * stateManager = new S_StateManager(); stateManager->addState(new S_Splash(stateManager, renderer, targetRes, backgroundMusic)); //Start Game Loop bool go = true; while (go) { //Time Check unsigned int current = SDL_GetTicks(); float deltaTime = (float)(current - lastTime) / 1000.0f; lastTime = current; //Handle the current state inputs go = stateManager->input(); //Update the current state stateManager->update(deltaTime); //set draw colour to black SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0xFF); //Clear the entire screen to the set colour SDL_RenderClear(renderer); //Draw the states stateManager->draw(); //display renderer SDL_RenderPresent(renderer); //Time Limiter if (deltaTime < (1.0f / 50.0f)) { SDL_Delay((unsigned int)(((1.0f / 50.0f) - deltaTime)*1000.0f)); } } //destroy data delete stateManager; //Stop music backgroundMusic->stopMusic(); //Delete audio pointers delete backgroundMusic; SDL_DestroyWindow(window); SDL_Quit(); return 0; }
int main(){ SDL_Window* window = NULL; SDL_Renderer* ren = NULL; SDL_Event event; //Entier controllant l'affichage de la fenetre int ON = 1; //Initialisation //Ajouter la gestion de l'erreur SDL_Init(SDL_INIT_VIDEO); IMG_Init(IMG_INIT_PNG); TTF_Init(); int map01[13][13] = { {0,0,0,6,15,2,2,2,2,2,4,0,0}, {9,0,0,6,2,1,1,1,1,2,11,9,0}, {3,0,0,6,2,5,5,1,1,15,2,4,0}, {0,0,0,6,2,5,5,5,1,15,2,4,0}, {0,0,0,6,2,2,5,5,1,2,2,4,0}, {0,0,0,6,14,14,1,1,2,2,7,3,0}, {9,0,0,6,2,2,1,1,2,2,4,0,0}, {4,0,0,6,2,2,2,15,2,7,3,0,0}, {3,0,0,13,8,8,8,12,8,3,0,0,0}, {0,0,0,0,0,0,0,12,0,0,0,0,0}, {0,0,0,16,10,10,10,12,9,0,0,0,0}, {0,0,0,6,2,14,2,2,11,10,9,0,0}, {0,0,0,6,2,5,1,1,5,2,4,0,0}, }; //Génération de la fenêtre window = SDL_CreateWindow("TankRider : Level 00", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 900, 720, SDL_WINDOW_SHOWN); ren = SDL_CreateRenderer( window, 0, SDL_RENDERER_TARGETTEXTURE); //Initialisation de la position du curseur int MouseX = 0; int MouseY = 0; //Drapeau int Drapeau[2]={385,635}; //Ces 3 tab enregistrentles coords et le bouton qui est down //36 est un nombre quelconque, à redefinir en fonction des courte int xcible[36]; int ycible[36]; int d_on_tab[36]; //Nombre de fleche posée int nb=0; //Element de la boucle de dessin int nbj; //indice de la fleche selected int d_on ; first_components_of_the_background(ren); carte(ren,map01,Drapeau); int nb_fleche[9]={0,2,0,1,0,1,0,0,0}; maj_panneau(ren,nb_fleche); int xE = 220; int yE = 170 ; int setE=6; mvt_tank(ren, xE,yE, setE, 0); int x = 320; int y = 20; int set = 2; mvt_tank(ren,x,y,set,1); //tableau de direction int dx[9]={-5,0,5,-5,0,5,-5,0,5}; int dy[9]={5,5,5,0,0,0,-5,-5,-5}; //Missiles SDL_Surface *Missile = NULL; SDL_Surface *m_1 = IMG_Load("IMG/missile1.png"); int angles[] ={0,45,90,-45,0,135,-90,-135,180}; //explosions SDL_Surface *Explosion = NULL; SDL_Surface *e_1 = IMG_Load("IMG/case_explosion1.png"); SDL_Surface *e_2 = IMG_Load("IMG/case_explosion2.png"); SDL_Surface *e_3 = IMG_Load("IMG/case_explosion3.png"); SDL_Surface *e_4 = IMG_Load("IMG/case_explosion4.png"); SDL_Surface *e_5 = IMG_Load("IMG/case_explosion5.png"); SDL_Surface *e_6 = IMG_Load("IMG/case_explosion6.png"); SDL_Surface *e_7 = IMG_Load("IMG/case_explosion7.png"); SDL_Surface* explosions[7]= {e_1,e_2,e_3,e_4,e_5,e_6,e_7}; //coordonnée de missile int xmissile=0; int ymissile=0; SDL_RenderPresent(ren); int action = 0; while( ON == 1 ) { SDL_WaitEvent(&event); switch( event.type){ //Gestion de la fermeture case SDL_QUIT : ON = 0; break; case SDL_MOUSEMOTION : MouseX=event.motion.x; MouseY=event.motion.y; break; case SDL_MOUSEBUTTONDOWN: //detection de la fleche selected if(MouseX>731 && MouseX<879 && MouseY<229 && MouseY>81){ d_on = choix_direction(MouseX,MouseY); if(nb_fleche[d_on-1]>=0){ nb_fleche[d_on-1]=(nb_fleche[d_on-1])-1; maj_panneau(ren,nb_fleche); } } if (event.button.button == SDL_BUTTON_LEFT){ if(MouseX>731 && MouseX<879 && MouseY>531 && MouseY<579){//BOUTON START action = 1; } if(MouseX>731 && MouseX<879 && MouseY>601 && MouseY<649){//BOUTON RESET carte(ren,map01,Drapeau); nb_fleche[0]= 0; nb_fleche[1]= 2; nb_fleche[2]= 0; nb_fleche[3]= 1; nb_fleche[4]= 0; nb_fleche[5]= 1; nb_fleche[6]= 0; nb_fleche[7]= 0; nb_fleche[8]= 0; maj_panneau(ren,nb_fleche); mvt_tank(ren, xE,yE, setE, 0); x = 320; y = 20; set = 2; nb=0; mvt_tank(ren,x,y,set,1); SDL_RenderPresent(ren); } } break; case SDL_MOUSEBUTTONUP: if (event.button.button == SDL_BUTTON_LEFT){ if(MouseX<685 && MouseX>38 && MouseY< 685 && MouseY>38 ){ if(d_on!=5 ){ if((nb_fleche[d_on-1])>(-1)){ xcible[nb]= 35+50*(((MouseX+12)/50)-1); ycible[nb]= 35+50*(((MouseY+12)/50)-1); d_on_tab[nb]=d_on; d_on=5; small_direction (ren,xcible[nb],ycible[nb],d_on_tab[nb]); nb++; } } SDL_RenderPresent(ren); } } break; } while (action==1 ){ carte(ren,map01,Drapeau); mvt_tank(ren, 220,170, 6, 0); for(nbj = 0; nbj<nb;nbj++){ if(nb!=0){ small_direction (ren,xcible[nbj],ycible[nbj],d_on_tab[nbj]); } } x=x+dx[set-1]; y=y+dy[set-1]; action = evite_mer(window, x, y, map01); mvt_tank(ren, x ,y,set ,1); SDL_RenderPresent(ren); if((x==630 || x==15 || y==630 || y==15)){ //borne a verifier action=0; SDL_ShowSimpleMessageBox(0, "out", "Vous etes hors champs ", window); } for(nbj=0;nbj<nb;nbj++){ if((x+15)==xcible[nbj] && (y+15)==ycible[nbj]){ set= d_on_tab[nbj]; } } if((x+15)==Drapeau[0] && (y+15)==Drapeau[1]){ action=0; SDL_ShowSimpleMessageBox(0, "WIN", "niv1 terminer ", window); } if (attaque_ennemi(x, y, set, xE, yE, setE)){ Missile=rotozoomSurface(m_1,angles[setE-1], 1, 1); xmissile=xE; ymissile=yE; while(!(xmissile==x && ymissile==y)){ fire(ren,Missile,xmissile,ymissile); xmissile=xmissile+dx[setE-1]; ymissile=ymissile+dy[setE-1]; SDL_RenderPresent(ren); } xmissile = 2000; ymissile = 2000; int k; for(k=0;k<7;k++){ Explosion = explosions[6-k]; fire(ren,Explosion,x,y); SDL_RenderPresent(ren); usleep(75000); } SDL_ShowSimpleMessageBox(0, "HIT", "Vous etes mort", window); action=0; } } } SDL_DestroyRenderer(ren); SDL_DestroyWindow(window); IMG_Quit(); TTF_Quit(); SDL_Quit(); return 0; }
int main(int argc, char *argv[]) { // Initializing and loading variables SDL_Window *window = nullptr; SDL_Texture *currentImage = nullptr; SDL_Renderer *renderTarget = nullptr; SDL_Rect playerRect; SDL_Rect playerPosition; playerPosition.x = playerPosition.y = 0; playerPosition.w = playerPosition.h = 32; int frameWidth, frameHeight; int textureWidth, textureHeight; float frameTime = 0; int prevTime = 0; int currentTime = 0; float deltaTime = 0; float moveSpeed = 200.0f; const Uint8 *keyState; SDL_Init(SDL_INIT_VIDEO); if(TTF_Init() < 0) std::cout << "Error: " << TTF_GetError() << std::endl; int imgFlags = IMG_INIT_PNG | IMG_INIT_JPG; if(IMG_Init(imgFlags) != imgFlags) std::cout << "Error: " << IMG_GetError() << std::endl; window = SDL_CreateWindow("SDL CodingMadeEasy Series", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_SHOWN); renderTarget = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); currentImage = LoadTexture("image.png", renderTarget); SDL_QueryTexture(currentImage, NULL, NULL, &textureWidth, &textureHeight); frameWidth = textureWidth / 3; frameHeight = textureHeight / 4; playerRect.x = playerRect.y = 0; playerRect.w = frameWidth; playerRect.h = frameHeight; TTF_Font *font = TTF_OpenFont("Stiff Staff.otf", 20); SDL_Color color = { 0, 255, 0, 255 }; SDL_Surface *textSurface = TTF_RenderText_Solid(font, "CodingMadeEasy SDL Series!", color); SDL_Texture *text = SDL_CreateTextureFromSurface(renderTarget, textSurface); SDL_Rect textRect; textRect.x = textRect.y = 0; SDL_QueryTexture(text, NULL, NULL, &textRect.w, &textRect.h); SDL_FreeSurface(textSurface); textSurface = nullptr; bool isRunning = true; SDL_Event ev; while(isRunning) { prevTime = currentTime; currentTime = SDL_GetTicks(); deltaTime = (currentTime - prevTime) / 1000.0f; while(SDL_PollEvent(&ev) != 0) { // Getting the events if(ev.type == SDL_QUIT) isRunning = false; } keyState = SDL_GetKeyboardState(NULL); if(keyState[SDL_SCANCODE_RIGHT]) playerPosition.x += moveSpeed * deltaTime; else if(keyState[SDL_SCANCODE_LEFT]) playerPosition.x -= moveSpeed * deltaTime; frameTime += deltaTime; if(frameTime >= 0.25f) { frameTime = 0; playerRect.x += frameWidth; if(playerRect.x >= textureWidth) playerRect.x = 0; } SDL_RenderClear(renderTarget); SDL_RenderCopy(renderTarget, currentImage, &playerRect, &playerPosition); SDL_RenderCopy(renderTarget, text, NULL, &textRect); SDL_RenderPresent(renderTarget); } SDL_DestroyWindow(window); SDL_DestroyTexture(currentImage); SDL_DestroyTexture(text); SDL_DestroyRenderer(renderTarget); TTF_CloseFont(font); window = nullptr; currentImage = nullptr; renderTarget = nullptr; text = nullptr; TTF_Quit(); IMG_Quit(); SDL_Quit(); return 0; }
Window::Window(const std::string &title, Settings &settings, unsigned int x, unsigned int y): Util::System ( "Window" ), _settings(settings) { _fullscreen = _settings.fullscreen; if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0) { throw SDLVideoInitFailedException(); } if (!displayInfo) { displayInfo = new DisplayInfo; } displayInfo->print(); _window = SDL_CreateWindow(title.c_str(), x, y, _settings.width, _settings.height, SDL_WINDOW_INPUT_FOCUS | SDL_WINDOW_HIDDEN | SDL_WINDOW_OPENGL); if (!_window) { throw WindowCreationFailedException(); } SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetSwapInterval(1); _context = SDL_GL_CreateContext(_window); if(!_context) { throw OpenGLContextCreationFailedException(); } glbinding::Binding::initialize(); { Game::log << "-- OpenGL context created:\n"; Game::log << "\t" << glGetString(GL_VENDOR) << "(" << glGetString(GL_RENDERER) << ", " << glGetString(GL_VERSION) << ")\n"; GLint major, minor; glGetIntegerv(GL_MAJOR_VERSION, &major); glGetIntegerv(GL_MINOR_VERSION, &minor); Game::log << "\tContext version: " << major << "." << minor << "\n"; Game::log << "\tShading language version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << "\n"; GLint numExtensions; glGetIntegerv(GL_NUM_EXTENSIONS, &numExtensions); Game::log << "\t+ Extensions:"; if ( numExtensions ) { for (int i = 0; i < numExtensions; ++i) { Game::log << "\n\t\t- (" << i + 1 << ") " << glGetStringi(GL_EXTENSIONS, i); } } else { Game::log << "\n\t\tNone."; } Game::log << std::endl; } glViewport(0, 0, _settings.width, _settings.height); //clearColor({.5f, .5f, .5f, 1.f}); started(); }
int main(int argc, char *argv[]) { /* Declare some variables */ SNDFILE *music_file = NULL; SF_INFO sfinfo; sfinfo.format = 0; printf("Audio visualizer for Comp 467\n"); printf("By: Jorenz Paragas, Carlos Henriquez, Joshua Licudo\n"); printf("----\n"); /* Check if the user provided a .wav file */ if (argc < 2) { fprintf(stderr, "Error: a .wav file was not provided.\n"); fprintf(stderr, "Usage: %s input.wav\n", argv[0]); return EXIT_FAILURE; } /* Open the .wav file */ music_file = sf_open(argv[1], SFM_READ, &sfinfo); if (music_file == NULL) { fprintf(stderr, "Cannot open .wav file: %s\n", argv[1]); return EXIT_FAILURE; } printf("Name of file: %s\n", argv[1]); printf("Sample rate: %d\n", sfinfo.samplerate); printf("Channels: %d\n", sfinfo.channels); /* The buffer size for libsndfile must be as large as the product of * the number of channels and the number of samples to be read */ const int buffer_size = SAMPLE_COUNT * sfinfo.channels; /* For a real-to-complex transform, according to the FFTW docs, * the expected size of the array is n / 2 + 1 */ const int out_buffer_size = buffer_size / 2 + 1; /* Declare the two buffers to hold the data and tell * FFTW how to calculate the frequencies */ double samples[buffer_size]; memset(&samples, 0, buffer_size); fftw_complex output[out_buffer_size]; fftw_plan plan = fftw_plan_dft_r2c_1d(buffer_size, samples, output, FFTW_ESTIMATE); if (plan == NULL) { fprintf(stderr, "Plan cannot be created.\n"); sf_close(music_file); return EXIT_FAILURE; } /* Start SDL */ if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { fprintf(stderr, "SDL_Init error: %s\n", SDL_GetError()); return EXIT_FAILURE; } atexit(SDL_Quit); /* Create the window */ SDL_Window *window = SDL_CreateWindow("Comp 467 Project", 10, 10, WINDOW_WIDTH, WINDOW_HEIGHT, 0); if (window == NULL) { fprintf(stderr, "SDL_CreateWindow error: %s\n", SDL_GetError()); return EXIT_FAILURE; } /* Get the window's surface */ SDL_Surface *surface = SDL_GetWindowSurface(window); /* Initialize the random number generator */ srand(time(NULL)); /* Open the music file */ Mix_OpenAudio(sfinfo.samplerate, MIX_DEFAULT_FORMAT, sfinfo.channels, 4096); Mix_Music *music = Mix_LoadMUS(argv[1]); if (music == NULL) { fprintf(stderr, "Mix_LoadMUS error: %s\n", Mix_GetError()); } /* Start playing it */ Mix_PlayMusic(music, 0); /* Timer-related variables */ unsigned int start_time = SDL_GetTicks(); unsigned int last_time = start_time; unsigned int current_time = start_time; /* The main loop */ bool running = true; while (running) { /* Obtain any user input */ SDL_Event event; while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { running = false; } } /* Based on the sample rate and the current time, * figure out what position to read the audio file from */ double seconds = (current_time - start_time) / 1000.0; //printf("Current time: %.2f\n", seconds); sf_count_t sample_pos = (int) sfinfo.samplerate * seconds; int result = sf_seek(music_file, sample_pos, SEEK_SET); if (result == -1) { running = false; } /* Read the samples */ int samples_read = sf_readf_double(music_file, samples, SAMPLE_COUNT); if (samples_read <= 0) { running = false; } /* Calculate the FFT */ fftw_execute(plan); /* Fill the screen with black first */ SDL_Rect surf_rect; surf_rect.w = WINDOW_WIDTH; surf_rect.h = WINDOW_HEIGHT; surf_rect.x = 0; surf_rect.y = 0; SDL_FillRect(surface, &surf_rect, SDL_MapRGB(surface->format, 0, 0, 0)); /* Draw all the rectangles */ int x_pos; for (x_pos = 0; x_pos < WINDOW_WIDTH; x_pos += 1) { SDL_Rect rect; /* Based on the rectangle's position, get a different * frequency; the second half of the buffer is useless * data, so ignore that portion */ double relative_pos = x_pos * 1.0f / WINDOW_WIDTH; int buf_range_max = out_buffer_size / 2; int index = (int) (relative_pos * buf_range_max); /* Figure out the normalized magnitude of the frequency */ double mag = sqrt(output[index][0] * output[index][0] + output[index][1] * output[index][1]); double norm_mag = mag * (1 / sqrt(buffer_size)); //printf("%d: %f\n", index, norm_mag); /* Set the rectangle's size */ rect.w = 1; rect.h = norm_mag * WINDOW_HEIGHT; /* Set the rectangle's lower left corner */ rect.x = x_pos; rect.y = WINDOW_HEIGHT - rect.h; /* Draw the rectangle to the screen */ SDL_FillRect(surface, &rect, SDL_MapRGB(surface->format, 0, 0, 255)); } /* Update the display */ SDL_UpdateWindowSurface(window); /* Ensure that it runs around 30 FPS and also update the * timer variables */ current_time = SDL_GetTicks(); int delta = current_time - last_time; if (delta <= 33) { SDL_Delay(33 - delta); } last_time = current_time; } /* Stop the music and free its memory */ Mix_HaltMusic(); Mix_FreeMusic(music); /* Clean up and exit */ SDL_FreeSurface(surface); SDL_DestroyWindow(window); fftw_destroy_plan(plan); sf_close(music_file); return EXIT_SUCCESS; }
int main(void) { gamestate game; SDL_Window* window = NULL; game.renderer = NULL; SDL_Init(SDL_INIT_VIDEO); time_t t; srand(time(&t)); window = SDL_CreateWindow( "Game Window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, 0 ); if (window == NULL) { printf("Window initialization failed: %s\n", SDL_GetError()); return 1; } game.renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); TTF_Init(); if (game.renderer == NULL) { printf("Rendering failed: %s\n", SDL_GetError()); return 1; } loadGame(&game); int done = 0; while (!done) { processEvents(window, &done, &game); process(&game); collisionDetect(&game); doRender(&game); } SDL_DestroyTexture(game.spook[0]); SDL_DestroyTexture(game.spook[1]); SDL_DestroyTexture(game.spook[2]); SDL_DestroyTexture(game.tile); if (game.label != NULL) { SDL_DestroyTexture(game.label); } TTF_CloseFont(game.font); SDL_DestroyWindow(window); SDL_DestroyRenderer(game.renderer); TTF_Quit(); SDL_Quit(); return 0; }
SDL_Window *GLFuncs::Initialize(int screenWidth, int screenHeight, GLboolean fullscreen, const char* name) { Uint32 flags; if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { Log::Out << "Unable to initialize SDL: " << SDL_GetError() << endl; return NULL; } atexit(SDL_Quit); flags = SDL_WINDOW_OPENGL; _screenWidth = screenWidth; _screenHeight = screenHeight; _windowWidth = _screenWidth; _windowHeight = _screenHeight; if (fullscreen) { flags |= SDL_WINDOW_FULLSCREEN; SDL_DisplayMode currentDisplay; if(SDL_GetCurrentDisplayMode(0, ¤tDisplay)) { Log::Out << "Couldn't get current display mode: " << SDL_GetError() << endl; } else { Log::Out << "Current display mode: " << currentDisplay.w << "x" << currentDisplay.h << endl; _windowWidth = currentDisplay.w; _windowHeight = currentDisplay.h; } } Log::Out << "Window size: " << _windowWidth << "x" << _windowHeight << endl; int realW, realH; GetRealSize(&realW, &realH); Log::Out << "Real size: " << realW << "x" << realH << endl; this->StaticProjection = glm::ortho(0.0f, (float)_windowWidth, (float)_windowHeight, 0.0f, -1.0f, 1.0f); setGLAttributes(); _window = SDL_CreateWindow(name, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, _windowWidth, _windowHeight, flags); if (!_window) { Log::Out << "Unable to create window." << endl; checkSDLError(__LINE__); } SDL_Surface *icon = Pack::GetInstance()->GetImg("data/UWOLIcon.png"); SDL_SetWindowIcon(_window, icon); _mainContext = SDL_GL_CreateContext(_window); SDL_GL_MakeCurrent(_window, _mainContext); #ifndef __APPLE__ glewExperimental = GL_TRUE; glewInit(); #endif char* obtainedVersion = (char*)glGetString(GL_VERSION); string glVersion = getVersionFromStr(obtainedVersion); Log::Out << "OpenGL: " << obtainedVersion << endl; int version; stringstream ss(glVersion); ss >> version; #ifdef __APPLE__ this->_useShaders = true; #else this->_useShaders = (glCreateProgram != NULL); //version >= 20; #endif if (_useShaders) { this->_vtxAttribIdx = 0; this->_uvAttribIdx = 1; this->_colAttribIdx = 2; this->_glslVersion = getGLSLVersion(); Log::Out << "GLSL: " << (this->_glslVersion == "" ? "Not available!" : this->_glslVersion) << endl; } else { Log::Out << "Shaders are not available" << endl; } this->_useVBO = (glGenVertexArrays!=NULL); //version >= 20; if (this->_useVBO) { this->_useFramebuffer = this->initFramebuffer(); } glViewport(0, 0, _screenWidth, _screenHeight); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glDisable(GL_DEPTH_TEST); glDepthMask(GL_FALSE); // glShadeModel(GL_SMOOTH); glDisable(GL_CULL_FACE); //#if !ESSENTIAL_GL_PRACTICES_SUPPORT_GL3 // //glEnable(GL_ALPHA_TEST); // //glAlphaFunc(GL_GREATER, 0.01f); // //glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); //#endif glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glPointSize(2.0f); if (this->_useVBO) { glGenVertexArrays(1, &_vaoVertex); glBindVertexArray(_vaoVertex); glGenBuffers(1, &_vboVertex); glGenBuffers(1, &_vboUV); glGenBuffers(1, &_vboColor); glGenBuffers(1, &_vboLineVertex); } this->ResetMVP(); GLint texture_units; glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &texture_units); _activeTextures.resize(texture_units, 0); return _window; }
render::render(std::string manifest) { std::string in = get_file_contents(manifest.c_str()); Json::Value root; Json::Reader reader; bool stat = reader.parse( in, root ); if (stat){ FONT_NAME_ARIAL = root["FontArial"].asString(); FONT_NAME_COMIC = root["FontComic"].asString(); WINDOW_SIZE_X = root["WindowSize"]["x"].asInt(); WINDOW_SIZE_Y = root["WindowSize"]["y"].asInt(); TILE_SIZE = root["TileSize"].asInt(); BATTLEBACKGROUND = root["BattleBackground"].asString(); FRAME = root["Frame"].asString(); FRAME_SIDE = root["FrameSide"].asString(); FRAME_TITLE = root["FrameTitle"].asString(); CHAR_MENU = root["CharMenuOption"].asString(); CHAR_MENU_SELECTED = root["CharMenuSelect"].asString(); PROMPT = root["Prompt"].asString(); BATTLEMENU = root["BattleMenu"].asString(); }else{ std::cout << "Failed to parse manifest\n" << reader.getFormatedErrorMessages(); exit(128); } if (SDL_Init(SDL_INIT_EVERYTHING) != 0){ std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl; throw(122); } win = SDL_CreateWindow("RPG", 100, 100, WINDOW_SIZE_X, WINDOW_SIZE_Y, SDL_WINDOW_SHOWN); if (win == nullptr){ std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl; throw(122); } ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (ren == nullptr){ std::cout << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl; throw(122); } TTF_Init(); font_arial16 = TTF_OpenFont(FONT_NAME_ARIAL.c_str(), 16); font_comic16 = TTF_OpenFont(FONT_NAME_COMIC.c_str(), 16); font_comic32 = TTF_OpenFont(FONT_NAME_COMIC.c_str(), 32); font_comic50 = TTF_OpenFont(FONT_NAME_COMIC.c_str(), 50); if (font_arial16 == nullptr){ std::cout << "SDL_CreateFont Error: " << SDL_GetError() << std::endl; throw(122); } if (font_comic16 == nullptr){ std::cout << "SDL_CreateFont Error: " << SDL_GetError() << std::endl; throw(122); } if (font_comic32 == nullptr){ std::cout << "SDL_CreateFont Error: " << SDL_GetError() << std::endl; throw(122); } if (font_comic50 == nullptr){ std::cout << "SDL_CreateFont Error: " << SDL_GetError() << std::endl; throw(122); } }
int main(int argc, char **argv) { if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl; return 0; } SDL_Window *win = SDL_CreateWindow("Hello World", 100, 100, 640, 480, SDL_WINDOW_SHOWN); if (win == nullptr) { std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl; SDL_Quit(); return 1; } SDL_Renderer *ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (ren == nullptr) { SDL_DestroyWindow(win); std::cout << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl; SDL_Quit(); return 1; } std::string imagePath = getResourcePath("Lesson1") + "mad_tux.bmp"; SDL_Surface *bmp = SDL_LoadBMP(imagePath.c_str()); if (bmp == nullptr) { SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); std::cout << "SDL_LoadBMP Error: " << SDL_GetError() << std::endl; SDL_Quit(); return 1; } SDL_Texture *tex = SDL_CreateTextureFromSurface(ren, bmp); SDL_FreeSurface(bmp); if (tex == nullptr) { SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); std::cout << "SDL_CreateTextureFromSurface Error: " << SDL_GetError() << std::endl; SDL_Quit(); return 1; } SDL_RenderClear(ren); SDL_RenderCopy(ren, tex, NULL, NULL); SDL_RenderPresent(ren); SDL_Delay(8000); // Cleaning up SDL_DestroyTexture(tex); SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); SDL_Quit(); return 0; }