/*
*  This program was created by AXELL CORPORATION.
*  Copyright (C) 2017 AXELL CORPORATION, all rights reserved.
*/
#include "gfx_sample.h"

#define SRCBUFFER_WIDTH  640
#define SRCBUFFER_HEIGHT 480
#define SRC_SX           460
#define SRC_SY           20
#define SRC_SW           160
#define SRC_SH           120

#define DSTBUFFER_WIDTH  1024
#define DSTBUFFER_HEIGHT 1024
#define DST_DX           246
#define DST_DY           357
#define DST_DW           400
#define DST_DH           300

static VGRectInfo srcBuffer, dstBuffer;
static VGImage image;
static void *image_data;

static void TestInit(int width, int height)
{
    VGfloat ClearColor[4]  = {1.0F, 1.0F, 1.0F, 1.0F};

    /* 画像を読込 */
    image_data = GfxGetFreeArea(VGA_WIDTH, VGA_HEIGHT, VGA_BPP<<3);
    GfxFsRead((int8_t*)VGA_NAME, VGA_STRIDE * VGA_HEIGHT, (void*)image_data);

    /* 描画サーフェスのクリアカラーを指定 */
    vgSetfv(VG_CLEAR_COLOR, 4, ClearColor);

    /* 描画サーフェス全体をクリア */
    vgClear(0, 0, width, height);

    /* get free area (zero initialized) */
    srcBuffer.addr = GfxGetFreeArea(SRCBUFFER_WIDTH, SRCBUFFER_HEIGHT, 32);
    srcBuffer.width = SRCBUFFER_WIDTH;
    srcBuffer.height = SRCBUFFER_HEIGHT;
    srcBuffer.stride = SRCBUFFER_WIDTH * 4;
    srcBuffer.format = VG_sRGBA_8888;

    dstBuffer.addr = GfxGetFreeArea(DSTBUFFER_WIDTH, DSTBUFFER_HEIGHT, 16);
    dstBuffer.width = DSTBUFFER_WIDTH;
    dstBuffer.height = DSTBUFFER_HEIGHT;
    dstBuffer.stride = DSTBUFFER_WIDTH * 2;
    dstBuffer.format = VG_sRGB_565;

    /* ソースバッファにイメージデータを転送 */
    GfxWriteMemory(srcBuffer.addr, image_data, VGA_STRIDE * VGA_HEIGHT);

    /* createimage */
    image = vgCreateDirectImageEXT(dstBuffer.format, dstBuffer.width, dstBuffer.height,
                      VG_IMAGE_QUALITY_NONANTIALIASED, dstBuffer.addr, dstBuffer.stride);
}

static void CopyRect(VGRectInfo *dst, VGint dx, VGint dy, VGint dw, VGint dh, 
                     VGRectInfo *src, VGint sx, VGint sy, VGint sw, VGint sh)
{
    vgCopyRectEXT(dst, dx, dy, src, sx, sy, sw, sh);
    vgSetPixels(20, 180, image, dx, dy, sw, sh);

    vgCopyScaleRectEXT(dst, dx, dy, dw, dh, src, sx, sy, sw, sh);
    vgSetPixels(200, 90, image, dx, dy, dw, dh);
}

static void TestTerm(void)
{
    GfxReleaseFreeArea(image_data);
    GfxReleaseFreeArea(srcBuffer.addr);
    GfxReleaseFreeArea(dstBuffer.addr);
    /* オブジェクトの破棄 */
    vgDestroyImage(image);
}

void CopyRectMain(void)
{
    /* 初期化処理 */
    TestInit(GFX_WIDTH, GFX_HEIGHT);

    /* 任意領域間の矩形コピー処理 */
    CopyRect(&dstBuffer, DST_DX, DST_DY, DST_DW, DST_DH,
             &srcBuffer, SRC_SX, SRC_SY, SRC_SW, SRC_SH);

    /* バッファスワップ */
    GfxSwapBuffer();

    /* 終了処理 */
    TestTerm();
}
