示例#1
0
const char *sysdep_display_update(mame_bitmap *bitmap,
  rectangle *vis_in_dest_out, rectangle *dirty_area,
  struct sysdep_palette_struct *palette, int keyb_leds, int flags)
{
  unsigned char *video_mem;
  
  /* do we need todo a full update? */
  if (first_update)
  {
    *dirty_area = *vis_in_dest_out;
    first_update = 0;
  }  

  SDL_LockSurface(video_surface);

  video_mem = video_surface->pixels;
  video_mem += startx * video_surface->format->BytesPerPixel;
  video_mem += starty * video_surface->pitch;
    
  blit_func(bitmap, vis_in_dest_out, dirty_area, palette, video_mem,
    video_surface->pitch/video_surface->format->BytesPerPixel);

  SDL_UnlockSurface(video_surface);

  if (video_surface->flags & SDL_DOUBLEBUF)
    SDL_Flip(video_surface);
  else if(!(video_surface->flags & SDL_HWSURFACE))
  {
    SDL_Rect drect;
    drect.x = startx + vis_in_dest_out->min_x;
    drect.y = starty + vis_in_dest_out->min_y;
    drect.w = vis_in_dest_out->max_x - vis_in_dest_out->min_x;
    drect.h = vis_in_dest_out->max_y - vis_in_dest_out->min_y;
    SDL_UpdateRects(video_surface,1, &drect);
  }
  
  if ((flags & SYSDEP_DISPLAY_HOTKEY_GRABMOUSE) &&
      !sysdep_display_params.fullscreen)
  {
    if(sdl_input_grabbed == SDL_GRAB_ON)
    {
      sdl_input_grabbed = SDL_WM_GrabInput(SDL_GRAB_OFF);
      if (sdl_input_grabbed == SDL_GRAB_OFF)
        sdl_grab_input = 0;
    }
    else
    {
      sdl_input_grabbed = SDL_WM_GrabInput(SDL_GRAB_ON);
      if (sdl_input_grabbed == SDL_GRAB_ON)
        sdl_grab_input = 1;
    }
    /* Show/Hide mouse cursor */
    if (sdl_show_cursor)
    {
      if (sdl_input_grabbed == SDL_GRAB_ON)
        SDL_ShowCursor(0);
      else
        SDL_ShowCursor(1);
    }
  }
      
  return NULL;
}
示例#2
0
文件: main.c 项目: Feirlane/scrpg
int render() {
    SDL_Rect src,dst;

    if((SDL_GetTicks() - lastRenderTick) > 20) {
        lastRenderTick = SDL_GetTicks();
        if(SDL_MUSTLOCK(screen))
            if (SDL_LockSurface(screen) < 0)
                return 1;

        if (((SDL_GetTicks() - lastBgRenderTick) > 40) && 0) {
            lastBgRenderTick = SDL_GetTicks();
            src.x=0;
            src.y=0;
            src.w=_X;
            src.h=_Y;

            bgy++;

            dst.x=0;
            dst.y=0 + bgy;
            dst.w=_X;
            dst.h=_Y;

            SDL_BlitSurface(background,&src,screen,&dst);

        }

        tmpe = fe;
        while(tmpe) {
            SC_DrawPartialSurface(tmpe->dst.x,tmpe->dst.y,tmpe->dst.x,tmpe->dst.y,tmpe->img->w,tmpe->img->h,background,screen);
            tmpe = tmpe->next;
        }
        tmps = fs;
        while(tmps) {
            SC_DrawPartialSurface(tmps->dst.x,tmps->dst.y,tmps->dst.x,tmps->dst.y,tmps->dst.w,tmps->dst.h,background,screen);
            tmps = tmps->next;
        }

        SC_DrawPartialSurface(player.dst.x,player.dst.y,player.dst.x,player.dst.y,player.dst.w,player.dst.h,background,screen);

        update();

        src.x=(player.dst.w*7) + (player.dst.w*(int)(playerCos*8));
        src.y=0;
        if(playerSin < 0)
            src.y=45;
/*        printf("X:%d Y:%d cos:%1.1f\n",src.x,src.y,playerCos); */
        src.w=player.dst.w;
        src.h=player.dst.h;

        if(!screen) {
            printf("Screen not found! WTF!!\n");
            return 0;
        }
/*        printf("BlitPlayer [%d %d %d %d] [%d %d %d %d]\n",src.x,src.y,src.w,src.h,player.dst.x,player.dst.y,player.dst.h,player.dst.w); */

        SDL_BlitSurface(player.img,&src,screen,&(player.dst));

        dst.x=5;
        dst.y=5;
        dst.h=5;
        dst.w=100;
        if(!points)
            SDL_FillRect(screen,&dst,0x000);
        dst.w=points;
        SDL_FillRect(screen,&dst,0xFF000);

        src.y=0;
        src.x=0;

        tmpe = fe;
        while(tmpe) {
            src.w=tmpe->img->w/3;
            src.h=tmpe->img->h;
            SDL_BlitSurface(tmpe->img,&src,screen,&(tmpe->dst));
            tmpe = tmpe->next;
        }

        tmps = fs;
        while(tmps) {
            src.w=tmps->dst.w;
            src.h=tmps->dst.h;
            SDL_BlitSurface(tmps->img,&src,screen,&(tmps->dst));
            tmps = tmps->next;
        }

        SDL_Flip(screen);

        if (SDL_MUSTLOCK(screen))
            SDL_UnlockSurface(screen);
    }
    return 0;
}
示例#3
0
int print_png(FILE *out, SDL_Surface *surf,int compression){
	png_structp png_ptr;
	png_infop info_ptr;
	SDL_PixelFormat *fmt=NULL;
	SDL_Surface *tempsurf=NULL;
	int ret,funky_format,used_alpha;
	unsigned int i,temp_alpha;
	png_colorp palette;
	Uint8 *palette_alpha=NULL;
	png_byte **row_pointers=NULL;
	png_ptr=NULL;info_ptr=NULL;palette=NULL;ret=-1;
	funky_format=0;
	
	if(!surf) {
		goto savedone; /* Nothing to do. */
	}

	row_pointers=(png_byte **)malloc(surf->h * sizeof(png_byte*));
	if (!row_pointers) { 
		SDL_SetError("Couldn't allocate memory for rowpointers");
		goto savedone;
	}
	
	png_ptr=png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL,NULL,NULL);
	if (!png_ptr){
		SDL_SetError("Couldn't allocate memory for PNG file");
		goto savedone;
	}
	info_ptr= png_create_info_struct(png_ptr);
	if (!info_ptr){
		SDL_SetError("Couldn't allocate image information for PNG file");
		goto savedone;
	}
	/* setup custom writer functions */
	png_set_write_fn(png_ptr,(voidp)out,png_write_data,NULL);

	if (setjmp(png_jmpbuf(png_ptr))){
		SDL_SetError("Unknown error writing PNG");
		goto savedone;
	}

	if(compression>Z_BEST_COMPRESSION)
		compression=Z_BEST_COMPRESSION;

	if(compression == Z_NO_COMPRESSION) // No compression
	{
		png_set_filter(png_ptr,0,PNG_FILTER_NONE);
		png_set_compression_level(png_ptr,Z_NO_COMPRESSION);
	}
        else if(compression<0) // Default compression
		png_set_compression_level(png_ptr,Z_DEFAULT_COMPRESSION);
        else
		png_set_compression_level(png_ptr,compression);

	fmt=surf->format;
	if(fmt->BitsPerPixel==8){ /* Paletted */
		png_set_IHDR(png_ptr,info_ptr,
			surf->w,surf->h,8,PNG_COLOR_TYPE_PALETTE,
			PNG_INTERLACE_NONE,PNG_COMPRESSION_TYPE_DEFAULT,
			PNG_FILTER_TYPE_DEFAULT);
		palette=(png_colorp) malloc(fmt->palette->ncolors * sizeof(png_color));
		if (!palette) {
			SDL_SetError("Couldn't create memory for palette");
			goto savedone;
		}
		for (i=0;i<fmt->palette->ncolors;i++) {
			palette[i].red=fmt->palette->colors[i].r;
			palette[i].green=fmt->palette->colors[i].g;
			palette[i].blue=fmt->palette->colors[i].b;
		}
		png_set_PLTE(png_ptr,info_ptr,palette,fmt->palette->ncolors);
		if (surf->flags&SDL_SRCCOLORKEY) {
			palette_alpha=(Uint8 *)malloc((fmt->colorkey+1)*sizeof(Uint8));
			if (!palette_alpha) {
				SDL_SetError("Couldn't create memory for palette transparency");
				goto savedone;
			}
			/* FIXME: memset? */
			for (i=0;i<(fmt->colorkey+1);i++) {
				palette_alpha[i]=255;
			}
			palette_alpha[fmt->colorkey]=0;
			png_set_tRNS(png_ptr,info_ptr,palette_alpha,fmt->colorkey+1,NULL);
		}
	}else{ /* Truecolor */
		if (fmt->Amask) {
			png_set_IHDR(png_ptr,info_ptr,
				surf->w,surf->h,8,PNG_COLOR_TYPE_RGB_ALPHA,
				PNG_INTERLACE_NONE,PNG_COMPRESSION_TYPE_DEFAULT,
				PNG_FILTER_TYPE_DEFAULT);
		} else {
			png_set_IHDR(png_ptr,info_ptr,
				surf->w,surf->h,8,PNG_COLOR_TYPE_RGB,
				PNG_INTERLACE_NONE,PNG_COMPRESSION_TYPE_DEFAULT,
				PNG_FILTER_TYPE_DEFAULT);
		}
	}
	png_write_info(png_ptr, info_ptr);

	if (fmt->BitsPerPixel==8) { /* Paletted */
		for(i=0;i<surf->h;i++){
			row_pointers[i]= ((png_byte*)surf->pixels) + i*surf->pitch;
		}
		if(SDL_MUSTLOCK(surf)){
			SDL_LockSurface(surf);
		}
		png_write_image(png_ptr, row_pointers);
		if(SDL_MUSTLOCK(surf)){
			SDL_UnlockSurface(surf);
		}
	}else{ /* Truecolor */
		if(fmt->BytesPerPixel==3){
			if(fmt->Amask){ /* check for 24 bit with alpha */
				funky_format=1;
			}else{
				/* Check for RGB/BGR/GBR/RBG/etc surfaces.*/
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
				if(fmt->Rmask!=0xFF0000 
				|| fmt->Gmask!=0x00FF00
				|| fmt->Bmask!=0x0000FF){
#else
				if(fmt->Rmask!=0x0000FF 
				|| fmt->Gmask!=0x00FF00
				|| fmt->Bmask!=0xFF0000){
#endif
					funky_format=1;
				}
			}
		}else if (fmt->BytesPerPixel==4){
			if (!fmt->Amask) { /* check for 32bit but no alpha */
				funky_format=1; 
			}else{
				/* Check for ARGB/ABGR/GBAR/RABG/etc surfaces.*/
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
				if(fmt->Rmask!=0xFF000000
				|| fmt->Gmask!=0x00FF0000
				|| fmt->Bmask!=0x0000FF00
				|| fmt->Amask!=0x000000FF){
#else
				if(fmt->Rmask!=0x000000FF
				|| fmt->Gmask!=0x0000FF00
				|| fmt->Bmask!=0x00FF0000
				|| fmt->Amask!=0xFF000000){
#endif
					funky_format=1;
				}
			}
		}else{ /* 555 or 565 16 bit color */
			funky_format=1;
		}
		if (funky_format) {
			/* Allocate non-funky format, and copy pixeldata in*/
			if(fmt->Amask){
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
				tempsurf = SDL_CreateRGBSurface(SDL_SWSURFACE, surf->w, surf->h, 24,
										0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff);
#else
				tempsurf = SDL_CreateRGBSurface(SDL_SWSURFACE, surf->w, surf->h, 24,
										0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000);
#endif
			}else{
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
				tempsurf = SDL_CreateRGBSurface(SDL_SWSURFACE, surf->w, surf->h, 24,
										0xff0000, 0x00ff00, 0x0000ff, 0x00000000);
#else
				tempsurf = SDL_CreateRGBSurface(SDL_SWSURFACE, surf->w, surf->h, 24,
										0x000000ff, 0x0000ff00, 0x00ff0000, 0x00000000);
#endif
			}
			if(!tempsurf){
				SDL_SetError("Couldn't allocate temp surface");
				goto savedone;
			}
			if(surf->flags&SDL_SRCALPHA){
				temp_alpha=fmt->alpha;
				used_alpha=1;
				SDL_SetAlpha(surf,0,255); /* Set for an opaque blit */
			}else{
				used_alpha=0;
			}
			if(SDL_BlitSurface(surf,NULL,tempsurf,NULL)!=0){
				SDL_SetError("Couldn't blit surface to temp surface");
				SDL_FreeSurface(tempsurf);
				goto savedone;
			}
			if (used_alpha) {
				SDL_SetAlpha(surf,SDL_SRCALPHA,(Uint8)temp_alpha); /* Restore alpha settings*/
			}
			for(i=0;i<tempsurf->h;i++){
				row_pointers[i]= ((png_byte*)tempsurf->pixels) + i*tempsurf->pitch;
			}
			if(SDL_MUSTLOCK(tempsurf)){
				SDL_LockSurface(tempsurf);
			}
			png_write_image(png_ptr, row_pointers);
			if(SDL_MUSTLOCK(tempsurf)){
				SDL_UnlockSurface(tempsurf);
			}
			SDL_FreeSurface(tempsurf);
		} else {
			for(i=0;i<surf->h;i++){
				row_pointers[i]= ((png_byte*)surf->pixels) + i*surf->pitch;
			}
			if(SDL_MUSTLOCK(surf)){
				SDL_LockSurface(surf);
			}
			png_write_image(png_ptr, row_pointers);
			if(SDL_MUSTLOCK(surf)){
				SDL_UnlockSurface(surf);
			}
		}
	}

	png_write_end(png_ptr, NULL);
	ret=0; /* got here, so nothing went wrong. YAY! */

savedone: /* clean up and return */
	png_destroy_write_struct(&png_ptr,&info_ptr);
	if (palette) {
		free(palette);
	}
	if (palette_alpha) {
		free(palette_alpha);
	}
	if (row_pointers) {
		free(row_pointers);
	}
	return ret;
}
/**
 * Copied from the RoboRobo branch of Nikita
 *
 * TODO: Use the ResourceFactory instead of this.
 
 * @param surface
 * @param sensorRay
 * @param ranges
 * @param pixels
 * @return
 */
int castSensorRay(SDL_Surface* surface, SensorRay sensorRay, int* ranges, int* pixels) {
    double x1 = sensorRay.x1;
    double y1 = sensorRay.y1;
    double x2 = sensorRay.x2;
    double y2 = sensorRay.y2;
    double maxRange = sensorRay.maxRange;

	if (SDL_MUSTLOCK(surface))
		SDL_LockSurface(surface);

	//Convert the pixels to 32 bit
	Uint32 *pixelData = (Uint32 *)surface->pixels;
    Uint32 activePixel;
    Uint32 regionPixel = G_COLOR_WHITE;
	Uint8 r, g, b;
	int count = 0;
	bool isObstacleCollision = false;

	int xInt, yInt, dxInt, dyInt; double xReal = x1, yReal = y1, dxReal, dyReal, xDist, yDist;

    dxInt = 1;
    dyInt = 1;
	dxReal = (x2 - x1) / (y2 - y1);
	dyReal = 1 / dxReal;

	if (abs(dxReal) > 1) {
	    if (x1 > x2) {
	        dxInt = -1;
	        dyReal = -dyReal;
        }
		for (xInt = (int)(x1 + 0.5); xInt != (int)(x2 + 0.5); xInt += dxInt, yReal += dyReal) {
		    yInt = (int)(yReal + 0.5);
			activePixel = pixelData[yInt * (surface->w) + xInt];
			// If current pixel is different from ones visited previously ...
			if (activePixel != regionPixel) {
                if (activePixel == G_COLOR_WHITE) {
                    regionPixel = G_COLOR_WHITE;
                } else {
                    // Then we have a collision, so we are going to record collision range ...
                    xReal = (double)xInt;
                    xDist = xReal - x1;
                    yDist = yReal - y1;
                    ranges[count] = sqrt(xDist * xDist + yDist * yDist);
                    // And pixel data at the collision point ...
                    SDL_GetRGB(activePixel, gEnvironmentImage->format, &r, &g, &b);
                    pixels[count++] = (r << 16) + (g << 8) + b;
                    // Stop scanning if collided with obstacle, but continue scanning if it was a puck.
                    if (r != 0xFF) {isObstacleCollision = true; break;}
                    regionPixel = activePixel;
                }
			}
		}
	} else {
	    if (y1 > y2) {
	        dyInt = -1;
	        dxReal = -dxReal;
	    }
		for (yInt = (int)(y1 + 0.5); yInt != (int)(y2 + 0.5); yInt += dyInt, xReal += dxReal) {
		    xInt = (int)(xReal + 0.5);
			activePixel = pixelData[yInt * (surface->w) + xInt];
			// If current pixel is different from ones visited previously ...
			if (activePixel != regionPixel) {
                if (activePixel == G_COLOR_WHITE) {
                    regionPixel = G_COLOR_WHITE;
                } else {
                    // Then we have a collision, so we are going to record collision range ...
                    yReal = (double)yInt;
                    xDist = xReal - x1;
                    yDist = yReal - y1;
                    ranges[count] = sqrt(xDist * xDist + yDist * yDist);
                    // And pixel data at the collision point ...
                    SDL_GetRGB(activePixel, gEnvironmentImage->format, &r, &g, &b);
                    pixels[count++] = (r << 16) + (g << 8) + b;
                    // Stop scanning if collided with obstacle, but continue scanning if it was a puck.
                    if (r != 0xFF) {isObstacleCollision = true; break;}
                    regionPixel = activePixel;
                }
			}
		}
	}

	if (SDL_MUSTLOCK(surface))
		SDL_UnlockSurface(surface);

    // If we recorded no collisions while scanning (even if there were some collisions with pucks).
    if (!isObstacleCollision) {
	    if (maxRange != -1) {
		    ranges[count] = maxRange;
	    } else {
            xDist = xReal - x1;
            yDist = yReal - y1;
            ranges[count] = sqrt(xDist * xDist + yDist * yDist);
        }
        pixels[count++] = 0xFFFFFF;
    }

    return count;
}
示例#5
0
Image* Image::merge(Image* image, const int x, const int y)
{
    SDL_Surface* surface = new SDL_Surface(*(image->mImage));

    Uint32 surface_pix, cur_pix;
    Uint8 r, g, b, a, p_r, p_g, p_b, p_a;
    double f_a, f_ca, f_pa;
    SDL_PixelFormat *current_fmt = mImage->format;
    SDL_PixelFormat *surface_fmt = surface->format;
    int current_offset, surface_offset;
    int offsetX = 0, offsetY = 0;

    if (SDL_MUSTLOCK(mImage))
    {
        SDL_LockSurface(surface);
        SDL_LockSurface(mImage);
    }

    // for each pixel lines of a source image
    for (offsetY = (y > 0 ? 0 : -y); offsetY < image->getHeight() &&
                    y + offsetY < getHeight(); offsetY++)
    {
        for (offsetX = (x > 0 ? 0 : -x); offsetX < image->getWidth() &&
                        x + offsetX < getWidth(); offsetX++)
        {
            // Computing offset on both images
            current_offset = (y + offsetY) * getWidth() + x + offsetX;
            surface_offset = offsetY * surface->w + offsetX;

            // Retrieving a pixel to merge
            surface_pix = ((Uint32*) surface->pixels)[surface_offset];
            cur_pix = ((Uint32*) mImage->pixels)[current_offset];

            // Retreiving each channel of the pixel using pixel format
            r = (Uint8)(((surface_pix & surface_fmt->Rmask) >> 
                          surface_fmt->Rshift) << surface_fmt->Rloss);
            g = (Uint8)(((surface_pix & surface_fmt->Gmask) >>
                          surface_fmt->Gshift) << surface_fmt->Gloss);
            b = (Uint8)(((surface_pix & surface_fmt->Bmask) >>
                          surface_fmt->Bshift) << surface_fmt->Bloss);
            a = (Uint8)(((surface_pix & surface_fmt->Amask) >>
                          surface_fmt->Ashift) << surface_fmt->Aloss);

            // Retreiving previous alpha value
            p_a = (Uint8)(((cur_pix & current_fmt->Amask) >>
                            current_fmt->Ashift) << current_fmt->Aloss);

            // new pixel with no alpha or nothing on previous pixel
            if (a == SDL_ALPHA_OPAQUE || (p_a == 0 && a > 0))
                ((Uint32 *)(surface->pixels))[current_offset] = 
                    SDL_MapRGBA(current_fmt, r, g, b, a);
            else if (a > 0) 
            { // alpha is lower => merge color with previous value
                f_a = (double) a / 255.0;
                f_ca = 1.0 - f_a;
                f_pa = (double) p_a / 255.0;
                p_r = (Uint8)(((cur_pix & current_fmt->Rmask) >> 
                                current_fmt->Rshift) << current_fmt->Rloss);
                p_g = (Uint8)(((cur_pix & current_fmt->Gmask) >>
                                current_fmt->Gshift) << current_fmt->Gloss);
                p_b = (Uint8)(((cur_pix & current_fmt->Bmask) >>
                                current_fmt->Bshift) << current_fmt->Bloss);
                r = (Uint8)((double) p_r * f_ca * f_pa + (double)r * f_a);
                g = (Uint8)((double) p_g * f_ca * f_pa + (double)g * f_a);
                b = (Uint8)((double) p_b * f_ca * f_pa + (double)b * f_a);
                a = (a > p_a ? a : p_a);
               ((Uint32 *)(surface->pixels))[current_offset] =
                   SDL_MapRGBA(current_fmt, r, g, b, a);
            }
        }
    }
示例#6
0
/* 
 * This function performs a fast fill of the given rectangle with 'color'
 */
int SDL_FillRect(SDL_Surface *dst, SDL_Rect *dstrect, Uint32 color)
{
	SDL_VideoDevice *video = current_video;
	SDL_VideoDevice *this  = current_video;
	int x, y;
	Uint8 *row;

	/* This function doesn't work on surfaces < 8 bpp */
	if ( dst->format->BitsPerPixel < 8 ) {
		switch(dst->format->BitsPerPixel) {
		    case 1:
			return SDL_FillRect1(dst, dstrect, color);
			break;
		    case 4:
			return SDL_FillRect4(dst, dstrect, color);
			break;
		    default:
			SDL_SetError("Fill rect on unsupported surface format");
			return(-1);
			break;
		}
	}

	/* If 'dstrect' == NULL, then fill the whole surface */
	if ( dstrect ) {
		/* Perform clipping */
		if ( !SDL_IntersectRect(dstrect, &dst->clip_rect, dstrect) ) {
			return(0);
		}
	} else {
		dstrect = &dst->clip_rect;
	}

	/* Check for hardware acceleration */
	if ( ((dst->flags & SDL_HWSURFACE) == SDL_HWSURFACE) &&
					video->info.blit_fill ) {
		SDL_Rect hw_rect;
		if ( dst == SDL_VideoSurface ) {
			hw_rect = *dstrect;
			hw_rect.x += current_video->offset_x;
			hw_rect.y += current_video->offset_y;
			dstrect = &hw_rect;
		}
		return(video->FillHWRect(this, dst, dstrect, color));
	}

	/* Perform software fill */
	if ( SDL_LockSurface(dst) != 0 ) {
		return(-1);
	}
	row = (Uint8 *)dst->pixels+dstrect->y*dst->pitch+
			dstrect->x*dst->format->BytesPerPixel;
	if ( dst->format->palette || (color == 0) ) {
		x = dstrect->w*dst->format->BytesPerPixel;
		if ( !color && !((uintptr_t)row&3) && !(x&3) && !(dst->pitch&3) ) {
			int n = x >> 2;
			for ( y=dstrect->h; y; --y ) {
				SDL_memset4(row, 0, n);
				row += dst->pitch;
			}
		} else {
示例#7
0
文件: SDL_blit.c 项目: fluxer/warmux
/* The general purpose software blit routine */
static int SDL_SoftBlit(SDL_Surface *src, SDL_Rect *srcrect,
			SDL_Surface *dst, SDL_Rect *dstrect)
{
	int okay;
	int src_locked;
	int dst_locked;

	/* Everything is okay at the beginning...  */
	okay = 1;

	/* Lock the destination if it's in hardware */
	dst_locked = 0;
	if ( SDL_MUSTLOCK(dst) ) {
		if ( SDL_LockSurface(dst) < 0 ) {
			okay = 0;
		} else {
			dst_locked = 1;
		}
	}
	/* Lock the source if it's in hardware */
	src_locked = 0;
	if ( SDL_MUSTLOCK(src) ) {
		if ( SDL_LockSurface(src) < 0 ) {
			okay = 0;
		} else {
			src_locked = 1;
		}
	}

	/* Set up source and destination buffer pointers, and BLIT! */
	if ( okay  && srcrect->w && srcrect->h ) {
		SDL_BlitInfo info;
		SDL_loblit RunBlit;

		/* Set up the blit information */
		info.s_pixels = (Uint8 *)src->pixels +
				(Uint16)srcrect->y*src->pitch +
				(Uint16)srcrect->x*src->format->BytesPerPixel;
		info.s_width = srcrect->w;
		info.s_height = srcrect->h;
		info.s_skip=src->pitch-info.s_width*src->format->BytesPerPixel;
		info.d_pixels = (Uint8 *)dst->pixels +
				(Uint16)dstrect->y*dst->pitch +
				(Uint16)dstrect->x*dst->format->BytesPerPixel;
		info.d_width = dstrect->w;
		info.d_height = dstrect->h;
		info.d_skip=dst->pitch-info.d_width*dst->format->BytesPerPixel;
		info.aux_data = src->map->sw_data->aux_data;
		info.src = src->format;
		info.table = src->map->table;
		info.dst = dst->format;
		RunBlit = src->map->sw_data->blit;

		/* Run the actual software blit */
		RunBlit(&info);
	}

	/* We need to unlock the surfaces if they're locked */
	if ( dst_locked ) {
		SDL_UnlockSurface(dst);
	}
	if ( src_locked ) {
		SDL_UnlockSurface(src);
	}
	/* Blit is done! */
	return(okay ? 0 : -1);
}
示例#8
0
bool CEGALatch::loadData( std::string &path, short episode, int version, unsigned char *data, bool compresseddata )
{
	std::string filename;
	byte *RawData;
    Uint16 width, height;
    SDL_Surface *sfc;


	filename = getResourceFilename("egalatch.ck" + itoa(episode), path);

	FILE* latchfile = OpenGameFile(filename,"rb");

	if(!latchfile)
		return false;

	RawData = new byte[m_latchplanesize * 4];
    // get the data out of the file into the memory, decompressing it if necessary.
    if (compresseddata)
    {
		if (lz_decompress(latchfile, (unsigned char*) RawData))
		{
			return 1;
		}
    }
    else
    {
    	for(int i=0 ; i<(m_latchplanesize*4) ; i++)
    		RawData[i] = fgetc(latchfile);
    }

    fclose(latchfile);

	// these are the offsets of the different video planes as
	// relative to each other--that is if a pixel in plane1
	// is at N, the byte for that same pixel in plane3 will be
	// at (N + plane3).
	unsigned long plane1, plane2, plane3, plane4;

	plane1 = 0;
	plane2 = (m_latchplanesize * 1);
	plane3 = (m_latchplanesize * 2);
	plane4 = (m_latchplanesize * 3);

	// ** read the 8x8 tiles **
	// set up the getbit() function of CPlanes class
	CPlanes Planes(RawData);
	Planes.setOffsets(plane1 + m_fontlocation, plane2 + m_fontlocation,
					  plane3 + m_fontlocation, plane4 + m_fontlocation, 0);
	// Load these graphics into the CFont Class of CGfxEngine
	// The original vorticon engine only uses one fontmap, but we use another for
	// extra icons. For example sliders are in that map

	g_pGfxEngine->freeFonts();
	g_pGfxEngine->createEmptyFontmaps(3);

	g_pGfxEngine->getFont(0).loadinternalFont();

	CFont &Font = g_pGfxEngine->getFont(1);
	Font.CreateSurface( g_pGfxEngine->Palette.m_Palette, SDL_SWSURFACE );
	sfc = Font.getSDLSurface();

	g_pGfxEngine->getFont(2).loadAlternateFont();


	if(SDL_MUSTLOCK(sfc)) SDL_LockSurface(sfc);

	Uint8 *pixel = (Uint8*) sfc->pixels;
	SDL_FillRect(sfc, NULL, 0);

	for(int p=0;p<4;p++)
		Planes.readPlaneofTiles(p, pixel, 16, 8, m_fonttiles);

	if(SDL_MUSTLOCK(sfc)) SDL_UnlockSurface(sfc);

	// ** read the 16x16 tiles **
	Planes.setOffsets(plane1 + m_tiles16location,
					 plane2 + m_tiles16location,
					 plane3 + m_tiles16location,
					 plane4 + m_tiles16location,
					 0);

	g_pGfxEngine->freeTilemap();
	g_pGfxEngine->createEmptyTilemap(2);
	CTilemap &Tilemap = g_pGfxEngine->getTileMap(1);
	Tilemap.CreateSurface( g_pGfxEngine->Palette.m_Palette, SDL_SWSURFACE, m_num16tiles, 4, 13 );
	sfc = Tilemap.getSDLSurface();
	SDL_FillRect(sfc,NULL, 0);
	if(SDL_MUSTLOCK(sfc))	SDL_LockSurface(sfc);
	Uint8 *u_pixel = (Uint8*) sfc->pixels;

	for(int p=0;p<4;p++)
		Planes.readPlaneofTiles(p, u_pixel, 13, 16, m_num16tiles);

	if(SDL_MUSTLOCK(sfc))	SDL_UnlockSurface(sfc);

	// Load Hi-Colour, VGA, SVGA Tiles into the tilemap
	filename = getResourceFilename("gfx/ck" + itoa(episode) + "tiles.bmp", path, false);
	if(Tilemap.loadHiresTile(filename))
		g_pLogFile->textOut(GREEN, "VGA Bitmap for Tileset has been loaded successfully!");

	// Adapt the tilemap to the display, so they are faster blit
	Tilemap.optimizeSurface();

	// make masked tiles according to it's surfaces
	applyMasks();

	////////////////////
	/// Load Bitmaps ///
	////////////////////

	Planes.setOffsets(plane1 + m_bitmaplocation,
					plane2 + m_bitmaplocation,
					plane3 + m_bitmaplocation,
					plane4 + m_bitmaplocation,
					0);

	// decode bitmaps into the BitmapData structure. The bitmaps are
	// loaded into one continuous stream of image data, with the bitmaps[]
	// array giving pointers to where each bitmap starts within the stream.

	for(int p=0 ; p<4 ; p++)
	{
		for(int b=0 ; b<m_bitmaps ; b++)
		{
		    CBitmap &bitmap = g_pGfxEngine->getBitmap(b);
			// this points to the location that we're currently
			// decoding bitmap data to

			sfc= bitmap.getSDLSurface();
			if(SDL_MUSTLOCK(sfc)) SDL_LockSurface(sfc);
			Uint8* pixel = (Uint8*) sfc->pixels;
			if(p==0)
				SDL_FillRect(sfc, NULL, 0);
			width = bitmap.getWidth(); height = bitmap.getHeight();
			// Now read the raw data

			Planes.readPlane(p, pixel, width, height);

			if(SDL_MUSTLOCK(sfc)) SDL_UnlockSurface(sfc);
		}
	}

	// optimize the bitmaps and load hq bitmaps if there are some.
	for(int b=0 ; b<m_bitmaps ; b++)
	{
		CBitmap &bitmap = g_pGfxEngine->getBitmap(b);
		bitmap.optimizeSurface();
	}

	std::set<std::string> filelist;
	FileListAdder fileListAdder;
	std::string gfxpath = JoinPaths(path, "gfx");
	GetFileList(filelist, fileListAdder, gfxpath, false, FM_REG);
	FilterFilelist(filelist, "bitmap");

	std::set<std::string>::iterator it = filelist.begin();

	for( ; it != filelist.end() ; it++ )
	{
		std::string filename=*it;
		int num = getRessourceID(filename, "bitmap");
		CBitmap &bitmap = g_pGfxEngine->getBitmap(num);
		filename = getResourceFilename("gfx/" + filename, path, false);
		bitmap.loadHQBitmap(filename);
	}

	if(RawData){ delete[] RawData; RawData = NULL;}

	return true;
}
示例#9
0
SDL_Surface * LoadCPS_RW(SDL_RWops* RWop, int freesrc)
{
	if(RWop == NULL) {
		return NULL;
	}

    uint8_t* pFiledata = NULL;
    uint8_t* pImageOut = NULL;
    SDL_Surface *pic = NULL;

	try {
        Uint32 CpsFilesize = SDL_RWseek(RWop,0,SEEK_END);
        if(CpsFilesize <= 0) {
            throw std::runtime_error("LoadCPS_RW(): Cannot determine size of this *.cps-File!");
        }

        if(SDL_RWseek(RWop,0,SEEK_SET) != 0) {
            throw std::runtime_error("LoadCPS_RW(): Seeking in this *.cps-File failed!");
        }

        pFiledata = new uint8_t[CpsFilesize];

        if(SDL_RWread(RWop, pFiledata, CpsFilesize, 1) != 1) {
            throw std::runtime_error("LoadCPS_RW(): Reading this *.cps-File failed!");
        }

        uint16_t format = SDL_SwapLE16(*(uint16_t*)(pFiledata + 2));

        if(format != 0x0004) {
            throw std::runtime_error("LoadCPS_RW(): Only Format80 encoded *.cps-Files are supported!");
        }

        unsigned int SizeXTimeSizeY = SDL_SwapLE16(*((uint16_t*)(pFiledata + 4)));
        SizeXTimeSizeY += SDL_SwapLE16(*((uint16_t*)(pFiledata + 6)));

        if(SizeXTimeSizeY != SIZE_X * SIZE_Y) {
            throw std::runtime_error("LoadCPS_RW(): Images must be 320x200 pixels big!");
        }

        uint16_t PaletteSize = SDL_SwapLE16(*((uint16_t*)(pFiledata + 8)));

        pImageOut = new uint8_t[SIZE_X*SIZE_Y];
        memset(pImageOut, 0, SIZE_X*SIZE_Y);

        if(decode80(pFiledata + 10 + PaletteSize, pImageOut, 0) == -2) {
            throw std::runtime_error("LoadCPS_RW(): Decoding this *.cps-File failed!");
        }

        // create new picture surface
        if((pic = SDL_CreateRGBSurface(SDL_HWSURFACE,SIZE_X,SIZE_Y,8,0,0,0,0))== NULL) {
            throw std::runtime_error("LoadCPS_RW(): SDL_CreateRGBSurface has failed!");
        }

        palette.applyToSurface(pic);
        SDL_LockSurface(pic);

        //Now we can copy line by line
        for(int y = 0; y < SIZE_Y;y++) {
            memcpy(	((char*) (pic->pixels)) + y * pic->pitch , pImageOut + y * SIZE_X, SIZE_X);
        }

        SDL_UnlockSurface(pic);

	    delete [] pFiledata;
	    delete [] pImageOut;

        if(freesrc) {
            SDL_RWclose(RWop);
        }

        return pic;
	} catch (std::exception &e) {
		fprintf(stderr, "%s\n", e.what());

	    delete [] pFiledata;
	    delete [] pImageOut;

	    if(pic != NULL) {
            SDL_FreeSurface(pic);
	    }

        if(freesrc) {
            SDL_RWclose(RWop);
        }

        return NULL;
	}
}
示例#10
0
// Creates some perlin noise
void Sprite::createClouds()
{
    // Note: This is HIGHLY unoptimzied for two reasons:
    // 1) I still haven't grasped Perlin noise completely, and wish to learn it as I go.
    //    Most of this stuff I found with random googling and implemented it as I could
    // 2) I want to experiment with multithreading and see the performance increase.
    //    Eventually I hope to do this on a fragment shader

    std::vector<boost::thread*> threadContainer;
    std::vector<boost::thread*>::iterator iter;

    SDL_LockSurface(spriteSurface);

    number_of_threads = 8;
    int work_per_thread = floor(float(w) / float(number_of_threads));

    float** base = generateBaseNoise();
    std::vector<SDL_Surface*> surfaceVector;
    SDL_Surface* lovely_perlin = generatePerlinNoise(base, 12);
    spriteSurface = lovely_perlin;
    threads_ready = 0;

    // Give some output on the screen while we are working =)
    SDL_UnlockSurface(spriteSurface);
    regenerateTexture();
    render();
    SDL_GL_SwapBuffers();
    SDL_LockSurface(spriteSurface); 

    SDL_Surface* big_perlin = generatePerlinNoise(base, 10);
    SDL_Surface* bigger_perlin = generatePerlinNoise(base, 13);
    SDL_Surface* placeHolder = SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, 32, 0, 0, 0, 0);

    threadContainer.clear();
    threads_ready = 0;

    for (int i = 0; i < number_of_threads; i++)
    {
        boost::thread surfaceMerger(mergeTwoSurfaces, bigger_perlin, big_perlin, placeHolder, 0.8f, true, i*work_per_thread, (i+1)*work_per_thread, 0, h);
        boost::thread* threadPtr = &surfaceMerger;
        threadContainer.push_back(threadPtr);
    }

    fprintf(stderr, "Waiting for threads to finish combining surfaces\n");

    while (threads_ready < number_of_threads)
    {
    }

    fprintf(stderr, "Joining threads\n");

    for (iter = threadContainer.begin(); iter != threadContainer.end(); iter++)
    {
        (*iter)->join();
    }

    spriteSurface = placeHolder;

    SDL_UnlockSurface(spriteSurface);
    regenerateTexture();
    render();
    SDL_GL_SwapBuffers();
    SDL_LockSurface(spriteSurface); 

    threadContainer.clear();
    threads_ready = 0;

    for (int i = 0; i < number_of_threads; i++)
    {
        boost::thread surfaceMerger(mergeTwoSurfaces, lovely_perlin, placeHolder, spriteSurface, 0.5f, true, i*work_per_thread, (i+1)*work_per_thread, 0, h);
        boost::thread* threadPtr = &surfaceMerger;
        threadContainer.push_back(threadPtr);
    }

    fprintf(stderr, "Waiting for threads to finish combining surfaces\n");

    while (threads_ready < number_of_threads)
    {
    }

    fprintf(stderr, "Joining threads\n");

    for (iter = threadContainer.begin(); iter != threadContainer.end(); iter++)
    {
        (*iter)->join();
    }

    SDL_UnlockSurface(spriteSurface);
    regenerateTexture();
    render();
    SDL_GL_SwapBuffers();
    SDL_LockSurface(spriteSurface); 

    threadContainer.clear();
    threads_ready = 0;


    for (int i = 0; i < number_of_threads; i++)
    {
        boost::thread blurrer(blurSurface, lovely_perlin, 8, 8, i*work_per_thread, (i+1)*work_per_thread, 0, h);
        boost::thread* threadPtr = &blurrer;
        threadContainer.push_back(threadPtr);
    }

    fprintf(stderr, "Waiting for threads to finish blurring\n");

    while (threads_ready < number_of_threads)
    {
    }

    for (iter = threadContainer.begin(); iter != threadContainer.end(); iter++)
    {
        (*iter)->join();
    }


    // Now that we have the first perlin noise, let's use that as a general global height map
    // Time to add sea level
    SDL_Color blue;
    blue.r = 255;   // What the eff is this anyway? I want blue, not red.
    blue.g = 0;
    blue.b = 0;
    lovely_perlin = filterMap(lovely_perlin, blue, 140);
    spriteSurface = lovely_perlin;

    SDL_UnlockSurface(spriteSurface);
    regenerateTexture();
    render();
    SDL_GL_SwapBuffers();
    SDL_LockSurface(spriteSurface); 
/*

    SDL_Surface* dark_and_messy = generatePerlinNoise(base, 2);

    SDL_UnlockSurface(spriteSurface);
    spriteSurface = dark_and_messy;
    regenerateTexture();
    render();
    SDL_GL_SwapBuffers();
    SDL_LockSurface(spriteSurface);

    fprintf(stderr, "Blurring\n");
    threads_ready = 0;

    // Blur the messy surface
    for (int i = 0; i < number_of_threads; i++)
    {
        boost::thread blurrer(blurSurface, dark_and_messy, 3, 3, i*work_per_thread, (i+1)*work_per_thread, 0, h);
        boost::thread* threadPtr = &blurrer;
        threadContainer.push_back(threadPtr);
    }

    fprintf(stderr, "Waiting for threads to finish blurring\n");

    while (threads_ready < number_of_threads)
    {
    }

    for (iter = threadContainer.begin(); iter != threadContainer.end(); iter++)
    {
        (*iter)->join();
    }

    spriteSurface = dark_and_messy;
    SDL_UnlockSurface(spriteSurface);
    regenerateTexture();
    render();
    SDL_GL_SwapBuffers();
    SDL_LockSurface(spriteSurface);

    surfaceVector.push_back(lovely_perlin);
    surfaceVector.push_back(dark_and_messy);

    threadContainer.clear();
    threads_ready = 0;

    for (int i = 0; i < number_of_threads; i++)
    {
        boost::thread surfaceMerger(mergeTwoSurfaces, lovely_perlin, dark_and_messy, spriteSurface, 0.8f, true, i*work_per_thread, (i+1)*work_per_thread, 0, h);
        boost::thread* threadPtr = &surfaceMerger;
        threadContainer.push_back(threadPtr);
    }

    fprintf(stderr, "Waiting for threads to finish combining surfaces\n");

    while (threads_ready < number_of_threads)
    {
    }

    fprintf(stderr, "Joining threads\n");

    for (iter = threadContainer.begin(); iter != threadContainer.end(); iter++)
    {
        (*iter)->join();
    }

    SDL_UnlockSurface(spriteSurface);
    regenerateTexture();
*/
}
示例#11
0
int lockscr (void)
{
  SDL_LockSurface(prSDLScreen);
  return 1;
}
示例#12
0
static void console_draw_cursor ( void )
{
	Uint32		*ScreenPointer;
	Uint32		y;

	if ( SDL_MUSTLOCK ( video_screen640 ) )
		SDL_LockSurface ( video_screen640 );

	ScreenPointer = ( Uint32* ) video_screen640->pixels;
	ScreenPointer += ( ( video_screen640->pitch * console_cursor_y * 8 ) + ( console_cursor_x * 32 ) ) / 4;

	switch ( console_cursor_type )
	{
	case CURSOR_SOLID:
		for ( y = 0;y < 8; y++ )
		{
			*ScreenPointer = ~ ( *ScreenPointer );
			ScreenPointer++;
			*ScreenPointer = ~ ( *ScreenPointer );
			ScreenPointer++;
			*ScreenPointer = ~ ( *ScreenPointer );
			ScreenPointer++;
			*ScreenPointer = ~ ( *ScreenPointer );
			ScreenPointer++;
			*ScreenPointer = ~ ( *ScreenPointer );
			ScreenPointer++;
			*ScreenPointer = ~ ( *ScreenPointer );
			ScreenPointer++;
			*ScreenPointer = ~ ( *ScreenPointer );
			ScreenPointer++;
			*ScreenPointer = ~ ( *ScreenPointer );
			ScreenPointer++;

			ScreenPointer += ( video_screen640->pitch / 4 ) - 8;
		}
		break;
	case CURSOR_NORMAL:
		ScreenPointer += ( video_screen640->pitch / 4 ) * 6;

		for ( y = 0;y < 2; y++ )
		{
			*ScreenPointer = ~ ( *ScreenPointer );
			ScreenPointer++;
			*ScreenPointer = ~ ( *ScreenPointer );
			ScreenPointer++;
			*ScreenPointer = ~ ( *ScreenPointer );
			ScreenPointer++;
			*ScreenPointer = ~ ( *ScreenPointer );
			ScreenPointer++;
			*ScreenPointer = ~ ( *ScreenPointer );
			ScreenPointer++;
			*ScreenPointer = ~ ( *ScreenPointer );
			ScreenPointer++;
			*ScreenPointer = ~ ( *ScreenPointer );
			ScreenPointer++;
			*ScreenPointer = ~ ( *ScreenPointer );
			ScreenPointer++;

			ScreenPointer += ( video_screen640->pitch / 4 ) - 8;
		}
		break;
	case CURSOR_INVISIBLE:
		break;
	}

	if ( SDL_MUSTLOCK ( video_screen640 ) )
		SDL_UnlockSurface ( video_screen640 );
}
示例#13
0
文件: SDL_bmp.c 项目: Evengard/UniMod
int
SDL_SaveBMP_RW(SDL_Surface * saveme, SDL_RWops * dst, int freedst)
{
    Sint64 fp_offset;
    int i, pad;
    SDL_Surface *surface;
    Uint8 *bits;
    SDL_bool save32bit = SDL_FALSE;
    SDL_bool saveLegacyBMP = SDL_FALSE;

    /* The Win32 BMP file header (14 bytes) */
    char magic[2] = { 'B', 'M' };
    Uint32 bfSize;
    Uint16 bfReserved1;
    Uint16 bfReserved2;
    Uint32 bfOffBits;

    /* The Win32 BITMAPINFOHEADER struct (40 bytes) */
    Uint32 biSize;
    Sint32 biWidth;
    Sint32 biHeight;
    Uint16 biPlanes;
    Uint16 biBitCount;
    Uint32 biCompression;
    Uint32 biSizeImage;
    Sint32 biXPelsPerMeter;
    Sint32 biYPelsPerMeter;
    Uint32 biClrUsed;
    Uint32 biClrImportant;

    /* The additional header members from the Win32 BITMAPV4HEADER struct (108 bytes in total) */
    Uint32 bV4RedMask = 0;
    Uint32 bV4GreenMask = 0;
    Uint32 bV4BlueMask = 0;
    Uint32 bV4AlphaMask = 0;
    Uint32 bV4CSType = 0;
    Sint32 bV4Endpoints[3 * 3] = {0};
    Uint32 bV4GammaRed = 0;
    Uint32 bV4GammaGreen = 0;
    Uint32 bV4GammaBlue = 0;

    /* Make sure we have somewhere to save */
    surface = NULL;
    if (dst) {
#ifdef SAVE_32BIT_BMP
        /* We can save alpha information in a 32-bit BMP */
        if (saveme->format->BitsPerPixel >= 8 && (saveme->format->Amask ||
            saveme->map->info.flags & SDL_COPY_COLORKEY)) {
            save32bit = SDL_TRUE;
        }
#endif /* SAVE_32BIT_BMP */

        if (saveme->format->palette && !save32bit) {
            if (saveme->format->BitsPerPixel == 8) {
                surface = saveme;
            } else {
                SDL_SetError("%d bpp BMP files not supported",
                             saveme->format->BitsPerPixel);
            }
        } else if ((saveme->format->BitsPerPixel == 24) && !save32bit &&
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
                   (saveme->format->Rmask == 0x00FF0000) &&
                   (saveme->format->Gmask == 0x0000FF00) &&
                   (saveme->format->Bmask == 0x000000FF)
#else
                   (saveme->format->Rmask == 0x000000FF) &&
                   (saveme->format->Gmask == 0x0000FF00) &&
                   (saveme->format->Bmask == 0x00FF0000)
#endif
            ) {
            surface = saveme;
        } else {
            SDL_PixelFormat format;

            /* If the surface has a colorkey or alpha channel we'll save a
               32-bit BMP with alpha channel, otherwise save a 24-bit BMP. */
            if (save32bit) {
                SDL_InitFormat(&format, SDL_PIXELFORMAT_BGRA32);
            } else {
                SDL_InitFormat(&format, SDL_PIXELFORMAT_BGR24);
            }
            surface = SDL_ConvertSurface(saveme, &format, 0);
            if (!surface) {
                SDL_SetError("Couldn't convert image to %d bpp",
                             format.BitsPerPixel);
            }
        }
    } else {
        /* Set no error here because it may overwrite a more useful message from
           SDL_RWFromFile() if SDL_SaveBMP_RW() is called from SDL_SaveBMP(). */
        return -1;
    }

    if (save32bit) {
        saveLegacyBMP = SDL_GetHintBoolean(SDL_HINT_BMP_SAVE_LEGACY_FORMAT, SDL_FALSE);
    }

    if (surface && (SDL_LockSurface(surface) == 0)) {
        const int bw = surface->w * surface->format->BytesPerPixel;

        /* Set the BMP file header values */
        bfSize = 0;             /* We'll write this when we're done */
        bfReserved1 = 0;
        bfReserved2 = 0;
        bfOffBits = 0;          /* We'll write this when we're done */

        /* Write the BMP file header values */
        fp_offset = SDL_RWtell(dst);
        SDL_ClearError();
        SDL_RWwrite(dst, magic, 2, 1);
        SDL_WriteLE32(dst, bfSize);
        SDL_WriteLE16(dst, bfReserved1);
        SDL_WriteLE16(dst, bfReserved2);
        SDL_WriteLE32(dst, bfOffBits);

        /* Set the BMP info values */
        biSize = 40;
        biWidth = surface->w;
        biHeight = surface->h;
        biPlanes = 1;
        biBitCount = surface->format->BitsPerPixel;
        biCompression = BI_RGB;
        biSizeImage = surface->h * surface->pitch;
        biXPelsPerMeter = 0;
        biYPelsPerMeter = 0;
        if (surface->format->palette) {
            biClrUsed = surface->format->palette->ncolors;
        } else {
            biClrUsed = 0;
        }
        biClrImportant = 0;

        /* Set the BMP info values for the version 4 header */
        if (save32bit && !saveLegacyBMP) {
            biSize = 108;
            biCompression = BI_BITFIELDS;
            /* The BMP format is always little endian, these masks stay the same */
            bV4RedMask   = 0x00ff0000;
            bV4GreenMask = 0x0000ff00;
            bV4BlueMask  = 0x000000ff;
            bV4AlphaMask = 0xff000000;
            bV4CSType = LCS_WINDOWS_COLOR_SPACE;
            bV4GammaRed = 0;
            bV4GammaGreen = 0;
            bV4GammaBlue = 0;
        }

        /* Write the BMP info values */
        SDL_WriteLE32(dst, biSize);
        SDL_WriteLE32(dst, biWidth);
        SDL_WriteLE32(dst, biHeight);
        SDL_WriteLE16(dst, biPlanes);
        SDL_WriteLE16(dst, biBitCount);
        SDL_WriteLE32(dst, biCompression);
        SDL_WriteLE32(dst, biSizeImage);
        SDL_WriteLE32(dst, biXPelsPerMeter);
        SDL_WriteLE32(dst, biYPelsPerMeter);
        SDL_WriteLE32(dst, biClrUsed);
        SDL_WriteLE32(dst, biClrImportant);

        /* Write the BMP info values for the version 4 header */
        if (save32bit && !saveLegacyBMP) {
            SDL_WriteLE32(dst, bV4RedMask);
            SDL_WriteLE32(dst, bV4GreenMask);
            SDL_WriteLE32(dst, bV4BlueMask);
            SDL_WriteLE32(dst, bV4AlphaMask);
            SDL_WriteLE32(dst, bV4CSType);
            for (i = 0; i < 3 * 3; i++) {
                SDL_WriteLE32(dst, bV4Endpoints[i]);
            }
            SDL_WriteLE32(dst, bV4GammaRed);
            SDL_WriteLE32(dst, bV4GammaGreen);
            SDL_WriteLE32(dst, bV4GammaBlue);
        }

        /* Write the palette (in BGR color order) */
        if (surface->format->palette) {
            SDL_Color *colors;
            int ncolors;

            colors = surface->format->palette->colors;
            ncolors = surface->format->palette->ncolors;
            for (i = 0; i < ncolors; ++i) {
                SDL_RWwrite(dst, &colors[i].b, 1, 1);
                SDL_RWwrite(dst, &colors[i].g, 1, 1);
                SDL_RWwrite(dst, &colors[i].r, 1, 1);
                SDL_RWwrite(dst, &colors[i].a, 1, 1);
            }
        }

        /* Write the bitmap offset */
        bfOffBits = (Uint32)(SDL_RWtell(dst) - fp_offset);
        if (SDL_RWseek(dst, fp_offset + 10, RW_SEEK_SET) < 0) {
            SDL_Error(SDL_EFSEEK);
        }
        SDL_WriteLE32(dst, bfOffBits);
        if (SDL_RWseek(dst, fp_offset + bfOffBits, RW_SEEK_SET) < 0) {
            SDL_Error(SDL_EFSEEK);
        }

        /* Write the bitmap image upside down */
        bits = (Uint8 *) surface->pixels + (surface->h * surface->pitch);
        pad = ((bw % 4) ? (4 - (bw % 4)) : 0);
        while (bits > (Uint8 *) surface->pixels) {
            bits -= surface->pitch;
            if (SDL_RWwrite(dst, bits, 1, bw) != bw) {
                SDL_Error(SDL_EFWRITE);
                break;
            }
            if (pad) {
                const Uint8 padbyte = 0;
                for (i = 0; i < pad; ++i) {
                    SDL_RWwrite(dst, &padbyte, 1, 1);
                }
            }
        }

        /* Write the BMP file size */
        bfSize = (Uint32)(SDL_RWtell(dst) - fp_offset);
        if (SDL_RWseek(dst, fp_offset + 2, RW_SEEK_SET) < 0) {
            SDL_Error(SDL_EFSEEK);
        }
        SDL_WriteLE32(dst, bfSize);
        if (SDL_RWseek(dst, fp_offset + bfSize, RW_SEEK_SET) < 0) {
            SDL_Error(SDL_EFSEEK);
        }

        /* Close it up.. */
        SDL_UnlockSurface(surface);
        if (surface != saveme) {
            SDL_FreeSurface(surface);
        }
    }

    if (freedst && dst) {
        SDL_RWclose(dst);
    }
    return ((SDL_strcmp(SDL_GetError(), "") == 0) ? 0 : -1);
}
示例#14
0
int main(int argc, char** argv)
{
  SDL_Event event;

  int keypress = 0;
  int t = 0;
  
  // Init everything
  sdl_init();
  init_sin_table();
  
  // Init random number generator
  srand(clock());
  
  // Init balls
  for(int i = 0; i < NUM_BALLS; i++)
    reset_ball(i);
  
  // Create sprites
  ball_surface[0] = sprite_create_ball(1.0, 0.0, 0.0);
  ball_surface[1] = sprite_create_ball(0.0, 1.0, 0.0);
  ball_surface[2] = sprite_create_ball(0.0, 0.0, 1.0);
  
  // Loop until the end
  while(!keypress) 
  {
    // Lock SDL surface if needed
    if(SDL_MUSTLOCK(screen)) 
      if(SDL_LockSurface(screen) < 0)
	exit(EXIT_FAILURE);
  
    // Draw the plasma
    draw_balls(screen, t);

    // Unlock the SDL surface if needed
    if(SDL_MUSTLOCK(screen))
      SDL_UnlockSurface(screen);
  
    // Flip surfaces
    SDL_UpdateRect(screen, 0, 0, 0, 0);
      
    // Handle SDL events
    while(SDL_PollEvent(&event)) 
    {      
      switch (event.type) 
      {
	case SDL_QUIT:
	case SDL_KEYDOWN:
	  keypress = 1;
	  break;
      }
    }
    
    // Sleep until next frame (25 FPS)
    usleep(40000);
    
    // Advance time
    t++;
  }
  
  // Exit gracefully
  SDL_Quit();
  return EXIT_SUCCESS;
}
示例#15
0
文件: sdltile.c 项目: BR903/tworld
/* Extract the large-format tile images from the given surface. The
 * surface is scanned to find the delimiter pixels. Upon return, the
 * pointers to each tile image is stored in the appropriate field of
 * the tileptr array.
 */
static int initlargetileset(SDL_Surface *tiles)
{
    SDL_Rect	       *tilepos = NULL;
    Uint32		transpclr;
    int			row, nextrow;
    int			n, x, y, w, h;

    if (SDL_MUSTLOCK(tiles))
	SDL_LockSurface(tiles);

    transpclr = pixelat(tiles, 1, 0);
    for (w = 1 ; w < tiles->w ; ++w)
	if (pixelat(tiles, w, 0) != transpclr)
	    break;
    if (w == tiles->w) {
	warn("Can't find tile separators");
	return FALSE;
    }
    if (w % 4 != 0) {
	warn("Tiles must have a width divisible by 4.");
	return FALSE;
    }
    for (h = 1 ; h < tiles->h ; ++h)
	if (pixelat(tiles, 0, h) != transpclr)
	    break;
    --h;
    if (h % 4 != 0) {
	warn("Tiles must have a height divisible by 4.");
	return FALSE;
    }

    if (!settilesize(w, h))
	return FALSE;

    xalloc(tilepos, (sizeof tileidmap / sizeof *tileidmap) * sizeof *tilepos);

    row = 0;
    nextrow = sdlg.htile + 1;
    h = 1;
    x = 0;
    y = 0;
    for (n = 0 ; n < (int)(sizeof tileidmap / sizeof *tileidmap) ; ++n) {
	if (tileidmap[n].shape == TILEIMG_IMPLICIT)
	    continue;
      findwidth:
	w = 0;
	for (;;) {
	    ++w;
	    if (x + w * sdlg.wtile >= tiles->w) {
		w = 0;
		break;
	    }
	    if (pixelat(tiles, x + w * sdlg.wtile, row) != transpclr)
		break;
	}
	if (!w) {
	    row = nextrow;
	    ++nextrow;
	    y += 1 + h * sdlg.htile;
	    h = 0;
	    do {
		++h;
		if (y + h * sdlg.htile >= tiles->h) {
		    h = 0;
		    break;
		}
		nextrow += sdlg.htile;
	    } while (pixelat(tiles, 0, nextrow) == transpclr);
	    if (!h) {
		warn("incomplete tile set: missing %02X", tileidmap[n].id);
		goto failure;
	    }
	    x = 0;
	    goto findwidth;
	}
	tilepos[n].x = x + 1;
	tilepos[n].y = y + 1;
	tilepos[n].w = w;
	tilepos[n].h = h;
	x += w * sdlg.wtile;
    }

    if (SDL_MUSTLOCK(tiles))
	SDL_UnlockSurface(tiles);

    tileptr[Empty].transpsize = 0;
    tileptr[Empty].celcount = 1;
    tileptr[Empty].opaque[0] = extractopaquetile(tiles, 1, 1,
						 sdlg.wtile, sdlg.htile);
    tileptr[Empty].transp[0] = NULL;
    remembersurface(tileptr[Empty].opaque[0]);

    for (n = 1 ; n < (int)(sizeof tileidmap / sizeof *tileidmap) ; ++n) {
	if (tileidmap[n].shape == TILEIMG_IMPLICIT)
	    continue;
	if (!extracttileimage(tiles,
			      tilepos[n].x, tilepos[n].y,
			      tilepos[n].w, tilepos[n].h,
			      tileidmap[n].id, tileidmap[n].shape, transpclr))
	    goto failure;
    }

    extracttileimage(tiles, 1, 1, 1, 1, Overlay_Buffer,
		     TILEIMG_SINGLEOPAQUE, transpclr);
    tileptr[Block_Static].celcount = 1;
    tileptr[Block_Static].opaque[0] = tileptr[Block].transp[0];
    tileptr[Block_Static].transp[0] = NULL;
    tileptr[HiddenWall_Perm] = tileptr[Empty];
    tileptr[HiddenWall_Temp] = tileptr[Empty];
    tileptr[BlueWall_Fake] = tileptr[BlueWall_Real];

    free(tilepos);
    return TRUE;

  failure:
    freetileset();
    free(tilepos);
    return FALSE;
}
示例#16
0
void scale2x(SDL_Surface *src, SDL_Surface *dst)
{
     if(SDL_LockSurface(src) < 0)
        PrintMessage("scale2x:Was not able to lock work surface");
    
    if(SDL_LockSurface(dst) < 0)
        PrintMessage("scale2x:Was not able to lock screen surface");

	int looph, loopw;
	
	Uint8* srcpix = (Uint8*)src->pixels;
	Uint8* dstpix = (Uint8*)dst->pixels;

	const int srcpitch = src->pitch;
	const int dstpitch = dst->pitch;
	const int width = src->w;
	const int height = src->h;

	switch(src->format->BytesPerPixel)
	{
	case 1: { 
	    	Uint8 E0, E1, E2, E3, B, D, E, F, H;
		for(looph = 0; looph < height; ++looph)
		{
			for(loopw = 0; loopw < width; ++ loopw)
			{
			    	B = *(Uint8*)(srcpix + (MAX(0,looph-1)*srcpitch) + (1*loopw));
			    	D = *(Uint8*)(srcpix + (looph*srcpitch) + (1*MAX(0,loopw-1)));
			    	E = *(Uint8*)(srcpix + (looph*srcpitch) + (1*loopw));
			    	F = *(Uint8*)(srcpix + (looph*srcpitch) + (1*MIN(width-1,loopw+1)));
			    	H = *(Uint8*)(srcpix + (MIN(height-1,looph+1)*srcpitch) + (1*loopw));
				
				E0 = D == B && B != F && D != H ? D : E;
    	    	    	    	E1 = B == F && B != D && F != H ? F : E;
				E2 = D == H && D != B && H != F ? D : E;
				E3 = H == F && D != H && B != F ? F : E;

				*(Uint8*)(dstpix + looph*2*dstpitch + loopw*2*1) = E0;
				*(Uint8*)(dstpix + looph*2*dstpitch + (loopw*2+1)*1) = E1;
				*(Uint8*)(dstpix + (looph*2+1)*dstpitch + loopw*2*1) = E2;
				*(Uint8*)(dstpix + (looph*2+1)*dstpitch + (loopw*2+1)*1) = E3;
			}
		}break;}
	case 2: { 
	    	Uint16 E0, E1, E2, E3, B, D, E, F, H;
		for(looph = 0; looph < height; ++looph)
		{
			for(loopw = 0; loopw < width; ++ loopw)
			{
			    	B = *(Uint16*)(srcpix + (MAX(0,looph-1)*srcpitch) + (2*loopw));
			    	D = *(Uint16*)(srcpix + (looph*srcpitch) + (2*MAX(0,loopw-1)));
			    	E = *(Uint16*)(srcpix + (looph*srcpitch) + (2*loopw));
			    	F = *(Uint16*)(srcpix + (looph*srcpitch) + (2*MIN(width-1,loopw+1)));
			    	H = *(Uint16*)(srcpix + (MIN(height-1,looph+1)*srcpitch) + (2*loopw));
				
				E0 = D == B && B != F && D != H ? D : E;
    	    	    	    	E1 = B == F && B != D && F != H ? F : E;
				E2 = D == H && D != B && H != F ? D : E;
				E3 = H == F && D != H && B != F ? F : E;

				*(Uint16*)(dstpix + looph*2*dstpitch + loopw*2*2) = E0;
				*(Uint16*)(dstpix + looph*2*dstpitch + (loopw*2+1)*2) = E1;
				*(Uint16*)(dstpix + (looph*2+1)*dstpitch + loopw*2*2) = E2;
				*(Uint16*)(dstpix + (looph*2+1)*dstpitch + (loopw*2+1)*2) = E3;
			}
		}break;}
	case 3: { 
	    	int E0, E1, E2, E3, B, D, E, F, H;
		for(looph = 0; looph < height; ++looph)
		{
			for(loopw = 0; loopw < width; ++ loopw)
			{
			    	B = READINT24(srcpix + (MAX(0,looph-1)*srcpitch) + (3*loopw));
			    	D = READINT24(srcpix + (looph*srcpitch) + (3*MAX(0,loopw-1)));
			    	E = READINT24(srcpix + (looph*srcpitch) + (3*loopw));
			    	F = READINT24(srcpix + (looph*srcpitch) + (3*MIN(width-1,loopw+1)));
			    	H = READINT24(srcpix + (MIN(height-1,looph+1)*srcpitch) + (3*loopw));
				
				E0 = D == B && B != F && D != H ? D : E;
    	    	    	    	E1 = B == F && B != D && F != H ? F : E;
				E2 = D == H && D != B && H != F ? D : E;
				E3 = H == F && D != H && B != F ? F : E;

				WRITEINT24((dstpix + looph*2*dstpitch + loopw*2*3), E0);
				WRITEINT24((dstpix + looph*2*dstpitch + (loopw*2+1)*3), E1);
				WRITEINT24((dstpix + (looph*2+1)*dstpitch + loopw*2*3), E2);
				WRITEINT24((dstpix + (looph*2+1)*dstpitch + (loopw*2+1)*3), E3);
			}
		}break;}
	default: { /*case 4:*/
	    	Uint32 E0, E1, E2, E3, B, D, E, F, H;
		for(looph = 0; looph < height; ++looph)
		{
			for(loopw = 0; loopw < width; ++ loopw)
			{
			    	B = *(Uint32*)(srcpix + (MAX(0,looph-1)*srcpitch) + (4*loopw));
			    	D = *(Uint32*)(srcpix + (looph*srcpitch) + (4*MAX(0,loopw-1)));
			    	E = *(Uint32*)(srcpix + (looph*srcpitch) + (4*loopw));
			    	F = *(Uint32*)(srcpix + (looph*srcpitch) + (4*MIN(width-1,loopw+1)));
			    	H = *(Uint32*)(srcpix + (MIN(height-1,looph+1)*srcpitch) + (4*loopw));
				
				E0 = D == B && B != F && D != H ? D : E;
    	    	    	    	E1 = B == F && B != D && F != H ? F : E;
				E2 = D == H && D != B && H != F ? D : E;
				E3 = H == F && D != H && B != F ? F : E;

				*(Uint32*)(dstpix + looph*2*dstpitch + loopw*2*4) = E0;
				*(Uint32*)(dstpix + looph*2*dstpitch + (loopw*2+1)*4) = E1;
				*(Uint32*)(dstpix + (looph*2+1)*dstpitch + loopw*2*4) = E2;
				*(Uint32*)(dstpix + (looph*2+1)*dstpitch + (loopw*2+1)*4) = E3;
			}
		}break;}
	}
   SDL_UnlockSurface(src);
   SDL_UnlockSurface(dst);
}
示例#17
0
int main(int argc, char *argv[])
{
	SDL_Surface *screen, *buffer;
	Uint32 videoflags;
	SDL_TimerID refreshTimerID;
	SDL_Event event;
	int width, height, bpp, refresh;
	int done;
	int shift;
	Uint8 *buffp;
	int i, j;
	int t, interval_stat;
	Uint32 startTimer, runTimer;

	redrawEvent.type = SDL_USEREVENT;
	redrawEvent.user.code = 1;
	redrawEvent.user.data1 = NULL;
	redrawEvent.user.data2 = NULL;

	/* Initialize SDL */
	if ( SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER) < 0 ) {
		fprintf(stderr, "Couldn't initialize SDL: %s\n",SDL_GetError());
		exit(1);
	}

	interval_stat = 0;
	t = 0;
	cycle = 0;

	sinewidth = SINEWIDTH;
	frequency = FREQUENCY;
	refresh = REFRESHINT;

	width = 200;
	height = 200;
	bpp = 32;

	videoflags =  SDL_DOUBLEBUF|SDL_FULLSCREEN;

	while ( argc > 1 ) {
	  --argc;
	  if ( argv[argc-1] && (strcmp(argv[argc-1], "-w") == 0) ) {
	    width = atoi(argv[argc]);
	    --argc;
	  } else if ( argv[argc-1] && (strcmp(argv[argc-1], "-h") == 0) ) {
	    height = atoi(argv[argc]);
	    --argc;
	  } else if ( argv[argc-1] && (strcmp(argv[argc-1], "-swidth") == 0) ) {
	    sinewidth = atof(argv[argc]);
	    --argc;
	  } else if ( argv[argc-1] && (strcmp(argv[argc-1], "-freq") == 0) ) {
	    frequency = atof(argv[argc]);
	    --argc;
	  } else if ( argv[argc-1] && (strcmp(argv[argc-1], "-bpp") == 0) ) {
	    bpp = atoi(argv[argc]);
	    --argc;
	  } else if ( argv[argc] && (strcmp(argv[argc], "-sw") == 0) ) {
	    videoflags |= SDL_SWSURFACE;
	  } else if ( argv[argc] && (strcmp(argv[argc], "-hwpalette") == 0) ) {
	    videoflags |= SDL_HWPALETTE;
	  } else if ( argv[argc] && (strcmp(argv[argc], "-window") == 0) ) {
	    videoflags ^= SDL_FULLSCREEN;
	  } else if ( argv[argc] && (strcmp(argv[argc], "-bar") == 0) ) {
		  bar=1;
	  } else 
	    {
	      fprintf(stderr, "Usage: %s [-bar] [-window] [-w #] [-h #] [-swidth #] [-freq #]\n", argv[0]);
	      exit(1);
	    }
	}
	
	/* calculate the amount of shift per ms */
	shift = ceil(sinewidth*frequency/(1000.0/refresh));
	fprintf(stderr,"frequency=%f, refresh=%d, shift=%d\n",frequency,refresh,shift);

	/* Set video mode */
	screen = CreateScreen(width, height, bpp, videoflags);
	if ( screen == NULL ) {
		exit(2);
	}

	/* create a buffer where the stimulus is prepared */
	buffer = SDL_CreateRGBSurface(SDL_HWSURFACE|SDL_HWACCEL, width, height, bpp, 0,0,0,0);
	buffer = SDL_DisplayFormat(buffer);

	bpp = screen->format->BytesPerPixel;
	SDL_ShowCursor(SDL_DISABLE);
	refreshTimerID = SDL_AddTimer((int)(refresh), refreshTimer, (void *)screen);
	runTimer = SDL_GetTicks();

	/* MAIN LOOP, do screen refresh and wait for keys */
	done = 0;
	while ( !done && SDL_WaitEvent(&event) ) {
	  switch (event.type) {
	  case SDL_KEYDOWN:
	    /* Ignore ALT-TAB for windows */
	    if ( (event.key.keysym.sym == SDLK_LALT) ||
		 (event.key.keysym.sym == SDLK_TAB) ) {
	      break;
	    }
	    /* Any key quits the application... */
	  case SDL_QUIT:
	    done = 1;
	    break;
	  case SDL_USEREVENT:
	    i = runTimer;
	    runTimer = SDL_GetTicks();
	    startTimer = i;
	    interval_stat +=  runTimer - i;
	    t++;
	    SDL_LockSurface(buffer);
	    buffp = (Uint8 *)buffer->pixels;
	    for ( i=0; i<screen->h; ++i ) {
		    memcpy(buffp, &c[cycle%(((int)sinewidth)*bpp)], screen->w*bpp);
	      buffp += screen->pitch;
	    }
	    SDL_UnlockSurface(buffer);
	    SDL_BlitSurface(buffer, NULL, screen, NULL);
	    SDL_Flip(screen);
	    cycle += shift*bpp;
	    break;
	  default:
	    break;
	  }
	}
	SDL_RemoveTimer(refreshTimerID);
	SDL_ShowCursor(SDL_ENABLE);
	printf("mean display interval:%f\n", ((float)interval_stat/(float)t));
	SDL_Quit();
	return(0);	
}
示例#18
0
文件: testwin.c 项目: gxf/heigong
void DrawPict(SDL_Surface *screen, char *bmpfile,
					int speedy, int flip, int nofade)
{
	SDL_Surface *picture;
	SDL_Rect dest, update;
	int i, centered;
	int ncolors;
	SDL_Color *colors, *cmap;

	/* Load the image into a surface */
	if ( bmpfile == NULL ) {
		bmpfile = "sample.bmp";		/* Sample image */
	}
fprintf(stderr, "Loading picture: %s\n", bmpfile);
	picture = SDL_LoadBMP(bmpfile);
	if ( picture == NULL ) {
		fprintf(stderr, "Couldn't load %s: %s\n", bmpfile,
							SDL_GetError());
		return;
	}

	/* Set the display colors -- on a hicolor display this is a no-op */
	if ( picture->format->palette ) {
		ncolors = picture->format->palette->ncolors;
		colors  = (SDL_Color *)malloc(ncolors*sizeof(SDL_Color));
		cmap    = (SDL_Color *)malloc(ncolors*sizeof(SDL_Color));
		memcpy(colors, picture->format->palette->colors,
						ncolors*sizeof(SDL_Color));
	} else {
		int       r, g, b;

		/* Allocate 256 color palette */
		ncolors = 256;
		colors  = (SDL_Color *)malloc(ncolors*sizeof(SDL_Color));
		cmap    = (SDL_Color *)malloc(ncolors*sizeof(SDL_Color));

		/* Set a 3,3,2 color cube */
		for ( r=0; r<8; ++r ) {
			for ( g=0; g<8; ++g ) {
				for ( b=0; b<4; ++b ) {
					i = ((r<<5)|(g<<2)|b);
					colors[i].r = r<<5;
					colors[i].g = g<<5;
					colors[i].b = b<<6;
				}
			}
		}
	}
NOTICE("testwin: setting colors\n");
	if ( ! SDL_SetColors(screen, colors, 0, ncolors) &&
				(screen->format->palette != NULL) ) {
		fprintf(stderr,
"Warning: Couldn't set all of the colors, but SDL will map the image\n"
"         (colormap fading will suffer - try the -warp option)\n"
		);
	}

	/* Set the screen to black (not really necessary) */
	if ( SDL_LockSurface(screen) == 0 ) {
		Uint32 black;
		Uint8 *pixels;

		black = SDL_MapRGB(screen->format, 0, 0, 0);
		pixels = (Uint8 *)screen->pixels;
		for ( i=0; i<screen->h; ++i ) {
			memset(pixels, black,
				screen->w*screen->format->BytesPerPixel);
			pixels += screen->pitch;
		}
		SDL_UnlockSurface(screen);
		SDL_UpdateRect(screen, 0, 0, 0, 0);
	}
	
	/* Display the picture */
	if ( speedy ) {
		SDL_Surface *displayfmt;

fprintf(stderr, "Converting picture\n");
		displayfmt = SDL_DisplayFormat(picture);
		if ( displayfmt == NULL ) {
			fprintf(stderr,
				"Couldn't convert image: %s\n", SDL_GetError());
			goto done;
		}
		SDL_FreeSurface(picture);
		picture = displayfmt;
	}
	printf("(image surface located in %s memory)\n", 
			(picture->flags&SDL_HWSURFACE) ? "video" : "system");
	centered = (screen->w - picture->w)/2;
	if ( centered < 0 ) {
		centered = 0;
	}
	dest.y = (screen->h - picture->h)/2;
	dest.w = picture->w;
	dest.h = picture->h;
NOTICE("testwin: moving image\n");
	for ( i=0; i<=centered; ++i ) {
		dest.x = i;
		update = dest;
		if ( SDL_BlitSurface(picture, NULL, screen, &update) < 0 ) {
			fprintf(stderr, "Blit failed: %s\n", SDL_GetError());
			break;
		}
		if ( flip ) {
			SDL_Flip(screen);
		} else {
			SDL_UpdateRects(screen, 1, &update);
		}

		SDL_Delay(5);
	}

#ifdef SCREENSHOT
	if ( SDL_SaveBMP(screen, "screen.bmp") < 0 )
		printf("Couldn't save screen: %s\n", SDL_GetError());
#endif

#ifndef BENCHMARK_SDL
	/* Let it sit there for a while */
	SDL_Delay(5*1000);
#endif
	/* Fade the colormap */
	if ( ! nofade ) {
		int maxstep;
		SDL_Color final;
		SDL_Color palcolors[256];
		struct {
			Sint16 r, g, b;
		} cdist[256];

NOTICE("testwin: fading out...\n");
		memcpy(cmap, colors, ncolors*sizeof(SDL_Color));
		maxstep = 32-1;
		final.r = 0xFF;
示例#19
0
/**
 * Locks the surface from outside access
 * for pixel-level access. Must be unlocked
 * afterwards.
 * @sa unlock()
 */
void Surface::lock()
{
	SDL_LockSurface(_surface);
}
示例#20
0
/* This is a fairly slow function to switch from colorkey to alpha */
static void
SDL_ConvertColorkeyToAlpha(SDL_Surface * surface)
{
    int x, y;

    if (!surface) {
        return;
    }

    if (!(surface->map->info.flags & SDL_COPY_COLORKEY) ||
            !surface->format->Amask) {
        return;
    }

    SDL_LockSurface(surface);

    switch (surface->format->BytesPerPixel) {
    case 2:
    {
        Uint16 *row, *spot;
        Uint16 ckey = (Uint16) surface->map->info.colorkey;
        Uint16 mask = (Uint16) (~surface->format->Amask);

        /* Ignore alpha in colorkey comparison */
        ckey &= mask;
        row = (Uint16 *) surface->pixels;
        for (y = surface->h; y--;) {
            spot = row;
            for (x = surface->w; x--;) {
                if ((*spot & mask) == ckey) {
                    *spot &= mask;
                }
                ++spot;
            }
            row += surface->pitch / 2;
        }
    }
    break;
    case 3:
        /* FIXME */
        break;
    case 4:
    {
        Uint32 *row, *spot;
        Uint32 ckey = surface->map->info.colorkey;
        Uint32 mask = ~surface->format->Amask;

        /* Ignore alpha in colorkey comparison */
        ckey &= mask;
        row = (Uint32 *) surface->pixels;
        for (y = surface->h; y--;) {
            spot = row;
            for (x = surface->w; x--;) {
                if ((*spot & mask) == ckey) {
                    *spot &= mask;
                }
                ++spot;
            }
            row += surface->pitch / 4;
        }
    }
    break;
    }

    SDL_UnlockSurface(surface);

    SDL_SetColorKey(surface, 0, 0);
    SDL_SetSurfaceBlendMode(surface, SDL_BLENDMODE_BLEND);
}
示例#21
0
/* call after creating window */
bool TCOD_opengl_init_state(int conw, int conh, void *font) {
	SDL_Surface *font_surf=(SDL_Surface *)font;
	
	/* convert font for opengl */
	Uint32 rmask, gmask, bmask, amask;
	SDL_Surface *temp;
	SDL_Surface *temp_alpha;

	/* check opengl extensions */
	if ( TCOD_ctx.renderer == TCOD_RENDERER_GLSL ) {
		bool hasShader = false;
		const char *glexts=(const char *)glGetString(GL_EXTENSIONS);
		if (glexts ) {
			hasShader = (strstr(glexts,"GL_ARB_shader_objects") != NULL);
		}
		if (! hasShader ) {
			TCOD_LOG(("Missing GL_ARB_shader_objects extension. Falling back to fixed pipeline...\n"));
			TCOD_ctx.renderer = TCOD_RENDERER_OPENGL;		
		}
	}

	/* set extensions functions pointers */
   	glCreateShaderObjectARB=(PFNGLCREATESHADEROBJECTARBPROC)SDL_GL_GetProcAddress("glCreateShaderObjectARB");
	glGetObjectParameterivARB=(PFNGLGETOBJECTPARAMETERIVARBPROC)SDL_GL_GetProcAddress("glGetObjectParameterivARB");
	glShaderSourceARB=(PFNGLSHADERSOURCEARBPROC)SDL_GL_GetProcAddress("glShaderSourceARB");
	glCompileShaderARB=(PFNGLCOMPILESHADERARBPROC)SDL_GL_GetProcAddress("glCompileShaderARB");
	glGetInfoLogARB=(PFNGLGETINFOLOGARBPROC)SDL_GL_GetProcAddress("glGetInfoLogARB");
	glCreateProgramObjectARB=(PFNGLCREATEPROGRAMOBJECTARBPROC)SDL_GL_GetProcAddress("glCreateProgramObjectARB");
	glAttachObjectARB=(PFNGLATTACHOBJECTARBPROC)SDL_GL_GetProcAddress("glAttachObjectARB");
	glLinkProgramARB=(PFNGLLINKPROGRAMARBPROC)SDL_GL_GetProcAddress("glLinkProgramARB");
	glUseProgramObjectARB=(PFNGLUSEPROGRAMOBJECTARBPROC)SDL_GL_GetProcAddress("glUseProgramObjectARB");
	glUniform2fARB=(PFNGLUNIFORM2FARBPROC)SDL_GL_GetProcAddress("glUniform2fARB");
	glGetUniformLocationARB=(PFNGLGETUNIFORMLOCATIONARBPROC)SDL_GL_GetProcAddress("glGetUniformLocationARB");
	glUniform1fARB=(PFNGLUNIFORM1FARBPROC)SDL_GL_GetProcAddress("glUniform1fARB");
	glUniform1iARB=(PFNGLUNIFORM1IARBPROC)SDL_GL_GetProcAddress("glUniform1iARB");
#ifdef TCOD_WINDOWS	
	glActiveTexture=(PFNGLACTIVETEXTUREPROC)SDL_GL_GetProcAddress("glActiveTexture");
#endif
	
	/* set opengl state */
	glEnable(GL_TEXTURE_2D);
	glClearColor(1.0f, 1.0f, 0.0f, 0.0f);
	glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
	glClear( GL_COLOR_BUFFER_BIT );
	glMatrixMode( GL_PROJECTION );
	glLoadIdentity();
	if ( TCOD_ctx.renderer == TCOD_RENDERER_GLSL ) {
		glOrtho(0, conw, 0, conh, -1.0f, 1.0f);
		glDisable (GL_BLEND); 
	} else {
		glOrtho(0, conw, conh, 0.0f, -1.0f, 1.0f);
		glEnable (GL_BLEND); 
		glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	}

	glMatrixMode( GL_MODELVIEW );
	glLoadIdentity();
/*#ifdef TCOD_WINDOWS  */
	if ( ! TCOD_ctx.fullscreen ) {
		/* turn vsync off in windowed mode */
		typedef bool (APIENTRY *PFNWGLSWAPINTERVALFARPROC)(int);
		PFNWGLSWAPINTERVALFARPROC wglSwapIntervalEXT = 0;

		wglSwapIntervalEXT = (PFNWGLSWAPINTERVALFARPROC)SDL_GL_GetProcAddress("wglSwapIntervalEXT");

		if (wglSwapIntervalEXT) wglSwapIntervalEXT(0);
	}
/*#endif */

	/* compute pot size */
	conwidth=conw;
	conheight=conh;
	POTconwidth=POTconheight=1;
	while ( POTconwidth < conw ) POTconwidth *= 2;
	while ( POTconheight < conh ) POTconheight *= 2;


	#if SDL_BYTEORDER == SDL_BIG_ENDIAN
	rmask = 0xff000000;
	gmask = 0x00ff0000;
	bmask = 0x0000ff00;
	amask = 0x000000ff;
	#else
	rmask = 0x000000ff;
	gmask = 0x0000ff00;
	bmask = 0x00ff0000;
	amask = 0xff000000;
	#endif

	fontwidth=font_surf->w;
	fontheight=font_surf->h;
	POTfontwidth=POTfontheight=1;
	while ( POTfontwidth < fontwidth ) POTfontwidth *= 2;
	while ( POTfontheight < fontheight ) POTfontheight *= 2;

	SDL_SetColorKey(font_surf, SDL_SRCCOLORKEY, SDL_MapRGB(font_surf->format, 0, 0, 0));
	temp_alpha = SDL_DisplayFormatAlpha(font_surf);
	SDL_SetAlpha(temp_alpha, 0, SDL_ALPHA_TRANSPARENT);

	temp = SDL_CreateRGBSurface(SDL_SWSURFACE, POTfontwidth, POTfontheight, 32, bmask, gmask, rmask, amask); /*BGRA */

	SDL_BlitSurface(temp_alpha, NULL, temp, NULL);
	SDL_FreeSurface(temp_alpha);

	CHECKGL(glGenTextures(1, &font_tex));
	CHECKGL(glBindTexture(GL_TEXTURE_2D, font_tex));
	SDL_LockSurface(temp);

	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );

	CHECKGL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, temp->w, temp->h, 0, GL_BGRA, GL_UNSIGNED_BYTE, temp->pixels));
	SDL_UnlockSurface(temp);
	SDL_FreeSurface(temp);
	return true;
}
示例#22
0
SDL_Surface *flip_surface( SDL_Surface *surface, int flags )
{
    //Pointer to the soon to be flipped surface
    SDL_Surface *flipped = NULL;

    //If the image is color keyed
    if( surface->flags & SDL_SRCCOLORKEY )
    {
        flipped = SDL_CreateRGBSurface( SDL_SWSURFACE, 
										surface->w, 
										surface->h, 
										surface->format->BitsPerPixel, 
										surface->format->Rmask, 
										surface->format->Gmask, 
										surface->format->Bmask, 
										0 );
    }
    //Otherwise
    else
    {
        flipped = SDL_CreateRGBSurface( SDL_SWSURFACE, 
										surface->w,	
										surface->h, 
										surface->format->BitsPerPixel, 
										surface->format->Rmask, 
										surface->format->Gmask, 
										surface->format->Bmask, 
										surface->format->Amask 
										);
    }

    //If the surface must be locked
    if( SDL_MUSTLOCK( surface ) )
    {
        //Lock the surface
        SDL_LockSurface( surface );
    }

    //Go through columns
    for( int x = 0, rx = flipped->w - 1; x < flipped->w; x++, rx-- )
    {
        //Go through rows
        for( int y = 0, ry = flipped->h - 1; y < flipped->h; y++, ry-- )
        {
            //Get pixel
            Uint32 pixel = get_pixel32( surface, x, y );

            //Copy pixel
            if( ( flags & FLIP_VERTICAL ) && ( flags & FLIP_HORIZONTAL ) )
            {
                put_pixel32( flipped, rx, ry, pixel );
            }
            else if( flags & FLIP_HORIZONTAL )
            {
                put_pixel32( flipped, rx, y, pixel );
            }
            else if( flags & FLIP_VERTICAL )
            {
                put_pixel32( flipped, x, ry, pixel );
            }
        }
    }

    //Unlock surface
    if( SDL_MUSTLOCK( surface ) )
    {
        SDL_UnlockSurface( surface );
    }

    //Copy color key
    if( surface->flags & SDL_SRCCOLORKEY )
    {
        SDL_SetColorKey( flipped, SDL_RLEACCEL | SDL_SRCCOLORKEY, surface->format->colorkey );
    }

    //Return flipped surface
    return flipped;
}
示例#23
0
Image *Image::load(SDL_Surface *tmpImage)
{
#ifdef USE_OPENGL
    if (mUseOpenGL)
    {
        // Flush current error flag.
        glGetError();

        int width = tmpImage->w;
        int height = tmpImage->h;
        int realWidth = powerOfTwo(width);
        int realHeight = powerOfTwo(height);

        if (realWidth < width || realHeight < height)
        {
            logger->log("Warning: image too large, cropping to %dx%d texture!",
                    tmpImage->w, tmpImage->h);
        }

        // Make sure the alpha channel is not used, but copied to destination
        SDL_SetAlpha(tmpImage, 0, SDL_ALPHA_OPAQUE);

        // Determine 32-bit masks based on byte order
        Uint32 rmask, gmask, bmask, amask;
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
        rmask = 0xff000000;
        gmask = 0x00ff0000;
        bmask = 0x0000ff00;
        amask = 0x000000ff;
#else
        rmask = 0x000000ff;
        gmask = 0x0000ff00;
        bmask = 0x00ff0000;
        amask = 0xff000000;
#endif

        SDL_Surface *oldImage = tmpImage;
        tmpImage = SDL_CreateRGBSurface(SDL_SWSURFACE, realWidth, realHeight,
                                        32, rmask, gmask, bmask, amask);

        if (!tmpImage)
        {
            logger->log("Error, image convert failed: out of memory");
            return NULL;
        }

        SDL_BlitSurface(oldImage, NULL, tmpImage, NULL);

        GLuint texture;
        glGenTextures(1, &texture);
        glBindTexture(mTextureType, texture);

        if (SDL_MUSTLOCK(tmpImage))
            SDL_LockSurface(tmpImage);

        glTexImage2D(mTextureType, 0, 4, tmpImage->w, tmpImage->h,
                     0, GL_RGBA, GL_UNSIGNED_BYTE, tmpImage->pixels);

        glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
        glTexParameteri(mTextureType, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glTexParameteri(mTextureType, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

        if (SDL_MUSTLOCK(tmpImage))
            SDL_UnlockSurface(tmpImage);

        SDL_FreeSurface(tmpImage);

        GLenum error = glGetError();
        if (error)
        {
            std::string errmsg = "Unknown error";
            switch (error)
            {
                case GL_INVALID_ENUM:
                    errmsg = "GL_INVALID_ENUM";
                    break;
                case GL_INVALID_VALUE:
                    errmsg = "GL_INVALID_VALUE";
                    break;
                case GL_INVALID_OPERATION:
                    errmsg = "GL_INVALID_OPERATION";
                    break;
                case GL_STACK_OVERFLOW:
                    errmsg = "GL_STACK_OVERFLOW";
                    break;
                case GL_STACK_UNDERFLOW:
                    errmsg = "GL_STACK_UNDERFLOW";
                    break;
                case GL_OUT_OF_MEMORY:
                    errmsg = "GL_OUT_OF_MEMORY";
                    break;
            }
            logger->log("Error: Image GL import failed: %s", errmsg.c_str());
            return NULL;
        }

        return new Image(texture, width, height, realWidth, realHeight);
    }
#endif

    bool hasAlpha = false;

    Uint8* imageAlphas = new Uint8[tmpImage->w * tmpImage->h];
    if (tmpImage->format->BitsPerPixel == 32)
    {
        // Figure out whether the image uses its alpha layer
        for (int i = 0; i < tmpImage->w * tmpImage->h; ++i)
        {
            Uint8 r, g, b, a;
            SDL_GetRGBA(((Uint32*) tmpImage->pixels)[i],
                          tmpImage->format, &r, &g, &b, &a);

            imageAlphas[i] = a;

            if (a != 255)
                hasAlpha = true;
        }
    }

    SDL_Surface *image;

    // Convert the surface to the current display format
    if (hasAlpha)
        image = SDL_DisplayFormatAlpha(tmpImage);
    else
        image = SDL_DisplayFormat(tmpImage);

    if (!image)
    {
        logger->log("Error: Image convert failed.");
        return NULL;
    }

    return new Image(image, imageAlphas);
}
示例#24
0
void Image::setLock(bool lock) {
  if(lock && !locked) SDL_LockSurface(s); if(locked && !lock) SDL_UnlockSurface(s); locked = lock;
  }
示例#25
0
文件: sw-sdl.c 项目: leiradel/mgba
bool mSDLSWInit(struct mSDLRenderer* renderer) {
#if !SDL_VERSION_ATLEAST(2, 0, 0)
#ifdef COLOR_16_BIT
	SDL_SetVideoMode(renderer->viewportWidth, renderer->viewportHeight, 16, SDL_DOUBLEBUF | SDL_HWSURFACE);
#else
	SDL_SetVideoMode(renderer->viewportWidth, renderer->viewportHeight, 32, SDL_DOUBLEBUF | SDL_HWSURFACE);
#endif
#endif

	unsigned width, height;
	renderer->core->desiredVideoDimensions(renderer->core, &width, &height);
#if SDL_VERSION_ATLEAST(2, 0, 0)
	renderer->window = SDL_CreateWindow(projectName, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, renderer->viewportWidth, renderer->viewportHeight, SDL_WINDOW_OPENGL | (SDL_WINDOW_FULLSCREEN_DESKTOP * renderer->player.fullscreen));
	SDL_GetWindowSize(renderer->window, &renderer->viewportWidth, &renderer->viewportHeight);
	renderer->player.window = renderer->window;
	renderer->sdlRenderer = SDL_CreateRenderer(renderer->window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
#ifdef COLOR_16_BIT
#ifdef COLOR_5_6_5
	renderer->sdlTex = SDL_CreateTexture(renderer->sdlRenderer, SDL_PIXELFORMAT_RGB565, SDL_TEXTUREACCESS_STREAMING, width, height);
#else
	renderer->sdlTex = SDL_CreateTexture(renderer->sdlRenderer, SDL_PIXELFORMAT_ABGR1555, SDL_TEXTUREACCESS_STREAMING, width, height);
#endif
#else
	renderer->sdlTex = SDL_CreateTexture(renderer->sdlRenderer, SDL_PIXELFORMAT_ABGR8888, SDL_TEXTUREACCESS_STREAMING, width, height);
#endif

	int stride;
	SDL_LockTexture(renderer->sdlTex, 0, (void**) &renderer->outputBuffer, &stride);
	renderer->core->setVideoBuffer(renderer->core, renderer->outputBuffer, stride / BYTES_PER_PIXEL);
#else
	SDL_Surface* surface = SDL_GetVideoSurface();
	SDL_LockSurface(surface);

	if (renderer->ratio == 1) {
		renderer->core->setVideoBuffer(renderer->core, surface->pixels, surface->pitch / BYTES_PER_PIXEL);
	} else {
#ifdef USE_PIXMAN
		renderer->outputBuffer = malloc(width * height * BYTES_PER_PIXEL);
		renderer->core->setVideoBuffer(renderer->core, renderer->outputBuffer, width);
#ifdef COLOR_16_BIT
#ifdef COLOR_5_6_5
		pixman_format_code_t format = PIXMAN_r5g6b5;
#else
		pixman_format_code_t format = PIXMAN_x1b5g5r5;
#endif
#else
		pixman_format_code_t format = PIXMAN_x8b8g8r8;
#endif
		renderer->pix = pixman_image_create_bits(format, width, height,
		    renderer->outputBuffer, width * BYTES_PER_PIXEL);
		renderer->screenpix = pixman_image_create_bits(format, renderer->viewportWidth, renderer->viewportHeight, surface->pixels, surface->pitch);

		pixman_transform_t transform;
		pixman_transform_init_identity(&transform);
		pixman_transform_scale(0, &transform, pixman_int_to_fixed(renderer->ratio), pixman_int_to_fixed(renderer->ratio));
		pixman_image_set_transform(renderer->pix, &transform);
		pixman_image_set_filter(renderer->pix, PIXMAN_FILTER_NEAREST, 0, 0);
#else
		return false;
#endif
	}
#endif

	return true;
}
int main(int argc, char **argv) {
  int    hres, vres, width, height, pixels;
  double aspect, scale;

  SDL_Surface    *sdl_surface;
  Uint32         next_frame;
  cairo_t        *cr;
  cairo_matrix_t cm_display, cm_field, cm_panel;

  int missed_frames = 0;

  int running = true;
  int subdiv  = 1;

  struct part part = {
    NULL, NULL, NULL, NULL, PATH_MOVE, 0, 0, 0, 0
  };

  struct path_segment *segment = (struct path_segment *)
    &part.paths.segments.base; /* first segment of the first path */
  struct path         *path    = &part.paths;

  struct pos *pen = &part.paths.segments.p;

  /* SETUP */

  SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER);

  { /* acquire video information */
    /* TODO: correct pixel format */
    SDL_Rect **modes = SDL_ListModes(NULL, SDL_VIDEO_FLAGS);

    if (NULL == modes) {
      fprintf(stderr, "no video modes available\n");
      exit(0);
    }

    if ( (SDL_Rect **) -1 == modes ) {
      hres = 640;
      vres = 480;
    } else {
      hres = modes[0]->w;
      vres = modes[0]->h;
    }

    width  = hres;
    height = vres;
    aspect = (double) hres / vres;
    pixels = hres * vres;
    scale  = sqrt(pixels);

    /* TODO: cap resolution if possible */
  }

  sdl_surface = SDL_SetVideoMode(hres, vres, 32, SDL_VIDEO_FLAGS);

  { /* Cairo */
    cairo_surface_t *cr_surface;
    cr_surface = cairo_image_surface_create_for_data(
        sdl_surface->pixels,
        CAIRO_FORMAT_RGB24,
        sdl_surface->w,
        sdl_surface->h,
        sdl_surface->pitch );
    cr = cairo_create(cr_surface);
    cairo_surface_destroy(cr_surface);
  }

  { /* screen-space transformation */
    cairo_matrix_t *m = &cm_display;

    cairo_matrix_init_identity(m);

    /* Cartesian */
    cairo_matrix_translate(m, hres/2.0, vres/2.0);
    cairo_matrix_scale(m, 1, -1);

    /* fixed scale */
    cairo_matrix_scale(m,
        scale * hres / width,
        scale * vres / height );
  }

  { /* field transformation */
    cairo_matrix_t *m = &cm_field;

    double scale = 1.0 / (2.0) / aspect;

    cairo_matrix_init_identity(m);
    cairo_matrix_multiply(m, m, &cm_display);

    cairo_matrix_scale(m, scale, scale);
  }

  { /* delay */
    Uint32 now = SDL_GetTicks();

    next_frame = now + 1000.0 / FRAMERATE;
  }

  fprintf(stderr, "-- MARK -- setup complete\n");

  SDL_LockSurface(sdl_surface);

  while (running) {

    { /* Render Frame */

      /* clear screen */
      cairo_set_operator(cr, CAIRO_OPERATOR_CLEAR);
      cairo_paint(cr);
      cairo_set_operator(cr, CAIRO_OPERATOR_OVER);

      /* Render Field */

      cairo_set_matrix(cr, &cm_field);

      render_1x1_box(cr);
      render_part(cr, &part);
      render_dots(cr, subdiv);
      render_pen(cr, pen);
    }

    { /* Update Display */
      SDL_UnlockSurface(sdl_surface);
      SDL_Flip(sdl_surface);
      SDL_LockSurface(sdl_surface);
    }

    { /* Delay */
      Uint32 now = SDL_GetTicks();

      if (now < next_frame) {
        missed_frames = 0;
        SDL_Delay(next_frame - now);
        next_frame = next_frame + 1000.0 / FRAMERATE;
      } else {
        missed_frames = missed_frames + 1;
        if (1 + TOLERATE_N_MISSED_FRAMES == missed_frames) {
          fprintf(stderr, "delay counter reset\n");
          next_frame = now + 1000.0 / FRAMERATE;
        } else {
          next_frame = next_frame + 1000.0 / FRAMERATE;
        }
      }
    }

    { /* Handle Events */
      SDL_Event event;

      while ( SDL_PollEvent(&event) ) {
        switch (event.type) {
          case SDL_QUIT:
            running = 0;
            break;
          case SDL_KEYDOWN:
            switch (event.key.keysym.sym) {
              case SDLK_q:
                running = 0;
                break;
              case SDLK_1:
                subdiv = 1;
                break;
              case SDLK_2:
                subdiv = 2;
                break;
              case SDLK_3:
                subdiv = 3;
                break;
              case SDLK_4:
                subdiv = 4;
                break;
              case SDLK_LEFT:
                pen->x = pen->x - 1.0 / (1 << subdiv);
                break;
              case SDLK_RIGHT:
                pen->x = pen->x + 1.0 / (1 << subdiv);
                break;
              case SDLK_DOWN:
                pen->y = pen->y - 1.0 / (1 << subdiv);
                break;
              case SDLK_UP:
                pen->y = pen->y + 1.0 / (1 << subdiv);
                break;
              case SDLK_RETURN:
                segment = (struct path_segment *)
                  path_segment_line_append(segment, &pen);
                fprintf(stderr, "-- MARK -- new segment created\n");
                break;
              case SDLK_c:
                path->color = 1 - path->color;
                break;
              case SDLK_f:
                path->fill  = 1 - path->fill;
                break;
            }
            break;
        }
      }
    }

  }

  SDL_UnlockSurface(sdl_surface);

  /* CLEANUP */

  cairo_destroy(cr);
  SDL_Quit();

  return 0;
}
示例#27
0
void blit_block_item_sheet()
{
    GLuint block_item_64_texture = 0;
    {
        unsigned int color_tex, fb, depth_rb;
        const int xres = 1024;
        const int yres = 1024;
        const float scale = 64.0f;

        //RGBA8 2D texture, 24 bit depth texture, 256x256
        glGenTextures(1, &color_tex);
        glBindTexture(GL_TEXTURE_2D, color_tex);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
        //NULL means reserve texture memory, but texels are undefined
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, xres,yres, 0, GL_BGRA, GL_UNSIGNED_BYTE, NULL);
        //-------------------------
        glGenFramebuffersEXT(1, &fb);
        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fb);
        //Attach 2D texture to this FBO
        glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, color_tex, 0);
        //-------------------------
        glGenRenderbuffersEXT(1, &depth_rb);
        glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, depth_rb);
        glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24, xres,yres);
        //-------------------------
        //Attach depth buffer to FBO
        glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depth_rb);
        //-------------------------
        //Does the GPU support current FBO configuration?
        GLenum status;
        status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
        switch (status)
        {
            case GL_FRAMEBUFFER_COMPLETE_EXT:
            //printf("FBO works\n");
            break;

            default:
            printf("blit_block_item_sheet: FBO error\n");
            break;
        }
        //-------------------------
        //and now you can render to GL_TEXTURE_2D
        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fb);
        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        //-------------------------
        glViewport(0, 0, xres, yres);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrtho(0.0f, (float) xres, 0.0f, (float) yres, -1.0f, 1.0f);
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();

        //-------------------------
        //glDisable(GL_TEXTURE_2D);
        glEnable(GL_TEXTURE_2D);
        GL_ASSERT(GL_BLEND, false);
        glDisable(GL_DEPTH_TEST);

        glBindTexture(GL_TEXTURE_2D, t_map::block_textures_normal);

        glBegin(GL_QUADS);
        for (int i=0; i<16; i++)
        for (int j=0; j<16; j++)
        {
            /*
                const int T = 0;
                const int B = 1;
                const int N = 2;
                const int S = 3;
                const int W = 4;
                const int E = 5;
            */

            int index = 16*j+i;
            // the NULL_CUBE is reserved at 255 (so that it fits in a packet)
            // must skip it
            if (!isValid((CubeType)index)) continue;

            int s1 = get_cube_side_texture((CubeType)index, 0); //T
            int s2 = get_cube_side_texture((CubeType)index, 2); //N
            int s3 = get_cube_side_texture((CubeType)index, 4); //W

            draw_iso_cube(i*scale, j*scale, scale, s1,s2,s3);
        }
        glEnd();

        block_item_64_surface = create_surface_from_nothing(xres, yres);

        SDL_LockSurface(block_item_64_surface);
        GLenum format = get_texture_format(block_item_64_surface);

        //glReadPixels(0, 0, xres, yres, GL_RGBA, GL_UNSIGNED_BYTE, (void*) block_item_64_surface->pixels);
        glReadPixels(0, 0, xres, yres, format, GL_UNSIGNED_BYTE, (void*) block_item_64_surface->pixels);

        SDL_UnlockSurface(block_item_64_surface);

        save_surface_to_png(block_item_64_surface, SCREENSHOT_PATH "fbo_test_64.png");

        //Delete resources
        glDeleteTextures(1, &color_tex);
        glDeleteRenderbuffersEXT(1, &depth_rb);
        //Bind 0, which means render to back buffer, as a result, fb is unbound
        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
        glDeleteFramebuffersEXT(1, &fb);

        //http://stackoverflow.com/questions/5102277/resizing-an-image-using-opengl
        // setup another framebuffer here
        // bind the 64 pixel texture
        // draw to a 256x256 framebuffer
        // save surface to png again

        create_texture_from_surface(block_item_64_surface, &block_item_64_texture, GL_NEAREST);
        //create_texture_from_surface(block_item_64_surface, &block_item_64_texture, GL_LINEAR);
        GS_ASSERT_ABORT(block_item_64_texture != 0);
        SDL_FreeSurface(block_item_64_surface);
    }

    {
        unsigned int color_tex, fb, depth_rb;
        const int xres = 256;
        const int yres = 256;
        //const float scale = 16.0;

        //RGBA8 2D texture, 24 bit depth texture, 256x256
        glGenTextures(1, &color_tex);
        glBindTexture(GL_TEXTURE_2D, color_tex);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
        //NULL means reserve texture memory, but texels are undefined
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, xres,yres, 0, GL_BGRA, GL_UNSIGNED_BYTE, NULL);
        //-------------------------
        glGenFramebuffersEXT(1, &fb);
        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fb);
        //Attach 2D texture to this FBO
        glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, color_tex, 0);
        //-------------------------
        glGenRenderbuffersEXT(1, &depth_rb);
        glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, depth_rb);
        glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24, xres,yres);
        //-------------------------
        //Attach depth buffer to FBO
        glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depth_rb);
        //-------------------------
        //Does the GPU support current FBO configuration?
        GLenum status;
        status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
        switch (status)
        {
            case GL_FRAMEBUFFER_COMPLETE_EXT:
            //printf("FBO works\n");
            break;

            default:
            printf("blit_block_item_sheet: FBO error\n");
            break;
        }
        //-------------------------
        //and now you can render to GL_TEXTURE_2D
        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fb);
        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        //-------------------------
        glViewport(0, 0, xres, yres);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrtho(0.0f, (float) xres, 0.0f, (float) yres, -1.0f, 1.0f);
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();

        //-------------------------
        //glDisable(GL_TEXTURE_2D);
        glEnable(GL_TEXTURE_2D);
        GL_ASSERT(GL_BLEND, false);
        glDisable(GL_DEPTH_TEST);

        //glBindTexture(GL_TEXTURE_2D, t_map::block_textures_normal);

        //glBegin(GL_QUADS);
        //for (int i=0; i<16; i++)
        //for (int j=0; j<16; j++)
        //{
            ///*
                //const int T = 0;
                //const int B = 1;
                //const int N = 2;
                //const int S = 3;
                //const int W = 4;
                //const int E = 5;
            //*/

            //int index = 16*j+i;
            //int s1 = get_cube_side_texture(index, 0); //T
            //int s2 = get_cube_side_texture(index, 2); //N
            //int s3 = get_cube_side_texture(index, 4); //W

            //draw_iso_cube(i*scale, j*scale, scale, s1,s2,s3);
        //}
        //glEnd();

        //glBegin(GL_TEXTURE_2D);
        glBindTexture(GL_TEXTURE_2D, block_item_64_texture);
        draw_bound_texture(0.0f, 0.0f, xres, yres);
        //glDisable(GL_TEXTURE_2D);

        block_item_16_surface = create_surface_from_nothing(xres, yres);
        SDL_LockSurface(block_item_16_surface);
        GLenum format = get_texture_format(block_item_16_surface);
        //glReadPixels(0, 0, xres, yres, GL_RGBA, GL_UNSIGNED_BYTE, (void*) block_item_16_surface->pixels);
        glReadPixels(0, 0, xres, yres, format, GL_UNSIGNED_BYTE, (void*) block_item_16_surface->pixels);

        SDL_UnlockSurface(block_item_16_surface);

        save_surface_to_png(block_item_16_surface, SCREENSHOT_PATH "fbo_test_16.png");

        //Delete resources
        glDeleteTextures(1, &color_tex);
        glDeleteRenderbuffersEXT(1, &depth_rb);
        //Bind 0, which means render to back buffer, as a result, fb is unbound
        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
        glDeleteFramebuffersEXT(1, &fb);
        SDL_FreeSurface(block_item_16_surface);
    }

    glBindFramebufferEXT(GL_FRAMEBUFFER, 0);
    glBindTexture(GL_TEXTURE_2D, 0);
    glViewport (0, 0, _xres, _yres);
}
示例#28
0
static int
SW_RenderCopyEx(SDL_Renderer * renderer, SDL_Texture * texture,
                const SDL_Rect * srcrect, const SDL_FRect * dstrect,
                const double angle, const SDL_FPoint * center, const SDL_RendererFlip flip)
{
    SDL_Surface *surface = SW_ActivateRenderer(renderer);
    SDL_Surface *src = (SDL_Surface *) texture->driverdata;
    SDL_Rect final_rect, tmp_rect;
    SDL_Surface *src_clone, *src_rotated, *src_scaled;
    SDL_Surface *mask = NULL, *mask_rotated = NULL;
    int retval = 0, dstwidth, dstheight, abscenterx, abscentery;
    double cangle, sangle, px, py, p1x, p1y, p2x, p2y, p3x, p3y, p4x, p4y;
    SDL_BlendMode blendmode;
    Uint8 alphaMod, rMod, gMod, bMod;
    int applyModulation = SDL_FALSE;
    int blitRequired = SDL_FALSE;
    int isOpaque = SDL_FALSE;

    if (!surface) {
        return -1;
    }

    if (renderer->viewport.x || renderer->viewport.y) {
        final_rect.x = (int)(renderer->viewport.x + dstrect->x);
        final_rect.y = (int)(renderer->viewport.y + dstrect->y);
    } else {
        final_rect.x = (int)dstrect->x;
        final_rect.y = (int)dstrect->y;
    }
    final_rect.w = (int)dstrect->w;
    final_rect.h = (int)dstrect->h;

    tmp_rect = final_rect;
    tmp_rect.x = 0;
    tmp_rect.y = 0;

    /* It is possible to encounter an RLE encoded surface here and locking it is
     * necessary because this code is going to access the pixel buffer directly.
     */
    if (SDL_MUSTLOCK(src)) {
        SDL_LockSurface(src);
    }

    /* Clone the source surface but use its pixel buffer directly.
     * The original source surface must be treated as read-only.
     */
    src_clone = SDL_CreateRGBSurfaceFrom(src->pixels, src->w, src->h, src->format->BitsPerPixel, src->pitch,
                                         src->format->Rmask, src->format->Gmask,
                                         src->format->Bmask, src->format->Amask);
    if (src_clone == NULL) {
        if (SDL_MUSTLOCK(src)) {
            SDL_UnlockSurface(src);
        }
        return -1;
    }

    SDL_GetSurfaceBlendMode(src, &blendmode);
    SDL_GetSurfaceAlphaMod(src, &alphaMod);
    SDL_GetSurfaceColorMod(src, &rMod, &gMod, &bMod);

    /* SDLgfx_rotateSurface only accepts 32-bit surfaces with a 8888 layout. Everything else has to be converted. */
    if (src->format->BitsPerPixel != 32 || SDL_PIXELLAYOUT(src->format->format) != SDL_PACKEDLAYOUT_8888 || !src->format->Amask) {
        blitRequired = SDL_TRUE;
    }

    /* If scaling and cropping is necessary, it has to be taken care of before the rotation. */
    if (!(srcrect->w == final_rect.w && srcrect->h == final_rect.h && srcrect->x == 0 && srcrect->y == 0)) {
        blitRequired = SDL_TRUE;
    }

    /* The color and alpha modulation has to be applied before the rotation when using the NONE and MOD blend modes. */
    if ((blendmode == SDL_BLENDMODE_NONE || blendmode == SDL_BLENDMODE_MOD) && (alphaMod & rMod & gMod & bMod) != 255) {
        applyModulation = SDL_TRUE;
        SDL_SetSurfaceAlphaMod(src_clone, alphaMod);
        SDL_SetSurfaceColorMod(src_clone, rMod, gMod, bMod);
    }

    /* Opaque surfaces are much easier to handle with the NONE blend mode. */
    if (blendmode == SDL_BLENDMODE_NONE && !src->format->Amask && alphaMod == 255) {
        isOpaque = SDL_TRUE;
    }

    /* The NONE blend mode requires a mask for non-opaque surfaces. This mask will be used
     * to clear the pixels in the destination surface. The other steps are explained below.
     */
    if (blendmode == SDL_BLENDMODE_NONE && !isOpaque) {
        mask = SDL_CreateRGBSurface(0, final_rect.w, final_rect.h, 32,
                                    0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000);
        if (mask == NULL) {
            retval = -1;
        } else {
            SDL_SetSurfaceBlendMode(mask, SDL_BLENDMODE_MOD);
        }
    }

    /* Create a new surface should there be a format mismatch or if scaling, cropping,
     * or modulation is required. It's possible to use the source surface directly otherwise.
     */
    if (!retval && (blitRequired || applyModulation)) {
        SDL_Rect scale_rect = tmp_rect;
        src_scaled = SDL_CreateRGBSurface(0, final_rect.w, final_rect.h, 32,
                                          0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000);
        if (src_scaled == NULL) {
            retval = -1;
        } else {
            SDL_SetSurfaceBlendMode(src_clone, SDL_BLENDMODE_NONE);
            retval = SDL_BlitScaled(src_clone, srcrect, src_scaled, &scale_rect);
            SDL_FreeSurface(src_clone);
            src_clone = src_scaled;
            src_scaled = NULL;
        }
    }

    /* SDLgfx_rotateSurface is going to make decisions depending on the blend mode. */
    SDL_SetSurfaceBlendMode(src_clone, blendmode);

    if (!retval) {
        SDLgfx_rotozoomSurfaceSizeTrig(tmp_rect.w, tmp_rect.h, angle, &dstwidth, &dstheight, &cangle, &sangle);
        src_rotated = SDLgfx_rotateSurface(src_clone, angle, dstwidth/2, dstheight/2, GetScaleQuality(), flip & SDL_FLIP_HORIZONTAL, flip & SDL_FLIP_VERTICAL, dstwidth, dstheight, cangle, sangle);
        if (src_rotated == NULL) {
            retval = -1;
        }
        if (!retval && mask != NULL) {
            /* The mask needed for the NONE blend mode gets rotated with the same parameters. */
            mask_rotated = SDLgfx_rotateSurface(mask, angle, dstwidth/2, dstheight/2, SDL_FALSE, 0, 0, dstwidth, dstheight, cangle, sangle);
            if (mask_rotated == NULL) {
                retval = -1;
            }
        }
        if (!retval) {
            /* Find out where the new origin is by rotating the four final_rect points around the center and then taking the extremes */
            abscenterx = final_rect.x + (int)center->x;
            abscentery = final_rect.y + (int)center->y;
            /* Compensate the angle inversion to match the behaviour of the other backends */
            sangle = -sangle;

            /* Top Left */
            px = final_rect.x - abscenterx;
            py = final_rect.y - abscentery;
            p1x = px * cangle - py * sangle + abscenterx;
            p1y = px * sangle + py * cangle + abscentery;

            /* Top Right */
            px = final_rect.x + final_rect.w - abscenterx;
            py = final_rect.y - abscentery;
            p2x = px * cangle - py * sangle + abscenterx;
            p2y = px * sangle + py * cangle + abscentery;

            /* Bottom Left */
            px = final_rect.x - abscenterx;
            py = final_rect.y + final_rect.h - abscentery;
            p3x = px * cangle - py * sangle + abscenterx;
            p3y = px * sangle + py * cangle + abscentery;

            /* Bottom Right */
            px = final_rect.x + final_rect.w - abscenterx;
            py = final_rect.y + final_rect.h - abscentery;
            p4x = px * cangle - py * sangle + abscenterx;
            p4y = px * sangle + py * cangle + abscentery;

            tmp_rect.x = (int)MIN(MIN(p1x, p2x), MIN(p3x, p4x));
            tmp_rect.y = (int)MIN(MIN(p1y, p2y), MIN(p3y, p4y));
            tmp_rect.w = dstwidth;
            tmp_rect.h = dstheight;

            /* The NONE blend mode needs some special care with non-opaque surfaces.
             * Other blend modes or opaque surfaces can be blitted directly.
             */
            if (blendmode != SDL_BLENDMODE_NONE || isOpaque) {
                if (applyModulation == SDL_FALSE) {
                    /* If the modulation wasn't already applied, make it happen now. */
                    SDL_SetSurfaceAlphaMod(src_rotated, alphaMod);
                    SDL_SetSurfaceColorMod(src_rotated, rMod, gMod, bMod);
                }
                retval = SDL_BlitSurface(src_rotated, NULL, surface, &tmp_rect);
            } else {
                /* The NONE blend mode requires three steps to get the pixels onto the destination surface.
                 * First, the area where the rotated pixels will be blitted to get set to zero.
                 * This is accomplished by simply blitting a mask with the NONE blend mode.
                 * The colorkey set by the rotate function will discard the correct pixels.
                 */
                SDL_Rect mask_rect = tmp_rect;
                SDL_SetSurfaceBlendMode(mask_rotated, SDL_BLENDMODE_NONE);
                retval = SDL_BlitSurface(mask_rotated, NULL, surface, &mask_rect);
                if (!retval) {
                    /* The next step copies the alpha value. This is done with the BLEND blend mode and
                     * by modulating the source colors with 0. Since the destination is all zeros, this
                     * will effectively set the destination alpha to the source alpha.
                     */
                    SDL_SetSurfaceColorMod(src_rotated, 0, 0, 0);
                    mask_rect = tmp_rect;
                    retval = SDL_BlitSurface(src_rotated, NULL, surface, &mask_rect);
                    if (!retval) {
                        /* The last step gets the color values in place. The ADD blend mode simply adds them to
                         * the destination (where the color values are all zero). However, because the ADD blend
                         * mode modulates the colors with the alpha channel, a surface without an alpha mask needs
                         * to be created. This makes all source pixels opaque and the colors get copied correctly.
                         */
                        SDL_Surface *src_rotated_rgb;
                        src_rotated_rgb = SDL_CreateRGBSurfaceFrom(src_rotated->pixels, src_rotated->w, src_rotated->h,
                                                                   src_rotated->format->BitsPerPixel, src_rotated->pitch,
                                                                   src_rotated->format->Rmask, src_rotated->format->Gmask,
                                                                   src_rotated->format->Bmask, 0);
                        if (src_rotated_rgb == NULL) {
                            retval = -1;
                        } else {
                            SDL_SetSurfaceBlendMode(src_rotated_rgb, SDL_BLENDMODE_ADD);
                            retval = SDL_BlitSurface(src_rotated_rgb, NULL, surface, &tmp_rect);
                            SDL_FreeSurface(src_rotated_rgb);
                        }
                    }
                }
                SDL_FreeSurface(mask_rotated);
            }
            if (src_rotated != NULL) {
                SDL_FreeSurface(src_rotated);
            }
        }
    }

    if (SDL_MUSTLOCK(src)) {
        SDL_UnlockSurface(src);
    }
    if (mask != NULL) {
        SDL_FreeSurface(mask);
    }
    if (src_clone != NULL) {
        SDL_FreeSurface(src_clone);
    }
    return retval;
}
示例#29
0
    void putEmergencyFont(K_Surface *screen, int xpos, int ypos, int scrw, int scrh, uint16 color, const char *buf)
    {
        const byte *buffer = (const byte *)buf;
        
        int clipw = 0;
        
        int px = xpos;
        int py = ypos;
        if ( SDL_MUSTLOCK(screen) ) {
            if ( SDL_LockSurface(screen) < 0 ) {
                //printf("putEmergencyFont(): Lock 실패\n");
                warning("putEmergencyFont(): Lock 실패\n");
                return;
            }
        }
        uint16 *dst;
        
        int c;
        
        int w = 8;
        int h = _engFontHeight;
        
        int engMargin = 0;
        
        do {
            c = *buffer++;
            if (c == 0) {
                break;
            }
            if (c == 0x0B)
                continue;
            if (c == '\\') {
                if ( *buffer == 'n' || *buffer == 'N' ) {
                    buffer++;
                    px = xpos;
                    py += h + 2;
                    dst = (uint16 *)screen->pixels + py * screen->pitch / 2 + px;
                } else if (*buffer == 'c' || *buffer == 'C' )	{
                    uint8 d = *buffer++;
                    if (color)	// 검은색(0,0,0)이 아니라면
                        color = getRGB(screen, _kPalette[d].r, _kPalette[d].g, _kPalette[d].b);
                }
                continue;
            } else if ( c == 13 ) {
                if ( *buffer == 10 ) {
                    px = xpos;
                    py += h + 2;
                }
                continue;
            }
            if (c & 0x80) {
                c += (*buffer++) * 256;	//LE
                w = _korFontWidth;
                h = _korFontHeight;
                engMargin = 0;
            } else {
                w = getEngWidth(c);
                h = _engFontHeight;
                engMargin = getTopMargin(c);
            }
            
            if(px < 0 || px + w > (scrw + (1 - clipw))) {	// 가로로 화면 밖
				px = xpos;
				py += h + 2;
            }
            dst = (uint16 *)screen->pixels + (py + engMargin) * screen->pitch / 2 + px;
            
            int offsetX[9] = { -1,  0, 1, 1, 1, 0, -1, -1, 0 };
            int offsetY[9] = {  -1, -1, -1, 0, 1, 1, 1, 0, 0 };
            int cTable[9] =  {  0,  0, 0, 0, 0, 0, 0, 0, color };
            int i = 0;
            
            int showShadow = 1;
            
            if (!showShadow)
                i = 8;
            
            for (; i < 9; i++) {
                dst = (uint16 *)screen->pixels + (py + engMargin + offsetY[i]) * screen->pitch / 2 + (px + offsetX[i]);
                putEmergencyChar(dst, (screen->pitch / 2), cTable[i], c);
            }
            dst += w;
            px += w;
        } while (1);
        
        if(SDL_MUSTLOCK(screen))
            SDL_UnlockSurface(screen);
    }
示例#30
0
int sysdep_display_driver_open(int reopen)
{
  int i,j;
  SDL_Rect** vid_modes;
  SDL_PixelFormat pixel_format;
  const SDL_VideoInfo* video_info;
  int video_flags, score, best_window = 0;
  int best_bpp = 0, best_width = 0, best_height = 0, best_score = 0;
  static int firsttime = 1;
  
  if (reopen)
    sysdep_display_effect_close();
  
  /* determine SetVideoMode flags */
  video_flags = SDL_HWSURFACE;
  if (sysdep_display_params.fullscreen)
    video_flags |= SDL_FULLSCREEN;
  if (doublebuf)
    video_flags |= SDL_DOUBLEBUF;

  /* Find a suitable mode, also determine the max size of the display */
  scaled_height = sysdep_display_params.yarbsize?
    sysdep_display_params.yarbsize:
    sysdep_display_params.height*sysdep_display_params.heightscale;
  scaled_width = ((sysdep_display_params.width+3)&~3) * 
    sysdep_display_params.widthscale;
  sysdep_display_properties.max_width  = 0;
  sysdep_display_properties.max_height = 0;
  
  for (i=0; i<5; i++)
  {
    /* We can't ask SDL which pixel formats are available, so we
       try all well known formats + the format preferred by the SDL
       videodriver, also trying the preferred format will ensure that
       we try at least one available format, so that we will always find
       some modes.
       
       The preferred format is tried last, so that if
       a just as good well known format is found this will be used instead of
       the preferred format. This is done because the effect code only supports
       well know formats, so if we can choose we want a well known format. */
    switch (i)
    {
      case 0:
        /* rgb 555 */
        pixel_format.palette = NULL;
        pixel_format.BitsPerPixel = 15;
        pixel_format.BytesPerPixel = 2;
        pixel_format.Rmask  = 0x01F << 10;
        pixel_format.Gmask  = 0x01F << 5;
        pixel_format.Bmask  = 0x01F << 0;
        pixel_format.Rshift = 10;
        pixel_format.Gshift = 5;
        pixel_format.Bshift = 0;
        pixel_format.Rloss  = 3;
        pixel_format.Gloss  = 3;
        pixel_format.Bloss  = 3;
        pixel_format.colorkey = 0;
        pixel_format.alpha  = 255;
        break;
      case 1:
        /* rgb 565 */
        pixel_format.palette = NULL;
        pixel_format.BitsPerPixel = 16;
        pixel_format.BytesPerPixel = 2;
        pixel_format.Rmask  = 0x01F << 11;
        pixel_format.Gmask  = 0x03F << 5;
        pixel_format.Bmask  = 0x01F << 0;
        pixel_format.Rshift = 11;
        pixel_format.Gshift = 5;
        pixel_format.Bshift = 0;
        pixel_format.Rloss  = 3;
        pixel_format.Gloss  = 2;
        pixel_format.Bloss  = 3;
        pixel_format.colorkey = 0;
        pixel_format.alpha  = 255;
        break;
      case 2:
        /* rgb 888 packed*/
        pixel_format.palette = NULL;
        pixel_format.BitsPerPixel = 24;
        pixel_format.BytesPerPixel = 3;
        pixel_format.Rmask  = 0x0FF << 16;
        pixel_format.Gmask  = 0x0FF << 8;
        pixel_format.Bmask  = 0x0FF << 0;
        pixel_format.Rshift = 16;
        pixel_format.Gshift = 8;
        pixel_format.Bshift = 0;
        pixel_format.Rloss  = 0;
        pixel_format.Gloss  = 0;
        pixel_format.Bloss  = 0;
        pixel_format.colorkey = 0;
        pixel_format.alpha  = 255;
        break;
      case 3:
        /* rgb 888 sparse */
        pixel_format.palette = NULL;
        pixel_format.BitsPerPixel = 32;
        pixel_format.BytesPerPixel = 4;
        pixel_format.Rmask  = 0x0FF << 16;
        pixel_format.Gmask  = 0x0FF << 8;
        pixel_format.Bmask  = 0x0FF << 0;
        pixel_format.Rshift = 16;
        pixel_format.Gshift = 8;
        pixel_format.Bshift = 0;
        pixel_format.Rloss  = 0;
        pixel_format.Gloss  = 0;
        pixel_format.Bloss  = 0;
        pixel_format.colorkey = 0;
        pixel_format.alpha  = 255;
        break;
      case 4:
        video_info = SDL_GetVideoInfo();
        pixel_format = *(video_info->vfmt);
        if (pixel_format.palette || (pixel_format.BitsPerPixel <= 8))
          continue;
        break;
    }
    vid_modes = SDL_ListModes(&pixel_format, video_flags);

    if(vid_modes == (SDL_Rect **)-1)
    {
      /* All resolutions available */
      score = mode_match(0, 0, 0, SDL_calc_depth(&pixel_format),
        pixel_format.BytesPerPixel*8);
      if (score > best_score)
      {
        best_score  = score;
        best_bpp    = pixel_format.BitsPerPixel;
        best_width  = scaled_width;
        best_height = scaled_height;
        best_window = 1;
      }
      /* also determine the max size of the display */
      sysdep_display_properties.max_width  = -1;
      sysdep_display_properties.max_height = -1;
    }
    else if (vid_modes)
    {
      for(j=0;vid_modes[j];j++)
      {
        /* No way to get the line_width from SDL, so assume that this
           is the viewport width */
        score = mode_match(vid_modes[j]->w, vid_modes[j]->h, vid_modes[j]->w,
          SDL_calc_depth(&pixel_format), pixel_format.BytesPerPixel*8);
        if (score > best_score)
        {
          best_score  = score;
          best_bpp    = pixel_format.BitsPerPixel;
          best_width  = vid_modes[j]->w;
          best_height = vid_modes[j]->h;
          best_window = 0;
        }
        /* also determine the max size of the display */
        if (vid_modes[j]->w > sysdep_display_properties.max_width)
          sysdep_display_properties.max_width  = vid_modes[j]->w;
        if (vid_modes[j]->h > sysdep_display_properties.max_height)
          sysdep_display_properties.max_height = vid_modes[j]->h;

        if (firsttime)
          fprintf(stderr, "SDL found mode:%dx%dx%d\n", vid_modes[j]->w,
            vid_modes[j]->h, pixel_format.BitsPerPixel);
      }
    }
  }
  firsttime = 0;
  
  if (best_score == 0)
  {
    fprintf(stderr, "SDL Error: could not find a suitable mode\n");
    return 1;
  }
  
  /* Set video mode */
  if (!video_surface ||
      (video_surface->w != best_width) ||
      (video_surface->h != best_height) ||
      (video_surface->format->BitsPerPixel != best_bpp))
  {
    if(! (video_surface = SDL_SetVideoMode(best_width, best_height, best_bpp,
            video_flags)))
    {
      fprintf (stderr, "SDL: Error: Setting video mode failed\n");
      return 1;
    }
    fprintf(stderr, "SDL: Using a mode with a resolution of: %dx%dx%d\n",
      best_width, best_height, best_bpp);
    if(!best_window)
    {
      mode_set_aspect_ratio((double)best_width / best_height);
      /* mode_set_aspect_ratio may have changed yarbsize */
      scaled_height = sysdep_display_params.yarbsize?
        sysdep_display_params.yarbsize:
        sysdep_display_params.height*sysdep_display_params.heightscale;
    }
  }
  else if ((video_flags & SDL_FULLSCREEN) !=
           (video_surface->flags & SDL_FULLSCREEN))
  {
    SDL_WM_ToggleFullScreen(video_surface);
  }
  /* fill the sysdep_display_properties struct */
  memset(&sysdep_display_properties.palette_info, 0, sizeof(struct
    sysdep_palette_info));
  sysdep_display_properties.palette_info.red_mask   =
    video_surface->format->Rmask;
  sysdep_display_properties.palette_info.green_mask =
    video_surface->format->Gmask;
  sysdep_display_properties.palette_info.blue_mask  =
    video_surface->format->Bmask;
  sysdep_display_properties.palette_info.depth      =
    SDL_calc_depth(video_surface->format);
  sysdep_display_properties.palette_info.bpp        =
    video_surface->format->BytesPerPixel * 8;
  sysdep_display_properties.vector_renderer         = NULL;

  if (video_surface->flags & SDL_HWSURFACE)
    sysdep_display_properties.mode_info[0] |=  SYSDEP_DISPLAY_DIRECT_FB;
  else
    sysdep_display_properties.mode_info[0] &= ~SYSDEP_DISPLAY_DIRECT_FB;
  
  /* calculate start of screen */
  startx = (video_surface->w - scaled_width ) / 2;
  starty = (video_surface->h - scaled_height) / 2;
  if (video_surface->flags & SDL_HWSURFACE)
    startx &= ~3;

  /* clear the unused area of the screen */
  for (i=0; i<2; i++)
  {
    unsigned char *video_mem;
    SDL_LockSurface(video_surface);
    video_mem = video_surface->pixels;
    
    /* top */
    memset(video_mem, 0, starty*video_surface->pitch);
    /* left and right */
    for (j=starty; j<(scaled_height+starty); j++)
    {
      /* left */
      memset(video_mem + j*video_surface->pitch, 0,
        startx * video_surface->format->BytesPerPixel);
      /* right */
      memset(video_mem + j*video_surface->pitch +
        (startx + scaled_width) * video_surface->format->BytesPerPixel,
        0, (video_surface->w - (startx + scaled_width)) *
        video_surface->format->BytesPerPixel);
    }
    /* bottom */
    memset(video_mem + (starty + scaled_height) *
      video_surface->pitch, 0,
      (video_surface->h - (starty + scaled_height)) *
      video_surface->pitch);
    
    SDL_UnlockSurface(video_surface);
    
    if (video_surface->flags & SDL_DOUBLEBUF)
      SDL_Flip(video_surface);
    else
      break;
  }

  /* Setup input */
  if (!reopen)
  {
    SDL_EventState(SDL_KEYUP, SDL_ENABLE);
    SDL_EventState(SDL_KEYDOWN, SDL_ENABLE);
    SDL_EnableUNICODE(1);
    if (sdl_grab_input)
      sdl_input_grabbed = SDL_WM_GrabInput(SDL_GRAB_ON);
  }
  
  /* Hide/Show mouse cursor? */
  if ((sdl_input_grabbed == SDL_GRAB_ON) || !sdl_show_cursor ||
      sysdep_display_params.fullscreen)
    SDL_ShowCursor(0);
  else
    SDL_ShowCursor(1);

  /* Set window title */
  SDL_WM_SetCaption(sysdep_display_params.title, NULL);
  /* let sysdep_display_update know that it's the first call after
     an (re)open */
  first_update = 1;

  /* get a blit function */
  return !(blit_func=sysdep_display_effect_open());
}