#include "pxl8_blit.h"

void pxl8_blit_hicolor(u16* fb, u32 fb_width, const u16* sprite, u32 atlas_width,
                       i32 x, i32 y, u32 w, u32 h) {
    u16* dest_base = fb + y * fb_width + x;
    const u16* src_base = sprite;

    for (u32 row = 0; row < h; row++) {
        u16* dest_row = dest_base + row * fb_width;
        const u16* src_row = src_base + row * atlas_width;

        u32 col = 0;
        u32 count2 = w / 2;
        for (u32 i = 0; i < count2; i++) {
            u32 pixels = ((const u32*)src_row)[i];
            if (pixels == 0) {
                col += 2;
                continue;
            }
            dest_row[col]     = pxl8_blend_hicolor((u16)(pixels), dest_row[col]);
            dest_row[col + 1] = pxl8_blend_hicolor((u16)(pixels >> 16), dest_row[col + 1]);
            col += 2;
        }
        if (w & 1) {
            dest_row[col] = pxl8_blend_hicolor(src_row[col], dest_row[col]);
        }
    }
}

void pxl8_blit_indexed(u8* fb, u32 fb_width, const u8* sprite, u32 atlas_width,
                       i32 x, i32 y, u32 w, u32 h) {
    u8* dest_base = fb + y * fb_width + x;
    const u8* src_base = sprite;

    for (u32 row = 0; row < h; row++) {
        u8* dest_row = dest_base + row * fb_width;
        const u8* src_row = src_base + row * atlas_width;

        u32 col = 0;
        u32 count4 = w / 4;
        for (u32 i = 0; i < count4; i++) {
            u32 pixels = ((const u32*)src_row)[i];
            if (pixels == 0) {
                col += 4;
                continue;
            }
            dest_row[col]     = pxl8_blend_indexed((u8)(pixels), dest_row[col]);
            dest_row[col + 1] = pxl8_blend_indexed((u8)(pixels >> 8), dest_row[col + 1]);
            dest_row[col + 2] = pxl8_blend_indexed((u8)(pixels >> 16), dest_row[col + 2]);
            dest_row[col + 3] = pxl8_blend_indexed((u8)(pixels >> 24), dest_row[col + 3]);
            col += 4;
        }
        for (; col < w; col++) {
            dest_row[col] = pxl8_blend_indexed(src_row[col], dest_row[col]);
        }
    }
}
