void SDLHardwareImage::fillWithColor(Uint32 color) {
	if (!surface) return;

	Uint32 u_format;
	SDL_QueryTexture(surface, &u_format, NULL, NULL, NULL);
	SDL_PixelFormat* format = SDL_AllocFormat(u_format);

	if (!format) return;

	SDL_Color rgba;
	SDL_GetRGBA(color, format, &rgba.r, &rgba.g, &rgba.b, &rgba.a);
	SDL_FreeFormat(format);

	SDL_SetRenderTarget(renderer, surface);
	SDL_SetTextureBlendMode(surface, SDL_BLENDMODE_BLEND);
	SDL_SetRenderDrawColor(renderer, rgba.r, rgba.g , rgba.b, rgba.a);
	SDL_RenderClear(renderer);
	SDL_SetRenderTarget(renderer, NULL);
}
/*
 * Set the pixel at (x, y) to the given value
 */
void SDLHardwareImage::drawPixel(int x, int y, Uint32 pixel) {
	if (!surface) return;

	Uint32 u_format;
	SDL_QueryTexture(surface, &u_format, NULL, NULL, NULL);
	SDL_PixelFormat* format = SDL_AllocFormat(u_format);

	if (!format) return;

	SDL_Color rgba;
	SDL_GetRGBA(pixel, format, &rgba.r, &rgba.g, &rgba.b, &rgba.a);
	SDL_FreeFormat(format);

	SDL_SetRenderTarget(renderer, surface);
	SDL_SetTextureBlendMode(surface, SDL_BLENDMODE_BLEND);
	SDL_SetRenderDrawColor(renderer, rgba.r, rgba.g, rgba.b, rgba.a);
	SDL_RenderDrawPoint(renderer, x, y);
	SDL_SetRenderTarget(renderer, NULL);
}
void SDLHardwareRenderDevice::drawLine(
	int x0,
	int y0,
	int x1,
	int y1,
	Uint32 color
) {
	Uint32 u_format = SDL_GetWindowPixelFormat(window);
	SDL_PixelFormat* format = SDL_AllocFormat(u_format);

	if (!format) return;

	SDL_Color rgba;
	SDL_GetRGBA(color, format, &rgba.r, &rgba.g, &rgba.b, &rgba.a);
	SDL_FreeFormat(format);

	SDL_SetRenderDrawColor(renderer, rgba.r, rgba.g, rgba.b, rgba.a);
	SDL_RenderDrawLine(renderer, x0, y0, x1, y1);
}
Esempio n. 4
0
const SDL_VideoInfo *
SDL_GetVideoInfo(void)
{
    static SDL_VideoInfo info;
    SDL_DisplayMode mode;

    /* Memory leak, compatibility code, who cares? */
    if (!info.vfmt && SDL_GetDesktopDisplayMode(&mode) == 0) {
        int bpp;
        Uint32 Rmask, Gmask, Bmask, Amask;

        SDL_PixelFormatEnumToMasks(mode.format, &bpp, &Rmask, &Gmask, &Bmask,
                                   &Amask);
        info.vfmt = SDL_AllocFormat(bpp, Rmask, Gmask, Bmask, Amask);
        info.current_w = mode.w;
        info.current_h = mode.h;
    }
    return &info;
}
Esempio n. 5
0
int main(int argc, char** argv) 
#endif
{
#ifdef _WIN32
	LPSTR *argv = __argv;
	int argc = __argc;
	(void) argv;
	(void) argc;
#endif 
	SDL_Window *screen;
	SDL_Renderer *renderer;
	SDL_Shader *shader;

	if ( SDL_Init(SDL_INIT_VIDEO) < 0 ){
		fprintf(stderr, "Error: %s \n", SDL_GetError());
		return 1;
	}

    SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 );
    SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 0 );
    SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
    SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 24 );

	SDL_SetHint( SDL_HINT_RENDER_DRIVER, getenv("RENDER_DRIVER") ); 

	int width = 500;
	int height = 700;
	screen = SDL_CreateWindow("Caption",
			SDL_WINDOWPOS_CENTERED,
			SDL_WINDOWPOS_CENTERED,
			width, height,
			SDL_WINDOW_RESIZABLE);
			// SDL_WINDOW_FULLSCREEN_DESKTOP );
	if ( screen == NULL ) {
		fprintf(stderr, "Error: %s \n", SDL_GetError());
		return 2;
	}
	renderer = SDL_CreateRenderer( screen, -1, SDL_RENDERER_ACCELERATED|SDL_RENDERER_TARGETTEXTURE );
	//renderer = SDL_CreateRenderer( screen, -1, SDL_RENDERER_SOFTWARE|SDL_RENDERER_TARGETTEXTURE );
	if ( renderer == NULL ) {
		fprintf(stderr, "Error: %s \n", SDL_GetError());
		return 3;
	}

	SDL_RenderSetLogicalSize(renderer, width, height);

	SDL_SetWindowTitle( screen, renderer->info.name );

	SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
	SDL_RenderClear(renderer);


	printf("renderer name: %s\n" , renderer->info.name );
	printf("SDL_PIXELFORMAT_UNKNOWN=    %d\n",SDL_PIXELFORMAT_UNKNOWN);
	printf("SDL_PIXELFORMAT_INDEX1LSB=  %d\n",SDL_PIXELFORMAT_INDEX1LSB);
	printf("SDL_PIXELFORMAT_INDEX1MSB=  %d\n",SDL_PIXELFORMAT_INDEX1MSB);
	printf("SDL_PIXELFORMAT_INDEX4LSB=  %d\n",SDL_PIXELFORMAT_INDEX4LSB);
	printf("SDL_PIXELFORMAT_INDEX4MSB=  %d\n",SDL_PIXELFORMAT_INDEX4MSB);
	printf("SDL_PIXELFORMAT_INDEX8=     %d\n",SDL_PIXELFORMAT_INDEX8);
	printf("SDL_PIXELFORMAT_RGB332=     %d\n",SDL_PIXELFORMAT_RGB332);
	printf("SDL_PIXELFORMAT_RGB444=     %d\n",SDL_PIXELFORMAT_RGB444);
	printf("SDL_PIXELFORMAT_RGB555=     %d\n",SDL_PIXELFORMAT_RGB555);
	printf("SDL_PIXELFORMAT_BGR555=     %d\n",SDL_PIXELFORMAT_BGR555);
	printf("SDL_PIXELFORMAT_ARGB4444=   %d\n",SDL_PIXELFORMAT_ARGB4444);
	printf("SDL_PIXELFORMAT_RGBA4444=   %d\n",SDL_PIXELFORMAT_RGBA4444);
	printf("SDL_PIXELFORMAT_ABGR4444=   %d\n",SDL_PIXELFORMAT_ABGR4444);
	printf("SDL_PIXELFORMAT_BGRA4444=   %d\n",SDL_PIXELFORMAT_BGRA4444);
	printf("SDL_PIXELFORMAT_ARGB1555=   %d\n",SDL_PIXELFORMAT_ARGB1555);
	printf("SDL_PIXELFORMAT_RGBA5551=   %d\n",SDL_PIXELFORMAT_RGBA5551);
	printf("SDL_PIXELFORMAT_ABGR1555=   %d\n",SDL_PIXELFORMAT_ABGR1555);
	printf("SDL_PIXELFORMAT_BGRA5551=   %d\n",SDL_PIXELFORMAT_BGRA5551);
	printf("SDL_PIXELFORMAT_RGB565=     %d\n",SDL_PIXELFORMAT_RGB565);
	printf("SDL_PIXELFORMAT_BGR565=     %d\n",SDL_PIXELFORMAT_BGR565);
	printf("SDL_PIXELFORMAT_RGB24=      %d\n",SDL_PIXELFORMAT_RGB24);
	printf("SDL_PIXELFORMAT_BGR24=      %d\n",SDL_PIXELFORMAT_BGR24);
	printf("SDL_PIXELFORMAT_RGB888=     %d\n",SDL_PIXELFORMAT_RGB888);
	printf("SDL_PIXELFORMAT_RGBX8888=   %d\n",SDL_PIXELFORMAT_RGBX8888);
	printf("SDL_PIXELFORMAT_BGR888=     %d\n",SDL_PIXELFORMAT_BGR888);
	printf("SDL_PIXELFORMAT_BGRX8888=   %d\n",SDL_PIXELFORMAT_BGRX8888);
	printf("SDL_PIXELFORMAT_ARGB8888=   %d\n",SDL_PIXELFORMAT_ARGB8888);
	printf("SDL_PIXELFORMAT_RGBA8888=   %d\n",SDL_PIXELFORMAT_RGBA8888);
	printf("SDL_PIXELFORMAT_ABGR8888=   %d\n",SDL_PIXELFORMAT_ABGR8888);
	printf("SDL_PIXELFORMAT_BGRA8888=   %d\n",SDL_PIXELFORMAT_BGRA8888);
	printf("SDL_PIXELFORMAT_ARGB2101010=%d\n",SDL_PIXELFORMAT_ARGB2101010);

	shader = SDL_createShader( renderer, "../shaders/do_nothing/do_nothing" );
	if ( shader == NULL ){
		fprintf(stderr, "Error: %s \n", SDL_GetError());
		return 4;
	}

	SDL_Surface* srf;
	srf = IMG_Load( "../img.png" );
	if ( !srf ) {
		fprintf(stderr, "Error: %s \n", SDL_GetError());
		return 5;
	}

	int i;
	Uint32 formats[] = {
		/* Indexed formats and YUV are not supported */
		SDL_PIXELFORMAT_RGB332,
		SDL_PIXELFORMAT_RGB444,
		SDL_PIXELFORMAT_RGB555,
		SDL_PIXELFORMAT_BGR555,
		SDL_PIXELFORMAT_ARGB4444,
		SDL_PIXELFORMAT_RGBA4444,
		SDL_PIXELFORMAT_ABGR4444,
		SDL_PIXELFORMAT_BGRA4444,
		SDL_PIXELFORMAT_ARGB1555,
		SDL_PIXELFORMAT_RGBA5551,
		SDL_PIXELFORMAT_ABGR1555,
		SDL_PIXELFORMAT_BGRA5551,
		SDL_PIXELFORMAT_RGB565,
		SDL_PIXELFORMAT_BGR565,
		SDL_PIXELFORMAT_RGB24,
		SDL_PIXELFORMAT_BGR24,
		SDL_PIXELFORMAT_RGB888,
		SDL_PIXELFORMAT_RGBX8888,
		SDL_PIXELFORMAT_BGR888,
		SDL_PIXELFORMAT_BGRX8888,
		SDL_PIXELFORMAT_ARGB8888,
		SDL_PIXELFORMAT_RGBA8888,
		SDL_PIXELFORMAT_ABGR8888,
		SDL_PIXELFORMAT_BGRA8888,
		SDL_PIXELFORMAT_ARGB2101010
	};
	
	char fmt_names[][NUM_OF_TEXTURES] = {
		"RGB332",
		"RGB444",
		"RGB555",
		"BGR555",
		"ARGB4444",
		"RGBA4444",
		"ABGR4444",
		"BGRA4444",
		"ARGB1555",
		"RGBA5551",
		"ABGR1555",
		"BGRA5551",
		"RGB565",
		"BGR565",
		"RGB24",
		"BGR24",
		"RGB888",
		"RGBX8888",
		"BGR888",
		"BGRX8888",
		"ARGB8888",
		"RGBA8888",
		"ABGR8888",
		"BGRA8888",
		"ARGB2101010"
	};

	SDL_BlendMode blendModes[] = {
		SDL_BLENDMODE_NONE,
		SDL_BLENDMODE_BLEND,
		SDL_BLENDMODE_ADD,
		SDL_BLENDMODE_MOD
	};
	char* blendNames[] = {
		"NONE",
		"BLEND",
		"ADD",
		"MOD"
	};
	int current_blend = 0;

	int colors[][4] = {
		{255,255,255,255},
		{255,  0,  0,255},
		{  0,255,  0,255},
		{  0,  0,255,255},
		{255,255,255,127}
	};
	char* colorNames[] = {
		"white",
		"red",
		"green",
		"blue",
		"semi transp."
	};
	int current_color = 0;

	SDL_Texture* textures[ NUM_OF_TEXTURES ];
	
	for ( i=0; i< (int)(NUM_OF_TEXTURES); i++) {
		SDL_PixelFormat* fmt = SDL_AllocFormat( formats[i] );
			SDL_assert(fmt != NULL);
		SDL_Surface* srf2 = SDL_ConvertSurface(srf, fmt, 0);
			SDL_assert(srf2 != NULL);
		textures[i] = SDL_CreateTextureFromSurface(renderer, srf2 );

		SDL_SetTextureBlendMode(textures[i], blendModes[current_blend]);
		SDL_FreeSurface( srf2 );
		SDL_FreeFormat(fmt);

		if ( !textures[i] ){
			return 1000 + i;
		}

		if ( textures[i]->native ){
			printf("native_tex: %d \n",textures[i]->native->format );
		}else{
			printf("SDL_tex: %d \n",textures[i]->format );
		}

	}
	SDL_FreeSurface(srf);

	SDL_SetRenderTarget( renderer, NULL );
	SDL_Event e;
	SDL_SetRenderDrawColor(renderer, 0,0,0,1);
	int ret = 0;
	int quit = 0;

	while ( !quit ) {
		SDLTest_DrawString( renderer,   8,   8, blendNames[current_blend] );
		SDLTest_DrawString( renderer, 108,   8, colorNames[current_color] );
		for ( i=0; i< (int)(NUM_OF_TEXTURES); i++) {
			int x=30+(i%8)*55;
			int y=30+(i/8)*75;
			SDL_Rect dst = {x,y,50,50};
			ret = SDL_renderCopyShd( shader, textures[i], NULL, &dst );
			if ( ret!=0 ){
				fprintf(stderr,"Err: %s\n", SDL_GetError());
			}
			SDLTest_DrawString( renderer, dst.x,dst.y+55 + (i%2==0 ? 10 : 0), fmt_names[i] );
			
			dst.y += (NUM_OF_TEXTURES)/8 * 75 + 85;
			SDL_RenderCopy( renderer, textures[i], NULL, &dst );
			SDLTest_DrawString( renderer, dst.x,dst.y+55 + (i%2==0 ? 10 : 0), fmt_names[i] );

		}
		while (SDL_PollEvent(&e)){
			switch ( e.type ) {
				case SDL_QUIT: 
					quit = 1; 
					break;
				case SDL_KEYDOWN: 
					switch ( e.key.keysym.sym ) {
						case SDLK_SPACE:
							current_blend = (current_blend+1)%4;
							for ( i=0; i< (int)(NUM_OF_TEXTURES); i++) {
								SDL_SetTextureBlendMode(textures[i], blendModes[current_blend]);
							}
							break;
						case SDLK_TAB:
							current_color = (current_color+1)%5;
							for ( i=0; i< (int)(NUM_OF_TEXTURES); i++) {
								SDL_SetTextureColorMod(textures[i], 
										colors[current_color][0],
										colors[current_color][1],
										colors[current_color][2]);
								SDL_SetTextureAlphaMod(textures[i], colors[current_color][3] );
							}
							break;
					}
					break;
				case SDL_WINDOWEVENT:
					SDL_updateViewport( shader );
			}
		}

		SDL_RenderPresent(renderer);

		SDL_SetRenderDrawColor(renderer, 160, 160, 160, 255);
		SDL_RenderClear(renderer);
		SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);

	}
	for ( i=0; i<(int)NUM_OF_TEXTURES; i++ ) {
		SDL_DestroyTexture( textures[i] );
		textures[i] = NULL;
	}
	SDL_destroyShader( shader );
	SDL_DestroyRenderer( renderer );
	SDL_DestroyWindow( screen );
	SDL_Quit();

	return 0;
}
Esempio n. 6
0
void GraphicsInitialize(GraphicsDevice *g)
{
    if (g->IsInitialized && !g->cachedConfig.RestartFlags)
    {
        return;
    }

    if (!g->IsWindowInitialized)
    {
        char buf[CDOGS_PATH_MAX];
        GetDataFilePath(buf, "cdogs_icon.bmp");
        g->icon = IMG_Load(buf);
        AddSupportedGraphicsModes(g);
        g->IsWindowInitialized = true;
    }

    g->IsInitialized = false;

    const int w = g->cachedConfig.Res.x;
    const int h = g->cachedConfig.Res.y;

    const bool initRenderer =
        !!(g->cachedConfig.RestartFlags & RESTART_RESOLUTION);
    const bool initTextures =
        !!(g->cachedConfig.RestartFlags &
           (RESTART_RESOLUTION | RESTART_SCALE_MODE));
    const bool initBrightness =
        !!(g->cachedConfig.RestartFlags &
           (RESTART_RESOLUTION | RESTART_SCALE_MODE | RESTART_BRIGHTNESS));

    if (initRenderer)
    {
        Uint32 sdlFlags = SDL_WINDOW_RESIZABLE;
        if (g->cachedConfig.Fullscreen)
        {
            sdlFlags |= SDL_WINDOW_FULLSCREEN;
        }

        LOG(LM_GFX, LL_INFO, "graphics mode(%dx%d %dx)",
            w, h, g->cachedConfig.ScaleFactor);
        // Get the previous window's size and recreate it
        Vec2i windowSize = Vec2iNew(
                               w * g->cachedConfig.ScaleFactor, h * g->cachedConfig.ScaleFactor);
        if (g->window)
        {
            SDL_GetWindowSize(g->window, &windowSize.x, &windowSize.y);
        }
        LOG(LM_GFX, LL_DEBUG, "destroying previous renderer");
        SDL_DestroyTexture(g->screen);
        SDL_DestroyTexture(g->bkg);
        SDL_DestroyTexture(g->brightnessOverlay);
        SDL_DestroyRenderer(g->renderer);
        SDL_FreeFormat(g->Format);
        SDL_DestroyWindow(g->window);
        LOG(LM_GFX, LL_DEBUG, "creating window %dx%d flags(%X)",
            windowSize.x, windowSize.y, sdlFlags);
        if (SDL_CreateWindowAndRenderer(
                    windowSize.x, windowSize.y, sdlFlags,
                    &g->window, &g->renderer) == -1 ||
                g->window == NULL || g->renderer == NULL)
        {
            LOG(LM_GFX, LL_ERROR, "cannot create window or renderer: %s",
                SDL_GetError());
            return;
        }
        char title[32];
        sprintf(title, "C-Dogs SDL %s%s",
                g->cachedConfig.IsEditor ? "Editor " : "",
                CDOGS_SDL_VERSION);
        LOG(LM_GFX, LL_DEBUG, "setting title(%s) and icon", title);
        SDL_SetWindowTitle(g->window, title);
        SDL_SetWindowIcon(g->window, g->icon);
        g->Format = SDL_AllocFormat(SDL_PIXELFORMAT_ARGB8888);

        if (SDL_RenderSetLogicalSize(g->renderer, w, h) != 0)
        {
            LOG(LM_GFX, LL_ERROR, "cannot set renderer logical size: %s",
                SDL_GetError());
            return;
        }

        GraphicsSetBlitClip(
            g, 0, 0, g->cachedConfig.Res.x - 1, g->cachedConfig.Res.y - 1);
    }

    if (initTextures)
    {
        if (!initRenderer)
        {
            SDL_DestroyTexture(g->screen);
            SDL_DestroyTexture(g->bkg);
            SDL_DestroyTexture(g->brightnessOverlay);
        }

        // Set render scale mode
        const char *renderScaleQuality = "nearest";
        switch ((ScaleMode)ConfigGetEnum(&gConfig, "Graphics.ScaleMode"))
        {
        case SCALE_MODE_NN:
            renderScaleQuality = "nearest";
            break;
        case SCALE_MODE_BILINEAR:
            renderScaleQuality = "linear";
            break;
        default:
            CASSERT(false, "unknown scale mode");
            break;
        }
        LOG(LM_GFX, LL_DEBUG, "setting scale quality %s", renderScaleQuality);
        if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, renderScaleQuality))
        {
            LOG(LM_GFX, LL_WARN, "cannot set render quality hint: %s",
                SDL_GetError());
        }

        g->screen = CreateTexture(
                        g->renderer, SDL_TEXTUREACCESS_STREAMING, Vec2iNew(w, h),
                        SDL_BLENDMODE_BLEND, 255);
        if (g->screen == NULL)
        {
            return;
        }

        CFREE(g->buf);
        CCALLOC(g->buf, GraphicsGetMemSize(&g->cachedConfig));
        g->bkg = CreateTexture(
                     g->renderer, SDL_TEXTUREACCESS_STATIC, Vec2iNew(w, h),
                     SDL_BLENDMODE_NONE, 255);
        if (g->bkg == NULL)
        {
            return;
        }
    }

    if (initBrightness)
    {
        if (!initRenderer && !initTextures)
        {
            SDL_DestroyTexture(g->brightnessOverlay);
        }

        const int brightness = ConfigGetInt(&gConfig, "Graphics.Brightness");
        // Alpha is approximately 50% max
        const Uint8 alpha = (Uint8)(brightness > 0 ? brightness : -brightness) * 13;
        g->brightnessOverlay = CreateTexture(
                                   g->renderer, SDL_TEXTUREACCESS_STATIC, Vec2iNew(w, h),
                                   SDL_BLENDMODE_BLEND, alpha);
        if (g->brightnessOverlay == NULL)
        {
            return;
        }
        const color_t overlayColour = brightness > 0 ? colorWhite : colorBlack;
        DrawRectangle(g, Vec2iZero(), g->cachedConfig.Res, overlayColour, 0);
        SDL_UpdateTexture(
            g->brightnessOverlay, NULL, g->buf,
            g->cachedConfig.Res.x * sizeof(Uint32));
        memset(g->buf, 0, GraphicsGetMemSize(&g->cachedConfig));
        g->cachedConfig.Brightness = brightness;
    }

    g->IsInitialized = true;
    g->cachedConfig.Res.x = w;
    g->cachedConfig.Res.y = h;
    g->cachedConfig.RestartFlags = 0;
}
Esempio n. 7
0
SDL_Renderer *
SW_CreateRenderer(SDL_Window * window, Uint32 flags)
{
    SDL_VideoDisplay *display = SDL_GetDisplayFromWindow(window);
    SDL_DisplayMode *displayMode = &display->current_mode;
    SDL_Renderer *renderer;
    SW_RenderData *data;
    int i, n;
    int bpp;
    Uint32 Rmask, Gmask, Bmask, Amask;
    Uint32 renderer_flags;
    const char *desired_driver;

    if (!SDL_PixelFormatEnumToMasks
        (displayMode->format, &bpp, &Rmask, &Gmask, &Bmask, &Amask)) {
        SDL_SetError("Unknown display format");
        return NULL;
    }

    renderer = (SDL_Renderer *) SDL_calloc(1, sizeof(*renderer));
    if (!renderer) {
        SDL_OutOfMemory();
        return NULL;
    }

    data = (SW_RenderData *) SDL_calloc(1, sizeof(*data));
    if (!data) {
        SW_DestroyRenderer(renderer);
        SDL_OutOfMemory();
        return NULL;
    }
    renderer->ActivateRenderer = SW_ActivateRenderer;
    renderer->DisplayModeChanged = SW_DisplayModeChanged;

    renderer->RenderPoint = SW_RenderPoint;
    renderer->RenderLine = SW_RenderLine;
    renderer->RenderFill = SW_RenderFill;
    renderer->RenderCopy = SW_RenderCopy;
    renderer->RenderPresent = SW_RenderPresent;
    renderer->DestroyRenderer = SW_DestroyRenderer;
    renderer->info.name = SW_RenderDriver.info.name;
    renderer->info.flags = 0;
    renderer->window = window->id;
    renderer->driverdata = data;
    Setup_SoftwareRenderer(renderer);

    if (flags & SDL_RENDERER_PRESENTFLIP2) {
        renderer->info.flags |= SDL_RENDERER_PRESENTFLIP2;
        n = 2;
    } else if (flags & SDL_RENDERER_PRESENTFLIP3) {
        renderer->info.flags |= SDL_RENDERER_PRESENTFLIP3;
        n = 3;
    } else {
        renderer->info.flags |= SDL_RENDERER_PRESENTCOPY;
        n = 1;
    }
    data->format = displayMode->format;

    /* Find a render driver that we can use to display data */
    renderer_flags = (SDL_RENDERER_SINGLEBUFFER |
                      SDL_RENDERER_PRESENTDISCARD);
    if (flags & SDL_RENDERER_PRESENTVSYNC) {
        renderer_flags |= SDL_RENDERER_PRESENTVSYNC;
    }
    desired_driver = SDL_getenv("SDL_VIDEO_RENDERER_SWDRIVER");
    for (i = 0; i < display->num_render_drivers; ++i) {
        SDL_RenderDriver *driver = &display->render_drivers[i];
        if (driver->info.name == SW_RenderDriver.info.name) {
            continue;
        }
        if (desired_driver
            && SDL_strcasecmp(desired_driver, driver->info.name) != 0) {
            continue;
        }
        data->renderer = driver->CreateRenderer(window, renderer_flags);
        if (data->renderer) {
            break;
        }
    }
    if (i == display->num_render_drivers) {
        SW_DestroyRenderer(renderer);
        SDL_SetError("Couldn't find display render driver");
        return NULL;
    }
    if (data->renderer->info.flags & SDL_RENDERER_PRESENTVSYNC) {
        renderer->info.flags |= SDL_RENDERER_PRESENTVSYNC;
    }

    /* Create the textures we'll use for display */
    for (i = 0; i < n; ++i) {
        data->texture[i] =
            CreateTexture(data->renderer, data->format, window->w, window->h);
        if (!data->texture[i]) {
            SW_DestroyRenderer(renderer);
            return NULL;
        }
    }
    data->current_texture = 0;

    /* Create a surface we'll use for rendering */
    data->surface.flags = SDL_PREALLOC;
    data->surface.format = SDL_AllocFormat(bpp, Rmask, Gmask, Bmask, Amask);
    if (!data->surface.format) {
        SW_DestroyRenderer(renderer);
        return NULL;
    }
    SDL_SetSurfacePalette(&data->surface, display->palette);

    /* Set up a palette watch on the display palette */
    if (display->palette) {
        SDL_AddPaletteWatch(display->palette, DisplayPaletteChanged, data);
    }

    return renderer;
}
/*
 * Create an empty RGB surface of the appropriate depth
 */
SDL_Surface * SDL_CreateRGBSurface (Uint32 flags,
			int width, int height, int depth,
			Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask)
{
	SDL_Surface *surface;

	/* Make sure the size requested doesn't overflow our datatypes */
	/* Next time I write a library like SDL, I'll use int for size. :) */
	if ( width >= 16384 || height >= 65536 ) {
		SDL_SetError("Width or height is too large");
		return(NULL);
	}

	flags &= ~SDL_HWSURFACE;

	/* Allocate the surface */
	surface = (SDL_Surface *)SDL_malloc(sizeof(*surface));
	if (!surface)
   {
		SDL_OutOfMemory();
		return(NULL);
	}
	surface->flags = SDL_SWSURFACE;

	surface->format = SDL_AllocFormat(depth, Rmask, Gmask, Bmask, Amask);
	if (!surface->format)
   {
		SDL_free(surface);
		return(NULL);
	}

	if (Amask)
		surface->flags |= SDL_SRCALPHA;
	surface->w = width;
	surface->h = height;
	surface->pitch = SDL_CalculatePitch(surface);
	surface->pixels = NULL;
	surface->offset = 0;
	surface->hwdata = NULL;
	surface->locked = 0;
	surface->map = NULL;
	surface->unused1 = 0;
	SDL_SetClipRect(surface, NULL);
	SDL_FormatChanged(surface);

	/* Get the pixels */
	if ( ((flags&SDL_HWSURFACE) == SDL_SWSURFACE))
   {
      if ( surface->w && surface->h )
      {
         surface->pixels = SDL_malloc(surface->h*surface->pitch);
         if (!surface->pixels)
         {
            SDL_FreeSurface(surface);
            SDL_OutOfMemory();
            return(NULL);
         }
         /* This is important for bitmaps */
         SDL_memset(surface->pixels, 0, surface->h*surface->pitch);
      }
   }

	/* Allocate an empty mapping */
	surface->map = SDL_AllocBlitMap();
	if (!surface->map)
   {
      SDL_FreeSurface(surface);
      return(NULL);
   }

	/* The surface is ready to go */
	surface->refcount = 1;
	return(surface);
}
Esempio n. 9
0
/* !
 *  Tests surface conversion across all pixel formats.
 */
int
surface_testCompleteSurfaceConversion(void *arg)
{
    Uint32 pixel_formats[] = {
        SDL_PIXELFORMAT_INDEX8,
        SDL_PIXELFORMAT_RGB332,
        SDL_PIXELFORMAT_RGB444,
        SDL_PIXELFORMAT_RGB555,
        SDL_PIXELFORMAT_BGR555,
        SDL_PIXELFORMAT_ARGB4444,
        SDL_PIXELFORMAT_RGBA4444,
        SDL_PIXELFORMAT_ABGR4444,
        SDL_PIXELFORMAT_BGRA4444,
        SDL_PIXELFORMAT_ARGB1555,
        SDL_PIXELFORMAT_RGBA5551,
        SDL_PIXELFORMAT_ABGR1555,
        SDL_PIXELFORMAT_BGRA5551,
        SDL_PIXELFORMAT_RGB565,
        SDL_PIXELFORMAT_BGR565,
        SDL_PIXELFORMAT_RGB24,
        SDL_PIXELFORMAT_BGR24,
        SDL_PIXELFORMAT_RGB888,
        SDL_PIXELFORMAT_RGBX8888,
        SDL_PIXELFORMAT_BGR888,
        SDL_PIXELFORMAT_BGRX8888,
        SDL_PIXELFORMAT_ARGB8888,
        SDL_PIXELFORMAT_RGBA8888,
        SDL_PIXELFORMAT_ABGR8888,
        SDL_PIXELFORMAT_BGRA8888,
        SDL_PIXELFORMAT_ARGB2101010,
    };
    SDL_Surface *face = NULL, *cvt1, *cvt2, *final;
    SDL_PixelFormat *fmt1, *fmt2;
    int i, j, ret = 0;

    /* Create sample surface */
    face = SDLTest_ImageFace();
    SDLTest_AssertCheck(face != NULL, "Verify face surface is not NULL");
    if (face == NULL)
        return TEST_ABORTED;

    /* Set transparent pixel as the pixel at (0,0) */
    if (face->format->palette) {
       ret = SDL_SetColorKey(face, SDL_RLEACCEL, *(Uint8 *) face->pixels);
       SDLTest_AssertPass("Call to SDL_SetColorKey()");
       SDLTest_AssertCheck(ret == 0, "Verify result from SDL_SetColorKey, expected: 0, got: %i", ret);
    }

    for ( i = 0; i < SDL_arraysize(pixel_formats); ++i ) {
        for ( j = 0; j < SDL_arraysize(pixel_formats); ++j ) {
            fmt1 = SDL_AllocFormat(pixel_formats[i]);
            SDL_assert(fmt1 != NULL);
            cvt1 = SDL_ConvertSurface(face, fmt1, 0);
            SDL_assert(cvt1 != NULL);

            fmt2 = SDL_AllocFormat(pixel_formats[j]);
            SDL_assert(fmt1 != NULL);
            cvt2 = SDL_ConvertSurface(cvt1, fmt2, 0);
            SDL_assert(cvt2 != NULL);

            if ( fmt1->BytesPerPixel == face->format->BytesPerPixel &&
                 fmt2->BytesPerPixel == face->format->BytesPerPixel &&
                 (fmt1->Amask != 0) == (face->format->Amask != 0) &&
                 (fmt2->Amask != 0) == (face->format->Amask != 0) ) {
                final = SDL_ConvertSurface( cvt2, face->format, 0 );
                SDL_assert(final != NULL);

                /* Compare surface. */
                ret = SDLTest_CompareSurfaces( face, final, 0 );
                SDLTest_AssertCheck(ret == 0, "Validate result from SDLTest_CompareSurfaces, expected: 0, got: %i", ret);
                SDL_FreeSurface(final);
            }

            SDL_FreeSurface(cvt1);
            SDL_FreeFormat(fmt1);
            SDL_FreeSurface(cvt2);
            SDL_FreeFormat(fmt2);
        }
    }
Esempio n. 10
0
/*
 * Create an empty RGB surface of the appropriate depth
 */
SDL_Surface * SDL_CreateRGBSurface (Uint32 flags,
			int width, int height, int depth,
			Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask)
{
	SDL_VideoDevice *video = current_video;
	SDL_VideoDevice *this  = current_video;
	SDL_Surface *screen;
	SDL_Surface *surface;

	/* Make sure the size requested doesn't overflow our datatypes */
	/* Next time I write a library like SDL, I'll use int for size. :) */
	if ( width > 16384 || height > 16384 ) {
		SDL_SetError("Width or height is too large");
		return(NULL);
	}

	/* Check to see if we desire the surface in video memory */
	if ( video ) {
		screen = SDL_PublicSurface;
	} else {
		screen = NULL;
	}
	if ( screen && ((screen->flags&SDL_HWSURFACE) == SDL_HWSURFACE) ) {
		if ( (flags&(SDL_SRCCOLORKEY|SDL_SRCALPHA)) != 0 ) {
			flags |= SDL_HWSURFACE;
		}
		if ( (flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY ) {
			if ( ! current_video->info.blit_hw_CC ) {
				flags &= ~SDL_HWSURFACE;
			}
		}
		if ( (flags & SDL_SRCALPHA) == SDL_SRCALPHA ) {
			if ( ! current_video->info.blit_hw_A ) {
				flags &= ~SDL_HWSURFACE;
			}
		}
	} else {
		flags &= ~SDL_HWSURFACE;
	}

	/* Allocate the surface */
	surface = (SDL_Surface *)malloc(sizeof(*surface));
	if ( surface == NULL ) {
		SDL_OutOfMemory();
		return(NULL);
	}
	surface->flags = SDL_SWSURFACE;
	if ( (flags & SDL_HWSURFACE) == SDL_HWSURFACE ) {
		depth = screen->format->BitsPerPixel;
		Rmask = screen->format->Rmask;
		Gmask = screen->format->Gmask;
		Bmask = screen->format->Bmask;
		Amask = screen->format->Amask;
	}
	surface->format = SDL_AllocFormat(depth, Rmask, Gmask, Bmask, Amask);
	if ( surface->format == NULL ) {
		free(surface);
		return(NULL);
	}
	if ( Amask ) {
		surface->flags |= SDL_SRCALPHA;
	}
	surface->w = width;
	surface->h = height;
	surface->pitch = SDL_CalculatePitch(surface);
	surface->pixels = NULL;
	surface->offset = 0;
	surface->hwdata = NULL;
	surface->locked = 0;
	surface->map = NULL;
	surface->unused1 = 0;
	SDL_SetClipRect(surface, NULL);
	SDL_FormatChanged(surface);

	/* Get the pixels */
	if ( ((flags&SDL_HWSURFACE) == SDL_SWSURFACE) || 
				(video->AllocHWSurface(this, surface) < 0) ) {
		if ( surface->w && surface->h ) {
			surface->pixels = malloc(surface->h*surface->pitch);
			if ( surface->pixels == NULL ) {
				SDL_FreeSurface(surface);
				SDL_OutOfMemory();
				return(NULL);
			}
			/* This is important for bitmaps */
			memset(surface->pixels, 0, surface->h*surface->pitch);
		}
	}

	/* Allocate an empty mapping */
	surface->map = SDL_AllocBlitMap();
	if ( surface->map == NULL ) {
		SDL_FreeSurface(surface);
		return(NULL);
	}

	/* The surface is ready to go */
	surface->refcount = 1;
#ifdef CHECK_LEAKS
	++surfaces_allocated;
#endif
	return(surface);
}
Esempio n. 11
0
int main(int argc, char * args[]) {
	UNUSED(argc);
	UNUSED(args);
	init_bob_rand();
    seedMT(4357U);
	srand(time(NULL));
	s_lcrand(time(NULL));
	s_rand_qpr(0, 0);
	int selected_mode = 999999;
	while(selected_mode>10){
		printf("Select random function by pressing number key\n1:Windows random \t2:LFSR \t3:Mersenne twister"
		"\t4BobByrtle \t5Linear Congruential\t6Random with array \t7xorShift \t8Quadratic Resides"
		"\t9Concatenate 16 \t10Tausworth\n");
		selected_mode = get_int_input();
	}
    SDL_Init(SDL_INIT_VIDEO);

    SDL_Window * sdlWindow = SDL_CreateWindow("Visualize PRNG",
        SDL_WINDOWPOS_UNDEFINED,
        SDL_WINDOWPOS_UNDEFINED,
        640, 480,
        SDL_WINDOW_OPENGL);


    if (sdlWindow == NULL) {
        printf("Could not create window: %s\n", SDL_GetError());
        return 1;
    }

    SDL_Renderer * sdlRenderer = SDL_CreateRenderer(sdlWindow, -1, 0);

    if (sdlRenderer == NULL) {
        printf("Could not create renderer: %s\n", SDL_GetError());
        return 1;
    }

    SDL_RenderClear(sdlRenderer);
    SDL_RenderPresent(sdlRenderer);

    SDL_Texture * sdlTexture = SDL_CreateTexture(sdlRenderer,
        SDL_PIXELFORMAT_RGBA8888,
        SDL_TEXTUREACCESS_STREAMING,
        640, 480);
    if (sdlTexture == NULL) {
        printf("Could not create texture: %s\n", SDL_GetError());
        return 1;
    }
	SDL_SetTextureBlendMode(sdlTexture, SDL_BLENDMODE_BLEND);
	
	
	uint8 * data = (uint8 * ) malloc(sizeof(uint8) * 640 * 480);
    uint32 * pixels = (uint32 * ) malloc(sizeof(uint32) * 640 * 480);
    memset(pixels, 0, 640 * 480 * sizeof(uint32));
	memset(data, 0, 640 * 480 * sizeof(uint8));
	int cnt=5999999;
	uint32 * itable =createdata(cnt,selected_mode);
	
	CameraData camData;
	camData.xshift=0;
	camData.yshift=0;
	camData.zoom=1;
	camData.phata=0;
	SDL_PixelFormat* format = SDL_AllocFormat(SDL_PIXELFORMAT_RGBA8888);

	
	
	int arr_size = 640 * 480;
	bool keep_running = true;
    while (keep_running) {
		memset(pixels, 0, 640 * 480 * sizeof(uint32));
		update_data(data,640,480,itable,cnt,&camData);
		for(int i=0;i<arr_size;++i){
			uint8 data_value = data[i];
			if(data_value){
				pixels[i] = SDL_MapRGBA( format, 0xFF, 0xFF, 0xFF, data_value );

			}
		}
		SDL_UpdateTexture(sdlTexture, NULL, pixels, 640 * sizeof(Uint32));
        SDL_RenderClear(sdlRenderer);
        SDL_RenderCopy(sdlRenderer, sdlTexture, NULL, NULL);
        SDL_RenderPresent(sdlRenderer);
        SDL_Delay(20);
		keep_running = handle_events(&camData);
	}
    SDL_DestroyWindow(sdlWindow);

    SDL_Quit();

    free(pixels);
    SDL_DestroyTexture(sdlTexture);
    SDL_DestroyRenderer(sdlRenderer);
    return 0;
}
Esempio n. 12
0
/*
 * Create an empty RGB surface of the appropriate depth using the given
 * enum SDL_PIXELFORMAT_* format
 */
SDL_Surface *
SDL_CreateRGBSurfaceWithFormat(Uint32 flags, int width, int height, int depth,
                               Uint32 format)
{
    SDL_Surface *surface;

    /* The flags are no longer used, make the compiler happy */
    (void)flags;

    /* Allocate the surface */
    surface = (SDL_Surface *) SDL_calloc(1, sizeof(*surface));
    if (surface == NULL) {
        SDL_OutOfMemory();
        return NULL;
    }

    surface->format = SDL_AllocFormat(format);
    if (!surface->format) {
        SDL_FreeSurface(surface);
        return NULL;
    }
    surface->w = width;
    surface->h = height;
    surface->pitch = SDL_CalculatePitch(format, width);
    SDL_SetClipRect(surface, NULL);

    if (SDL_ISPIXELFORMAT_INDEXED(surface->format->format)) {
        SDL_Palette *palette =
            SDL_AllocPalette((1 << surface->format->BitsPerPixel));
        if (!palette) {
            SDL_FreeSurface(surface);
            return NULL;
        }
        if (palette->ncolors == 2) {
            /* Create a black and white bitmap palette */
            palette->colors[0].r = 0xFF;
            palette->colors[0].g = 0xFF;
            palette->colors[0].b = 0xFF;
            palette->colors[1].r = 0x00;
            palette->colors[1].g = 0x00;
            palette->colors[1].b = 0x00;
        }
        SDL_SetSurfacePalette(surface, palette);
        SDL_FreePalette(palette);
    }

    /* Get the pixels */
    if (surface->w && surface->h) {
        /* Assumptions checked in surface_size_assumptions assert above */
        Sint64 size = ((Sint64)surface->h * surface->pitch);
        if (size < 0 || size > SDL_MAX_SINT32) {
            /* Overflow... */
            SDL_FreeSurface(surface);
            SDL_OutOfMemory();
            return NULL;
        }

        surface->pixels = SDL_malloc((size_t)size);
        if (!surface->pixels) {
            SDL_FreeSurface(surface);
            SDL_OutOfMemory();
            return NULL;
        }
        /* This is important for bitmaps */
        SDL_memset(surface->pixels, 0, surface->h * surface->pitch);
    }

    /* Allocate an empty mapping */
    surface->map = SDL_AllocBlitMap();
    if (!surface->map) {
        SDL_FreeSurface(surface);
        return NULL;
    }

    /* By default surface with an alpha mask are set up for blending */
    if (surface->format->Amask) {
        SDL_SetSurfaceBlendMode(surface, SDL_BLENDMODE_BLEND);
    }

    /* The surface is ready to go */
    surface->refcount = 1;
    return surface;
}
Esempio n. 13
0
uint32 RGBA ( const Color4i& color, uint32 fmt )
{
  return SDL_MapRGBA ( SDL_AllocFormat(fmt), color.r, color.g, color.b, color.a );
}
Esempio n. 14
0
const Color4i alpha_pixel ( uint32 pixel, uint32 fmt )
{
  return nom::alpha_pixel ( pixel, SDL_AllocFormat(fmt) );
}
Esempio n. 15
0
	UPSDLFormat MakeUPFormat(uint32_t fmt) {
		return std::unique_ptr<SDL_PixelFormat, decltype(&SDL_FreeFormat)>(SDL_AllocFormat(fmt), SDL_FreeFormat);
	}
Esempio n. 16
0
// create a font with a drop-shadow (used for "MNA" stage-name displays)
bool NXFont::InitCharsShadowed(TTF_Font *font, uint32_t color, uint32_t shadowcolor)
{
SDL_Color fgcolor, shcolor;
SDL_Surface *top, *bottom;
SDL_Rect dstrect;

	fgcolor.r = (uint8_t)(color >> 16);
	fgcolor.g = (uint8_t)(color >> 8);
	fgcolor.b = (uint8_t)(color);
	
	shcolor.r = (uint8_t)(shadowcolor >> 16);
	shcolor.g = (uint8_t)(shadowcolor >> 8);
	shcolor.b = (uint8_t)(shadowcolor);
	
	char str[2];
	str[1] = 0;
	
	SDL_PixelFormat* pxformat = SDL_AllocFormat(screen->Format()->format);
	if (!pxformat)
	{
		staterr("InitBitmapChars: SDL_AllocFormat failed: %s", SDL_GetError());
		return 1;
	}

	uint32_t transp = SDL_ALPHA_TRANSPARENT;

	for(int i=1;i<NUM_LETTERS_RENDERED;i++)
	{
		str[0] = i;
		
		top = TTF_RenderText_Solid(font, str, fgcolor);
		bottom = TTF_RenderText_Solid(font, str, shcolor);
		if (!top || !bottom)
		{
			staterr("InitCharsShadowed: failed to render character %d: %s", i, TTF_GetError());
			SDL_FreeFormat(pxformat);
			SDL_FreeSurface(top);
			SDL_FreeSurface(bottom);
			return 1;
		}
		
		letters[i] = SDL_CreateRGBSurface(0, top->w, top->h+SHADOW_OFFSET,
							pxformat->BitsPerPixel, pxformat->Rmask, pxformat->Gmask,
							pxformat->Bmask, pxformat->Amask);
		if (!letters[i])
		{
			staterr("InitCharsShadowed: failed to create surface for character %d: %s", i, SDL_GetError());
			SDL_FreeFormat(pxformat);
			SDL_FreeSurface(top);
			SDL_FreeSurface(bottom);
			return 1;
		}
		
		SDL_FillRect(letters[i], NULL, transp);
		SDL_SetColorKey(letters[i], SDL_TRUE, transp);
		
		dstrect.x = 0;
		dstrect.y = SHADOW_OFFSET;
		SDL_BlitSurface(bottom, NULL, letters[i], &dstrect);
		
		dstrect.x = 0;
		dstrect.y = 0;
		SDL_BlitSurface(top, NULL, letters[i], &dstrect);

		SDL_FreeSurface(top);
		SDL_FreeSurface(bottom);
	}
	
	return 0;
}
Esempio n. 17
0
/*
 * Create an empty RGB surface of the appropriate depth
 */
SDL_Surface *
SDL_CreateRGBSurface(Uint32 flags,
                     int width, int height, int depth,
                     Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask)
{
    SDL_Surface *surface;
    Uint32 format;

    /* The flags are no longer used, make the compiler happy */
    (void)flags;

    /* Get the pixel format */
    format = SDL_MasksToPixelFormatEnum(depth, Rmask, Gmask, Bmask, Amask);
    if (format == SDL_PIXELFORMAT_UNKNOWN) {
        SDL_SetError("Unknown pixel format");
        return NULL;
    }

    /* Allocate the surface */
    surface = (SDL_Surface *) SDL_calloc(1, sizeof(*surface));
    if (surface == NULL) {
        SDL_OutOfMemory();
        return NULL;
    }

    surface->format = SDL_AllocFormat(format);
    if (!surface->format) {
        SDL_FreeSurface(surface);
        return NULL;
    }
    surface->w = width;
    surface->h = height;
    surface->pitch = SDL_CalculatePitch(surface);
    SDL_SetClipRect(surface, NULL);

    if (SDL_ISPIXELFORMAT_INDEXED(surface->format->format)) {
        SDL_Palette *palette =
            SDL_AllocPalette((1 << surface->format->BitsPerPixel));
        if (!palette) {
            SDL_FreeSurface(surface);
            return NULL;
        }
        if (palette->ncolors == 2) {
            /* Create a black and white bitmap palette */
            palette->colors[0].r = 0xFF;
            palette->colors[0].g = 0xFF;
            palette->colors[0].b = 0xFF;
            palette->colors[1].r = 0x00;
            palette->colors[1].g = 0x00;
            palette->colors[1].b = 0x00;
        }
        SDL_SetSurfacePalette(surface, palette);
        SDL_FreePalette(palette);
    }

    /* Get the pixels */
    if (surface->w && surface->h) {
        surface->pixels = SDL_malloc(surface->h * surface->pitch);
        if (!surface->pixels) {
            SDL_FreeSurface(surface);
            SDL_OutOfMemory();
            return NULL;
        }
        /* This is important for bitmaps */
        SDL_memset(surface->pixels, 0, surface->h * surface->pitch);
    }

    /* Allocate an empty mapping */
    surface->map = SDL_AllocBlitMap();
    if (!surface->map) {
        SDL_FreeSurface(surface);
        return NULL;
    }

    /* By default surface with an alpha mask are set up for blending */
    if (Amask) {
        SDL_SetSurfaceBlendMode(surface, SDL_BLENDMODE_BLEND);
    }

    /* The surface is ready to go */
    surface->refcount = 1;
    return surface;
}
Esempio n. 18
0
// Create a font from a bitmapped font sheet.
// sheet: a 8bpp (paletted) sheet to create the font from.
// fgindex: color index of foreground color of letters.
// color: the color you want the letters to be.
bool NXFont::InitBitmapChars(SDL_Surface *sheet, uint32_t fgcolor, uint32_t color)
{
Uint32 format = screen->Format()->format;
SDL_Rect srcrect, dstrect;
SDL_Surface *letter;
int x, y, i;

	SDL_PixelFormat* pxformat = SDL_AllocFormat(format);
	if (!pxformat)
	{
		staterr("InitBitmapChars: SDL_AllocFormat failed: %s", SDL_GetError());
		return 1;
	}

	// NULL out letters we don't have a character for
	memset(this->letters, 0, sizeof(this->letters));
	
	// change the color of the letters by messing with the palette on the sheet
	ReplaceColor(sheet, fgcolor, color);
	
	// start at the top of the letter sheet.
	x = 0;
	y = 0;
	for(i=0;bitmap_map[i];i++)
	{
		uint8_t ch = bitmap_map[i];
		//stat("copying letter %d: '%c' from [%d,%d]", i, ch, x, y);
		
		// make character surface one pixel larger than the actual char so that there
		// is some space between letters in autospaced text such as on the menus.
		letter = SDL_CreateRGBSurface(0, \
							BITMAP_CHAR_WIDTH+1, BITMAP_CHAR_HEIGHT+1,
							pxformat->BitsPerPixel, \
							pxformat->Rmask, pxformat->Gmask,
							pxformat->Bmask, pxformat->Amask);
		if (!letter)
		{
			staterr("InitBitmapChars: failed to create surface for character %d/%d", i, ch);
			SDL_FreeFormat(pxformat);
			return 1;
		}
		
		SDL_FillRect(letter, NULL, SDL_MapRGB(pxformat, 0, 0, 0));
		
		// copy letter off of sheet
		srcrect.x = x;
		srcrect.y = y;
		srcrect.w = BITMAP_CHAR_WIDTH;
		srcrect.h = BITMAP_CHAR_HEIGHT;
		
		dstrect.x = 0;
		dstrect.y = 0;
		
		SDL_BlitSurface(sheet, &srcrect, letter, &dstrect);
		
		// make background transparent and copy into final position
		SDL_SetColorKey(letter, SDL_TRUE, SDL_MapRGB(pxformat, 0, 0, 0));

		SDL_PixelFormat * format = screen->Format();
		letters[ch] = SDL_ConvertSurfaceFormat(letter, format->format, 0);
		
		SDL_FreeSurface(letter);
		// letters[ch] = letter;
		
		// advance to next position on sheet
		x += BITMAP_SPAC_WIDTH;
		if (x >= sheet->w)
		{
			x = 0;
			y += BITMAP_SPAC_HEIGHT;
		}
	}

	return 0;
}
Esempio n. 19
0
int main(int argc,char** argv) {
  rfbClient* cl;
  int i, j;
  SDL_Event e;

  for (i = 1, j = 1; i < argc; i++)
    if (!strcmp(argv[i], "-viewonly"))
      viewOnly = 1;
    else if (!strcmp(argv[i], "-listen")) {
      listenLoop = 1;
      argv[i] = const_cast<char*>("-listennofork");
      ++j;
    }
    else if (!strcmp(argv[i], "-joystick")) {
      drcInputFeeder = TRUE;
    }
    else {
      if (i != j)
        argv[j] = argv[i];
      j++;
    }
  argc = j;

  Init_DRC();
  drc::InputData drc_input_data;

  if (drcInputFeeder) {
    printf("Started in Joystick mode, toggle Mouse mode with POWER button\n");
    g_streamer->EnableSystemInputFeeder();
    drcJoystickMode = 1;
  } else {
    printf("Started in Mouse-only mode\n");
    drcJoystickMode = 0;
  }

  SDL_Init(SDL_INIT_VIDEO);
  SDL_StartTextInput();

  atexit(SDL_Quit);
  signal(SIGINT, exit);

  do {
    /* 16-bit: cl=rfbGetClient(5,3,2); */
    cl=rfbGetClient(8,3,4);

    SDL_PixelFormat *fmt = SDL_AllocFormat(SDL_PIXELFORMAT_ARGB8888);
    cl->format.bitsPerPixel = fmt->BitsPerPixel;
    cl->format.redShift     = fmt->Rshift;
    cl->format.greenShift   = fmt->Gshift;
    cl->format.blueShift    = fmt->Bshift;
    cl->format.redMax       = fmt->Rmask>>cl->format.redShift;
    cl->format.greenMax     = fmt->Gmask>>cl->format.greenShift;
    cl->format.blueMax      = fmt->Bmask>>cl->format.blueShift;

    cl->MallocFrameBuffer=resize;
    cl->canHandleNewFBSize = TRUE;
    cl->GotFrameBufferUpdate=update;
    cl->HandleKeyboardLedState=kbd_leds;
    cl->listenPort = LISTEN_PORT_OFFSET;
    cl->listen6Port = LISTEN_PORT_OFFSET;

    if(!rfbInitClient(cl,&argc,argv)) {
      cl = NULL; /* rfbInitClient has already freed the client struct */
      cleanup(cl);
      break;
    }

    while(1) {
      g_streamer->PollInput(&drc_input_data);
      if (drc_input_data.valid) {
        Process_DRC_Input(cl, drc_input_data);
      }
      if(SDL_PollEvent(&e)) {
      /*
        handleSDLEvent() return 0 if user requested window close.
        In this case, handleSDLEvent() will have called cleanup().
      */
        if(!handleSDLEvent(cl, &e))
          break;
      } else {
        i=WaitForMessage(cl,500);
        if(i<0) {
          cleanup(cl);
          break;
        }
        if(i) {
          if(!HandleRFBServerMessage(cl)) {
            cleanup(cl);
            break;
          }
        }
      }

      if (vncUpdate) {
        SDL_UpdateTexture(sdlTexture, NULL, cl->frameBuffer, drc::kScreenWidth * 4);
        SDL_RenderCopy(sdlRenderer, sdlTexture, NULL, NULL);
        SDL_RenderPresent(sdlRenderer);
        Push_DRC_Frame(cl);
        vncUpdate = FALSE;
      }
    }
  } while(listenLoop);

  return 0;
}
Esempio n. 20
0
int main(int argc, char *argv[])
{
	Uint32 *buf = NULL;
	SDL_Texture *t = NULL;
	SDL_PixelFormat *format = NULL;
	SDL_Window *window = NULL;
	SDL_Renderer *renderer = NULL;

	// Init SDL
	if (SDL_Init(SDL_INIT_VIDEO) != 0)
	{
		printf("SDL_Init error: %s\n", SDL_GetError());
		goto bail;
	}

	// Create surface
	buf = malloc(SCREEN_W * SCREEN_H * sizeof(Uint32));
	if (buf == NULL)
	{
		printf("Failed to allocate buffer\n");
		goto bail;
	}

	// Create display window based on image size
	window = SDL_CreateWindow(
		argv[1], SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
		SCREEN_W, SCREEN_H, 0);
	if (window == NULL)
	{
		printf("Failed to create window: %s\n", SDL_GetError());
		goto bail;
	}
	format = SDL_AllocFormat(SDL_GetWindowPixelFormat(window));
	if (format == NULL)
	{
		printf("Failed to alloc pixel format: %s\n", SDL_GetError());
		goto bail;
	}
	renderer = SDL_CreateRenderer(window, -1, 0);
	if (renderer == NULL)
	{
		printf("Failed to create renderer: %s\n", SDL_GetError());
		goto bail;
	}
	SDL_RenderSetLogicalSize(renderer, SCREEN_W, SCREEN_H);

	// Create texture
	t = SDL_CreateTexture(
		renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING,
		SCREEN_W, SCREEN_H);
	if (t == NULL)
	{
		printf("Failed to create screen texture: %s\n", SDL_GetError());
		goto bail;
	}

	// Draw a palette on the buffer
#define MAX(x, y) ((x) > (y) ? (x) : (y))
#define MIN(x, y) ((x) < (y) ? (x) : (y))
#define CLAMP(v, _min, _max) MAX((_min), MIN((_max), (v)))
#define GREY_MARGIN 20
	for (int y = 0; y < SCREEN_H; y++)
	{
		Uint8 v = (Uint8)CLAMP((SCREEN_H - y) * 255.0 / (SCREEN_H / 2), 0, 255);
		double s = CLAMP(y * 1.0 / (SCREEN_H / 2), 0.0, 1.0);
		for (int x = 0; x < SCREEN_W; x++)
		{
			SDL_Color c;
			c.a = 255;
			if (x < SCREEN_W - GREY_MARGIN)
			{
				double h = x * 360.0 / (SCREEN_W - GREY_MARGIN);
				double ff;
				Uint8 p, q, t;
				long i;
				double hh = h;
				if (hh >= 360.0)
				{
					hh = 0.0;
				}
				hh /= 60.0;
				i = (long)hh;
				ff = hh - i;
				p = (Uint8)CLAMP(v * (1.0 - s), 0, 255);
				q = (Uint8)CLAMP(v * (1.0 - (s * ff)), 0, 255);
				t = (Uint8)CLAMP(v * (1.0 - (s * (1.0 - ff))), 0, 255);

				switch (i)
				{
				case 0:
					c.r = v;
					c.g = t;
					c.b = p;
					break;
				case 1:
					c.r = q;
					c.g = v;
					c.b = p;
					break;
				case 2:
					c.r = p;
					c.g = v;
					c.b = t;
					break;

				case 3:
					c.r = p;
					c.g = q;
					c.b = v;
					break;
				case 4:
					c.r = t;
					c.g = p;
					c.b = v;
					break;
				case 5:
				default:
					c.r = v;
					c.g = p;
					c.b = q;
					break;
				}
			}
			else
			{
				c.r = c.g = c.b = (Uint8)CLAMP((SCREEN_H - y) * 255.0 / SCREEN_H, 0, 255);
			}
			Uint32 pixel = SDL_MapRGBA(format, c.r, c.g, c.b, c.a);
			buf[x + y*SCREEN_W] = pixel;
		}
	}

	// Render to texture
	SDL_UpdateTexture(t, NULL, buf, SCREEN_W * sizeof(Uint32));
	if (SDL_RenderClear(renderer) != 0)
	{
		printf("Failed to clear renderer: %s\n", SDL_GetError());
		goto bail;
	}

	// Blit the texture to screen
	if (SDL_RenderCopy(renderer, t, NULL, NULL) != 0)
	{
		printf("Failed to blit surface: %s\n", SDL_GetError());
		goto bail;
	}

	// Display
	SDL_RenderPresent(renderer);

	// Wait for keypress to exit
	bool quit = false;
	while (!quit)
	{
		SDL_Event e;
		while (SDL_PollEvent(&e))
		{
			if (e.type == SDL_KEYDOWN || e.type == SDL_QUIT)
			{
				quit = true;
			}
		}
		SDL_Delay(100);
	}


bail:
	SDL_DestroyTexture(t);
	free(buf);
	SDL_DestroyRenderer(renderer);
	SDL_FreeFormat(format);
	SDL_DestroyWindow(window);
	SDL_Quit();
	return 0;
}
Esempio n. 21
0
SDLWindowManager::SDLWindowManager(Application* application):
	WindowManager(application)
{
	if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER) == -1)
	{
		throw RuntimeException("SDL initialization failed.");
	}

	int displayCount = SDL_GetNumVideoDisplays();
	displays.resize(displayCount);
	primaryDisplay = &displays[0];

	for (int i = 0; i < displayCount; ++i)
	{
		Display* display = &displays[i];

		const char* displayName = SDL_GetDisplayName(i);
		if (displayName)
		{
			display->setName(displayName);
		}

		SDL_DisplayMode sdlCurrentDisplayMode;
		SDL_GetCurrentDisplayMode(i, &sdlCurrentDisplayMode);

		int displayModeCount = SDL_GetNumDisplayModes(i);
		for (int j = 0; j < displayModeCount; ++j)
		{
			SDL_DisplayMode sdlDisplayMode;
			SDL_GetDisplayMode(i, j, &sdlDisplayMode);
			
			SDL_PixelFormat* format = SDL_AllocFormat(sdlDisplayMode.format);
			if (!format)
			{
				std::cerr << "Failed to create SDL pixel format: " << SDL_GetPixelFormatName(sdlDisplayMode.format) << '\n';
				continue;
			}

			int width = sdlDisplayMode.w;
			int height = sdlDisplayMode.h;
			int refreshRate = sdlDisplayMode.refresh_rate;
			int redBits, greenBits, blueBits, alphaBits;
			SDLPixelFormatMap::getChannelBits(format, &redBits, &greenBits, &blueBits, &alphaBits);

			SDL_FreeFormat(format);

			display->addMode(
				DisplayMode(width, height, redBits, greenBits, blueBits, alphaBits, refreshRate));

			if (sdlCurrentDisplayMode.w == sdlDisplayMode.w &&
				sdlCurrentDisplayMode.h == sdlDisplayMode.h &&
				sdlCurrentDisplayMode.format == sdlDisplayMode.format &&
				sdlCurrentDisplayMode.refresh_rate == sdlDisplayMode.refresh_rate)
			{
				display->setCurrentMode(j);
			}
		}
	}

	keyboard = new Keyboard("Default Keyboard");
	mouse = new Mouse("Default Mouse");
	
	application->getInputManager()->registerKeyboard(keyboard);
	application->getInputManager()->registerMouse(mouse);
}
Esempio n. 22
0
SDL_Texture *
SDL_CreateTextureFromSurface(SDL_Renderer * renderer, SDL_Surface * surface)
{
    const SDL_PixelFormat *fmt;
    SDL_bool needAlpha;
    Uint32 i;
    Uint32 format;
    SDL_Texture *texture;

    CHECK_RENDERER_MAGIC(renderer, NULL);

    if (!surface) {
        SDL_SetError("SDL_CreateTextureFromSurface() passed NULL surface");
        return NULL;
    }

    /* See what the best texture format is */
    fmt = surface->format;
    if (fmt->Amask || SDL_GetColorKey(surface, NULL) == 0) {
        needAlpha = SDL_TRUE;
    } else {
        needAlpha = SDL_FALSE;
    }
    format = renderer->info.texture_formats[0];
    for (i = 0; i < renderer->info.num_texture_formats; ++i) {
        if (!SDL_ISPIXELFORMAT_FOURCC(renderer->info.texture_formats[i]) &&
                SDL_ISPIXELFORMAT_ALPHA(renderer->info.texture_formats[i]) == needAlpha) {
            format = renderer->info.texture_formats[i];
            break;
        }
    }

    texture = SDL_CreateTexture(renderer, format, SDL_TEXTUREACCESS_STATIC,
                                surface->w, surface->h);
    if (!texture) {
        return NULL;
    }

    if (format == surface->format->format) {
        if (SDL_MUSTLOCK(surface)) {
            SDL_LockSurface(surface);
            SDL_UpdateTexture(texture, NULL, surface->pixels, surface->pitch);
            SDL_UnlockSurface(surface);
        } else {
            SDL_UpdateTexture(texture, NULL, surface->pixels, surface->pitch);
        }
    } else {
        SDL_PixelFormat *dst_fmt;
        SDL_Surface *temp = NULL;

        /* Set up a destination surface for the texture update */
        dst_fmt = SDL_AllocFormat(format);
        temp = SDL_ConvertSurface(surface, dst_fmt, 0);
        SDL_FreeFormat(dst_fmt);
        if (temp) {
            SDL_UpdateTexture(texture, NULL, temp->pixels, temp->pitch);
            SDL_FreeSurface(temp);
        } else {
            SDL_DestroyTexture(texture);
            return NULL;
        }
    }

    {
        Uint8 r, g, b, a;
        SDL_BlendMode blendMode;

        SDL_GetSurfaceColorMod(surface, &r, &g, &b);
        SDL_SetTextureColorMod(texture, r, g, b);

        SDL_GetSurfaceAlphaMod(surface, &a);
        SDL_SetTextureAlphaMod(texture, a);

        if (SDL_GetColorKey(surface, NULL) == 0) {
            /* We converted to a texture with alpha format */
            SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_BLEND);
        } else {
            SDL_GetSurfaceBlendMode(surface, &blendMode);
            SDL_SetTextureBlendMode(texture, blendMode);
        }
    }
    return texture;
}
Esempio n. 23
0
int main(int argc, char *argv[])
{
    google::InitGoogleLogging(argv[0]);

    // Setup the filename
    if(argc != 2) {
    	printUsage();
    	return 1;
    } else {
        std::string romName = argv[1];
        LOG(INFO) << "Reading rom " << romName;
        std::vector<unsigned char> rom = Chip8::FileUtils::readRom(romName);
        LOG(INFO) << "Rom size = " << rom.size();
        for(unsigned int i = 0; i < rom.size(); i++) {
            if(!Chip8::Memory::instance().write(Chip8::Memory::StartAddress + i, rom.at(i))) {
                LOG(INFO) << "Failed to load rom into " << (int) Chip8::Memory::StartAddress + i;
                std::cout << "Failed to load rom into " << (int) Chip8::Memory::StartAddress + i << std::endl;
                return 1;
            }
        }
        LOG(INFO) << "Loaded rom";
        for(unsigned int i = 0; i < rom.size(); i++) {
            unsigned char data = 0;
            Chip8::Memory::instance().read(Chip8::Memory::StartAddress + i, data);
            LOG(INFO) << (int) data;
        }
    }

    // Setup SDL.
    // Chip8 has a render size of 64x32 
    int upScale = 24;
    int error = SDL_Init(SDL_INIT_VIDEO);
    if(error < 0) {
        LOG(FATAL) << "Failed to init SDL - " << SDL_GetError(); 
    }
    SDL_Window *window = SDL_CreateWindow("Chip8", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, Chip8::Video::Width * upScale, Chip8::Video::Height * upScale, SDL_WINDOW_RESIZABLE);
    //SDL_Window *window = SDL_CreateWindow("Chip8", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 0, 0, SDL_WINDOW_FULLSCREEN_DESKTOP);
    if(window == NULL) {
        LOG(FATAL) << "Failed to create window - " << SDL_GetError();
    }
    SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
    if(renderer == NULL) {
        LOG(FATAL) << "Failed to create renderer - " << SDL_GetError();
    }
    SDL_RenderSetScale(renderer, upScale, upScale);
    SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, 0); 
    error = SDL_RenderSetLogicalSize(renderer, Chip8::Video::Width, Chip8::Video::Height);
    if(error < 0) {
        LOG(FATAL) << "Failed to set render size - " << SDL_GetError(); 
    }

    // Create the texture that will be drawn to the screen every frame.
    SDL_Texture *texture  = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING, Chip8::Video::Width, Chip8::Video::Height);
    if(texture == NULL) {
        LOG(FATAL) << "Failed to create texture - " << SDL_GetError();
    }
    
    // Make sure to set the correct pixel format for the Video module
    SDL_PixelFormat *format = SDL_AllocFormat(SDL_PIXELFORMAT_RGBA8888);
    if(format == NULL) {
        LOG(FATAL) << "Failed to create format - " << SDL_GetError();
    }

    Chip8::Video::instance().setPixelFormat(format);

    // Load fonts into memory
    for(unsigned char  i = 0; i < 0xF + 1; i++) {
        LOG(INFO) << "Getting font sprite " << (int) i;
        const unsigned char *sprite = Chip8::Fonts::getSprite(i);
        for(unsigned char j = 0; j < Chip8::Fonts::SpriteHeight; j++) {
            unsigned int address = 0x0 + (i * Chip8::Fonts::SpriteHeight) + j;
            LOG(INFO) << "Loading font sprite byte " << (int) j << " to memory address " << address;
            if(!Chip8::Memory::instance().write(address, sprite[j])) {
               LOG(INFO) << "Failed to load font sprite " << (int) i << " into memory address " << address;
            }
        } 
    }

    // Jump to start of rom
    Chip8::Cpu::instance().jump(Chip8::Memory::StartAddress);

    SDL_Event event;
    Uint32 lastFrame = SDL_GetTicks();
    Uint32 sixtyFrame = 1000 / 60;
    do {
        Uint32 currentFrame = SDL_GetTicks();
        Uint32 elapsed = currentFrame - lastFrame;
        lastFrame = currentFrame;
        if(elapsed < sixtyFrame) {
            SDL_Delay(sixtyFrame - elapsed);
        }

        // Handle event
        SDL_PollEvent(&event);
        switch(event.type) {
            case SDL_KEYDOWN:
                LOG(INFO) << "Key pressed " << event.key.keysym.scancode;
                if(event.key.keysym.scancode == SDL_SCANCODE_ESCAPE) {
                    LOG(INFO) << "Escape pressed exiting now";
                    SDL_FreeFormat(format);
                    SDL_DestroyTexture(texture);
                    SDL_DestroyRenderer(renderer);
                    SDL_DestroyWindow(window);
                    SDL_Quit();
                    return 0;
                } else if(Chip8::InputManager::instance().IsWaitingForKeyPress) {
                    unsigned char hex;
                    Chip8::InputManager::instance().toHex(event.key.keysym.scancode, hex);
                    LOG(INFO) << "InputManager waiting for key press key pressed = " << hex;
                    if(Chip8::InputManager::instance().isValidKey(hex)) {
                        LOG(INFO) << "Valid key detected, setting register " << Chip8::InputManager::instance().KeyPressRegister;
                        Chip8::InputManager::instance().IsWaitingForKeyPress = false;
                        Chip8::Memory::instance().setRegister(Chip8::InputManager::KeyPressRegister, hex);
                    }
                }
                break;
        }

        if(!Chip8::InputManager::instance().IsWaitingForKeyPress) {
            // Cpu step
            Chip8::Cpu::instance().step();
            Chip8::Timers::instance().step();
        }

        // Render screen
        SDL_RenderClear(renderer);
        SDL_UpdateTexture(texture, NULL, Chip8::Video::instance().getPixels(), Chip8::Video::Width * sizeof(Uint32));
        SDL_RenderCopy(renderer, texture, NULL, NULL);
        SDL_RenderPresent(renderer);
    } while(event.type != SDL_QUIT);

    SDL_FreeFormat(format);
    SDL_DestroyTexture(texture);
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();
    return 0;
}
Esempio n. 24
0
U32 SGL_DataSaveImage(const char* name, SDL_Surface * surf)
{
	U32 loc;
	U32 hash;
	SDL_Surface* convSurf;
	if (surf == NULL)
	{
		SDL_Log("SGL_DataSaveImage couldn't save because surf pointer is NULL");
		return SGL_FALSE;
	}
	if (surf->format->format != SDL_PIXELFORMAT_ARGB8888)
	{
		convSurf = surf;
	}
	else if (surf->format->BytesPerPixel <= 4)
	{
		//SDL_PIXELFORMAT_ARGB8888 == VK_FORMAT_B8G8R8A8_UNORM
		//I havent had time to check why the SDL pixel format is reversed in comparison to the vulkan format
		//27.2.2016 Vulkan doesnt currently support 3 component pixel formats, actually the only format i found working was mentioned above
		SDL_PixelFormat* format = SDL_AllocFormat(SDL_PIXELFORMAT_ARGB8888);
		convSurf = SDL_ConvertSurface(surf, format, 0);
		SDL_FreeFormat(format);
		if (convSurf == NULL)
		{
			SDL_Log("SGL_DataSaveImage couldn't convert surface to SDL_PIXELFORMAT_ARGB8888/VK_FORMAT_B8G8R8A8_UNORM, you could maybe add unimplemented format if vulkan supports it?");
			return SGL_FALSE;
		}
	}
	else
	{
		SDL_Log("SGL_DataSaveImage encountered unsupported pixel format. Aborting save");
		return SGL_FALSE;
	}
	targetData.block.imageCount++;
	{
		SDL_RWops* rw = SDL_RWFromFile(targetData.path, "rb+");
		if (rw == NULL)
		{
			SDL_Log("SGL_DataSaveImage couldn't open file in path: %s, SDL_Error:%s", targetData.path, SDL_GetError());
			return SGL_FALSE;
		}
		loc = (U32)SDL_RWseek(rw, 0, RW_SEEK_END);
		const SGL_FileSurface surfData = 
		{ 
			convSurf->flags, 
			convSurf->w, convSurf->h,
			convSurf->format->BitsPerPixel, 
			convSurf->format->Rmask, convSurf->format->Gmask, convSurf->format->Bmask, convSurf->format->Amask
		};
		if (SDL_RWwrite(rw, &surfData, sizeof(SGL_FileSurface), 1) != 1)
		{
			SDL_RWclose(rw);
			SDL_Log("SGL_DataSaveImage couldn't write to data file in path: %s", targetData.path);
			return SGL_FALSE;
		}
		{
			I32 y;
			const U32 pixelSize = convSurf->format->BytesPerPixel;
			//y axis gets flipped here
			//this prolly hurts the writing speed but this is done only when saving the textures
			for (y = surfData.h-1; y >= 0; y--)
			{
				I32 x;
				for (x = 0; x < surfData.w; x++)
				{
					SDL_RWwrite(rw, ((U8*)convSurf->pixels)+(y*surfData.w*pixelSize)+(x*pixelSize), pixelSize, 1);
				}
			}
		}
		SDL_RWseek(rw, 0, RW_SEEK_SET);
		if (SDL_RWwrite(rw, &targetData.block, sizeof(SGL_DataBlock), 1) != 1)
		{
			SDL_RWclose(rw);
			SDL_Log("SGL_DataSaveImage couldn't write to data file in path: %s, SDL_Error: %s", targetData.path, SDL_GetError());
			return SGL_FALSE;
		}
		SDL_RWclose(rw);
	}
	MurmurHash3_x86_32(name, (I32)SDL_strlen(name), targetData.block.seed, &hash);
	return AddNode(hash, loc);
}
Esempio n. 25
0
//Registers, creates, and shows the Window!!
bool WinCreate()
{
    std::string version = string_format("Cataclysm: Dark Days Ahead - %s", getVersionString());

    //Flags used for setting up SDL VideoMode
    int window_flags = 0;

    //If FULLSCREEN was selected in options add SDL_WINDOW_FULLSCREEN flag to screen_flags, causing screen to go fullscreen.
    if(OPTIONS["FULLSCREEN"]) {
        window_flags = window_flags | SDL_WINDOW_FULLSCREEN;
    }

    window = SDL_CreateWindow(version.c_str(),
            SDL_WINDOWPOS_CENTERED,
            SDL_WINDOWPOS_CENTERED,
            WindowWidth,
            WindowHeight,
            window_flags
        );

	//create renderer and convert that to a SDL_Surface?

    if (window == NULL) return false;

    format = SDL_AllocFormat(SDL_GetWindowPixelFormat(window));

    bool software_renderer = OPTIONS["SOFTWARE_RENDERING"];
    if( !software_renderer ) {
        DebugLog() << "Attempting to initialize accelerated SDL renderer.\n";

        renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED |
                                       SDL_RENDERER_PRESENTVSYNC );
        if( renderer == NULL ) {
            DebugLog() << "Failed to initialize accelerated renderer, falling back to software rendering: " << SDL_GetError() << "\n";
            software_renderer = true;
        }
    }
    if( software_renderer ) {
        renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_SOFTWARE );
        if( renderer == NULL ) {
            DebugLog() << "Failed to initialize software renderer: " << SDL_GetError() << "\n";
            return false;
        }
    }

    ClearScreen();

    if(OPTIONS["HIDE_CURSOR"] != "show" && SDL_ShowCursor(-1)) {
        SDL_ShowCursor(SDL_DISABLE);
    } else {
        SDL_ShowCursor(SDL_ENABLE);
    }

    // Initialize joysticks.
    int numjoy = SDL_NumJoysticks();

    if(numjoy > 1) {
        DebugLog() << "You have more than one gamepads/joysticks plugged in, only the first will be used.\n";
    }

    if(numjoy >= 1) {
        joystick = SDL_JoystickOpen(0);
    } else {
        joystick = NULL;
    }

    SDL_JoystickEventState(SDL_ENABLE);

    return true;
};
Esempio n. 26
0
int main()
{
  // apply FFT to real 2D data.

  double *in;
  double *apex;
  int W = 640;
  int H = 480;
  int half_H = (H / 2) + 1;
  int x;
  int y;
  fftw_complex *out;
  fftw_complex *apex_f;
  fftw_plan plan_backward;
  fftw_plan plan_apex;
  fftw_plan plan_forward;
  unsigned int seed = 123456789;
  srand(seed);

  in = (double *) malloc_check(sizeof(double) * W * H);
  for(x = 0; x < W; x++)
  {
    for(y = 0; y < H; y++)
    {
#if 1
      in[x*H+y] =  ( double ) rand ( ) / ( RAND_MAX );
#else
      in[x*H+y] =  0;
#endif
    }
  }
  in[(H/2) + (W/2)*H] = 1;
  in[(H/2)+3 + (W/2 + 3)*H] = 1;
  in[10 + (20)*H] = 1;
  in[H-3 + (W-3)*H] = 1;

  y = W * H;
  for (x = 0; x < y; x++) {
    in[x] *= PALETTE_LEN -10;
  }


  apex = (double*)malloc_check(sizeof(double) * W * H);
  double apex_sum = 0;
  for(x = 0; x < W; x++)
  {
    for(y = 0; y < H; y++)
    {
      double dist = 0;
      int xx = x;
      int yy = y;
      if (xx >= W/2)
        xx = W - x;
      if (yy >= H/2)
        yy = H - y;
      dist = sqrt(xx*xx + yy*yy);
      double v = 8.01 - dist;
      if (v < 0)
        v = 0;
#if 0
      if (x == 2 && y == 1)
        v = 302.1;
#endif

#if 0
      if (x == W / 2 && y == H / 2)
        v = 850;
#endif

#if 0
      if (x < W/2 || y > H / 2)
        v = -v * 1.85;
#endif
#if 0
      if (x == W/3-1 && y == H/3-1)
        v = 200;
      if (x == W/3 && y == H/3)
        v = -200;
#endif
      apex_sum += v;
      apex[x*H+y] = v;
    }
  }

  double burn = 1.005;
  double apex_mul = (burn / (W*H)) / apex_sum;
  printf("%f %f\n", apex_sum, apex_mul);

  y = W * H;
  for (x = 0; x < y; x++) {
    apex[x] *= apex_mul;
  }

  apex_f = fftw_malloc(sizeof(fftw_complex) * W * half_H);
  plan_apex = fftw_plan_dft_r2c_2d(W, H, apex, apex_f, FFTW_ESTIMATE);
  fftw_execute(plan_apex);


  out = fftw_malloc(sizeof(fftw_complex) * W * half_H);
  plan_forward = fftw_plan_dft_r2c_2d(W, H, in, out, FFTW_ESTIMATE);
  plan_backward = fftw_plan_dft_c2r_2d(W, H, out, in, FFTW_ESTIMATE);

  int winW = W;
  int winH = H;

  SDL_Window *window;
  window = SDL_CreateWindow("fftw3_test", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
                            winW, winH, 0);

  if (!window) {
    fprintf(stderr, "Unable to set %dx%d video: %s\n", winW, winH, SDL_GetError());
    exit(1);
  }

  SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, 0);
  if (!renderer) {
    fprintf(stderr, "Unable to set %dx%d video: %s\n", winW, winH, SDL_GetError());
    exit(1);
  }

  SDL_ShowCursor(SDL_DISABLE);
  SDL_PixelFormat *pixelformat = SDL_AllocFormat(SDL_PIXELFORMAT_RGBA8888);
  SDL_Texture *texture = SDL_CreateTexture(renderer, pixelformat->format,
                                           SDL_TEXTUREACCESS_STREAMING, winW, winH);
  if (!texture) {
    fprintf(stderr, "Cannot create texture\n");
    exit(1);
  }

#if 0
#define n_palette_points 2
  palette_point_t palette_points[n_palette_points] = {
    { 0., 0, 0, 0 },
    { 1., 1, 1, 1 },
  };
#else
#define n_palette_points 11
  palette_point_t palette_points[n_palette_points] = {
    { 0./6, 1, 1, 1 },
    { 0.5/6, 1, .9, 0 },
    { 1./6, 1, .1, 1 },
    { 1.5/6, 0, 0, 1 },
    { 3./6, .5, 0, .7 },
    { 3.5/6, 0, 1, .7 },
    { 4.5/6, .2, .8, .2 },
    { 4.8/6, 0, 0, 1 },
    { 5.25/6, .8, .8, 0 },
    { 5.55/6, .8, .2, 0.4 },
    { 5.85/6, .0,.60,.50 },
  };
#endif

  palette_t palette;
  make_palette(&palette, PALETTE_LEN,
               palette_points, n_palette_points,
               pixelformat);

  bool running = true;
  int frame_period = 50;
  int last_ticks = SDL_GetTicks() - frame_period;

  Uint32 *winbuf = (Uint32*)malloc_check(winW * winH * sizeof(Uint32));

  while (running)
  {
    bool do_render = false;

    int elapsed = SDL_GetTicks() - last_ticks;
    if (elapsed > frame_period) {
      last_ticks += frame_period * (elapsed / frame_period);
      do_render = true;
    }

    if (do_render) {
      render(winbuf, winW, winH, &palette, in, W, H);
      SDL_UpdateTexture(texture, NULL, winbuf, winW * sizeof(Uint32));
      SDL_RenderClear(renderer);
      SDL_RenderCopy(renderer, texture, NULL, NULL);
      SDL_RenderPresent(renderer);

      fftw_execute(plan_forward);

#if 1
      for (x = 0; x < W; x++) {
        for (y = 0; y < half_H; y++) {
          double *o = out[x*half_H + y];
          double *af = apex_f[x*half_H + y];
          double a, b, c, d;
          a = o[0]; b = o[1];
          c = af[0]; d = af[1];
#if 1
          o[0] = (a*c - b*d);
          o[1] = (b*c + a*d);
#else
          double l = sqrt(c*c + d*d);
          o[0] *= l;
          o[1] *= l;
#endif
        }
      }
#endif

      fftw_execute(plan_backward);
    }
    else
      SDL_Delay(5);

    SDL_Event event;
    while (SDL_PollEvent(&event))
    {
      switch (event.type)
      {
        case SDL_KEYDOWN:
          // If escape is pressed, return (and thus, quit)

          switch(event.key.keysym.sym) {
            case SDLK_ESCAPE:
              running = false;
              break;

            default:
              break;
          }
          break;

        case SDL_QUIT:
          running = false;
          break;
      }
    }

  }
  SDL_Quit();

  fftw_destroy_plan(plan_apex);
  fftw_destroy_plan(plan_forward);
  fftw_destroy_plan(plan_backward);

  free(in);
  free(apex);
  fftw_free(out);
  fftw_free(apex_f);

  return 0;
}
/**
 * @brief Call to SDL_AllocFormat and SDL_FreeFormat
 *
 * @sa http://wiki.libsdl.org/moin.fcg/SDL_AllocFormat
 * @sa http://wiki.libsdl.org/moin.fcg/SDL_FreeFormat
 */
int
pixels_allocFreeFormat(void *arg)
{
  const char *unknownFormat = "SDL_PIXELFORMAT_UNKNOWN";
  const char *expectedError = "Parameter 'format' is invalid";
  const char *error;
  int i;
  Uint32 format;
  Uint32 masks;
  SDL_PixelFormat* result;

  /* Blank/unknown format */
  format = 0;
  SDLTest_Log("RGB Format: %s (%u)", unknownFormat, format);

  /* Allocate format */
  result = SDL_AllocFormat(format);
  SDLTest_AssertPass("Call to SDL_AllocFormat()");
  SDLTest_AssertCheck(result != NULL, "Verify result is not NULL");
  if (result != NULL) {
    SDLTest_AssertCheck(result->format == format, "Verify value of result.format; expected: %u, got %u", format, result->format);
    SDLTest_AssertCheck(result->BitsPerPixel == 0, "Verify value of result.BitsPerPixel; expected: 0, got %u", result->BitsPerPixel);
    SDLTest_AssertCheck(result->BytesPerPixel == 0, "Verify value of result.BytesPerPixel; expected: 0, got %u", result->BytesPerPixel);
    masks = result->Rmask | result->Gmask | result->Bmask | result->Amask;
    SDLTest_AssertCheck(masks == 0, "Verify value of result.[RGBA]mask combined; expected: 0, got %u", masks);

    /* Deallocate again */
    SDL_FreeFormat(result);
    SDLTest_AssertPass("Call to SDL_FreeFormat()");
  }

  /* RGB formats */
  for (i = 0; i < _numRGBPixelFormats; i++) {
    format = _RGBPixelFormats[i];
    SDLTest_Log("RGB Format: %s (%u)", _RGBPixelFormatsVerbose[i], format);

    /* Allocate format */
    result = SDL_AllocFormat(format);
    SDLTest_AssertPass("Call to SDL_AllocFormat()");
    SDLTest_AssertCheck(result != NULL, "Verify result is not NULL");
    if (result != NULL) {
      SDLTest_AssertCheck(result->format == format, "Verify value of result.format; expected: %u, got %u", format, result->format);
      SDLTest_AssertCheck(result->BitsPerPixel > 0, "Verify value of result.BitsPerPixel; expected: >0, got %u", result->BitsPerPixel);
      SDLTest_AssertCheck(result->BytesPerPixel > 0, "Verify value of result.BytesPerPixel; expected: >0, got %u", result->BytesPerPixel);
      if (result->palette != NULL) {
         masks = result->Rmask | result->Gmask | result->Bmask | result->Amask;
         SDLTest_AssertCheck(masks > 0, "Verify value of result.[RGBA]mask combined; expected: >0, got %u", masks);
      }

      /* Deallocate again */
      SDL_FreeFormat(result);
      SDLTest_AssertPass("Call to SDL_FreeFormat()");
    }
  }

  /* Non-RGB formats */
  for (i = 0; i < _numNonRGBPixelFormats; i++) {
    format = _nonRGBPixelFormats[i];
    SDLTest_Log("non-RGB Format: %s (%u)", _nonRGBPixelFormatsVerbose[i], format);

    /* Try to allocate format */
    result = SDL_AllocFormat(format);
    SDLTest_AssertPass("Call to SDL_AllocFormat()");
    SDLTest_AssertCheck(result == NULL, "Verify result is NULL");
  }

  /* Negative cases */

  /* Invalid Formats */
  for (i = 0; i < _numInvalidPixelFormats; i++) {
    SDL_ClearError();
    SDLTest_AssertPass("Call to SDL_ClearError()");
    format = _invalidPixelFormats[i];
    result = SDL_AllocFormat(format);
    SDLTest_AssertPass("Call to SDL_AllocFormat(%u)", format);
    SDLTest_AssertCheck(result == NULL, "Verify result is NULL");
    error = SDL_GetError();
    SDLTest_AssertPass("Call to SDL_GetError()");
    SDLTest_AssertCheck(error != NULL, "Validate that error message was not NULL");
    if (error != NULL) {
      SDLTest_AssertCheck(SDL_strcmp(error, expectedError) == 0,
          "Validate error message, expected: '%s', got: '%s'", expectedError, error);
    }
  }

  /* Invalid free pointer */
  SDL_ClearError();
  SDLTest_AssertPass("Call to SDL_ClearError()");
  SDL_FreeFormat(NULL);
  SDLTest_AssertPass("Call to SDL_FreeFormat(NULL)");
  error = SDL_GetError();
  SDLTest_AssertPass("Call to SDL_GetError()");
  SDLTest_AssertCheck(error != NULL, "Validate that error message was not NULL");
  if (error != NULL) {
      SDLTest_AssertCheck(SDL_strcmp(error, expectedError) == 0,
          "Validate error message, expected: '%s', got: '%s'", expectedError, error);
  }

  return TEST_COMPLETED;
}