#include "conversion.h"

void ofxMsdfgen::toOfImage(const msdfgen::Bitmap <float, 3> bitmap,
                           ofFloatImage & image){
    image.allocate(bitmap.width(), bitmap.height(), OF_IMAGE_COLOR);
    memcpy(image.getPixels().getData(), static_cast <const float *>(bitmap), bitmap.width() * bitmap.height() * 3 * sizeof(float));
    image.update(); // float is slow here
}

void ofxMsdfgen::toOfImage(const msdfgen::Bitmap <float, 3> bitmap,
                           ofImage & image){
    image.allocate(bitmap.width(), bitmap.height(), OF_IMAGE_COLOR);
    image.getTexture().getTextureData().bFlipTexture = true;
    ofPixels & pixels = image.getPixels();
    int w = bitmap.width();
    int h = bitmap.height();
    for(int y = 0; y < h; y++){
        for(int x = 0; x < w; x++){
            const auto & rgb = bitmap(x, y);
            int index = 3 * (x + y * w);
            pixels.getData()[index] = (unsigned char)std::clamp(rgb[0] * 256.0,
                                                                0.0, 255.0);
            pixels.getData()[index + 1] = (unsigned char)std::clamp(rgb[1] * 256.0,
                                                                    0.0, 255.0);
            pixels.getData()[index + 2] = (unsigned char)std::clamp(rgb[2] * 256.0,
                                                                    0.0, 255.0);
        }
    }

    image.update();
}

void ofxMsdfgen::toOfImage(const msdfgen::Bitmap <byte, 3> bitmap,
                           ofImage & image){
    image.allocate(bitmap.width(), bitmap.height(), OF_IMAGE_COLOR);
    image.getTexture().getTextureData().bFlipTexture = true;
    memcpy(image.getPixels().getData(), static_cast <const byte *>(bitmap), bitmap.width() * bitmap.height() * 3 * sizeof(byte));

    image.update();
}

ofImage ofxMsdfgen::toOfImage(const msdfgen::Bitmap <float, 3> bitmap){
    ofImage image;
    image.allocate(bitmap.width(), bitmap.height(), OF_IMAGE_COLOR);
    ofPixels & pixels = image.getPixels();
    int w = bitmap.width();
    int h = bitmap.height();
    for(int y = 0; y < h; y++){
        for(int x = 0; x < w; x++){
            const auto & rgb = bitmap(x, y);
            int index = 3 * (x + y * w);
            pixels.getData()[index] = (unsigned char)std::clamp(rgb[0] * 256.0,
                                                                0.0, 255.0);
            pixels.getData()[index + 1] = (unsigned char)std::clamp(rgb[1] * 256.0,
                                                                    0.0, 255.0);
            pixels.getData()[index + 2] = (unsigned char)std::clamp(rgb[2] * 256.0,
                                                                    0.0, 255.0);
        }
    }
    image.update();
    return image;
}
