+ int red_offs, green_offs, blue_offs;
+ get_rgb_order(&red_offs, &green_offs, &blue_offs);
+
+ Rect irect = rect_intersection(get_clipping_rect(), dest_rect);
+
+ int width = src_rect.width;
+ int height = src_rect.height;
+
+ int xoffs = dest_x - irect.x;
+ if(xoffs < 0) {
+ dest_x = irect.x;
+ width += xoffs;
+ }
+
+ int yoffs = dest_y - irect.y;
+ if(yoffs < 0) {
+ dest_y = irect.y;
+ height += yoffs;
+ }
+
+ int xend = dest_x + width;
+ if(xend >= irect.width) {
+ width -= xend - irect.width;
+ }
+
+ int yend = dest_y + height;
+ if(yend >= irect.height) {
+ height -= yend - irect.height;
+ }
+
+ if(width <= 0 || height <= 0) {
+ return;
+ }
+
+ unsigned char *sptr = src_img + (src_rect.y * src_rect.width + src_rect.x) * 4;
+ unsigned char *dptr = dest_img + (dest_y * dest_rect.width + dest_x) * 4;
+
+ for(int i=0; i<height; i++) {
+ for(int j=0; j<width; j++) {
+ int r = sptr[j * 4];
+ int g = sptr[j * 4 + 1];
+ int b = sptr[j * 4 + 2];
+
+ if(r != key_r || g != key_g || b != key_b) {
+ dptr[j * 4 + red_offs] = r;
+ dptr[j * 4 + green_offs] = g;
+ dptr[j * 4 + blue_offs] = b;
+ }
+ }